ada: output.adb: fix newline being inserted when buffer is full
[official-gcc.git] / gcc / cp / decl2.cc
blobf95529a5c9a743dfa18642e95f5a14bfa4f8da74
1 /* Process declarations and variables for C++ compiler.
2 Copyright (C) 1988-2022 Free Software Foundation, Inc.
3 Hacked 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 "memmodel.h"
33 #include "target.h"
34 #include "cp-tree.h"
35 #include "c-family/c-common.h"
36 #include "timevar.h"
37 #include "stringpool.h"
38 #include "cgraph.h"
39 #include "varasm.h"
40 #include "attribs.h"
41 #include "stor-layout.h"
42 #include "calls.h"
43 #include "decl.h"
44 #include "toplev.h"
45 #include "c-family/c-objc.h"
46 #include "c-family/c-pragma.h"
47 #include "dumpfile.h"
48 #include "intl.h"
49 #include "c-family/c-ada-spec.h"
50 #include "asan.h"
51 #include "optabs-query.h"
52 #include "omp-general.h"
54 /* Id for dumping the raw trees. */
55 int raw_dump_id;
57 extern cpp_reader *parse_in;
59 static tree start_objects (bool, unsigned, bool);
60 static tree finish_objects (bool, unsigned, tree, bool = true);
61 static tree start_partial_init_fini_fn (bool, unsigned, unsigned);
62 static void finish_partial_init_fini_fn (tree);
63 static void emit_partial_init_fini_fn (bool, unsigned, tree,
64 unsigned, location_t);
65 static void one_static_initialization_or_destruction (bool, tree, tree);
66 static void generate_ctor_or_dtor_function (bool, unsigned, tree, location_t);
67 static tree prune_vars_needing_no_initialization (tree *);
68 static void write_out_vars (tree);
69 static void import_export_class (tree);
70 static tree get_guard_bits (tree);
71 static void determine_visibility_from_class (tree, tree);
72 static bool determine_hidden_inline (tree);
74 /* A list of static class variables. This is needed, because a
75 static class variable can be declared inside the class without
76 an initializer, and then initialized, statically, outside the class. */
77 static GTY(()) vec<tree, va_gc> *pending_statics;
79 /* A list of functions which were declared inline, but which we
80 may need to emit outline anyway. */
81 static GTY(()) vec<tree, va_gc> *deferred_fns;
83 /* A list of decls that use types with no linkage, which we need to make
84 sure are defined. */
85 static GTY(()) vec<tree, va_gc> *no_linkage_decls;
87 /* A vector of alternating decls and identifiers, where the latter
88 is to be an alias for the former if the former is defined. */
89 static GTY(()) vec<tree, va_gc> *mangling_aliases;
91 /* hash traits for declarations. Hashes single decls via
92 DECL_ASSEMBLER_NAME_RAW. */
94 struct mangled_decl_hash : ggc_remove <tree>
96 typedef tree value_type; /* A DECL. */
97 typedef tree compare_type; /* An identifier. */
99 static hashval_t hash (const value_type decl)
101 return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME_RAW (decl));
103 static bool equal (const value_type existing, compare_type candidate)
105 tree name = DECL_ASSEMBLER_NAME_RAW (existing);
106 return candidate == name;
109 static const bool empty_zero_p = true;
110 static inline void mark_empty (value_type &p) {p = NULL_TREE;}
111 static inline bool is_empty (value_type p) {return !p;}
113 static bool is_deleted (value_type e)
115 return e == reinterpret_cast <value_type> (1);
117 static void mark_deleted (value_type &e)
119 e = reinterpret_cast <value_type> (1);
123 /* A hash table of decls keyed by mangled name. Used to figure out if
124 we need compatibility aliases. */
125 static GTY(()) hash_table<mangled_decl_hash> *mangled_decls;
127 // Hash table mapping priority to lists of variables or functions.
128 struct priority_map_traits
130 typedef unsigned key_type;
131 typedef tree value_type;
132 static const bool maybe_mx = true;
133 static hashval_t hash (key_type v)
135 return hashval_t (v);
137 static bool equal_keys (key_type k1, key_type k2)
139 return k1 == k2;
141 template <typename T> static void remove (T &)
144 // Zero is not a priority
145 static const bool empty_zero_p = true;
146 template <typename T> static bool is_empty (const T &entry)
148 return entry.m_key == 0;
150 template <typename T> static void mark_empty (T &entry)
152 entry.m_key = 0;
154 // Entries are not deleteable
155 template <typename T> static bool is_deleted (const T &)
157 return false;
159 template <typename T> static void mark_deleted (T &)
161 gcc_unreachable ();
165 typedef hash_map<unsigned/*Priority*/, tree/*List*/,
166 priority_map_traits> priority_map_t;
168 /* A pair of such hash tables, indexed by initp -- one for fini and
169 one for init. The fini table is only ever used when !cxa_atexit. */
170 static GTY(()) priority_map_t *static_init_fini_fns[2];
172 /* Nonzero if we're done parsing and into end-of-file activities. */
174 int at_eof;
176 /* True if note_mangling_alias should enqueue mangling aliases for
177 later generation, rather than emitting them right away. */
179 bool defer_mangling_aliases = true;
182 /* Return a member function type (a METHOD_TYPE), given FNTYPE (a
183 FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
184 that apply to the function). */
186 tree
187 build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
188 cp_ref_qualifier rqual)
190 if (fntype == error_mark_node || ctype == error_mark_node)
191 return error_mark_node;
193 gcc_assert (FUNC_OR_METHOD_TYPE_P (fntype));
195 cp_cv_quals type_quals = quals & ~TYPE_QUAL_RESTRICT;
196 ctype = cp_build_qualified_type (ctype, type_quals);
198 tree newtype
199 = build_method_type_directly (ctype, TREE_TYPE (fntype),
200 (TREE_CODE (fntype) == METHOD_TYPE
201 ? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
202 : TYPE_ARG_TYPES (fntype)));
203 if (tree attrs = TYPE_ATTRIBUTES (fntype))
204 newtype = cp_build_type_attribute_variant (newtype, attrs);
205 newtype = build_cp_fntype_variant (newtype, rqual,
206 TYPE_RAISES_EXCEPTIONS (fntype),
207 TYPE_HAS_LATE_RETURN_TYPE (fntype));
209 return newtype;
212 /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
213 return type changed to NEW_RET. */
215 tree
216 change_return_type (tree new_ret, tree fntype)
218 if (new_ret == error_mark_node)
219 return fntype;
221 if (same_type_p (new_ret, TREE_TYPE (fntype)))
222 return fntype;
224 tree newtype;
225 tree args = TYPE_ARG_TYPES (fntype);
227 if (TREE_CODE (fntype) == FUNCTION_TYPE)
229 newtype = build_function_type (new_ret, args);
230 newtype = apply_memfn_quals (newtype,
231 type_memfn_quals (fntype));
233 else
234 newtype = build_method_type_directly
235 (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
237 if (tree attrs = TYPE_ATTRIBUTES (fntype))
238 newtype = cp_build_type_attribute_variant (newtype, attrs);
239 newtype = cxx_copy_lang_qualifiers (newtype, fntype);
241 return newtype;
244 /* Build a PARM_DECL of FN with NAME and TYPE, and set DECL_ARG_TYPE
245 appropriately. */
247 tree
248 cp_build_parm_decl (tree fn, tree name, tree type)
250 tree parm = build_decl (input_location,
251 PARM_DECL, name, type);
252 DECL_CONTEXT (parm) = fn;
254 /* DECL_ARG_TYPE is only used by the back end and the back end never
255 sees templates. */
256 if (!processing_template_decl)
257 DECL_ARG_TYPE (parm) = type_passed_as (type);
259 return parm;
262 /* Returns a PARM_DECL of FN for a parameter of the indicated TYPE, with the
263 indicated NAME. */
265 tree
266 build_artificial_parm (tree fn, tree name, tree type)
268 tree parm = cp_build_parm_decl (fn, name, type);
269 DECL_ARTIFICIAL (parm) = 1;
270 /* All our artificial parms are implicitly `const'; they cannot be
271 assigned to. */
272 TREE_READONLY (parm) = 1;
273 return parm;
276 /* Constructors for types with virtual baseclasses need an "in-charge" flag
277 saying whether this constructor is responsible for initialization of
278 virtual baseclasses or not. All destructors also need this "in-charge"
279 flag, which additionally determines whether or not the destructor should
280 free the memory for the object.
282 This function adds the "in-charge" flag to member function FN if
283 appropriate. It is called from grokclassfn and tsubst.
284 FN must be either a constructor or destructor.
286 The in-charge flag follows the 'this' parameter, and is followed by the
287 VTT parm (if any), then the user-written parms. */
289 void
290 maybe_retrofit_in_chrg (tree fn)
292 tree basetype, arg_types, parms, parm, fntype;
294 /* If we've already add the in-charge parameter don't do it again. */
295 if (DECL_HAS_IN_CHARGE_PARM_P (fn))
296 return;
298 /* When processing templates we can't know, in general, whether or
299 not we're going to have virtual baseclasses. */
300 if (processing_template_decl)
301 return;
303 /* We don't need an in-charge parameter for constructors that don't
304 have virtual bases. */
305 if (DECL_CONSTRUCTOR_P (fn)
306 && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
307 return;
309 arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
310 basetype = TREE_TYPE (TREE_VALUE (arg_types));
311 arg_types = TREE_CHAIN (arg_types);
313 parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
315 /* If this is a subobject constructor or destructor, our caller will
316 pass us a pointer to our VTT. */
317 if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
319 parm = build_artificial_parm (fn, vtt_parm_identifier, vtt_parm_type);
321 /* First add it to DECL_ARGUMENTS between 'this' and the real args... */
322 DECL_CHAIN (parm) = parms;
323 parms = parm;
325 /* ...and then to TYPE_ARG_TYPES. */
326 arg_types = hash_tree_chain (vtt_parm_type, arg_types);
328 DECL_HAS_VTT_PARM_P (fn) = 1;
331 /* Then add the in-charge parm (before the VTT parm). */
332 parm = build_artificial_parm (fn, in_charge_identifier, integer_type_node);
333 DECL_CHAIN (parm) = parms;
334 parms = parm;
335 arg_types = hash_tree_chain (integer_type_node, arg_types);
337 /* Insert our new parameter(s) into the list. */
338 DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
340 /* And rebuild the function type. */
341 fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
342 arg_types);
343 if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
344 fntype = (cp_build_type_attribute_variant
345 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
346 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (fn));
347 TREE_TYPE (fn) = fntype;
349 /* Now we've got the in-charge parameter. */
350 DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
353 /* Classes overload their constituent function names automatically.
354 When a function name is declared in a record structure,
355 its name is changed to it overloaded name. Since names for
356 constructors and destructors can conflict, we place a leading
357 '$' for destructors.
359 CNAME is the name of the class we are grokking for.
361 FUNCTION is a FUNCTION_DECL. It was created by `grokdeclarator'.
363 FLAGS contains bits saying what's special about today's
364 arguments. DTOR_FLAG == DESTRUCTOR.
366 If FUNCTION is a destructor, then we must add the `auto-delete' field
367 as a second parameter. There is some hair associated with the fact
368 that we must "declare" this variable in the manner consistent with the
369 way the rest of the arguments were declared.
371 QUALS are the qualifiers for the this pointer. */
373 void
374 grokclassfn (tree ctype, tree function, enum overload_flags flags)
376 tree fn_name = DECL_NAME (function);
378 /* Even within an `extern "C"' block, members get C++ linkage. See
379 [dcl.link] for details. */
380 SET_DECL_LANGUAGE (function, lang_cplusplus);
382 if (fn_name == NULL_TREE)
384 error ("name missing for member function");
385 fn_name = get_identifier ("<anonymous>");
386 DECL_NAME (function) = fn_name;
389 DECL_CONTEXT (function) = ctype;
391 if (flags == DTOR_FLAG)
392 DECL_CXX_DESTRUCTOR_P (function) = 1;
394 if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
395 maybe_retrofit_in_chrg (function);
398 /* Create an ARRAY_REF, checking for the user doing things backwards
399 along the way.
400 If INDEX_EXP is non-NULL, then that is the index expression,
401 otherwise INDEX_EXP_LIST is the list of index expressions. */
403 tree
404 grok_array_decl (location_t loc, tree array_expr, tree index_exp,
405 vec<tree, va_gc> **index_exp_list, tsubst_flags_t complain)
407 tree type;
408 tree expr;
409 tree orig_array_expr = array_expr;
410 tree orig_index_exp = index_exp;
411 vec<tree, va_gc> *orig_index_exp_list
412 = index_exp_list ? *index_exp_list : NULL;
413 tree overload = NULL_TREE;
415 if (error_operand_p (array_expr) || error_operand_p (index_exp))
416 return error_mark_node;
418 if (processing_template_decl)
420 if (type_dependent_expression_p (array_expr)
421 || (index_exp ? type_dependent_expression_p (index_exp)
422 : any_type_dependent_arguments_p (*index_exp_list)))
424 if (index_exp == NULL)
425 index_exp = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
426 *index_exp_list);
427 return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
428 NULL_TREE, NULL_TREE);
430 array_expr = build_non_dependent_expr (array_expr);
431 if (index_exp)
432 index_exp = build_non_dependent_expr (index_exp);
433 else
435 orig_index_exp_list = make_tree_vector_copy (*index_exp_list);
436 make_args_non_dependent (*index_exp_list);
440 type = TREE_TYPE (array_expr);
441 gcc_assert (type);
442 type = non_reference (type);
444 /* If they have an `operator[]', use that. */
445 if (MAYBE_CLASS_TYPE_P (type)
446 || (index_exp && MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
447 || (index_exp == NULL_TREE
448 && !(*index_exp_list)->is_empty ()
449 && MAYBE_CLASS_TYPE_P (TREE_TYPE ((*index_exp_list)->last ()))))
451 if (index_exp)
452 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
453 index_exp, NULL_TREE, NULL_TREE,
454 &overload, complain);
455 else if ((*index_exp_list)->is_empty ())
456 expr = build_op_subscript (loc, array_expr, index_exp_list, &overload,
457 complain);
458 else
460 expr = build_op_subscript (loc, array_expr, index_exp_list,
461 &overload, complain & tf_decltype);
462 if (expr == error_mark_node)
464 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
465 tf_none);
466 if (idx != error_mark_node)
467 expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
468 idx, NULL_TREE, NULL_TREE, &overload,
469 complain & tf_decltype);
470 if (expr == error_mark_node)
472 overload = NULL_TREE;
473 expr = build_op_subscript (loc, array_expr, index_exp_list,
474 &overload, complain);
476 else
477 /* If it would be valid albeit deprecated expression in C++20,
478 just pedwarn on it and treat it as if wrapped in (). */
479 pedwarn (loc, OPT_Wcomma_subscript,
480 "top-level comma expression in array subscript "
481 "changed meaning in C++23");
485 else
487 tree p1, p2, i1, i2;
488 bool swapped = false;
490 /* Otherwise, create an ARRAY_REF for a pointer or array type.
491 It is a little-known fact that, if `a' is an array and `i' is
492 an int, you can write `i[a]', which means the same thing as
493 `a[i]'. */
494 if (TREE_CODE (type) == ARRAY_TYPE || VECTOR_TYPE_P (type))
495 p1 = array_expr;
496 else
497 p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
499 if (index_exp == NULL_TREE)
501 if ((*index_exp_list)->is_empty ())
503 error_at (loc, "built-in subscript operator without expression "
504 "list");
505 return error_mark_node;
507 tree idx = build_x_compound_expr_from_vec (*index_exp_list, NULL,
508 tf_none);
509 if (idx != error_mark_node)
510 /* If it would be valid albeit deprecated expression in C++20,
511 just pedwarn on it and treat it as if wrapped in (). */
512 pedwarn (loc, OPT_Wcomma_subscript,
513 "top-level comma expression in array subscript "
514 "changed meaning in C++23");
515 else
517 error_at (loc, "built-in subscript operator with more than one "
518 "expression in expression list");
519 return error_mark_node;
521 index_exp = idx;
524 if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
525 p2 = index_exp;
526 else
527 p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
529 i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
530 false);
531 i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
532 false);
534 if ((p1 && i2) && (i1 && p2))
535 error ("ambiguous conversion for array subscript");
537 if (p1 && i2)
538 array_expr = p1, index_exp = i2;
539 else if (i1 && p2)
540 swapped = true, array_expr = p2, index_exp = i1;
541 else
543 error_at (loc, "invalid types %<%T[%T]%> for array subscript",
544 type, TREE_TYPE (index_exp));
545 return error_mark_node;
548 if (array_expr == error_mark_node || index_exp == error_mark_node)
549 error ("ambiguous conversion for array subscript");
551 if (TYPE_PTR_P (TREE_TYPE (array_expr)))
552 array_expr = mark_rvalue_use (array_expr);
553 else
554 array_expr = mark_lvalue_use_nonread (array_expr);
555 index_exp = mark_rvalue_use (index_exp);
556 if (swapped
557 && flag_strong_eval_order == 2
558 && (TREE_SIDE_EFFECTS (array_expr) || TREE_SIDE_EFFECTS (index_exp)))
559 expr = build_array_ref (input_location, index_exp, array_expr);
560 else
561 expr = build_array_ref (input_location, array_expr, index_exp);
563 if (processing_template_decl && expr != error_mark_node)
565 if (overload != NULL_TREE)
567 if (orig_index_exp == NULL_TREE)
569 expr = build_min_non_dep_op_overload (expr, overload,
570 orig_array_expr,
571 orig_index_exp_list);
572 release_tree_vector (orig_index_exp_list);
573 return expr;
575 return build_min_non_dep_op_overload (ARRAY_REF, expr, overload,
576 orig_array_expr,
577 orig_index_exp);
580 if (orig_index_exp == NULL_TREE)
582 orig_index_exp
583 = build_min_nt_call_vec (ovl_op_identifier (ARRAY_REF),
584 orig_index_exp_list);
585 release_tree_vector (orig_index_exp_list);
588 return build_min_non_dep (ARRAY_REF, expr, orig_array_expr,
589 orig_index_exp, NULL_TREE, NULL_TREE);
591 return expr;
594 /* Given the cast expression EXP, checking out its validity. Either return
595 an error_mark_node if there was an unavoidable error, return a cast to
596 void for trying to delete a pointer w/ the value 0, or return the
597 call to delete. If DOING_VEC is true, we handle things differently
598 for doing an array delete.
599 Implements ARM $5.3.4. This is called from the parser. */
601 tree
602 delete_sanity (location_t loc, tree exp, tree size, bool doing_vec,
603 int use_global_delete, tsubst_flags_t complain)
605 tree t, type;
607 if (exp == error_mark_node)
608 return exp;
610 if (processing_template_decl)
612 t = build_min (DELETE_EXPR, void_type_node, exp, size);
613 DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
614 DELETE_EXPR_USE_VEC (t) = doing_vec;
615 TREE_SIDE_EFFECTS (t) = 1;
616 SET_EXPR_LOCATION (t, loc);
617 return t;
620 location_t exp_loc = cp_expr_loc_or_loc (exp, loc);
622 /* An array can't have been allocated by new, so complain. */
623 if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
624 && (complain & tf_warning))
625 warning_at (exp_loc, 0, "deleting array %q#E", exp);
627 t = build_expr_type_conversion (WANT_POINTER, exp, true);
629 if (t == NULL_TREE || t == error_mark_node)
631 if (complain & tf_error)
632 error_at (exp_loc,
633 "type %q#T argument given to %<delete%>, expected pointer",
634 TREE_TYPE (exp));
635 return error_mark_node;
638 type = TREE_TYPE (t);
640 /* As of Valley Forge, you can delete a pointer to const. */
642 /* You can't delete functions. */
643 if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
645 if (complain & tf_error)
646 error_at (exp_loc,
647 "cannot delete a function. Only pointer-to-objects are "
648 "valid arguments to %<delete%>");
649 return error_mark_node;
652 /* Deleting ptr to void is undefined behavior [expr.delete/3]. */
653 if (VOID_TYPE_P (TREE_TYPE (type)))
655 if (complain & tf_warning)
656 warning_at (exp_loc, OPT_Wdelete_incomplete,
657 "deleting %qT is undefined", type);
658 doing_vec = 0;
661 /* Deleting a pointer with the value zero is valid and has no effect. */
662 if (integer_zerop (t))
663 return build1_loc (loc, NOP_EXPR, void_type_node, t);
665 if (doing_vec)
666 return build_vec_delete (loc, t, /*maxindex=*/NULL_TREE,
667 sfk_deleting_destructor,
668 use_global_delete, complain);
669 else
670 return build_delete (loc, type, t, sfk_deleting_destructor,
671 LOOKUP_NORMAL, use_global_delete,
672 complain);
675 /* Report an error if the indicated template declaration is not the
676 sort of thing that should be a member template. */
678 void
679 check_member_template (tree tmpl)
681 tree decl;
683 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
684 decl = DECL_TEMPLATE_RESULT (tmpl);
686 if (TREE_CODE (decl) == FUNCTION_DECL
687 || DECL_ALIAS_TEMPLATE_P (tmpl)
688 || (TREE_CODE (decl) == TYPE_DECL
689 && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
691 /* The parser rejects template declarations in local classes
692 (with the exception of generic lambdas). */
693 gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl));
694 /* The parser rejects any use of virtual in a function template. */
695 gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
696 && DECL_VIRTUAL_P (decl)));
698 /* The debug-information generating code doesn't know what to do
699 with member templates. */
700 DECL_IGNORED_P (tmpl) = 1;
702 else if (variable_template_p (tmpl))
703 /* OK */;
704 else
705 error ("template declaration of %q#D", decl);
708 /* Sanity check: report error if this function FUNCTION is not
709 really a member of the class (CTYPE) it is supposed to belong to.
710 TEMPLATE_PARMS is used to specify the template parameters of a member
711 template passed as FUNCTION_DECL. If the member template is passed as a
712 TEMPLATE_DECL, it can be NULL since the parameters can be extracted
713 from the declaration. If the function is not a function template, it
714 must be NULL.
715 It returns the original declaration for the function, NULL_TREE if
716 no declaration was found, error_mark_node if an error was emitted. */
718 tree
719 check_classfn (tree ctype, tree function, tree template_parms)
721 if (DECL_USE_TEMPLATE (function)
722 && !(TREE_CODE (function) == TEMPLATE_DECL
723 && DECL_TEMPLATE_SPECIALIZATION (function))
724 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
725 /* Since this is a specialization of a member template,
726 we're not going to find the declaration in the class.
727 For example, in:
729 struct S { template <typename T> void f(T); };
730 template <> void S::f(int);
732 we're not going to find `S::f(int)', but there's no
733 reason we should, either. We let our callers know we didn't
734 find the method, but we don't complain. */
735 return NULL_TREE;
737 /* Basic sanity check: for a template function, the template parameters
738 either were not passed, or they are the same of DECL_TEMPLATE_PARMS. */
739 if (TREE_CODE (function) == TEMPLATE_DECL)
741 if (template_parms
742 && !comp_template_parms (template_parms,
743 DECL_TEMPLATE_PARMS (function)))
745 error ("template parameter lists provided don%'t match the "
746 "template parameters of %qD", function);
747 return error_mark_node;
749 template_parms = DECL_TEMPLATE_PARMS (function);
752 /* OK, is this a definition of a member template? */
753 bool is_template = (template_parms != NULL_TREE);
755 /* [temp.mem]
757 A destructor shall not be a member template. */
758 if (DECL_DESTRUCTOR_P (function) && is_template)
760 error ("destructor %qD declared as member template", function);
761 return error_mark_node;
764 /* We must enter the scope here, because conversion operators are
765 named by target type, and type equivalence relies on typenames
766 resolving within the scope of CTYPE. */
767 tree pushed_scope = push_scope (ctype);
768 tree matched = NULL_TREE;
769 tree fns = get_class_binding (ctype, DECL_NAME (function));
770 bool saw_template = false;
772 for (ovl_iterator iter (fns); !matched && iter; ++iter)
774 tree fndecl = *iter;
776 if (TREE_CODE (fndecl) == TEMPLATE_DECL)
777 saw_template = true;
779 /* A member template definition only matches a member template
780 declaration. */
781 if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
782 continue;
784 if (!DECL_DECLARES_FUNCTION_P (fndecl))
785 continue;
787 tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
788 tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
790 /* We cannot simply call decls_match because this doesn't work
791 for static member functions that are pretending to be
792 methods, and because the name may have been changed by
793 asm("new_name"). */
795 /* Get rid of the this parameter on functions that become
796 static. */
797 if (DECL_STATIC_FUNCTION_P (fndecl)
798 && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
799 p1 = TREE_CHAIN (p1);
801 /* ref-qualifier or absence of same must match. */
802 if (type_memfn_rqual (TREE_TYPE (function))
803 != type_memfn_rqual (TREE_TYPE (fndecl)))
804 continue;
806 // Include constraints in the match.
807 tree c1 = get_constraints (function);
808 tree c2 = get_constraints (fndecl);
810 /* While finding a match, same types and params are not enough
811 if the function is versioned. Also check version ("target")
812 attributes. */
813 if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
814 TREE_TYPE (TREE_TYPE (fndecl)))
815 && compparms (p1, p2)
816 && !targetm.target_option.function_versions (function, fndecl)
817 && (!is_template
818 || comp_template_parms (template_parms,
819 DECL_TEMPLATE_PARMS (fndecl)))
820 && equivalent_constraints (c1, c2)
821 && (DECL_TEMPLATE_SPECIALIZATION (function)
822 == DECL_TEMPLATE_SPECIALIZATION (fndecl))
823 && (!DECL_TEMPLATE_SPECIALIZATION (function)
824 || (DECL_TI_TEMPLATE (function) == DECL_TI_TEMPLATE (fndecl))))
825 matched = fndecl;
828 if (!matched && !is_template && saw_template
829 && !processing_template_decl && DECL_UNIQUE_FRIEND_P (function))
831 /* "[if no non-template match is found,] each remaining function template
832 is replaced with the specialization chosen by deduction from the
833 friend declaration or discarded if deduction fails."
835 So tell check_explicit_specialization to look for a match. */
836 SET_DECL_IMPLICIT_INSTANTIATION (function);
837 matched = function;
840 if (!matched)
842 if (!COMPLETE_TYPE_P (ctype))
843 cxx_incomplete_type_error (DECL_SOURCE_LOCATION (function),
844 function, ctype);
845 else
847 if (DECL_CONV_FN_P (function))
848 fns = get_class_binding (ctype, conv_op_identifier);
850 error_at (DECL_SOURCE_LOCATION (function),
851 "no declaration matches %q#D", function);
852 if (fns)
853 print_candidates (fns);
854 else if (DECL_CONV_FN_P (function))
855 inform (DECL_SOURCE_LOCATION (function),
856 "no conversion operators declared");
857 else
858 inform (DECL_SOURCE_LOCATION (function),
859 "no functions named %qD", function);
860 inform (DECL_SOURCE_LOCATION (TYPE_NAME (ctype)),
861 "%#qT defined here", ctype);
863 matched = error_mark_node;
866 if (pushed_scope)
867 pop_scope (pushed_scope);
869 return matched;
872 /* DECL is a function with vague linkage. Remember it so that at the
873 end of the translation unit we can decide whether or not to emit
874 it. */
876 void
877 note_vague_linkage_fn (tree decl)
879 if (processing_template_decl)
880 return;
882 DECL_DEFER_OUTPUT (decl) = 1;
883 vec_safe_push (deferred_fns, decl);
886 /* As above, but for variable template instantiations. */
888 void
889 note_variable_template_instantiation (tree decl)
891 vec_safe_push (pending_statics, decl);
894 /* We have just processed the DECL, which is a static data member.
895 The other parameters are as for cp_finish_decl. */
897 void
898 finish_static_data_member_decl (tree decl,
899 tree init, bool init_const_expr_p,
900 tree asmspec_tree,
901 int flags)
903 if (DECL_TEMPLATE_INSTANTIATED (decl))
904 /* We already needed to instantiate this, so the processing in this
905 function is unnecessary/wrong. */
906 return;
908 DECL_CONTEXT (decl) = current_class_type;
910 /* We cannot call pushdecl here, because that would fill in the
911 TREE_CHAIN of our decl. Instead, we modify cp_finish_decl to do
912 the right thing, namely, to put this decl out straight away. */
914 if (! processing_template_decl)
915 vec_safe_push (pending_statics, decl);
917 if (LOCAL_CLASS_P (current_class_type)
918 /* We already complained about the template definition. */
919 && !DECL_TEMPLATE_INSTANTIATION (decl))
920 permerror (DECL_SOURCE_LOCATION (decl),
921 "local class %q#T shall not have static data member %q#D",
922 current_class_type, decl);
923 else
924 for (tree t = current_class_type; TYPE_P (t);
925 t = CP_TYPE_CONTEXT (t))
926 if (TYPE_UNNAMED_P (t))
928 auto_diagnostic_group d;
929 if (permerror (DECL_SOURCE_LOCATION (decl),
930 "static data member %qD in unnamed class", decl))
931 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)),
932 "unnamed class defined here");
933 break;
936 if (DECL_INLINE_VAR_P (decl) && !DECL_TEMPLATE_INSTANTIATION (decl))
937 /* An inline variable is immediately defined, so don't set DECL_IN_AGGR_P.
938 Except that if decl is a template instantiation, it isn't defined until
939 instantiate_decl. */;
940 else
941 DECL_IN_AGGR_P (decl) = 1;
943 if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
944 && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
945 SET_VAR_HAD_UNKNOWN_BOUND (decl);
947 if (init)
949 /* Similarly to start_decl_1, we want to complete the type in order
950 to do the right thing in cp_apply_type_quals_to_decl, possibly
951 clear TYPE_QUAL_CONST (c++/65579). */
952 tree type = TREE_TYPE (decl) = complete_type (TREE_TYPE (decl));
953 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
956 cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
959 /* DECLARATOR and DECLSPECS correspond to a class member. The other
960 parameters are as for cp_finish_decl. Return the DECL for the
961 class member declared. */
963 tree
964 grokfield (const cp_declarator *declarator,
965 cp_decl_specifier_seq *declspecs,
966 tree init, bool init_const_expr_p,
967 tree asmspec_tree,
968 tree attrlist)
970 tree value;
971 const char *asmspec = 0;
972 int flags;
974 if (init
975 && TREE_CODE (init) == TREE_LIST
976 && TREE_VALUE (init) == error_mark_node
977 && TREE_CHAIN (init) == NULL_TREE)
978 init = NULL_TREE;
980 int initialized;
981 if (init == ridpointers[(int)RID_DELETE])
982 initialized = SD_DELETED;
983 else if (init == ridpointers[(int)RID_DEFAULT])
984 initialized = SD_DEFAULTED;
985 else if (init)
986 initialized = SD_INITIALIZED;
987 else
988 initialized = SD_UNINITIALIZED;
990 value = grokdeclarator (declarator, declspecs, FIELD, initialized, &attrlist);
991 if (! value || value == error_mark_node)
992 /* friend or constructor went bad. */
993 return error_mark_node;
994 if (TREE_TYPE (value) == error_mark_node)
995 return value;
997 if (TREE_CODE (value) == TYPE_DECL && init)
999 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value)),
1000 "typedef %qD is initialized (use %qs instead)",
1001 value, "decltype");
1002 init = NULL_TREE;
1005 /* Pass friendly classes back. */
1006 if (value == void_type_node)
1007 return value;
1009 if (DECL_NAME (value)
1010 && TREE_CODE (DECL_NAME (value)) == TEMPLATE_ID_EXPR)
1012 error_at (declarator->id_loc,
1013 "explicit template argument list not allowed");
1014 return error_mark_node;
1017 /* Stash away type declarations. */
1018 if (TREE_CODE (value) == TYPE_DECL)
1020 DECL_NONLOCAL (value) = 1;
1021 DECL_CONTEXT (value) = current_class_type;
1023 if (attrlist)
1025 int attrflags = 0;
1027 /* If this is a typedef that names the class for linkage purposes
1028 (7.1.3p8), apply any attributes directly to the type. */
1029 if (OVERLOAD_TYPE_P (TREE_TYPE (value))
1030 && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
1031 attrflags = ATTR_FLAG_TYPE_IN_PLACE;
1033 cplus_decl_attributes (&value, attrlist, attrflags);
1036 if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
1037 && TREE_TYPE (value) != error_mark_node
1038 && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
1039 set_underlying_type (value);
1041 /* It's important that push_template_decl below follows
1042 set_underlying_type above so that the created template
1043 carries the properly set type of VALUE. */
1044 if (processing_template_decl)
1045 value = push_template_decl (value);
1047 record_locally_defined_typedef (value);
1048 return value;
1051 int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
1053 if (!friendp && DECL_IN_AGGR_P (value))
1055 error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
1056 return void_type_node;
1059 if (asmspec_tree && asmspec_tree != error_mark_node)
1060 asmspec = TREE_STRING_POINTER (asmspec_tree);
1062 if (init)
1064 if (TREE_CODE (value) == FUNCTION_DECL)
1066 if (init == ridpointers[(int)RID_DELETE])
1068 DECL_DELETED_FN (value) = 1;
1069 DECL_DECLARED_INLINE_P (value) = 1;
1071 else if (init == ridpointers[(int)RID_DEFAULT])
1073 if (defaultable_fn_check (value))
1075 DECL_DEFAULTED_FN (value) = 1;
1076 DECL_INITIALIZED_IN_CLASS_P (value) = 1;
1077 DECL_DECLARED_INLINE_P (value) = 1;
1078 /* grokfndecl set this to error_mark_node, but we want to
1079 leave it unset until synthesize_method. */
1080 DECL_INITIAL (value) = NULL_TREE;
1083 else if (TREE_CODE (init) == DEFERRED_PARSE)
1084 error ("invalid initializer for member function %qD", value);
1085 else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
1087 if (integer_zerop (init))
1088 DECL_PURE_VIRTUAL_P (value) = 1;
1089 else if (error_operand_p (init))
1090 ; /* An error has already been reported. */
1091 else
1092 error ("invalid initializer for member function %qD",
1093 value);
1095 else
1097 gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
1098 location_t iloc
1099 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (value));
1100 if (friendp)
1101 error_at (iloc, "initializer specified for friend "
1102 "function %qD", value);
1103 else
1104 error_at (iloc, "initializer specified for static "
1105 "member function %qD", value);
1108 else if (TREE_CODE (value) == FIELD_DECL)
1109 /* C++11 NSDMI, keep going. */;
1110 else if (!VAR_P (value))
1111 gcc_unreachable ();
1114 /* Pass friend decls back. */
1115 if ((TREE_CODE (value) == FUNCTION_DECL
1116 || TREE_CODE (value) == TEMPLATE_DECL)
1117 && DECL_CONTEXT (value) != current_class_type)
1119 if (attrlist)
1120 cplus_decl_attributes (&value, attrlist, 0);
1121 return value;
1124 /* Need to set this before push_template_decl. */
1125 if (VAR_P (value))
1126 DECL_CONTEXT (value) = current_class_type;
1128 if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value))
1130 value = push_template_decl (value);
1131 if (error_operand_p (value))
1132 return error_mark_node;
1135 if (attrlist)
1136 cplus_decl_attributes (&value, attrlist, 0);
1138 if (init && DIRECT_LIST_INIT_P (init))
1139 flags = LOOKUP_NORMAL;
1140 else
1141 flags = LOOKUP_IMPLICIT;
1143 switch (TREE_CODE (value))
1145 case VAR_DECL:
1146 finish_static_data_member_decl (value, init, init_const_expr_p,
1147 asmspec_tree, flags);
1148 return value;
1150 case FIELD_DECL:
1151 if (asmspec)
1152 error ("%<asm%> specifiers are not permitted on non-static data members");
1153 if (DECL_INITIAL (value) == error_mark_node)
1154 init = error_mark_node;
1155 cp_finish_decl (value, init, /*init_const_expr_p=*/false,
1156 NULL_TREE, flags);
1157 DECL_IN_AGGR_P (value) = 1;
1158 return value;
1160 case FUNCTION_DECL:
1161 if (asmspec)
1162 set_user_assembler_name (value, asmspec);
1164 cp_finish_decl (value,
1165 /*init=*/NULL_TREE,
1166 /*init_const_expr_p=*/false,
1167 asmspec_tree, flags);
1169 /* Pass friends back this way. */
1170 if (DECL_UNIQUE_FRIEND_P (value))
1171 return void_type_node;
1173 DECL_IN_AGGR_P (value) = 1;
1174 return value;
1176 default:
1177 gcc_unreachable ();
1179 return NULL_TREE;
1182 /* Like `grokfield', but for bitfields.
1183 WIDTH is the width of the bitfield, a constant expression.
1184 The other parameters are as for grokfield. */
1186 tree
1187 grokbitfield (const cp_declarator *declarator,
1188 cp_decl_specifier_seq *declspecs, tree width, tree init,
1189 tree attrlist)
1191 tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1192 init != NULL_TREE, &attrlist);
1194 if (value == error_mark_node)
1195 return NULL_TREE; /* friends went bad. */
1197 tree type = TREE_TYPE (value);
1198 if (type == error_mark_node)
1199 return value;
1201 /* Pass friendly classes back. */
1202 if (VOID_TYPE_P (value))
1203 return void_type_node;
1205 if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type)
1206 && (INDIRECT_TYPE_P (type) || !dependent_type_p (type)))
1208 error_at (DECL_SOURCE_LOCATION (value),
1209 "bit-field %qD with non-integral type %qT",
1210 value, type);
1211 return error_mark_node;
1214 if (TREE_CODE (value) == TYPE_DECL)
1216 error_at (DECL_SOURCE_LOCATION (value),
1217 "cannot declare %qD to be a bit-field type", value);
1218 return NULL_TREE;
1221 /* Usually, finish_struct_1 catches bitfields with invalid types.
1222 But, in the case of bitfields with function type, we confuse
1223 ourselves into thinking they are member functions, so we must
1224 check here. */
1225 if (TREE_CODE (value) == FUNCTION_DECL)
1227 error_at (DECL_SOURCE_LOCATION (value),
1228 "cannot declare bit-field %qD with function type", value);
1229 return NULL_TREE;
1232 if (TYPE_WARN_IF_NOT_ALIGN (type))
1234 error_at (DECL_SOURCE_LOCATION (value), "cannot declare bit-field "
1235 "%qD with %<warn_if_not_aligned%> type", value);
1236 return NULL_TREE;
1239 if (DECL_IN_AGGR_P (value))
1241 error ("%qD is already defined in the class %qT", value,
1242 DECL_CONTEXT (value));
1243 return void_type_node;
1246 if (TREE_STATIC (value))
1248 error_at (DECL_SOURCE_LOCATION (value),
1249 "static member %qD cannot be a bit-field", value);
1250 return NULL_TREE;
1253 int flags = LOOKUP_IMPLICIT;
1254 if (init && DIRECT_LIST_INIT_P (init))
1255 flags = LOOKUP_NORMAL;
1256 cp_finish_decl (value, init, false, NULL_TREE, flags);
1258 if (width != error_mark_node)
1260 /* The width must be an integer type. */
1261 if (!type_dependent_expression_p (width)
1262 && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
1263 error ("width of bit-field %qD has non-integral type %qT", value,
1264 TREE_TYPE (width));
1265 else if (!check_for_bare_parameter_packs (width))
1267 /* Temporarily stash the width in DECL_BIT_FIELD_REPRESENTATIVE.
1268 check_bitfield_decl picks it from there later and sets DECL_SIZE
1269 accordingly. */
1270 DECL_BIT_FIELD_REPRESENTATIVE (value) = width;
1271 SET_DECL_C_BIT_FIELD (value);
1275 DECL_IN_AGGR_P (value) = 1;
1277 if (attrlist)
1278 cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1280 return value;
1284 /* Returns true iff ATTR is an attribute which needs to be applied at
1285 instantiation time rather than template definition time. */
1287 static bool
1288 is_late_template_attribute (tree attr, tree decl)
1290 tree name = get_attribute_name (attr);
1291 tree args = TREE_VALUE (attr);
1292 const struct attribute_spec *spec = lookup_attribute_spec (name);
1293 tree arg;
1295 if (!spec)
1296 /* Unknown attribute. */
1297 return false;
1299 /* Attribute weak handling wants to write out assembly right away. */
1300 if (is_attribute_p ("weak", name))
1301 return true;
1303 /* Attributes used and unused are applied directly to typedefs for the
1304 benefit of maybe_warn_unused_local_typedefs. */
1305 if (TREE_CODE (decl) == TYPE_DECL
1306 && (is_attribute_p ("unused", name)
1307 || is_attribute_p ("used", name)))
1308 return false;
1310 /* Attribute tls_model wants to modify the symtab. */
1311 if (is_attribute_p ("tls_model", name))
1312 return true;
1314 /* #pragma omp declare simd attribute needs to be always deferred. */
1315 if (flag_openmp
1316 && is_attribute_p ("omp declare simd", name))
1317 return true;
1319 if (args == error_mark_node)
1320 return false;
1322 /* An attribute pack is clearly dependent. */
1323 if (args && PACK_EXPANSION_P (args))
1324 return true;
1326 /* If any of the arguments are dependent expressions, we can't evaluate
1327 the attribute until instantiation time. */
1328 for (arg = args; arg; arg = TREE_CHAIN (arg))
1330 tree t = TREE_VALUE (arg);
1332 /* If the first attribute argument is an identifier, only consider
1333 second and following arguments. Attributes like mode, format,
1334 cleanup and several target specific attributes aren't late
1335 just because they have an IDENTIFIER_NODE as first argument. */
1336 if (arg == args && attribute_takes_identifier_p (name)
1337 && identifier_p (t))
1338 continue;
1340 if (value_dependent_expression_p (t))
1341 return true;
1344 if (TREE_CODE (decl) == TYPE_DECL
1345 || TYPE_P (decl)
1346 || spec->type_required)
1348 tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1350 if (!type)
1351 return true;
1353 /* We can't apply any attributes to a completely unknown type until
1354 instantiation time. */
1355 enum tree_code code = TREE_CODE (type);
1356 if (code == TEMPLATE_TYPE_PARM
1357 || code == BOUND_TEMPLATE_TEMPLATE_PARM
1358 || code == TYPENAME_TYPE)
1359 return true;
1360 /* Also defer most attributes on dependent types. This is not
1361 necessary in all cases, but is the better default. */
1362 else if (dependent_type_p (type)
1363 /* But some attributes specifically apply to templates. */
1364 && !is_attribute_p ("abi_tag", name)
1365 && !is_attribute_p ("deprecated", name)
1366 && !is_attribute_p ("unavailable", name)
1367 && !is_attribute_p ("visibility", name))
1368 return true;
1369 else
1370 return false;
1372 else
1373 return false;
1376 /* ATTR_P is a list of attributes. Remove any attributes which need to be
1377 applied at instantiation time and return them. If IS_DEPENDENT is true,
1378 the declaration itself is dependent, so all attributes should be applied
1379 at instantiation time. */
1381 tree
1382 splice_template_attributes (tree *attr_p, tree decl)
1384 tree *p = attr_p;
1385 tree late_attrs = NULL_TREE;
1386 tree *q = &late_attrs;
1388 if (!p || *p == error_mark_node)
1389 return NULL_TREE;
1391 for (; *p; )
1393 if (is_late_template_attribute (*p, decl))
1395 ATTR_IS_DEPENDENT (*p) = 1;
1396 *q = *p;
1397 *p = TREE_CHAIN (*p);
1398 q = &TREE_CHAIN (*q);
1399 *q = NULL_TREE;
1401 else
1402 p = &TREE_CHAIN (*p);
1405 return late_attrs;
1408 /* Attach any LATE_ATTRS to DECL_P, after the non-dependent attributes have
1409 been applied by a previous call to decl_attributes. */
1411 static void
1412 save_template_attributes (tree late_attrs, tree *decl_p, int flags)
1414 tree *q;
1416 if (!late_attrs)
1417 return;
1419 if (DECL_P (*decl_p))
1420 q = &DECL_ATTRIBUTES (*decl_p);
1421 else
1422 q = &TYPE_ATTRIBUTES (*decl_p);
1424 tree old_attrs = *q;
1426 /* Place the late attributes at the beginning of the attribute
1427 list. */
1428 late_attrs = chainon (late_attrs, *q);
1429 if (*q != late_attrs
1430 && !DECL_P (*decl_p)
1431 && !(flags & ATTR_FLAG_TYPE_IN_PLACE))
1433 if (!dependent_type_p (*decl_p))
1434 *decl_p = cp_build_type_attribute_variant (*decl_p, late_attrs);
1435 else
1437 *decl_p = build_variant_type_copy (*decl_p);
1438 TYPE_ATTRIBUTES (*decl_p) = late_attrs;
1441 else
1442 *q = late_attrs;
1444 if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1446 /* We've added new attributes directly to the main variant, so
1447 now we need to update all of the other variants to include
1448 these new attributes. */
1449 tree variant;
1450 for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1451 variant = TYPE_NEXT_VARIANT (variant))
1453 gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1454 TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1459 /* True if ATTRS contains any dependent attributes that affect type
1460 identity. */
1462 bool
1463 any_dependent_type_attributes_p (tree attrs)
1465 for (tree a = attrs; a; a = TREE_CHAIN (a))
1466 if (ATTR_IS_DEPENDENT (a))
1468 const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (a));
1469 if (as && as->affects_type_identity)
1470 return true;
1472 return false;
1475 /* Return true iff ATTRS are acceptable attributes to be applied in-place
1476 to a typedef which gives a previously unnamed class or enum a name for
1477 linkage purposes. */
1479 bool
1480 attributes_naming_typedef_ok (tree attrs)
1482 for (; attrs; attrs = TREE_CHAIN (attrs))
1484 tree name = get_attribute_name (attrs);
1485 if (is_attribute_p ("vector_size", name))
1486 return false;
1488 return true;
1491 /* Like reconstruct_complex_type, but handle also template trees. */
1493 tree
1494 cp_reconstruct_complex_type (tree type, tree bottom)
1496 tree inner, outer;
1498 if (TYPE_PTR_P (type))
1500 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1501 outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1502 TYPE_REF_CAN_ALIAS_ALL (type));
1504 else if (TYPE_REF_P (type))
1506 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1507 outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1508 TYPE_REF_CAN_ALIAS_ALL (type));
1510 else if (TREE_CODE (type) == ARRAY_TYPE)
1512 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1513 outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1514 /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1515 element type qualification will be handled by the recursive
1516 cp_reconstruct_complex_type call and cp_build_qualified_type
1517 for ARRAY_TYPEs changes the element type. */
1518 return outer;
1520 else if (TREE_CODE (type) == FUNCTION_TYPE)
1522 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1523 outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1524 outer = apply_memfn_quals (outer, type_memfn_quals (type));
1526 else if (TREE_CODE (type) == METHOD_TYPE)
1528 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1529 /* The build_method_type_directly() routine prepends 'this' to argument list,
1530 so we must compensate by getting rid of it. */
1531 outer
1532 = build_method_type_directly
1533 (class_of_this_parm (type), inner,
1534 TREE_CHAIN (TYPE_ARG_TYPES (type)));
1536 else if (TREE_CODE (type) == OFFSET_TYPE)
1538 inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1539 outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1541 else
1542 return bottom;
1544 if (TYPE_ATTRIBUTES (type))
1545 outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1546 outer = cp_build_qualified_type (outer, cp_type_quals (type));
1547 outer = cxx_copy_lang_qualifiers (outer, type);
1549 return outer;
1552 /* Replaces any constexpr expression that may be into the attributes
1553 arguments with their reduced value. */
1555 void
1556 cp_check_const_attributes (tree attributes)
1558 if (attributes == error_mark_node)
1559 return;
1561 tree attr;
1562 for (attr = attributes; attr; attr = TREE_CHAIN (attr))
1564 if (cxx_contract_attribute_p (attr))
1565 continue;
1567 tree arg;
1568 /* As we implement alignas using gnu::aligned attribute and
1569 alignas argument is a constant expression, force manifestly
1570 constant evaluation of aligned attribute argument. */
1571 bool manifestly_const_eval
1572 = is_attribute_p ("aligned", get_attribute_name (attr));
1573 for (arg = TREE_VALUE (attr); arg && TREE_CODE (arg) == TREE_LIST;
1574 arg = TREE_CHAIN (arg))
1576 tree expr = TREE_VALUE (arg);
1577 if (EXPR_P (expr))
1578 TREE_VALUE (arg)
1579 = fold_non_dependent_expr (expr, tf_warning_or_error,
1580 manifestly_const_eval);
1585 /* Return the last pushed declaration for the symbol DECL or NULL
1586 when no such declaration exists. */
1588 static tree
1589 find_last_decl (tree decl)
1591 tree last_decl = NULL_TREE;
1593 if (tree name = DECL_P (decl) ? DECL_NAME (decl) : NULL_TREE)
1595 /* Look up the declaration in its scope. */
1596 tree pushed_scope = NULL_TREE;
1597 if (tree ctype = DECL_CONTEXT (decl))
1598 pushed_scope = push_scope (ctype);
1600 last_decl = lookup_name (name);
1602 if (pushed_scope)
1603 pop_scope (pushed_scope);
1605 /* The declaration may be a member conversion operator
1606 or a bunch of overfloads (handle the latter below). */
1607 if (last_decl && BASELINK_P (last_decl))
1608 last_decl = BASELINK_FUNCTIONS (last_decl);
1611 if (!last_decl)
1612 return NULL_TREE;
1614 if (DECL_P (last_decl) || TREE_CODE (last_decl) == OVERLOAD)
1616 /* A set of overloads of the same function. */
1617 for (lkp_iterator iter (last_decl); iter; ++iter)
1619 if (TREE_CODE (*iter) == OVERLOAD)
1620 continue;
1622 tree d = *iter;
1624 /* We can't compare versions in the middle of processing the
1625 attribute that has the version. */
1626 if (TREE_CODE (d) == FUNCTION_DECL
1627 && DECL_FUNCTION_VERSIONED (d))
1628 return NULL_TREE;
1630 if (decls_match (decl, d, /*record_decls=*/false))
1631 return d;
1633 return NULL_TREE;
1636 return NULL_TREE;
1639 /* Like decl_attributes, but handle C++ complexity. */
1641 void
1642 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1644 if (*decl == NULL_TREE || *decl == void_type_node
1645 || *decl == error_mark_node || attributes == error_mark_node)
1646 return;
1648 /* Add implicit "omp declare target" attribute if requested. */
1649 if (vec_safe_length (scope_chain->omp_declare_target_attribute)
1650 && ((VAR_P (*decl)
1651 && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
1652 || TREE_CODE (*decl) == FUNCTION_DECL))
1654 if (VAR_P (*decl)
1655 && DECL_CLASS_SCOPE_P (*decl))
1656 error ("%q+D static data member inside of declare target directive",
1657 *decl);
1658 else
1660 if (VAR_P (*decl)
1661 && (processing_template_decl
1662 || !omp_mappable_type (TREE_TYPE (*decl))))
1663 attributes
1664 = tree_cons (get_identifier ("omp declare target implicit"),
1665 NULL_TREE, attributes);
1666 else
1668 attributes = tree_cons (get_identifier ("omp declare target"),
1669 NULL_TREE, attributes);
1670 attributes
1671 = tree_cons (get_identifier ("omp declare target block"),
1672 NULL_TREE, attributes);
1674 if (TREE_CODE (*decl) == FUNCTION_DECL)
1676 cp_omp_declare_target_attr &last
1677 = scope_chain->omp_declare_target_attribute->last ();
1678 int device_type = MAX (last.device_type, 0);
1679 if ((device_type & OMP_CLAUSE_DEVICE_TYPE_HOST) != 0
1680 && !lookup_attribute ("omp declare target host",
1681 attributes))
1682 attributes
1683 = tree_cons (get_identifier ("omp declare target host"),
1684 NULL_TREE, attributes);
1685 if ((device_type & OMP_CLAUSE_DEVICE_TYPE_NOHOST) != 0
1686 && !lookup_attribute ("omp declare target nohost",
1687 attributes))
1688 attributes
1689 = tree_cons (get_identifier ("omp declare target nohost"),
1690 NULL_TREE, attributes);
1695 tree late_attrs = NULL_TREE;
1696 if (processing_template_decl)
1698 if (check_for_bare_parameter_packs (attributes))
1699 return;
1700 late_attrs = splice_template_attributes (&attributes, *decl);
1703 cp_check_const_attributes (attributes);
1705 if (flag_openmp || flag_openmp_simd)
1707 bool diagnosed = false;
1708 for (tree *pa = &attributes; *pa; )
1710 if (get_attribute_namespace (*pa) == omp_identifier)
1712 tree name = get_attribute_name (*pa);
1713 if (is_attribute_p ("directive", name)
1714 || is_attribute_p ("sequence", name))
1716 if (!diagnosed)
1718 error ("%<omp::%E%> not allowed to be specified in this "
1719 "context", name);
1720 diagnosed = true;
1722 *pa = TREE_CHAIN (*pa);
1723 continue;
1726 pa = &TREE_CHAIN (*pa);
1730 if (TREE_CODE (*decl) == TEMPLATE_DECL)
1731 decl = &DECL_TEMPLATE_RESULT (*decl);
1733 if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
1735 attributes
1736 = decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
1737 decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
1738 attributes, flags);
1740 else
1742 tree last_decl = find_last_decl (*decl);
1743 decl_attributes (decl, attributes, flags, last_decl);
1746 if (late_attrs)
1747 save_template_attributes (late_attrs, decl, flags);
1749 /* Propagate deprecation out to the template. */
1750 if (TREE_DEPRECATED (*decl))
1751 if (tree ti = get_template_info (*decl))
1753 tree tmpl = TI_TEMPLATE (ti);
1754 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1755 : DECL_TEMPLATE_RESULT (tmpl));
1756 if (*decl == pattern)
1757 TREE_DEPRECATED (tmpl) = true;
1760 /* Likewise, propagate unavailability out to the template. */
1761 if (TREE_UNAVAILABLE (*decl))
1762 if (tree ti = get_template_info (*decl))
1764 tree tmpl = TI_TEMPLATE (ti);
1765 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1766 : DECL_TEMPLATE_RESULT (tmpl));
1767 if (*decl == pattern)
1768 TREE_UNAVAILABLE (tmpl) = true;
1772 /* Walks through the namespace- or function-scope anonymous union
1773 OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1774 Returns one of the fields for use in the mangled name. */
1776 static tree
1777 build_anon_union_vars (tree type, tree object)
1779 tree main_decl = NULL_TREE;
1780 tree field;
1782 /* Rather than write the code to handle the non-union case,
1783 just give an error. */
1784 if (TREE_CODE (type) != UNION_TYPE)
1786 error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
1787 "anonymous struct not inside named type");
1788 return error_mark_node;
1791 for (field = TYPE_FIELDS (type);
1792 field != NULL_TREE;
1793 field = DECL_CHAIN (field))
1795 tree decl;
1796 tree ref;
1798 if (DECL_ARTIFICIAL (field))
1799 continue;
1800 if (TREE_CODE (field) != FIELD_DECL)
1802 permerror (DECL_SOURCE_LOCATION (field),
1803 "%q#D invalid; an anonymous union can only "
1804 "have non-static data members", field);
1805 continue;
1808 if (TREE_PRIVATE (field))
1809 permerror (DECL_SOURCE_LOCATION (field),
1810 "private member %q#D in anonymous union", field);
1811 else if (TREE_PROTECTED (field))
1812 permerror (DECL_SOURCE_LOCATION (field),
1813 "protected member %q#D in anonymous union", field);
1815 if (processing_template_decl)
1816 ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1817 DECL_NAME (field), NULL_TREE);
1818 else
1819 ref = build_class_member_access_expr (object, field, NULL_TREE,
1820 false, tf_warning_or_error);
1822 if (DECL_NAME (field))
1824 tree base;
1826 decl = build_decl (input_location,
1827 VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1828 DECL_ANON_UNION_VAR_P (decl) = 1;
1829 DECL_ARTIFICIAL (decl) = 1;
1831 base = get_base_address (object);
1832 TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1833 TREE_STATIC (decl) = TREE_STATIC (base);
1834 DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1836 SET_DECL_VALUE_EXPR (decl, ref);
1837 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1839 decl = pushdecl (decl);
1841 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1842 decl = build_anon_union_vars (TREE_TYPE (field), ref);
1843 else
1844 decl = 0;
1846 if (main_decl == NULL_TREE)
1847 main_decl = decl;
1850 return main_decl;
1853 /* Finish off the processing of a UNION_TYPE structure. If the union is an
1854 anonymous union, then all members must be laid out together. PUBLIC_P
1855 is nonzero if this union is not declared static. */
1857 void
1858 finish_anon_union (tree anon_union_decl)
1860 tree type;
1861 tree main_decl;
1862 bool public_p;
1864 if (anon_union_decl == error_mark_node)
1865 return;
1867 type = TREE_TYPE (anon_union_decl);
1868 public_p = TREE_PUBLIC (anon_union_decl);
1870 /* The VAR_DECL's context is the same as the TYPE's context. */
1871 DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1873 if (TYPE_FIELDS (type) == NULL_TREE)
1874 return;
1876 if (public_p)
1878 error ("namespace-scope anonymous aggregates must be static");
1879 return;
1882 main_decl = build_anon_union_vars (type, anon_union_decl);
1883 if (main_decl == error_mark_node)
1884 return;
1885 if (main_decl == NULL_TREE)
1887 pedwarn (input_location, 0, "anonymous union with no members");
1888 return;
1891 if (!processing_template_decl)
1893 /* Use main_decl to set the mangled name. */
1894 DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1895 maybe_commonize_var (anon_union_decl);
1896 if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1898 if (DECL_DISCRIMINATOR_P (anon_union_decl))
1899 determine_local_discriminator (anon_union_decl);
1900 mangle_decl (anon_union_decl);
1902 DECL_NAME (anon_union_decl) = NULL_TREE;
1905 pushdecl (anon_union_decl);
1906 cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
1909 /* Auxiliary functions to make type signatures for
1910 `operator new' and `operator delete' correspond to
1911 what compiler will be expecting. */
1913 tree
1914 coerce_new_type (tree type, location_t loc)
1916 int e = 0;
1917 tree args = TYPE_ARG_TYPES (type);
1919 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1921 if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1923 e = 1;
1924 error_at (loc, "%<operator new%> must return type %qT",
1925 ptr_type_node);
1928 if (args && args != void_list_node)
1930 if (TREE_PURPOSE (args))
1932 /* [basic.stc.dynamic.allocation]
1934 The first parameter shall not have an associated default
1935 argument. */
1936 error_at (loc, "the first parameter of %<operator new%> cannot "
1937 "have a default argument");
1938 /* Throw away the default argument. */
1939 TREE_PURPOSE (args) = NULL_TREE;
1942 if (!same_type_p (TREE_VALUE (args), size_type_node))
1944 e = 2;
1945 args = TREE_CHAIN (args);
1948 else
1949 e = 2;
1951 if (e == 2)
1952 permerror (loc, "%<operator new%> takes type %<size_t%> (%qT) "
1953 "as first parameter", size_type_node);
1955 switch (e)
1957 case 2:
1958 args = tree_cons (NULL_TREE, size_type_node, args);
1959 /* Fall through. */
1960 case 1:
1961 type = (cxx_copy_lang_qualifiers
1962 (build_function_type (ptr_type_node, args),
1963 type));
1964 /* Fall through. */
1965 default:;
1967 return type;
1970 void
1971 coerce_delete_type (tree decl, location_t loc)
1973 int e = 0;
1974 tree type = TREE_TYPE (decl);
1975 tree args = TYPE_ARG_TYPES (type);
1977 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1979 if (!same_type_p (TREE_TYPE (type), void_type_node))
1981 e = 1;
1982 error_at (loc, "%<operator delete%> must return type %qT",
1983 void_type_node);
1986 tree ptrtype = ptr_type_node;
1987 if (destroying_delete_p (decl))
1989 if (DECL_CLASS_SCOPE_P (decl))
1990 /* If the function is a destroying operator delete declared in class
1991 type C, the type of its first parameter shall be C*. */
1992 ptrtype = build_pointer_type (DECL_CONTEXT (decl));
1993 else
1994 /* A destroying operator delete shall be a class member function named
1995 operator delete. */
1996 error_at (loc,
1997 "destroying %<operator delete%> must be a member function");
1998 const ovl_op_info_t *op = IDENTIFIER_OVL_OP_INFO (DECL_NAME (decl));
1999 if (op->flags & OVL_OP_FLAG_VEC)
2000 error_at (loc, "%<operator delete[]%> cannot be a destroying delete");
2001 if (!usual_deallocation_fn_p (decl))
2002 error_at (loc, "destroying %<operator delete%> must be a usual "
2003 "deallocation function");
2006 if (!args || args == void_list_node
2007 || !same_type_p (TREE_VALUE (args), ptrtype))
2009 e = 2;
2010 if (args && args != void_list_node)
2011 args = TREE_CHAIN (args);
2012 error_at (loc, "%<operator delete%> takes type %qT as first parameter",
2013 ptrtype);
2015 switch (e)
2017 case 2:
2018 args = tree_cons (NULL_TREE, ptrtype, args);
2019 /* Fall through. */
2020 case 1:
2021 type = (cxx_copy_lang_qualifiers
2022 (build_function_type (void_type_node, args),
2023 type));
2024 /* Fall through. */
2025 default:;
2028 TREE_TYPE (decl) = type;
2031 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
2032 and mark them as needed. */
2034 static void
2035 mark_vtable_entries (tree decl, vec<tree> &consteval_vtables)
2037 /* It's OK for the vtable to refer to deprecated virtual functions. */
2038 warning_sentinel w(warn_deprecated_decl);
2040 bool consteval_seen = false;
2042 for (auto &e: CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
2044 tree fnaddr = e.value;
2046 STRIP_NOPS (fnaddr);
2048 if (TREE_CODE (fnaddr) != ADDR_EXPR
2049 && TREE_CODE (fnaddr) != FDESC_EXPR)
2050 /* This entry is an offset: a virtual base class offset, a
2051 virtual call offset, an RTTI offset, etc. */
2052 continue;
2054 tree fn = TREE_OPERAND (fnaddr, 0);
2055 if (TREE_CODE (fn) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (fn))
2057 if (!consteval_seen)
2059 consteval_seen = true;
2060 consteval_vtables.safe_push (decl);
2062 continue;
2064 TREE_ADDRESSABLE (fn) = 1;
2065 /* When we don't have vcall offsets, we output thunks whenever
2066 we output the vtables that contain them. With vcall offsets,
2067 we know all the thunks we'll need when we emit a virtual
2068 function, so we emit the thunks there instead. */
2069 if (DECL_THUNK_P (fn))
2070 use_thunk (fn, /*emit_p=*/0);
2071 /* Set the location, as marking the function could cause
2072 instantiation. We do not need to preserve the incoming
2073 location, as we're called from c_parse_final_cleanups, which
2074 takes care of that. */
2075 input_location = DECL_SOURCE_LOCATION (fn);
2076 mark_used (fn);
2080 /* Replace any consteval functions in vtables with null pointers. */
2082 static void
2083 clear_consteval_vfns (vec<tree> &consteval_vtables)
2085 for (tree vtable : consteval_vtables)
2086 for (constructor_elt &elt : CONSTRUCTOR_ELTS (DECL_INITIAL (vtable)))
2088 tree fn = cp_get_fndecl_from_callee (elt.value, /*fold*/false);
2089 if (fn && DECL_IMMEDIATE_FUNCTION_P (fn))
2090 elt.value = build_zero_cst (vtable_entry_type);
2094 /* Adjust the TLS model on variable DECL if need be, typically after
2095 the linkage of DECL has been modified. */
2097 static void
2098 adjust_var_decl_tls_model (tree decl)
2100 if (CP_DECL_THREAD_LOCAL_P (decl)
2101 && !lookup_attribute ("tls_model", DECL_ATTRIBUTES (decl)))
2102 set_decl_tls_model (decl, decl_default_tls_model (decl));
2105 /* Set DECL up to have the closest approximation of "initialized common"
2106 linkage available. */
2108 void
2109 comdat_linkage (tree decl)
2111 if (flag_weak)
2113 make_decl_one_only (decl, cxx_comdat_group (decl));
2114 if (HAVE_COMDAT_GROUP && flag_contracts && DECL_CONTRACTS (decl))
2116 symtab_node *n = symtab_node::get (decl);
2117 if (tree pre = DECL_PRE_FN (decl))
2118 cgraph_node::get_create (pre)->add_to_same_comdat_group (n);
2119 if (tree post = DECL_POST_FN (decl))
2120 cgraph_node::get_create (post)->add_to_same_comdat_group (n);
2123 else if (TREE_CODE (decl) == FUNCTION_DECL
2124 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2125 /* We can just emit function and compiler-generated variables
2126 statically; having multiple copies is (for the most part) only
2127 a waste of space.
2129 There are two correctness issues, however: the address of a
2130 template instantiation with external linkage should be the
2131 same, independent of what translation unit asks for the
2132 address, and this will not hold when we emit multiple copies of
2133 the function. However, there's little else we can do.
2135 Also, by default, the typeinfo implementation assumes that
2136 there will be only one copy of the string used as the name for
2137 each type. Therefore, if weak symbols are unavailable, the
2138 run-time library should perform a more conservative check; it
2139 should perform a string comparison, rather than an address
2140 comparison. */
2141 TREE_PUBLIC (decl) = 0;
2142 else
2144 /* Static data member template instantiations, however, cannot
2145 have multiple copies. */
2146 if (DECL_INITIAL (decl) == 0
2147 || DECL_INITIAL (decl) == error_mark_node)
2148 DECL_COMMON (decl) = 1;
2149 else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
2151 DECL_COMMON (decl) = 1;
2152 DECL_INITIAL (decl) = error_mark_node;
2154 else if (!DECL_EXPLICIT_INSTANTIATION (decl))
2156 /* We can't do anything useful; leave vars for explicit
2157 instantiation. */
2158 DECL_EXTERNAL (decl) = 1;
2159 DECL_NOT_REALLY_EXTERN (decl) = 0;
2163 if (TREE_PUBLIC (decl))
2164 DECL_COMDAT (decl) = 1;
2166 if (VAR_P (decl))
2167 adjust_var_decl_tls_model (decl);
2170 /* For win32 we also want to put explicit instantiations in
2171 linkonce sections, so that they will be merged with implicit
2172 instantiations; otherwise we get duplicate symbol errors.
2173 For Darwin we do not want explicit instantiations to be
2174 linkonce. */
2176 void
2177 maybe_make_one_only (tree decl)
2179 /* We used to say that this was not necessary on targets that support weak
2180 symbols, because the implicit instantiations will defer to the explicit
2181 one. However, that's not actually the case in SVR4; a strong definition
2182 after a weak one is an error. Also, not making explicit
2183 instantiations one_only means that we can end up with two copies of
2184 some template instantiations. */
2185 if (! flag_weak)
2186 return;
2188 /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
2189 we can get away with not emitting them if they aren't used. We need
2190 to for variables so that cp_finish_decl will update their linkage,
2191 because their DECL_INITIAL may not have been set properly yet. */
2193 if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
2194 || (! DECL_EXPLICIT_INSTANTIATION (decl)
2195 && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
2197 make_decl_one_only (decl, cxx_comdat_group (decl));
2199 if (VAR_P (decl))
2201 varpool_node *node = varpool_node::get_create (decl);
2202 DECL_COMDAT (decl) = 1;
2203 /* Mark it needed so we don't forget to emit it. */
2204 node->forced_by_abi = true;
2205 TREE_USED (decl) = 1;
2207 adjust_var_decl_tls_model (decl);
2212 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
2213 This predicate will give the right answer during parsing of the
2214 function, which other tests may not. */
2216 bool
2217 vague_linkage_p (tree decl)
2219 if (!TREE_PUBLIC (decl))
2221 /* maybe_thunk_body clears TREE_PUBLIC and DECL_ABSTRACT_P on the
2222 maybe-in-charge 'tor variants; in that case we need to check one of
2223 the "clones" for the real linkage. But only in that case; before
2224 maybe_clone_body we haven't yet copied the linkage to the clones. */
2225 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl)
2226 && !DECL_ABSTRACT_P (decl)
2227 && DECL_CHAIN (decl)
2228 && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)))
2229 return vague_linkage_p (DECL_CHAIN (decl));
2231 gcc_checking_assert (!DECL_COMDAT (decl));
2232 return false;
2234 /* Unfortunately, import_export_decl has not always been called
2235 before the function is processed, so we cannot simply check
2236 DECL_COMDAT. */
2237 if (DECL_COMDAT (decl)
2238 || (TREE_CODE (decl) == FUNCTION_DECL
2239 && DECL_DECLARED_INLINE_P (decl))
2240 || (DECL_LANG_SPECIFIC (decl)
2241 && DECL_TEMPLATE_INSTANTIATION (decl))
2242 || (VAR_P (decl) && DECL_INLINE_VAR_P (decl)))
2243 return true;
2244 else if (DECL_FUNCTION_SCOPE_P (decl))
2245 /* A local static in an inline effectively has vague linkage. */
2246 return (TREE_STATIC (decl)
2247 && vague_linkage_p (DECL_CONTEXT (decl)));
2248 else
2249 return false;
2252 /* Determine whether or not we want to specifically import or export CTYPE,
2253 using various heuristics. */
2255 static void
2256 import_export_class (tree ctype)
2258 /* -1 for imported, 1 for exported. */
2259 int import_export = 0;
2261 /* It only makes sense to call this function at EOF. The reason is
2262 that this function looks at whether or not the first non-inline
2263 non-abstract virtual member function has been defined in this
2264 translation unit. But, we can't possibly know that until we've
2265 seen the entire translation unit. */
2266 gcc_assert (at_eof);
2268 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2269 return;
2271 /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
2272 we will have CLASSTYPE_INTERFACE_ONLY set but not
2273 CLASSTYPE_INTERFACE_KNOWN. In that case, we don't want to use this
2274 heuristic because someone will supply a #pragma implementation
2275 elsewhere, and deducing it here would produce a conflict. */
2276 if (CLASSTYPE_INTERFACE_ONLY (ctype))
2277 return;
2279 if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
2280 import_export = -1;
2281 else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
2282 import_export = 1;
2283 else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
2284 && !flag_implicit_templates)
2285 /* For a template class, without -fimplicit-templates, check the
2286 repository. If the virtual table is assigned to this
2287 translation unit, then export the class; otherwise, import
2288 it. */
2289 import_export = -1;
2290 else if (TYPE_POLYMORPHIC_P (ctype))
2292 /* The ABI specifies that the virtual table and associated
2293 information are emitted with the key method, if any. */
2294 tree method = CLASSTYPE_KEY_METHOD (ctype);
2295 /* If weak symbol support is not available, then we must be
2296 careful not to emit the vtable when the key function is
2297 inline. An inline function can be defined in multiple
2298 translation units. If we were to emit the vtable in each
2299 translation unit containing a definition, we would get
2300 multiple definition errors at link-time. */
2301 if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
2302 import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
2305 /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
2306 a definition anywhere else. */
2307 if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
2308 import_export = 0;
2310 /* Allow back ends the chance to overrule the decision. */
2311 if (targetm.cxx.import_export_class)
2312 import_export = targetm.cxx.import_export_class (ctype, import_export);
2314 if (import_export)
2316 SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
2317 CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
2321 /* Return true if VAR has already been provided to the back end; in that
2322 case VAR should not be modified further by the front end. */
2323 static bool
2324 var_finalized_p (tree var)
2326 return varpool_node::get_create (var)->definition;
2329 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
2330 must be emitted in this translation unit. Mark it as such. */
2332 void
2333 mark_needed (tree decl)
2335 TREE_USED (decl) = 1;
2336 if (TREE_CODE (decl) == FUNCTION_DECL)
2338 /* Extern inline functions don't become needed when referenced.
2339 If we know a method will be emitted in other TU and no new
2340 functions can be marked reachable, just use the external
2341 definition. */
2342 struct cgraph_node *node = cgraph_node::get_create (decl);
2343 node->forced_by_abi = true;
2345 /* #pragma interface can call mark_needed for
2346 maybe-in-charge 'tors; mark the clones as well. */
2347 tree clone;
2348 FOR_EACH_CLONE (clone, decl)
2349 mark_needed (clone);
2351 else if (VAR_P (decl))
2353 varpool_node *node = varpool_node::get_create (decl);
2354 /* C++ frontend use mark_decl_references to force COMDAT variables
2355 to be output that might appear dead otherwise. */
2356 node->forced_by_abi = true;
2360 /* DECL is either a FUNCTION_DECL or a VAR_DECL. This function
2361 returns true if a definition of this entity should be provided in
2362 this object file. Callers use this function to determine whether
2363 or not to let the back end know that a definition of DECL is
2364 available in this translation unit. */
2366 bool
2367 decl_needed_p (tree decl)
2369 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2370 /* This function should only be called at the end of the translation
2371 unit. We cannot be sure of whether or not something will be
2372 COMDAT until that point. */
2373 gcc_assert (at_eof);
2375 /* All entities with external linkage that are not COMDAT/EXTERN should be
2376 emitted; they may be referred to from other object files. */
2377 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
2378 return true;
2380 /* Functions marked "dllexport" must be emitted so that they are
2381 visible to other DLLs. */
2382 if (flag_keep_inline_dllexport
2383 && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
2384 return true;
2386 /* When not optimizing, do not bother to produce definitions for extern
2387 symbols. */
2388 if (DECL_REALLY_EXTERN (decl)
2389 && ((TREE_CODE (decl) != FUNCTION_DECL
2390 && !optimize)
2391 || (TREE_CODE (decl) == FUNCTION_DECL
2392 && !opt_for_fn (decl, optimize)))
2393 && !lookup_attribute ("always_inline", decl))
2394 return false;
2396 /* If this entity was used, let the back end see it; it will decide
2397 whether or not to emit it into the object file. */
2398 if (TREE_USED (decl))
2399 return true;
2401 /* Virtual functions might be needed for devirtualization. */
2402 if (flag_devirtualize
2403 && TREE_CODE (decl) == FUNCTION_DECL
2404 && DECL_VIRTUAL_P (decl))
2405 return true;
2407 /* Otherwise, DECL does not need to be emitted -- yet. A subsequent
2408 reference to DECL might cause it to be emitted later. */
2409 return false;
2412 /* If necessary, write out the vtables for the dynamic class CTYPE.
2413 Returns true if any vtables were emitted. */
2415 static bool
2416 maybe_emit_vtables (tree ctype, vec<tree> &consteval_vtables)
2418 tree vtbl;
2419 tree primary_vtbl;
2420 int needed = 0;
2421 varpool_node *current = NULL, *last = NULL;
2423 /* If the vtables for this class have already been emitted there is
2424 nothing more to do. */
2425 primary_vtbl = CLASSTYPE_VTABLES (ctype);
2426 if (var_finalized_p (primary_vtbl))
2427 return false;
2428 /* Ignore dummy vtables made by get_vtable_decl. */
2429 if (TREE_TYPE (primary_vtbl) == void_type_node)
2430 return false;
2432 /* On some targets, we cannot determine the key method until the end
2433 of the translation unit -- which is when this function is
2434 called. */
2435 if (!targetm.cxx.key_method_may_be_inline ())
2436 determine_key_method (ctype);
2438 /* See if any of the vtables are needed. */
2439 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2441 import_export_decl (vtbl);
2442 if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
2443 needed = 1;
2445 if (!needed)
2447 /* If the references to this class' vtables are optimized away,
2448 still emit the appropriate debugging information. See
2449 dfs_debug_mark. */
2450 if (DECL_COMDAT (primary_vtbl)
2451 && CLASSTYPE_DEBUG_REQUESTED (ctype))
2452 note_debug_info_needed (ctype);
2453 return false;
2456 /* The ABI requires that we emit all of the vtables if we emit any
2457 of them. */
2458 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2460 /* Mark entities references from the virtual table as used. */
2461 mark_vtable_entries (vtbl, consteval_vtables);
2463 if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
2465 vec<tree, va_gc> *cleanups = NULL;
2466 tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
2467 LOOKUP_NORMAL);
2469 /* It had better be all done at compile-time. */
2470 gcc_assert (!expr && !cleanups);
2473 /* Write it out. */
2474 DECL_EXTERNAL (vtbl) = 0;
2475 rest_of_decl_compilation (vtbl, 1, 1);
2477 /* Because we're only doing syntax-checking, we'll never end up
2478 actually marking the variable as written. */
2479 if (flag_syntax_only)
2480 TREE_ASM_WRITTEN (vtbl) = 1;
2481 else if (DECL_ONE_ONLY (vtbl))
2483 current = varpool_node::get_create (vtbl);
2484 if (last)
2485 current->add_to_same_comdat_group (last);
2486 last = current;
2490 /* For abstract classes, the destructor has been removed from the
2491 vtable (in class.cc's build_vtbl_initializer). For a compiler-
2492 generated destructor, it hence might not have been generated in
2493 this translation unit - and with '#pragma interface' it might
2494 never get generated. */
2495 if (CLASSTYPE_PURE_VIRTUALS (ctype)
2496 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (ctype)
2497 && !CLASSTYPE_LAZY_DESTRUCTOR (ctype)
2498 && DECL_DEFAULTED_IN_CLASS_P (CLASSTYPE_DESTRUCTOR (ctype)))
2499 note_vague_linkage_fn (CLASSTYPE_DESTRUCTOR (ctype));
2501 /* Since we're writing out the vtable here, also write the debug
2502 info. */
2503 note_debug_info_needed (ctype);
2505 return true;
2508 /* A special return value from type_visibility meaning internal
2509 linkage. */
2511 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
2513 static int expr_visibility (tree);
2514 static int type_visibility (tree);
2516 /* walk_tree helper function for type_visibility. */
2518 static tree
2519 min_vis_r (tree *tp, int *walk_subtrees, void *data)
2521 int *vis_p = (int *)data;
2522 int this_vis = VISIBILITY_DEFAULT;
2523 if (! TYPE_P (*tp))
2524 *walk_subtrees = 0;
2525 else if (OVERLOAD_TYPE_P (*tp)
2526 && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
2528 this_vis = VISIBILITY_ANON;
2529 *walk_subtrees = 0;
2531 else if (CLASS_TYPE_P (*tp))
2533 this_vis = CLASSTYPE_VISIBILITY (*tp);
2534 *walk_subtrees = 0;
2536 else if (TREE_CODE (*tp) == ARRAY_TYPE
2537 && uses_template_parms (TYPE_DOMAIN (*tp)))
2538 this_vis = expr_visibility (TYPE_MAX_VALUE (TYPE_DOMAIN (*tp)));
2540 if (this_vis > *vis_p)
2541 *vis_p = this_vis;
2543 /* Tell cp_walk_subtrees to look through typedefs. */
2544 if (*walk_subtrees == 1)
2545 *walk_subtrees = 2;
2547 return NULL;
2550 /* walk_tree helper function for expr_visibility. */
2552 static tree
2553 min_vis_expr_r (tree *tp, int */*walk_subtrees*/, void *data)
2555 int *vis_p = (int *)data;
2556 int tpvis = VISIBILITY_DEFAULT;
2558 switch (TREE_CODE (*tp))
2560 case CAST_EXPR:
2561 case IMPLICIT_CONV_EXPR:
2562 case STATIC_CAST_EXPR:
2563 case REINTERPRET_CAST_EXPR:
2564 case CONST_CAST_EXPR:
2565 case DYNAMIC_CAST_EXPR:
2566 case NEW_EXPR:
2567 case CONSTRUCTOR:
2568 case LAMBDA_EXPR:
2569 tpvis = type_visibility (TREE_TYPE (*tp));
2570 break;
2572 case VAR_DECL:
2573 case FUNCTION_DECL:
2574 if (! TREE_PUBLIC (*tp))
2575 tpvis = VISIBILITY_ANON;
2576 else
2577 tpvis = DECL_VISIBILITY (*tp);
2578 break;
2580 default:
2581 break;
2584 if (tpvis > *vis_p)
2585 *vis_p = tpvis;
2587 return NULL_TREE;
2590 /* Returns the visibility of TYPE, which is the minimum visibility of its
2591 component types. */
2593 static int
2594 type_visibility (tree type)
2596 int vis = VISIBILITY_DEFAULT;
2597 cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
2598 return vis;
2601 /* Returns the visibility of an expression EXPR that appears in the signature
2602 of a function template, which is the minimum visibility of names that appear
2603 in its mangling. */
2605 static int
2606 expr_visibility (tree expr)
2608 int vis = VISIBILITY_DEFAULT;
2609 cp_walk_tree_without_duplicates (&expr, min_vis_expr_r, &vis);
2610 return vis;
2613 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
2614 specified (or if VISIBILITY is static). If TMPL is true, this
2615 constraint is for a template argument, and takes precedence
2616 over explicitly-specified visibility on the template. */
2618 static void
2619 constrain_visibility (tree decl, int visibility, bool tmpl)
2621 if (visibility == VISIBILITY_ANON)
2623 /* extern "C" declarations aren't affected by the anonymous
2624 namespace. */
2625 if (!DECL_EXTERN_C_P (decl))
2627 TREE_PUBLIC (decl) = 0;
2628 DECL_WEAK (decl) = 0;
2629 DECL_COMMON (decl) = 0;
2630 DECL_COMDAT (decl) = false;
2631 if (VAR_OR_FUNCTION_DECL_P (decl))
2633 struct symtab_node *snode = symtab_node::get (decl);
2635 if (snode)
2636 snode->set_comdat_group (NULL);
2638 DECL_INTERFACE_KNOWN (decl) = 1;
2639 if (DECL_LANG_SPECIFIC (decl))
2640 DECL_NOT_REALLY_EXTERN (decl) = 1;
2643 else if (visibility > DECL_VISIBILITY (decl)
2644 && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
2646 DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
2647 /* This visibility was not specified. */
2648 DECL_VISIBILITY_SPECIFIED (decl) = false;
2652 /* Constrain the visibility of DECL based on the visibility of its template
2653 arguments. */
2655 static void
2656 constrain_visibility_for_template (tree decl, tree targs)
2658 /* If this is a template instantiation, check the innermost
2659 template args for visibility constraints. The outer template
2660 args are covered by the class check. */
2661 tree args = INNERMOST_TEMPLATE_ARGS (targs);
2662 int i;
2663 for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2665 int vis = 0;
2667 tree arg = TREE_VEC_ELT (args, i-1);
2668 if (TYPE_P (arg))
2669 vis = type_visibility (arg);
2670 else
2671 vis = expr_visibility (arg);
2672 if (vis)
2673 constrain_visibility (decl, vis, true);
2677 /* Like c_determine_visibility, but with additional C++-specific
2678 behavior.
2680 Function-scope entities can rely on the function's visibility because
2681 it is set in start_preparsed_function.
2683 Class-scope entities cannot rely on the class's visibility until the end
2684 of the enclosing class definition.
2686 Note that because namespaces have multiple independent definitions,
2687 namespace visibility is handled elsewhere using the #pragma visibility
2688 machinery rather than by decorating the namespace declaration.
2690 The goal is for constraints from the type to give a diagnostic, and
2691 other constraints to be applied silently. */
2693 void
2694 determine_visibility (tree decl)
2696 /* Remember that all decls get VISIBILITY_DEFAULT when built. */
2698 /* Only relevant for names with external linkage. */
2699 if (!TREE_PUBLIC (decl))
2700 return;
2702 /* Cloned constructors and destructors get the same visibility as
2703 the underlying function. That should be set up in
2704 maybe_clone_body. */
2705 gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2707 bool orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2708 enum symbol_visibility orig_visibility = DECL_VISIBILITY (decl);
2710 /* The decl may be a template instantiation, which could influence
2711 visibilty. */
2712 tree template_decl = NULL_TREE;
2713 if (TREE_CODE (decl) == TYPE_DECL)
2715 if (CLASS_TYPE_P (TREE_TYPE (decl)))
2717 if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
2718 template_decl = decl;
2720 else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2721 template_decl = decl;
2723 else if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
2724 template_decl = decl;
2726 if (TREE_CODE (decl) == TYPE_DECL
2727 && LAMBDA_TYPE_P (TREE_TYPE (decl))
2728 && CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (decl)) != error_mark_node)
2729 if (tree extra = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (decl)))
2731 /* The lambda's visibility is limited by that of its extra
2732 scope. */
2733 int vis = 0;
2734 if (TYPE_P (extra))
2735 vis = type_visibility (extra);
2736 else
2737 vis = expr_visibility (extra);
2738 constrain_visibility (decl, vis, false);
2741 /* If DECL is a member of a class, visibility specifiers on the
2742 class can influence the visibility of the DECL. */
2743 tree class_type = NULL_TREE;
2744 if (DECL_CLASS_SCOPE_P (decl))
2745 class_type = DECL_CONTEXT (decl);
2746 else
2748 /* Not a class member. */
2750 /* Virtual tables have DECL_CONTEXT set to their associated class,
2751 so they are automatically handled above. */
2752 gcc_assert (!VAR_P (decl)
2753 || !DECL_VTABLE_OR_VTT_P (decl));
2755 if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2757 /* Local statics and classes get the visibility of their
2758 containing function by default, except that
2759 -fvisibility-inlines-hidden doesn't affect them. */
2760 tree fn = DECL_CONTEXT (decl);
2761 if (DECL_VISIBILITY_SPECIFIED (fn))
2763 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2764 DECL_VISIBILITY_SPECIFIED (decl) =
2765 DECL_VISIBILITY_SPECIFIED (fn);
2767 else
2769 if (DECL_CLASS_SCOPE_P (fn))
2770 determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2771 else if (determine_hidden_inline (fn))
2773 DECL_VISIBILITY (decl) = default_visibility;
2774 DECL_VISIBILITY_SPECIFIED (decl) =
2775 visibility_options.inpragma;
2777 else
2779 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2780 DECL_VISIBILITY_SPECIFIED (decl) =
2781 DECL_VISIBILITY_SPECIFIED (fn);
2785 /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2786 but have no TEMPLATE_INFO, so don't try to check it. */
2787 template_decl = NULL_TREE;
2789 else if (VAR_P (decl) && DECL_TINFO_P (decl)
2790 && flag_visibility_ms_compat)
2792 /* Under -fvisibility-ms-compat, types are visible by default,
2793 even though their contents aren't. */
2794 tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2795 int underlying_vis = type_visibility (underlying_type);
2796 if (underlying_vis == VISIBILITY_ANON
2797 || (CLASS_TYPE_P (underlying_type)
2798 && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2799 constrain_visibility (decl, underlying_vis, false);
2800 else
2801 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2803 else if (VAR_P (decl) && DECL_TINFO_P (decl))
2805 /* tinfo visibility is based on the type it's for. */
2806 constrain_visibility
2807 (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2809 /* Give the target a chance to override the visibility associated
2810 with DECL. */
2811 if (TREE_PUBLIC (decl)
2812 && !DECL_REALLY_EXTERN (decl)
2813 && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2814 && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2815 targetm.cxx.determine_class_data_visibility (decl);
2817 else if (template_decl)
2818 /* Template instantiations and specializations get visibility based
2819 on their template unless they override it with an attribute. */;
2820 else if (! DECL_VISIBILITY_SPECIFIED (decl))
2822 if (determine_hidden_inline (decl))
2823 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2824 else
2826 /* Set default visibility to whatever the user supplied with
2827 #pragma GCC visibility or a namespace visibility attribute. */
2828 DECL_VISIBILITY (decl) = default_visibility;
2829 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2834 if (template_decl)
2836 /* If the specialization doesn't specify visibility, use the
2837 visibility from the template. */
2838 tree tinfo = get_template_info (template_decl);
2839 tree args = TI_ARGS (tinfo);
2840 tree attribs = (TREE_CODE (decl) == TYPE_DECL
2841 ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2842 : DECL_ATTRIBUTES (decl));
2843 tree attr = lookup_attribute ("visibility", attribs);
2845 if (args != error_mark_node)
2847 tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2849 if (!DECL_VISIBILITY_SPECIFIED (decl))
2851 if (!attr
2852 && determine_hidden_inline (decl))
2853 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2854 else
2856 DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2857 DECL_VISIBILITY_SPECIFIED (decl)
2858 = DECL_VISIBILITY_SPECIFIED (pattern);
2862 if (args
2863 /* Template argument visibility outweighs #pragma or namespace
2864 visibility, but not an explicit attribute. */
2865 && !attr)
2867 int depth = TMPL_ARGS_DEPTH (args);
2868 if (DECL_VISIBILITY_SPECIFIED (decl))
2870 /* A class template member with explicit visibility
2871 overrides the class visibility, so we need to apply
2872 all the levels of template args directly. */
2873 int i;
2874 for (i = 1; i <= depth; ++i)
2876 tree lev = TMPL_ARGS_LEVEL (args, i);
2877 constrain_visibility_for_template (decl, lev);
2880 else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2881 /* Limit visibility based on its template arguments. */
2882 constrain_visibility_for_template (decl, args);
2887 if (class_type)
2888 determine_visibility_from_class (decl, class_type);
2890 if (decl_internal_context_p (decl))
2891 /* Names in an anonymous namespace get internal linkage. */
2892 constrain_visibility (decl, VISIBILITY_ANON, false);
2893 else if (TREE_CODE (decl) != TYPE_DECL)
2895 /* Propagate anonymity from type to decl. */
2896 int tvis = type_visibility (TREE_TYPE (decl));
2897 if (tvis == VISIBILITY_ANON
2898 || ! DECL_VISIBILITY_SPECIFIED (decl))
2899 constrain_visibility (decl, tvis, false);
2901 else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2902 /* DR 757: A type without linkage shall not be used as the type of a
2903 variable or function with linkage, unless
2904 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2905 o the variable or function is not used (3.2 [basic.def.odr]) or is
2906 defined in the same translation unit.
2908 Since non-extern "C" decls need to be defined in the same
2909 translation unit, we can make the type internal. */
2910 constrain_visibility (decl, VISIBILITY_ANON, false);
2912 /* If visibility changed and DECL already has DECL_RTL, ensure
2913 symbol flags are updated. */
2914 if ((DECL_VISIBILITY (decl) != orig_visibility
2915 || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2916 && ((VAR_P (decl) && TREE_STATIC (decl))
2917 || TREE_CODE (decl) == FUNCTION_DECL)
2918 && DECL_RTL_SET_P (decl))
2919 make_decl_rtl (decl);
2922 /* By default, static data members and function members receive
2923 the visibility of their containing class. */
2925 static void
2926 determine_visibility_from_class (tree decl, tree class_type)
2928 if (DECL_VISIBILITY_SPECIFIED (decl))
2929 return;
2931 if (determine_hidden_inline (decl))
2932 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2933 else
2935 /* Default to the class visibility. */
2936 DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2937 DECL_VISIBILITY_SPECIFIED (decl)
2938 = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2941 /* Give the target a chance to override the visibility associated
2942 with DECL. */
2943 if (VAR_P (decl)
2944 && TREE_PUBLIC (decl)
2945 && (DECL_TINFO_P (decl) || DECL_VTABLE_OR_VTT_P (decl))
2946 && !DECL_REALLY_EXTERN (decl)
2947 && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2948 targetm.cxx.determine_class_data_visibility (decl);
2951 /* Returns true iff DECL is an inline that should get hidden visibility
2952 because of -fvisibility-inlines-hidden. */
2954 static bool
2955 determine_hidden_inline (tree decl)
2957 return (visibility_options.inlines_hidden
2958 /* Don't do this for inline templates; specializations might not be
2959 inline, and we don't want them to inherit the hidden
2960 visibility. We'll set it here for all inline instantiations. */
2961 && !processing_template_decl
2962 && TREE_CODE (decl) == FUNCTION_DECL
2963 && DECL_DECLARED_INLINE_P (decl)
2964 && (! DECL_LANG_SPECIFIC (decl)
2965 || ! DECL_EXPLICIT_INSTANTIATION (decl)));
2968 /* Constrain the visibility of a class TYPE based on the visibility of its
2969 field types. Warn if any fields require lesser visibility. */
2971 void
2972 constrain_class_visibility (tree type)
2974 tree binfo;
2975 tree t;
2976 int i;
2978 int vis = type_visibility (type);
2980 if (vis == VISIBILITY_ANON
2981 || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2982 return;
2984 /* Don't warn about visibility if the class has explicit visibility. */
2985 if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2986 vis = VISIBILITY_INTERNAL;
2988 for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
2989 if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node
2990 && !DECL_ARTIFICIAL (t))
2992 tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2993 int subvis = type_visibility (ftype);
2995 if (subvis == VISIBILITY_ANON)
2997 if (!in_main_input_context())
2999 tree nlt = no_linkage_check (ftype, /*relaxed_p=*/false);
3000 if (nlt)
3002 if (same_type_p (TREE_TYPE (t), nlt))
3003 warning (OPT_Wsubobject_linkage, "\
3004 %qT has a field %q#D whose type has no linkage",
3005 type, t);
3006 else
3007 warning (OPT_Wsubobject_linkage, "\
3008 %qT has a field %qD whose type depends on the type %qT which has no linkage",
3009 type, t, nlt);
3011 else if (cxx_dialect > cxx98
3012 && !decl_anon_ns_mem_p (ftype))
3013 warning (OPT_Wsubobject_linkage, "\
3014 %qT has a field %q#D whose type has internal linkage",
3015 type, t);
3016 else // In C++98 this can only happen with unnamed namespaces.
3017 warning (OPT_Wsubobject_linkage, "\
3018 %qT has a field %q#D whose type uses the anonymous namespace",
3019 type, t);
3022 else if (MAYBE_CLASS_TYPE_P (ftype)
3023 && vis < VISIBILITY_HIDDEN
3024 && subvis >= VISIBILITY_HIDDEN)
3025 warning (OPT_Wattributes, "\
3026 %qT declared with greater visibility than the type of its field %qD",
3027 type, t);
3030 binfo = TYPE_BINFO (type);
3031 for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
3033 tree btype = BINFO_TYPE (t);
3034 int subvis = type_visibility (btype);
3036 if (subvis == VISIBILITY_ANON)
3038 if (!in_main_input_context())
3040 tree nlt = no_linkage_check (btype, /*relaxed_p=*/false);
3041 if (nlt)
3043 if (same_type_p (btype, nlt))
3044 warning (OPT_Wsubobject_linkage, "\
3045 %qT has a base %qT which has no linkage",
3046 type, btype);
3047 else
3048 warning (OPT_Wsubobject_linkage, "\
3049 %qT has a base %qT which depends on the type %qT which has no linkage",
3050 type, btype, nlt);
3052 else if (cxx_dialect > cxx98
3053 && !decl_anon_ns_mem_p (btype))
3054 warning (OPT_Wsubobject_linkage, "\
3055 %qT has a base %qT which has internal linkage",
3056 type, btype);
3057 else // In C++98 this can only happen with unnamed namespaces.
3058 warning (OPT_Wsubobject_linkage, "\
3059 %qT has a base %qT which uses the anonymous namespace",
3060 type, btype);
3063 else if (vis < VISIBILITY_HIDDEN
3064 && subvis >= VISIBILITY_HIDDEN)
3065 warning (OPT_Wattributes, "\
3066 %qT declared with greater visibility than its base %qT",
3067 type, TREE_TYPE (t));
3071 /* Functions for adjusting the visibility of a tagged type and its nested
3072 types and declarations when it gets a name for linkage purposes from a
3073 typedef. */
3074 // FIXME: It is now a DR for such a class type to contain anything
3075 // other than C. So at minium most of this can probably be deleted.
3077 /* First reset the visibility of all the types. */
3079 static void
3080 reset_type_linkage_1 (tree type)
3082 set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
3083 if (CLASS_TYPE_P (type))
3084 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
3085 if (DECL_IMPLICIT_TYPEDEF_P (member))
3086 reset_type_linkage_1 (TREE_TYPE (member));
3089 /* Then reset the visibility of any static data members or member
3090 functions that use those types. */
3092 static void
3093 reset_decl_linkage (tree decl)
3095 if (TREE_PUBLIC (decl))
3096 return;
3097 if (DECL_CLONED_FUNCTION_P (decl))
3098 return;
3099 TREE_PUBLIC (decl) = true;
3100 DECL_INTERFACE_KNOWN (decl) = false;
3101 determine_visibility (decl);
3102 tentative_decl_linkage (decl);
3105 void
3106 reset_type_linkage (tree type)
3108 reset_type_linkage_1 (type);
3109 if (CLASS_TYPE_P (type))
3111 if (tree vt = CLASSTYPE_VTABLES (type))
3113 tree name = mangle_vtbl_for_type (type);
3114 DECL_NAME (vt) = name;
3115 SET_DECL_ASSEMBLER_NAME (vt, name);
3116 reset_decl_linkage (vt);
3118 if (!ANON_AGGR_TYPE_P (type))
3119 if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
3121 tree name = mangle_typeinfo_for_type (type);
3122 DECL_NAME (ti) = name;
3123 SET_DECL_ASSEMBLER_NAME (ti, name);
3124 TREE_TYPE (name) = type;
3125 reset_decl_linkage (ti);
3127 for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
3129 tree mem = STRIP_TEMPLATE (m);
3130 if (TREE_CODE (mem) == VAR_DECL || TREE_CODE (mem) == FUNCTION_DECL)
3131 reset_decl_linkage (mem);
3132 else if (DECL_IMPLICIT_TYPEDEF_P (mem))
3133 reset_type_linkage (TREE_TYPE (mem));
3138 /* Set up our initial idea of what the linkage of DECL should be. */
3140 void
3141 tentative_decl_linkage (tree decl)
3143 if (DECL_INTERFACE_KNOWN (decl))
3144 /* We've already made a decision as to how this function will
3145 be handled. */;
3146 else if (vague_linkage_p (decl))
3148 if (TREE_CODE (decl) == FUNCTION_DECL
3149 && decl_defined_p (decl))
3151 DECL_EXTERNAL (decl) = 1;
3152 DECL_NOT_REALLY_EXTERN (decl) = 1;
3153 note_vague_linkage_fn (decl);
3154 /* A non-template inline function with external linkage will
3155 always be COMDAT. As we must eventually determine the
3156 linkage of all functions, and as that causes writes to
3157 the data mapped in from the PCH file, it's advantageous
3158 to mark the functions at this point. */
3159 if (DECL_DECLARED_INLINE_P (decl)
3160 && (!DECL_IMPLICIT_INSTANTIATION (decl)
3161 || DECL_DEFAULTED_FN (decl)))
3163 /* This function must have external linkage, as
3164 otherwise DECL_INTERFACE_KNOWN would have been
3165 set. */
3166 gcc_assert (TREE_PUBLIC (decl));
3167 comdat_linkage (decl);
3168 DECL_INTERFACE_KNOWN (decl) = 1;
3171 else if (VAR_P (decl))
3172 maybe_commonize_var (decl);
3176 /* DECL is a FUNCTION_DECL or VAR_DECL. If the object file linkage
3177 for DECL has not already been determined, do so now by setting
3178 DECL_EXTERNAL, DECL_COMDAT and other related flags. Until this
3179 function is called entities with vague linkage whose definitions
3180 are available must have TREE_PUBLIC set.
3182 If this function decides to place DECL in COMDAT, it will set
3183 appropriate flags -- but will not clear DECL_EXTERNAL. It is up to
3184 the caller to decide whether or not to clear DECL_EXTERNAL. Some
3185 callers defer that decision until it is clear that DECL is actually
3186 required. */
3188 void
3189 import_export_decl (tree decl)
3191 bool comdat_p;
3192 bool import_p;
3193 tree class_type = NULL_TREE;
3195 if (DECL_INTERFACE_KNOWN (decl))
3196 return;
3198 /* We cannot determine what linkage to give to an entity with vague
3199 linkage until the end of the file. For example, a virtual table
3200 for a class will be defined if and only if the key method is
3201 defined in this translation unit. */
3202 gcc_assert (at_eof);
3203 /* Object file linkage for explicit instantiations is handled in
3204 mark_decl_instantiated. For static variables in functions with
3205 vague linkage, maybe_commonize_var is used.
3207 Therefore, the only declarations that should be provided to this
3208 function are those with external linkage that are:
3210 * implicit instantiations of function templates
3212 * inline function
3214 * implicit instantiations of static data members of class
3215 templates
3217 * virtual tables
3219 * typeinfo objects
3221 Furthermore, all entities that reach this point must have a
3222 definition available in this translation unit.
3224 The following assertions check these conditions. */
3225 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
3226 /* Any code that creates entities with TREE_PUBLIC cleared should
3227 also set DECL_INTERFACE_KNOWN. */
3228 gcc_assert (TREE_PUBLIC (decl));
3229 if (TREE_CODE (decl) == FUNCTION_DECL)
3230 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3231 || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
3232 || DECL_DECLARED_INLINE_P (decl));
3233 else
3234 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3235 || DECL_VTABLE_OR_VTT_P (decl)
3236 || DECL_TINFO_P (decl));
3237 /* Check that a definition of DECL is available in this translation
3238 unit. */
3239 gcc_assert (!DECL_REALLY_EXTERN (decl));
3241 /* Assume that DECL will not have COMDAT linkage. */
3242 comdat_p = false;
3243 /* Assume that DECL will not be imported into this translation
3244 unit. */
3245 import_p = false;
3247 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
3249 class_type = DECL_CONTEXT (decl);
3250 import_export_class (class_type);
3251 if (CLASSTYPE_INTERFACE_KNOWN (class_type)
3252 && CLASSTYPE_INTERFACE_ONLY (class_type))
3253 import_p = true;
3254 else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
3255 && !CLASSTYPE_USE_TEMPLATE (class_type)
3256 && CLASSTYPE_KEY_METHOD (class_type)
3257 && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
3258 /* The ABI requires that all virtual tables be emitted with
3259 COMDAT linkage. However, on systems where COMDAT symbols
3260 don't show up in the table of contents for a static
3261 archive, or on systems without weak symbols (where we
3262 approximate COMDAT linkage by using internal linkage), the
3263 linker will report errors about undefined symbols because
3264 it will not see the virtual table definition. Therefore,
3265 in the case that we know that the virtual table will be
3266 emitted in only one translation unit, we make the virtual
3267 table an ordinary definition with external linkage. */
3268 DECL_EXTERNAL (decl) = 0;
3269 else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
3271 /* CLASS_TYPE is being exported from this translation unit,
3272 so DECL should be defined here. */
3273 if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
3274 /* If a class is declared in a header with the "extern
3275 template" extension, then it will not be instantiated,
3276 even in translation units that would normally require
3277 it. Often such classes are explicitly instantiated in
3278 one translation unit. Therefore, the explicit
3279 instantiation must be made visible to other translation
3280 units. */
3281 DECL_EXTERNAL (decl) = 0;
3282 else
3284 /* The generic C++ ABI says that class data is always
3285 COMDAT, even if there is a key function. Some
3286 variants (e.g., the ARM EABI) says that class data
3287 only has COMDAT linkage if the class data might be
3288 emitted in more than one translation unit. When the
3289 key method can be inline and is inline, we still have
3290 to arrange for comdat even though
3291 class_data_always_comdat is false. */
3292 if (!CLASSTYPE_KEY_METHOD (class_type)
3293 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
3294 || targetm.cxx.class_data_always_comdat ())
3296 /* The ABI requires COMDAT linkage. Normally, we
3297 only emit COMDAT things when they are needed;
3298 make sure that we realize that this entity is
3299 indeed needed. */
3300 comdat_p = true;
3301 mark_needed (decl);
3305 else if (!flag_implicit_templates
3306 && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
3307 import_p = true;
3308 else
3309 comdat_p = true;
3311 else if (VAR_P (decl) && DECL_TINFO_P (decl))
3313 tree type = TREE_TYPE (DECL_NAME (decl));
3314 if (CLASS_TYPE_P (type))
3316 class_type = type;
3317 import_export_class (type);
3318 if (CLASSTYPE_INTERFACE_KNOWN (type)
3319 && TYPE_POLYMORPHIC_P (type)
3320 && CLASSTYPE_INTERFACE_ONLY (type)
3321 /* If -fno-rtti was specified, then we cannot be sure
3322 that RTTI information will be emitted with the
3323 virtual table of the class, so we must emit it
3324 wherever it is used. */
3325 && flag_rtti)
3326 import_p = true;
3327 else
3329 if (CLASSTYPE_INTERFACE_KNOWN (type)
3330 && !CLASSTYPE_INTERFACE_ONLY (type))
3332 comdat_p = (targetm.cxx.class_data_always_comdat ()
3333 || (CLASSTYPE_KEY_METHOD (type)
3334 && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
3335 mark_needed (decl);
3336 if (!flag_weak)
3338 comdat_p = false;
3339 DECL_EXTERNAL (decl) = 0;
3342 else
3343 comdat_p = true;
3346 else
3347 comdat_p = true;
3349 else if (DECL_TEMPLOID_INSTANTIATION (decl))
3351 /* DECL is an implicit instantiation of a function or static
3352 data member. */
3353 if (flag_implicit_templates
3354 || (flag_implicit_inline_templates
3355 && TREE_CODE (decl) == FUNCTION_DECL
3356 && DECL_DECLARED_INLINE_P (decl)))
3357 comdat_p = true;
3358 else
3359 /* If we are not implicitly generating templates, then mark
3360 this entity as undefined in this translation unit. */
3361 import_p = true;
3363 else if (DECL_FUNCTION_MEMBER_P (decl))
3365 if (!DECL_DECLARED_INLINE_P (decl))
3367 tree ctype = DECL_CONTEXT (decl);
3368 import_export_class (ctype);
3369 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
3371 DECL_NOT_REALLY_EXTERN (decl)
3372 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
3373 || (DECL_DECLARED_INLINE_P (decl)
3374 && ! flag_implement_inlines
3375 && !DECL_VINDEX (decl)));
3377 if (!DECL_NOT_REALLY_EXTERN (decl))
3378 DECL_EXTERNAL (decl) = 1;
3380 /* Always make artificials weak. */
3381 if (DECL_ARTIFICIAL (decl) && flag_weak)
3382 comdat_p = true;
3383 else
3384 maybe_make_one_only (decl);
3387 else
3388 comdat_p = true;
3390 else
3391 comdat_p = true;
3393 if (import_p)
3395 /* If we are importing DECL into this translation unit, mark is
3396 an undefined here. */
3397 DECL_EXTERNAL (decl) = 1;
3398 DECL_NOT_REALLY_EXTERN (decl) = 0;
3400 else if (comdat_p)
3402 /* If we decided to put DECL in COMDAT, mark it accordingly at
3403 this point. */
3404 comdat_linkage (decl);
3407 DECL_INTERFACE_KNOWN (decl) = 1;
3410 /* Return an expression that performs the destruction of DECL, which
3411 must be a VAR_DECL whose type has a non-trivial destructor, or is
3412 an array whose (innermost) elements have a non-trivial destructor. */
3414 tree
3415 build_cleanup (tree decl)
3417 tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
3418 gcc_assert (clean != NULL_TREE);
3419 return clean;
3422 /* GUARD is a helper variable for DECL; make them have the same linkage and
3423 visibility. */
3425 void
3426 copy_linkage (tree guard, tree decl)
3428 TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
3429 TREE_STATIC (guard) = TREE_STATIC (decl);
3430 DECL_COMMON (guard) = DECL_COMMON (decl);
3431 DECL_COMDAT (guard) = DECL_COMDAT (decl);
3432 if (TREE_STATIC (guard))
3434 CP_DECL_THREAD_LOCAL_P (guard) = CP_DECL_THREAD_LOCAL_P (decl);
3435 set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
3436 if (DECL_ONE_ONLY (decl))
3437 make_decl_one_only (guard, cxx_comdat_group (guard));
3438 if (TREE_PUBLIC (decl))
3439 DECL_WEAK (guard) = DECL_WEAK (decl);
3440 /* Also check vague_linkage_p, as DECL_WEAK and DECL_ONE_ONLY might not
3441 be set until import_export_decl at EOF. */
3442 if (vague_linkage_p (decl))
3443 comdat_linkage (guard);
3444 DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
3445 DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
3449 /* Returns the initialization guard variable for the variable DECL,
3450 which has static storage duration. */
3452 tree
3453 get_guard (tree decl)
3455 tree sname = mangle_guard_variable (decl);
3456 tree guard = get_global_binding (sname);
3457 if (! guard)
3459 tree guard_type;
3461 /* We use a type that is big enough to contain a mutex as well
3462 as an integer counter. */
3463 guard_type = targetm.cxx.guard_type ();
3464 guard = build_decl (DECL_SOURCE_LOCATION (decl),
3465 VAR_DECL, sname, guard_type);
3467 /* The guard should have the same linkage as what it guards. */
3468 copy_linkage (guard, decl);
3470 DECL_ARTIFICIAL (guard) = 1;
3471 DECL_IGNORED_P (guard) = 1;
3472 TREE_USED (guard) = 1;
3473 pushdecl_top_level_and_finish (guard, NULL_TREE);
3475 return guard;
3478 /* Returns true if accessing the GUARD atomic is expensive,
3479 i.e. involves a call to __sync_synchronize or similar.
3480 In this case let __cxa_guard_acquire handle the atomics. */
3482 static bool
3483 is_atomic_expensive_p (machine_mode mode)
3485 if (!flag_inline_atomics)
3486 return true;
3488 if (!can_compare_and_swap_p (mode, false) || !can_atomic_load_p (mode))
3489 return true;
3491 return false;
3494 /* Return an atomic load of src with the appropriate memory model. */
3496 static tree
3497 build_atomic_load_type (tree src, HOST_WIDE_INT model, tree type)
3499 tree ptr_type = build_pointer_type (type);
3500 tree mem_model = build_int_cst (integer_type_node, model);
3501 tree t, addr, val;
3502 unsigned int size;
3503 int fncode;
3505 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
3507 fncode = BUILT_IN_ATOMIC_LOAD_N + exact_log2 (size) + 1;
3508 t = builtin_decl_implicit ((enum built_in_function) fncode);
3510 addr = build1 (ADDR_EXPR, ptr_type, src);
3511 val = build_call_expr (t, 2, addr, mem_model);
3512 return val;
3515 /* Return those bits of the GUARD variable that should be set when the
3516 guarded entity is actually initialized. */
3518 static tree
3519 get_guard_bits (tree guard)
3521 if (!targetm.cxx.guard_mask_bit ())
3523 /* We only set the first byte of the guard, in order to leave room
3524 for a mutex in the high-order bits. */
3525 guard = build1 (ADDR_EXPR,
3526 build_pointer_type (TREE_TYPE (guard)),
3527 guard);
3528 guard = build1 (NOP_EXPR,
3529 build_pointer_type (char_type_node),
3530 guard);
3531 guard = build1 (INDIRECT_REF, char_type_node, guard);
3534 return guard;
3537 /* Return an expression which determines whether or not the GUARD
3538 variable has already been initialized. */
3540 tree
3541 get_guard_cond (tree guard, bool thread_safe)
3543 tree guard_value;
3545 if (!thread_safe)
3546 guard = get_guard_bits (guard);
3547 else
3549 tree type = targetm.cxx.guard_mask_bit ()
3550 ? TREE_TYPE (guard) : char_type_node;
3552 if (is_atomic_expensive_p (TYPE_MODE (type)))
3553 guard = integer_zero_node;
3554 else
3555 guard = build_atomic_load_type (guard, MEMMODEL_ACQUIRE, type);
3558 /* Mask off all but the low bit. */
3559 if (targetm.cxx.guard_mask_bit ())
3561 guard_value = integer_one_node;
3562 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3563 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3564 guard = cp_build_binary_op (input_location,
3565 BIT_AND_EXPR, guard, guard_value,
3566 tf_warning_or_error);
3569 guard_value = integer_zero_node;
3570 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3571 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3572 return cp_build_binary_op (input_location,
3573 EQ_EXPR, guard, guard_value,
3574 tf_warning_or_error);
3577 /* Return an expression which sets the GUARD variable, indicating that
3578 the variable being guarded has been initialized. */
3580 tree
3581 set_guard (tree guard)
3583 tree guard_init;
3585 /* Set the GUARD to one. */
3586 guard = get_guard_bits (guard);
3587 guard_init = integer_one_node;
3588 if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
3589 guard_init = fold_convert (TREE_TYPE (guard), guard_init);
3590 return cp_build_modify_expr (input_location, guard, NOP_EXPR, guard_init,
3591 tf_warning_or_error);
3594 /* Returns true iff we can tell that VAR does not have a dynamic
3595 initializer. */
3597 static bool
3598 var_defined_without_dynamic_init (tree var)
3600 /* constinit vars are guaranteed to not have dynamic initializer,
3601 but still registering the destructor counts as dynamic initialization. */
3602 if (DECL_DECLARED_CONSTINIT_P (var)
3603 && COMPLETE_TYPE_P (TREE_TYPE (var))
3604 && !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3605 return true;
3606 /* If it's defined in another TU, we can't tell. */
3607 if (DECL_EXTERNAL (var))
3608 return false;
3609 /* If it has a non-trivial destructor, registering the destructor
3610 counts as dynamic initialization. */
3611 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3612 return false;
3613 /* If it's in this TU, its initializer has been processed, unless
3614 it's a case of self-initialization, then DECL_INITIALIZED_P is
3615 false while the initializer is handled by finish_id_expression. */
3616 if (!DECL_INITIALIZED_P (var))
3617 return false;
3618 /* If it has no initializer or a constant one, it's not dynamic. */
3619 return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
3620 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
3623 /* Returns true iff VAR is a variable that needs uses to be
3624 wrapped for possible dynamic initialization. */
3626 static bool
3627 var_needs_tls_wrapper (tree var)
3629 return (!error_operand_p (var)
3630 && CP_DECL_THREAD_LOCAL_P (var)
3631 && !DECL_GNU_TLS_P (var)
3632 && !DECL_FUNCTION_SCOPE_P (var)
3633 && !var_defined_without_dynamic_init (var));
3636 /* Get the FUNCTION_DECL for the shared TLS init function for this
3637 translation unit. */
3639 static tree
3640 get_local_tls_init_fn (location_t loc)
3642 tree sname = get_identifier ("__tls_init");
3643 tree fn = get_global_binding (sname);
3644 if (!fn)
3646 fn = build_lang_decl_loc (loc, FUNCTION_DECL, sname,
3647 build_function_type (void_type_node,
3648 void_list_node));
3649 SET_DECL_LANGUAGE (fn, lang_c);
3650 TREE_PUBLIC (fn) = false;
3651 DECL_ARTIFICIAL (fn) = true;
3652 mark_used (fn);
3653 set_global_binding (fn);
3655 return fn;
3658 /* Get a FUNCTION_DECL for the init function for the thread_local
3659 variable VAR. The init function will be an alias to the function
3660 that initializes all the non-local TLS variables in the translation
3661 unit. The init function is only used by the wrapper function. */
3663 static tree
3664 get_tls_init_fn (tree var)
3666 /* Only C++11 TLS vars need this init fn. */
3667 if (!var_needs_tls_wrapper (var))
3668 return NULL_TREE;
3670 /* If -fno-extern-tls-init, assume that we don't need to call
3671 a tls init function for a variable defined in another TU. */
3672 if (!flag_extern_tls_init && DECL_EXTERNAL (var))
3673 return NULL_TREE;
3675 /* If the variable is internal, or if we can't generate aliases,
3676 call the local init function directly. */
3677 if (!TREE_PUBLIC (var) || !TARGET_SUPPORTS_ALIASES)
3678 return get_local_tls_init_fn (DECL_SOURCE_LOCATION (var));
3680 tree sname = mangle_tls_init_fn (var);
3681 tree fn = get_global_binding (sname);
3682 if (!fn)
3684 fn = build_lang_decl (FUNCTION_DECL, sname,
3685 build_function_type (void_type_node,
3686 void_list_node));
3687 SET_DECL_LANGUAGE (fn, lang_c);
3688 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3689 DECL_ARTIFICIAL (fn) = true;
3690 DECL_COMDAT (fn) = DECL_COMDAT (var);
3691 DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
3692 if (DECL_ONE_ONLY (var))
3693 make_decl_one_only (fn, cxx_comdat_group (fn));
3694 if (TREE_PUBLIC (var))
3696 tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
3697 /* If the variable is defined somewhere else and might have static
3698 initialization, make the init function a weak reference. */
3699 if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
3700 || TYPE_HAS_CONSTEXPR_CTOR (obtype)
3701 || TYPE_HAS_TRIVIAL_DFLT (obtype))
3702 && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
3703 && DECL_EXTERNAL (var))
3704 declare_weak (fn);
3705 else
3706 DECL_WEAK (fn) = DECL_WEAK (var);
3708 DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
3709 DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
3710 DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
3711 DECL_IGNORED_P (fn) = 1;
3712 mark_used (fn);
3714 DECL_BEFRIENDING_CLASSES (fn) = var;
3716 set_global_binding (fn);
3718 return fn;
3721 /* Get a FUNCTION_DECL for the init wrapper function for the thread_local
3722 variable VAR. The wrapper function calls the init function (if any) for
3723 VAR and then returns a reference to VAR. The wrapper function is used
3724 in place of VAR everywhere VAR is mentioned. */
3726 static tree
3727 get_tls_wrapper_fn (tree var)
3729 /* Only C++11 TLS vars need this wrapper fn. */
3730 if (!var_needs_tls_wrapper (var))
3731 return NULL_TREE;
3733 tree sname = mangle_tls_wrapper_fn (var);
3734 tree fn = get_global_binding (sname);
3735 if (!fn)
3737 /* A named rvalue reference is an lvalue, so the wrapper should
3738 always return an lvalue reference. */
3739 tree type = non_reference (TREE_TYPE (var));
3740 type = build_reference_type (type);
3741 tree fntype = build_function_type (type, void_list_node);
3743 fn = build_lang_decl_loc (DECL_SOURCE_LOCATION (var),
3744 FUNCTION_DECL, sname, fntype);
3745 SET_DECL_LANGUAGE (fn, lang_c);
3746 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3747 DECL_ARTIFICIAL (fn) = true;
3748 DECL_IGNORED_P (fn) = 1;
3749 /* The wrapper is inline and emitted everywhere var is used. */
3750 DECL_DECLARED_INLINE_P (fn) = true;
3751 if (TREE_PUBLIC (var))
3753 comdat_linkage (fn);
3754 #ifdef HAVE_GAS_HIDDEN
3755 /* Make the wrapper bind locally; there's no reason to share
3756 the wrapper between multiple shared objects. */
3757 DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
3758 DECL_VISIBILITY_SPECIFIED (fn) = true;
3759 #endif
3761 if (!TREE_PUBLIC (fn))
3762 DECL_INTERFACE_KNOWN (fn) = true;
3763 mark_used (fn);
3764 note_vague_linkage_fn (fn);
3766 #if 0
3767 /* We want CSE to commonize calls to the wrapper, but marking it as
3768 pure is unsafe since it has side-effects. I guess we need a new
3769 ECF flag even weaker than ECF_PURE. FIXME! */
3770 DECL_PURE_P (fn) = true;
3771 #endif
3773 DECL_BEFRIENDING_CLASSES (fn) = var;
3775 set_global_binding (fn);
3777 return fn;
3780 /* If EXPR is a thread_local variable that should be wrapped by init
3781 wrapper function, return a call to that function, otherwise return
3782 NULL. */
3784 tree
3785 maybe_get_tls_wrapper_call (tree expr)
3787 if (VAR_P (expr)
3788 && !processing_template_decl
3789 && !cp_unevaluated_operand
3790 && CP_DECL_THREAD_LOCAL_P (expr))
3791 if (tree wrap = get_tls_wrapper_fn (expr))
3792 return build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
3793 return NULL;
3796 /* At EOF, generate the definition for the TLS wrapper function FN:
3798 T& var_wrapper() {
3799 if (init_fn) init_fn();
3800 return var;
3801 } */
3803 static void
3804 generate_tls_wrapper (tree fn)
3806 tree var = DECL_BEFRIENDING_CLASSES (fn);
3808 start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
3809 tree body = begin_function_body ();
3810 /* Only call the init fn if there might be one. */
3811 if (tree init_fn = get_tls_init_fn (var))
3813 tree if_stmt = NULL_TREE;
3814 /* If init_fn is a weakref, make sure it exists before calling. */
3815 if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
3817 if_stmt = begin_if_stmt ();
3818 tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
3819 tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
3820 NE_EXPR, addr, nullptr_node,
3821 tf_warning_or_error);
3822 finish_if_stmt_cond (cond, if_stmt);
3824 finish_expr_stmt (build_cxx_call
3825 (init_fn, 0, NULL, tf_warning_or_error));
3826 if (if_stmt)
3828 finish_then_clause (if_stmt);
3829 finish_if_stmt (if_stmt);
3832 else
3833 /* If there's no initialization, the wrapper is a constant function. */
3834 TREE_READONLY (fn) = true;
3835 finish_return_stmt (convert_from_reference (var));
3836 finish_function_body (body);
3837 expand_or_defer_fn (finish_function (/*inline_p=*/false));
3840 /* Start a global constructor or destructor function. */
3842 static tree
3843 start_objects (bool initp, unsigned priority, bool has_body)
3845 bool default_init = initp && priority == DEFAULT_INIT_PRIORITY;
3846 bool is_module_init = default_init && module_global_init_needed ();
3847 tree name = NULL_TREE;
3849 if (is_module_init)
3850 name = mangle_module_global_init (0);
3851 else
3853 char type[14];
3855 /* We use `I' to indicate initialization and `D' to indicate
3856 destruction. */
3857 unsigned len = sprintf (type, "sub_%c", initp ? 'I' : 'D');
3858 if (priority != DEFAULT_INIT_PRIORITY)
3860 char joiner = '_';
3861 #ifdef JOINER
3862 joiner = JOINER;
3863 #endif
3864 type[len++] = joiner;
3865 sprintf (type + len, "%.5u", priority);
3867 name = get_file_function_name (type);
3870 tree fntype = build_function_type (void_type_node, void_list_node);
3871 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
3872 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
3873 if (is_module_init)
3875 SET_DECL_ASSEMBLER_NAME (fndecl, name);
3876 TREE_PUBLIC (fndecl) = true;
3877 determine_visibility (fndecl);
3879 else
3880 TREE_PUBLIC (fndecl) = 0;
3881 start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3883 /* Mark as artificial because it's not explicitly in the user's
3884 source code. */
3885 DECL_ARTIFICIAL (current_function_decl) = 1;
3887 /* Mark this declaration as used to avoid spurious warnings. */
3888 TREE_USED (current_function_decl) = 1;
3890 /* Mark this function as a global constructor or destructor. */
3891 if (initp)
3892 DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3893 else
3894 DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3896 tree body = begin_compound_stmt (BCS_FN_BODY);
3898 if (is_module_init && has_body)
3900 // If the function is going to be empty, don't emit idempotency.
3901 // 'static bool __in_chrg = false;
3902 // if (__inchrg) return;
3903 // __inchrg = true
3904 tree var = build_lang_decl (VAR_DECL, in_charge_identifier,
3905 boolean_type_node);
3906 DECL_CONTEXT (var) = fndecl;
3907 DECL_ARTIFICIAL (var) = true;
3908 TREE_STATIC (var) = true;
3909 pushdecl (var);
3910 cp_finish_decl (var, NULL_TREE, false, NULL_TREE, 0);
3912 tree if_stmt = begin_if_stmt ();
3913 finish_if_stmt_cond (var, if_stmt);
3914 finish_return_stmt (NULL_TREE);
3915 finish_then_clause (if_stmt);
3916 finish_if_stmt (if_stmt);
3918 tree assign = build2 (MODIFY_EXPR, boolean_type_node,
3919 var, boolean_true_node);
3920 TREE_SIDE_EFFECTS (assign) = true;
3921 finish_expr_stmt (assign);
3924 return body;
3927 /* Finish a global constructor or destructor. Add it to the global
3928 ctors or dtors, if STARTP is true. */
3930 static tree
3931 finish_objects (bool initp, unsigned priority, tree body, bool startp)
3933 /* Finish up. */
3934 finish_compound_stmt (body);
3935 tree fn = finish_function (/*inline_p=*/false);
3937 if (!startp)
3938 ; // Neither ctor nor dtor I be.
3939 else if (initp)
3941 DECL_STATIC_CONSTRUCTOR (fn) = 1;
3942 decl_init_priority_insert (fn, priority);
3944 else
3946 DECL_STATIC_DESTRUCTOR (fn) = 1;
3947 decl_fini_priority_insert (fn, priority);
3950 return fn;
3953 /* The name of the function we create to handle initializations and
3954 destructions for objects with static storage duration. */
3955 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
3957 /* Begins the generation of the function that will handle all
3958 initialization or destruction of objects with static storage
3959 duration at PRIORITY.
3961 It is assumed that this function will only be called once. */
3963 static tree
3964 start_partial_init_fini_fn (bool initp, unsigned priority, unsigned count)
3966 char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
3968 /* Create the identifier for this function. It will be of the form
3969 SSDF_IDENTIFIER_<number>. */
3970 sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
3972 tree type = build_function_type (void_type_node, void_list_node);
3974 /* Create the FUNCTION_DECL itself. */
3975 tree fn = build_lang_decl (FUNCTION_DECL, get_identifier (id), type);
3976 TREE_PUBLIC (fn) = 0;
3977 DECL_ARTIFICIAL (fn) = 1;
3979 /* Put this function in the list of functions to be called from the
3980 static constructors and destructors. */
3981 if (!static_init_fini_fns[initp])
3982 static_init_fini_fns[initp] = priority_map_t::create_ggc ();
3983 auto &slot = static_init_fini_fns[initp]->get_or_insert (priority);
3984 slot = tree_cons (fn, NULL_TREE, slot);
3986 /* Put the function in the global scope. */
3987 pushdecl (fn);
3989 /* Start the function itself. This is equivalent to declaring the
3990 function as:
3992 static void __ssdf (int __initialize_p, init __priority_p);
3994 It is static because we only need to call this function from the
3995 various constructor and destructor functions for this module. */
3996 start_preparsed_function (fn, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3998 /* Set up the scope of the outermost block in the function. */
3999 return begin_compound_stmt (BCS_FN_BODY);
4002 /* Finish the generation of the function which performs initialization
4003 or destruction of objects with static storage duration. */
4005 static void
4006 finish_partial_init_fini_fn (tree body)
4008 /* Close out the function. */
4009 finish_compound_stmt (body);
4010 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4013 /* The effective initialization priority of a DECL. */
4015 #define DECL_EFFECTIVE_INIT_PRIORITY(decl) \
4016 ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
4017 ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
4019 /* Whether a DECL needs a guard to protect it against multiple
4020 initialization. */
4022 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl) \
4023 || DECL_ONE_ONLY (decl) \
4024 || DECL_WEAK (decl)))
4026 /* Walks the initializer list of a global variable and looks for
4027 temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
4028 and that have their DECL_CONTEXT() == NULL. For each such
4029 temporary variable, set their DECL_CONTEXT() to CTX -- the
4030 initializing function. This is necessary because otherwise some
4031 optimizers (enabled by -O2 -fprofile-arcs) might crash when trying
4032 to refer to a temporary variable that does not have its
4033 DECL_CONTEXT() properly set. */
4035 static tree
4036 fix_temporary_vars_context_r (tree *node,
4037 int * /*unused*/,
4038 void *ctx)
4040 if (TREE_CODE (*node) == BIND_EXPR)
4041 for (tree var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
4042 if (VAR_P (var) && !DECL_NAME (var)
4043 && DECL_ARTIFICIAL (var) && !DECL_CONTEXT (var))
4044 DECL_CONTEXT (var) = tree (ctx);
4046 return NULL_TREE;
4049 /* Set up to handle the initialization or destruction of DECL. If
4050 INITP is nonzero, we are initializing the variable. Otherwise, we
4051 are destroying it. */
4053 static void
4054 one_static_initialization_or_destruction (bool initp, tree decl, tree init)
4056 /* If we are supposed to destruct and there's a trivial destructor,
4057 nothing has to be done. */
4058 gcc_checking_assert (init || !TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)));
4060 /* Trick the compiler into thinking we are at the file and line
4061 where DECL was declared so that error-messages make sense, and so
4062 that the debugger will show somewhat sensible file and line
4063 information. */
4064 input_location = DECL_SOURCE_LOCATION (decl);
4066 /* Make sure temporary variables in the initialiser all have
4067 their DECL_CONTEXT() set to a value different from NULL_TREE.
4068 This can happen when global variables initializers are built.
4069 In that case, the DECL_CONTEXT() of the global variables _AND_ of all
4070 the temporary variables that might have been generated in the
4071 accompanying initializers is NULL_TREE, meaning the variables have been
4072 declared in the global namespace.
4073 What we want to do here is to fix that and make sure the DECL_CONTEXT()
4074 of the temporaries are set to the current function decl. */
4075 cp_walk_tree_without_duplicates (&init,
4076 fix_temporary_vars_context_r,
4077 current_function_decl);
4079 /* Because of:
4081 [class.access.spec]
4083 Access control for implicit calls to the constructors,
4084 the conversion functions, or the destructor called to
4085 create and destroy a static data member is performed as
4086 if these calls appeared in the scope of the member's
4087 class.
4089 we pretend we are in a static member function of the class of
4090 which the DECL is a member. */
4091 if (member_p (decl))
4093 DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
4094 DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
4097 /* Assume we don't need a guard. */
4098 tree guard_if_stmt = NULL_TREE;
4100 /* We need a guard if this is an object with external linkage that
4101 might be initialized in more than one place. (For example, a
4102 static data member of a template, when the data member requires
4103 construction.) */
4104 if (NEEDS_GUARD_P (decl))
4106 tree guard = get_guard (decl);
4107 tree guard_cond;
4109 if (flag_use_cxa_atexit)
4111 /* When using __cxa_atexit, we just check the GUARD as we
4112 would for a local static. We never try to destroy
4113 anything from a static destructor. */
4114 gcc_assert (initp);
4115 guard_cond = get_guard_cond (guard, false);
4117 else
4119 /* If we don't have __cxa_atexit, then we will be running
4120 destructors from .fini sections, or their equivalents.
4121 So, we need to know how many times we've tried to
4122 initialize this object. We do initializations only if
4123 the GUARD was or becomes zero (initp vs !initp
4124 respectively). */
4125 guard_cond = cp_build_unary_op (initp ? POSTINCREMENT_EXPR
4126 : PREDECREMENT_EXPR,
4127 guard,
4128 /*noconvert=*/true,
4129 tf_warning_or_error);
4130 guard_cond = cp_build_binary_op (input_location, EQ_EXPR, guard_cond,
4131 integer_zero_node,
4132 tf_warning_or_error);
4135 guard_if_stmt = begin_if_stmt ();
4136 finish_if_stmt_cond (guard_cond, guard_if_stmt);
4138 if (flag_use_cxa_atexit)
4139 /* Set the GUARD now. */
4140 finish_expr_stmt (set_guard (guard));
4143 /* Perform the initialization or destruction. */
4144 if (initp)
4146 if (init)
4148 finish_expr_stmt (init);
4149 if (sanitize_flags_p (SANITIZE_ADDRESS, decl))
4150 if (varpool_node *vnode = varpool_node::get (decl))
4151 vnode->dynamically_initialized = 1;
4154 /* If we're using __cxa_atexit, register a function that calls the
4155 destructor for the object. */
4156 if (flag_use_cxa_atexit)
4157 finish_expr_stmt (register_dtor_fn (decl));
4159 else
4160 finish_expr_stmt (build_cleanup (decl));
4162 /* Finish the guard if-stmt, if necessary. */
4163 if (guard_if_stmt)
4165 finish_then_clause (guard_if_stmt);
4166 finish_if_stmt (guard_if_stmt);
4169 /* Now that we're done with DECL we don't need to pretend to be a
4170 member of its class any longer. */
4171 DECL_CONTEXT (current_function_decl) = NULL_TREE;
4172 DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
4175 /* Generate code to do the initialization or destruction of the decls in VARS,
4176 a TREE_LIST of VAR_DECL with static storage duration.
4177 Whether initialization or destruction is performed is specified by INITP. */
4179 static void
4180 emit_partial_init_fini_fn (bool initp, unsigned priority, tree vars,
4181 unsigned counter, location_t locus)
4183 input_location = locus;
4184 tree body = start_partial_init_fini_fn (initp, priority, counter);
4186 for (tree node = vars; node; node = TREE_CHAIN (node))
4187 /* Do one initialization or destruction. */
4188 one_static_initialization_or_destruction (initp, TREE_VALUE (node),
4189 TREE_PURPOSE (node));
4191 /* Finish up the static storage duration function for this
4192 round. */
4193 input_location = locus;
4194 finish_partial_init_fini_fn (body);
4197 /* VARS is a list of variables with static storage duration which may
4198 need initialization and/or finalization. Remove those variables
4199 that don't really need to be initialized or finalized, and return
4200 the resulting list. The order in which the variables appear in
4201 VARS is in reverse order of the order in which they should actually
4202 be initialized. That order is preserved. */
4204 static tree
4205 prune_vars_needing_no_initialization (tree *vars)
4207 tree *var = vars;
4208 tree result = NULL_TREE;
4210 while (*var)
4212 tree t = *var;
4213 tree decl = TREE_VALUE (t);
4214 tree init = TREE_PURPOSE (t);
4216 /* Deal gracefully with error. */
4217 if (error_operand_p (decl))
4219 var = &TREE_CHAIN (t);
4220 continue;
4223 /* The only things that can be initialized are variables. */
4224 gcc_assert (VAR_P (decl));
4226 /* If this object is not defined, we don't need to do anything
4227 here. */
4228 if (DECL_EXTERNAL (decl))
4230 var = &TREE_CHAIN (t);
4231 continue;
4234 /* Also, if the initializer already contains errors, we can bail
4235 out now. */
4236 if (init && TREE_CODE (init) == TREE_LIST
4237 && value_member (error_mark_node, init))
4239 var = &TREE_CHAIN (t);
4240 continue;
4243 /* This variable is going to need initialization and/or
4244 finalization, so we add it to the list. */
4245 *var = TREE_CHAIN (t);
4246 TREE_CHAIN (t) = result;
4247 result = t;
4250 return result;
4253 /* Split VAR_LIST by init priority and add into PARTS hash table.
4254 This reverses the variable ordering. */
4256 void
4257 partition_vars_for_init_fini (tree var_list, priority_map_t *(&parts)[2])
4259 for (auto node = var_list; node; node = TREE_CHAIN (node))
4261 tree decl = TREE_VALUE (node);
4262 tree init = TREE_PURPOSE (node);
4263 bool has_cleanup = !TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl));
4264 unsigned priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
4266 if (init || (flag_use_cxa_atexit && has_cleanup))
4268 // Add to initialization list.
4269 if (!parts[true])
4270 parts[true] = priority_map_t::create_ggc ();
4271 auto &slot = parts[true]->get_or_insert (priority);
4272 slot = tree_cons (init, decl, slot);
4275 if (!flag_use_cxa_atexit && has_cleanup)
4277 // Add to finalization list.
4278 if (!parts[false])
4279 parts[false] = priority_map_t::create_ggc ();
4280 auto &slot = parts[false]->get_or_insert (priority);
4281 slot = tree_cons (NULL_TREE, decl, slot);
4286 /* Make sure we have told the back end about all the variables in
4287 VARS. */
4289 static void
4290 write_out_vars (tree vars)
4292 tree v;
4294 for (v = vars; v; v = TREE_CHAIN (v))
4296 tree var = TREE_VALUE (v);
4297 if (!var_finalized_p (var))
4299 import_export_decl (var);
4300 rest_of_decl_compilation (var, 1, 1);
4305 /* Generate a static constructor or destructor that calls the given
4306 init/fini fns at the indicated priority. */
4308 static void
4309 generate_ctor_or_dtor_function (bool initp, unsigned priority,
4310 tree fns, location_t locus)
4312 input_location = locus;
4313 tree body = start_objects (initp, priority, bool (fns));
4315 if (fns)
4317 /* To make sure dynamic construction doesn't access globals from
4318 other compilation units where they might not be yet
4319 constructed, for -fsanitize=address insert
4320 __asan_before_dynamic_init call that prevents access to
4321 either all global variables that need construction in other
4322 compilation units, or at least those that haven't been
4323 initialized yet. Variables that need dynamic construction in
4324 the current compilation unit are kept accessible. */
4325 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4326 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
4328 /* Call the static init/fini functions. */
4329 for (tree node = fns; node; node = TREE_CHAIN (node))
4331 tree fn = TREE_PURPOSE (node);
4333 // We should never find a pure or constant cdtor.
4334 gcc_checking_assert (!(flags_from_decl_or_type (fn)
4335 & (ECF_CONST | ECF_PURE)));
4337 tree call = cp_build_function_call_nary (fn, tf_warning_or_error,
4338 NULL_TREE);
4339 finish_expr_stmt (call);
4342 /* Revert what __asan_before_dynamic_init did by calling
4343 __asan_after_dynamic_init. */
4344 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4345 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
4348 /* Close out the function, and arrange for it to be called at init
4349 or fini time, if non-empty. (Even non-nop module initializer
4350 functions need this, as we cannot guarantee the module is
4351 imported somewhere in the program.) */
4352 expand_or_defer_fn (finish_objects (initp, priority, body, fns != NULL_TREE));
4355 /* Return C++ property of T, based on given operation OP. */
4357 static int
4358 cpp_check (tree t, cpp_operation op)
4360 switch (op)
4362 case HAS_DEPENDENT_TEMPLATE_ARGS:
4364 tree ti = CLASSTYPE_TEMPLATE_INFO (t);
4365 if (!ti)
4366 return 0;
4367 ++processing_template_decl;
4368 const bool dep = any_dependent_template_arguments_p (TI_ARGS (ti));
4369 --processing_template_decl;
4370 return dep;
4372 case IS_ABSTRACT:
4373 return DECL_PURE_VIRTUAL_P (t);
4374 case IS_ASSIGNMENT_OPERATOR:
4375 return DECL_ASSIGNMENT_OPERATOR_P (t);
4376 case IS_CONSTRUCTOR:
4377 return DECL_CONSTRUCTOR_P (t);
4378 case IS_DESTRUCTOR:
4379 return DECL_DESTRUCTOR_P (t);
4380 case IS_COPY_CONSTRUCTOR:
4381 return DECL_COPY_CONSTRUCTOR_P (t);
4382 case IS_MOVE_CONSTRUCTOR:
4383 return DECL_MOVE_CONSTRUCTOR_P (t);
4384 case IS_TEMPLATE:
4385 return TREE_CODE (t) == TEMPLATE_DECL;
4386 case IS_TRIVIAL:
4387 return trivial_type_p (t);
4388 default:
4389 return 0;
4393 /* Collect source file references recursively, starting from NAMESPC. */
4395 static void
4396 collect_source_refs (tree namespc)
4398 /* Iterate over names in this name space. */
4399 for (tree t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
4400 if (DECL_IS_UNDECLARED_BUILTIN (t))
4402 else if (TREE_CODE (t) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (t))
4403 collect_source_refs (t);
4404 else
4405 collect_source_ref (DECL_SOURCE_FILE (t));
4408 /* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
4409 starting from NAMESPC. */
4411 static void
4412 collect_ada_namespace (tree namespc, const char *source_file)
4414 tree decl = NAMESPACE_LEVEL (namespc)->names;
4416 /* Collect decls from this namespace. This will skip
4417 NAMESPACE_DECLs (both aliases and regular, it cannot tell). */
4418 collect_ada_nodes (decl, source_file);
4420 /* Now scan for namespace children, and dump them. */
4421 for (; decl; decl = TREE_CHAIN (decl))
4422 if (TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl))
4423 collect_ada_namespace (decl, source_file);
4426 /* Returns true iff there is a definition available for variable or
4427 function DECL. */
4429 bool
4430 decl_defined_p (tree decl)
4432 if (TREE_CODE (decl) == FUNCTION_DECL)
4433 return (DECL_INITIAL (decl) != NULL_TREE
4434 /* A pending instantiation of a friend temploid is defined. */
4435 || (DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
4436 && DECL_INITIAL (DECL_TEMPLATE_RESULT
4437 (DECL_TI_TEMPLATE (decl)))));
4438 else
4440 gcc_assert (VAR_P (decl));
4441 return !DECL_EXTERNAL (decl);
4445 /* Nonzero for a VAR_DECL whose value can be used in a constant expression.
4447 [expr.const]
4449 An integral constant-expression can only involve ... const
4450 variables of integral or enumeration types initialized with
4451 constant expressions ...
4453 C++0x also allows constexpr variables and temporaries initialized
4454 with constant expressions. We handle the former here, but the latter
4455 are just folded away in cxx_eval_constant_expression.
4457 The standard does not require that the expression be non-volatile.
4458 G++ implements the proposed correction in DR 457. */
4460 bool
4461 decl_constant_var_p (tree decl)
4463 if (!decl_maybe_constant_var_p (decl))
4464 return false;
4466 /* We don't know if a template static data member is initialized with
4467 a constant expression until we instantiate its initializer. Even
4468 in the case of a constexpr variable, we can't treat it as a
4469 constant until its initializer is complete in case it's used in
4470 its own initializer. */
4471 maybe_instantiate_decl (decl);
4472 return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
4475 /* Returns true if DECL could be a symbolic constant variable, depending on
4476 its initializer. */
4478 bool
4479 decl_maybe_constant_var_p (tree decl)
4481 tree type = TREE_TYPE (decl);
4482 if (!VAR_P (decl))
4483 return false;
4484 if (DECL_DECLARED_CONSTEXPR_P (decl) && !TREE_THIS_VOLATILE (decl))
4485 return true;
4486 if (DECL_HAS_VALUE_EXPR_P (decl))
4487 /* A proxy isn't constant. */
4488 return false;
4489 if (TYPE_REF_P (type))
4490 /* References can be constant. */;
4491 else if (CP_TYPE_CONST_NON_VOLATILE_P (type)
4492 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4493 /* And const integers. */;
4494 else
4495 return false;
4497 if (DECL_INITIAL (decl)
4498 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
4499 /* We know the initializer, and it isn't constant. */
4500 return false;
4501 else
4502 return true;
4505 /* Complain that DECL uses a type with no linkage. In C++98 mode this is
4506 called from grokfndecl and grokvardecl; in all modes it is called from
4507 cp_write_global_declarations. */
4509 void
4510 no_linkage_error (tree decl)
4512 if (cxx_dialect >= cxx11
4513 && (decl_defined_p (decl)
4514 /* Treat templates which limit_bad_template_recursion decided
4515 not to instantiate as if they were defined. */
4516 || (errorcount + sorrycount > 0
4517 && DECL_LANG_SPECIFIC (decl)
4518 && DECL_TEMPLATE_INFO (decl)
4519 && warning_suppressed_p (decl /* What warning? */))))
4520 /* In C++11 it's ok if the decl is defined. */
4521 return;
4523 if (DECL_LANG_SPECIFIC (decl) && DECL_MODULE_IMPORT_P (decl))
4524 /* An imported decl is ok. */
4525 return;
4527 tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
4528 if (t == NULL_TREE)
4529 /* The type that got us on no_linkage_decls must have gotten a name for
4530 linkage purposes. */;
4531 else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
4532 // FIXME: This is now invalid, as a DR to c++98
4533 /* The type might end up having a typedef name for linkage purposes. */
4534 vec_safe_push (no_linkage_decls, decl);
4535 else if (TYPE_UNNAMED_P (t))
4537 bool d = false;
4538 auto_diagnostic_group grp;
4539 if (cxx_dialect >= cxx11)
4540 d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
4541 "unnamed type, is used but never defined", decl);
4542 else if (DECL_EXTERN_C_P (decl))
4543 /* Allow this; it's pretty common in C. */;
4544 else if (VAR_P (decl))
4545 /* DRs 132, 319 and 389 seem to indicate types with
4546 no linkage can only be used to declare extern "C"
4547 entities. Since it's not always an error in the
4548 ISO C++ 90 Standard, we only issue a warning. */
4549 d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "unnamed type "
4550 "with no linkage used to declare variable %q#D with "
4551 "linkage", decl);
4552 else
4553 d = permerror (DECL_SOURCE_LOCATION (decl), "unnamed type with no "
4554 "linkage used to declare function %q#D with linkage",
4555 decl);
4556 if (d && is_typedef_decl (TYPE_NAME (t)))
4557 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
4558 "to the unqualified type, so it is not used for linkage",
4559 TYPE_NAME (t));
4561 else if (cxx_dialect >= cxx11)
4563 if (VAR_P (decl) || !DECL_PURE_VIRTUAL_P (decl))
4564 permerror (DECL_SOURCE_LOCATION (decl),
4565 "%q#D, declared using local type "
4566 "%qT, is used but never defined", decl, t);
4568 else if (VAR_P (decl))
4569 warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
4570 "used to declare variable %q#D with linkage", t, decl);
4571 else
4572 permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
4573 "to declare function %q#D with linkage", t, decl);
4576 /* Collect declarations from all namespaces relevant to SOURCE_FILE. */
4578 static void
4579 collect_all_refs (const char *source_file)
4581 collect_ada_namespace (global_namespace, source_file);
4584 /* Clear DECL_EXTERNAL for NODE. */
4586 static bool
4587 clear_decl_external (struct cgraph_node *node, void * /*data*/)
4589 DECL_EXTERNAL (node->decl) = 0;
4590 return false;
4593 /* Build up the function to run dynamic initializers for thread_local
4594 variables in this translation unit and alias the init functions for the
4595 individual variables to it. */
4597 static void
4598 handle_tls_init (void)
4600 tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
4601 if (vars == NULL_TREE)
4602 return;
4604 location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
4606 write_out_vars (vars);
4608 tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
4609 boolean_type_node);
4610 TREE_PUBLIC (guard) = false;
4611 TREE_STATIC (guard) = true;
4612 DECL_ARTIFICIAL (guard) = true;
4613 DECL_IGNORED_P (guard) = true;
4614 TREE_USED (guard) = true;
4615 CP_DECL_THREAD_LOCAL_P (guard) = true;
4616 set_decl_tls_model (guard, decl_default_tls_model (guard));
4617 pushdecl_top_level_and_finish (guard, NULL_TREE);
4619 tree fn = get_local_tls_init_fn (loc);
4620 start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
4621 tree body = begin_function_body ();
4622 tree if_stmt = begin_if_stmt ();
4623 tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
4624 tf_warning_or_error);
4625 finish_if_stmt_cond (cond, if_stmt);
4626 finish_expr_stmt (cp_build_modify_expr (loc, guard, NOP_EXPR,
4627 boolean_true_node,
4628 tf_warning_or_error));
4629 for (; vars; vars = TREE_CHAIN (vars))
4631 tree var = TREE_VALUE (vars);
4632 tree init = TREE_PURPOSE (vars);
4633 one_static_initialization_or_destruction (/*initp=*/true, var, init);
4635 /* Output init aliases even with -fno-extern-tls-init. */
4636 if (TARGET_SUPPORTS_ALIASES && TREE_PUBLIC (var))
4638 tree single_init_fn = get_tls_init_fn (var);
4639 if (single_init_fn == NULL_TREE)
4640 continue;
4641 cgraph_node *alias
4642 = cgraph_node::get_create (fn)->create_same_body_alias
4643 (single_init_fn, fn);
4644 gcc_assert (alias != NULL);
4648 finish_then_clause (if_stmt);
4649 finish_if_stmt (if_stmt);
4650 finish_function_body (body);
4651 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4654 /* We're at the end of compilation, so generate any mangling aliases that
4655 we've been saving up, if DECL is going to be output and ID2 isn't
4656 already taken by another declaration. */
4658 static void
4659 generate_mangling_alias (tree decl, tree id2)
4661 struct cgraph_node *n = NULL;
4663 if (TREE_CODE (decl) == FUNCTION_DECL)
4665 n = cgraph_node::get (decl);
4666 if (!n)
4667 /* Don't create an alias to an unreferenced function. */
4668 return;
4671 tree *slot
4672 = mangled_decls->find_slot_with_hash (id2, IDENTIFIER_HASH_VALUE (id2),
4673 INSERT);
4675 /* If there's a declaration already using this mangled name,
4676 don't create a compatibility alias that conflicts. */
4677 if (*slot)
4678 return;
4680 tree alias = make_alias_for (decl, id2);
4681 *slot = alias;
4683 DECL_IGNORED_P (alias) = 1;
4684 TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
4685 DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
4686 if (vague_linkage_p (decl))
4687 DECL_WEAK (alias) = 1;
4689 if (n)
4690 n->create_same_body_alias (alias, decl);
4691 else
4692 varpool_node::create_extra_name_alias (alias, decl);
4695 /* Note that we might want to emit an alias with the symbol ID2 for DECL at
4696 the end of translation, for compatibility across bugs in the mangling
4697 implementation. */
4699 void
4700 note_mangling_alias (tree decl, tree id2)
4702 if (TARGET_SUPPORTS_ALIASES)
4704 if (!defer_mangling_aliases)
4705 generate_mangling_alias (decl, id2);
4706 else
4708 vec_safe_push (mangling_aliases, decl);
4709 vec_safe_push (mangling_aliases, id2);
4714 /* Emit all mangling aliases that were deferred up to this point. */
4716 void
4717 generate_mangling_aliases ()
4719 while (!vec_safe_is_empty (mangling_aliases))
4721 tree id2 = mangling_aliases->pop();
4722 tree decl = mangling_aliases->pop();
4723 generate_mangling_alias (decl, id2);
4725 defer_mangling_aliases = false;
4728 /* Record a mangling of DECL, whose DECL_ASSEMBLER_NAME has just been
4729 set. NEED_WARNING is true if we must warn about collisions. We do
4730 this to spot changes in mangling that may require compatibility
4731 aliases. */
4733 void
4734 record_mangling (tree decl, bool need_warning)
4736 if (!mangled_decls)
4737 mangled_decls = hash_table<mangled_decl_hash>::create_ggc (499);
4739 gcc_checking_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
4740 tree id = DECL_ASSEMBLER_NAME_RAW (decl);
4741 tree *slot
4742 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4743 INSERT);
4745 /* If this is already an alias, remove the alias, because the real
4746 decl takes precedence. */
4747 if (*slot && DECL_ARTIFICIAL (*slot) && DECL_IGNORED_P (*slot))
4748 if (symtab_node *n = symtab_node::get (*slot))
4749 if (n->cpp_implicit_alias)
4751 n->remove ();
4752 *slot = NULL_TREE;
4755 if (!*slot)
4756 *slot = decl;
4757 else if (need_warning)
4759 error_at (DECL_SOURCE_LOCATION (decl),
4760 "mangling of %q#D as %qE conflicts with a previous mangle",
4761 decl, id);
4762 inform (DECL_SOURCE_LOCATION (*slot),
4763 "previous mangling %q#D", *slot);
4764 inform (DECL_SOURCE_LOCATION (decl),
4765 "a later %<-fabi-version=%> (or =0)"
4766 " avoids this error with a change in mangling");
4767 *slot = decl;
4771 /* The mangled name of DECL is being forcibly changed to NAME. Remove
4772 any existing knowledge of DECL's mangled name meaning DECL. */
4774 void
4775 overwrite_mangling (tree decl, tree name)
4777 if (tree id = DECL_ASSEMBLER_NAME_RAW (decl))
4778 if ((TREE_CODE (decl) == VAR_DECL
4779 || TREE_CODE (decl) == FUNCTION_DECL)
4780 && mangled_decls)
4781 if (tree *slot
4782 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4783 NO_INSERT))
4784 if (*slot == decl)
4786 mangled_decls->clear_slot (slot);
4788 /* If this is an alias, remove it from the symbol table. */
4789 if (DECL_ARTIFICIAL (decl) && DECL_IGNORED_P (decl))
4790 if (symtab_node *n = symtab_node::get (decl))
4791 if (n->cpp_implicit_alias)
4792 n->remove ();
4795 DECL_ASSEMBLER_NAME_RAW (decl) = name;
4798 /* The entire file is now complete. If requested, dump everything
4799 to a file. */
4801 static void
4802 dump_tu (void)
4804 dump_flags_t flags;
4805 if (FILE *stream = dump_begin (raw_dump_id, &flags))
4807 dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4808 dump_end (raw_dump_id, stream);
4812 static location_t locus_at_end_of_parsing;
4814 /* Check the deallocation functions for CODE to see if we want to warn that
4815 only one was defined. */
4817 static void
4818 maybe_warn_sized_delete (enum tree_code code)
4820 tree sized = NULL_TREE;
4821 tree unsized = NULL_TREE;
4823 for (ovl_iterator iter (get_global_binding (ovl_op_identifier (false, code)));
4824 iter; ++iter)
4826 tree fn = *iter;
4827 /* We're only interested in usual deallocation functions. */
4828 if (!usual_deallocation_fn_p (fn))
4829 continue;
4830 if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4831 unsized = fn;
4832 else
4833 sized = fn;
4835 if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
4836 warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
4837 "the program should also define %qD", sized);
4838 else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
4839 warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
4840 "the program should also define %qD", unsized);
4843 /* Check the global deallocation functions to see if we want to warn about
4844 defining unsized without sized (or vice versa). */
4846 static void
4847 maybe_warn_sized_delete ()
4849 if (!flag_sized_deallocation || !warn_sized_deallocation)
4850 return;
4851 maybe_warn_sized_delete (DELETE_EXPR);
4852 maybe_warn_sized_delete (VEC_DELETE_EXPR);
4855 /* Earlier we left PTRMEM_CST in variable initializers alone so that we could
4856 look them up when evaluating non-type template parameters. Now we need to
4857 lower them to something the back end can understand. */
4859 static void
4860 lower_var_init ()
4862 varpool_node *node;
4863 FOR_EACH_VARIABLE (node)
4865 tree d = node->decl;
4866 if (tree init = DECL_INITIAL (d))
4867 DECL_INITIAL (d) = cplus_expand_constant (init);
4871 /* This routine is called at the end of compilation.
4872 Its job is to create all the code needed to initialize and
4873 destroy the global aggregates. We do the destruction
4874 first, since that way we only need to reverse the decls once. */
4876 void
4877 c_parse_final_cleanups (void)
4879 size_t i;
4880 tree decl;
4882 locus_at_end_of_parsing = input_location;
4883 at_eof = 1;
4885 /* Bad parse errors. Just forget about it. */
4886 if (! global_bindings_p () || current_class_type
4887 || !vec_safe_is_empty (decl_namespace_list))
4888 return;
4890 /* This is the point to write out a PCH if we're doing that.
4891 In that case we do not want to do anything else. */
4892 if (pch_file)
4894 /* Mangle all symbols at PCH creation time. */
4895 symtab_node *node;
4896 FOR_EACH_SYMBOL (node)
4897 if (! is_a <varpool_node *> (node)
4898 || ! DECL_HARD_REGISTER (node->decl))
4899 DECL_ASSEMBLER_NAME (node->decl);
4900 c_common_write_pch ();
4901 dump_tu ();
4902 /* Ensure even the callers don't try to finalize the CU. */
4903 flag_syntax_only = 1;
4904 return;
4907 timevar_stop (TV_PHASE_PARSING);
4908 timevar_start (TV_PHASE_DEFERRED);
4910 symtab->process_same_body_aliases ();
4912 /* Handle -fdump-ada-spec[-slim] */
4913 if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
4915 collect_source_ref (main_input_filename);
4916 if (!flag_dump_ada_spec_slim)
4917 collect_source_refs (global_namespace);
4919 dump_ada_specs (collect_all_refs, cpp_check);
4922 /* FIXME - huh? was input_line -= 1;*/
4924 /* We now have to write out all the stuff we put off writing out.
4925 These include:
4927 o Template specializations that we have not yet instantiated,
4928 but which are needed.
4929 o Initialization and destruction for non-local objects with
4930 static storage duration. (Local objects with static storage
4931 duration are initialized when their scope is first entered,
4932 and are cleaned up via atexit.)
4933 o Virtual function tables.
4935 All of these may cause others to be needed. For example,
4936 instantiating one function may cause another to be needed, and
4937 generating the initializer for an object may cause templates to be
4938 instantiated, etc., etc. */
4940 emit_support_tinfos ();
4942 /* Track vtables we want to emit that refer to consteval functions. */
4943 auto_vec<tree> consteval_vtables;
4945 int retries = 0;
4946 unsigned ssdf_count = 0;
4947 for (bool reconsider = true; reconsider; retries++)
4949 reconsider = false;
4951 /* If there are templates that we've put off instantiating, do
4952 them now. */
4953 instantiate_pending_templates (retries);
4954 ggc_collect ();
4956 if (header_module_p ())
4957 /* A header modules initializations are handled in its
4958 importer. */
4959 continue;
4961 /* Write out virtual tables as required. Writing out the
4962 virtual table for a template class may cause the
4963 instantiation of members of that class. If we write out
4964 vtables then we remove the class from our list so we don't
4965 have to look at it again. */
4966 tree t;
4967 for (i = keyed_classes->length ();
4968 keyed_classes->iterate (--i, &t);)
4969 if (maybe_emit_vtables (t, consteval_vtables))
4971 reconsider = true;
4972 keyed_classes->unordered_remove (i);
4974 /* The input_location may have been changed during marking of
4975 vtable entries. */
4976 input_location = locus_at_end_of_parsing;
4978 /* Write out needed type info variables. We have to be careful
4979 looping through unemitted decls, because emit_tinfo_decl may
4980 cause other variables to be needed. New elements will be
4981 appended, and we remove from the vector those that actually
4982 get emitted. */
4983 for (i = unemitted_tinfo_decls->length ();
4984 unemitted_tinfo_decls->iterate (--i, &t);)
4985 if (emit_tinfo_decl (t))
4987 reconsider = true;
4988 unemitted_tinfo_decls->unordered_remove (i);
4991 /* The list of objects with static storage duration is built up
4992 in reverse order. We clear STATIC_AGGREGATES so that any new
4993 aggregates added during the initialization of these will be
4994 initialized in the correct order when we next come around the
4995 loop. */
4996 if (tree vars = prune_vars_needing_no_initialization (&static_aggregates))
4998 if (flag_openmp)
4999 /* Add initializer information from VARS into
5000 DYNAMIC_INITIALIZERS. */
5001 for (t = vars; t; t = TREE_CHAIN (t))
5002 hash_map_safe_put<hm_ggc> (dynamic_initializers,
5003 TREE_VALUE (t), TREE_PURPOSE (t));
5005 /* Make sure the back end knows about all the variables. */
5006 write_out_vars (vars);
5008 function_depth++; // Disable GC
5009 priority_map_t *parts[2] = {nullptr, nullptr};
5010 partition_vars_for_init_fini (vars, parts);
5012 for (unsigned initp = 2; initp--;)
5013 if (parts[initp])
5014 for (auto iter : *parts[initp])
5016 auto list = iter.second;
5017 if (initp)
5018 // Partitioning kept the vars in reverse order.
5019 // We only want that for dtors.
5020 list = nreverse (list);
5021 emit_partial_init_fini_fn (initp, iter.first, list,
5022 ssdf_count++,
5023 locus_at_end_of_parsing);
5025 function_depth--; // Re-enable GC
5027 /* All those initializations and finalizations might cause
5028 us to need more inline functions, more template
5029 instantiations, etc. */
5030 reconsider = true;
5033 /* Now do the same for thread_local variables. */
5034 handle_tls_init ();
5036 /* Go through the set of inline functions whose bodies have not
5037 been emitted yet. If out-of-line copies of these functions
5038 are required, emit them. */
5039 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5041 /* Does it need synthesizing? */
5042 if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
5043 && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
5045 /* Even though we're already at the top-level, we push
5046 there again. That way, when we pop back a few lines
5047 hence, all of our state is restored. Otherwise,
5048 finish_function doesn't clean things up, and we end
5049 up with CURRENT_FUNCTION_DECL set. */
5050 push_to_top_level ();
5051 /* The decl's location will mark where it was first
5052 needed. Save that so synthesize method can indicate
5053 where it was needed from, in case of error */
5054 input_location = DECL_SOURCE_LOCATION (decl);
5055 synthesize_method (decl);
5056 pop_from_top_level ();
5057 reconsider = true;
5060 if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
5061 generate_tls_wrapper (decl);
5063 if (!DECL_SAVED_TREE (decl))
5064 continue;
5066 cgraph_node *node = cgraph_node::get_create (decl);
5068 /* We lie to the back end, pretending that some functions
5069 are not defined when they really are. This keeps these
5070 functions from being put out unnecessarily. But, we must
5071 stop lying when the functions are referenced, or if they
5072 are not comdat since they need to be put out now. If
5073 DECL_INTERFACE_KNOWN, then we have already set
5074 DECL_EXTERNAL appropriately, so there's no need to check
5075 again, and we do not want to clear DECL_EXTERNAL if a
5076 previous call to import_export_decl set it.
5078 This is done in a separate for cycle, because if some
5079 deferred function is contained in another deferred
5080 function later in deferred_fns varray,
5081 rest_of_compilation would skip this function and we
5082 really cannot expand the same function twice. */
5083 import_export_decl (decl);
5084 if (DECL_NOT_REALLY_EXTERN (decl)
5085 && DECL_INITIAL (decl)
5086 && decl_needed_p (decl))
5088 if (node->cpp_implicit_alias)
5089 node = node->get_alias_target ();
5091 node->call_for_symbol_thunks_and_aliases (clear_decl_external,
5092 NULL, true);
5093 /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
5094 group, we need to mark all symbols in the same comdat group
5095 that way. */
5096 if (node->same_comdat_group)
5097 for (cgraph_node *next
5098 = dyn_cast<cgraph_node *> (node->same_comdat_group);
5099 next != node;
5100 next = dyn_cast<cgraph_node *> (next->same_comdat_group))
5101 next->call_for_symbol_thunks_and_aliases (clear_decl_external,
5102 NULL, true);
5105 /* If we're going to need to write this function out, and
5106 there's already a body for it, create RTL for it now.
5107 (There might be no body if this is a method we haven't
5108 gotten around to synthesizing yet.) */
5109 if (!DECL_EXTERNAL (decl)
5110 && decl_needed_p (decl)
5111 && !TREE_ASM_WRITTEN (decl)
5112 && !DECL_IMMEDIATE_FUNCTION_P (decl)
5113 && !node->definition)
5115 /* We will output the function; no longer consider it in this
5116 loop. */
5117 DECL_DEFER_OUTPUT (decl) = 0;
5118 /* Generate RTL for this function now that we know we
5119 need it. */
5120 expand_or_defer_fn (decl);
5121 reconsider = true;
5125 if (wrapup_namespace_globals ())
5126 reconsider = true;
5128 /* Static data members are just like namespace-scope globals. */
5129 FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
5131 if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
5132 /* Don't write it out if we haven't seen a definition. */
5133 || DECL_IN_AGGR_P (decl))
5134 continue;
5135 import_export_decl (decl);
5136 /* If this static data member is needed, provide it to the
5137 back end. */
5138 if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
5139 DECL_EXTERNAL (decl) = 0;
5142 if (vec_safe_length (pending_statics) != 0
5143 && wrapup_global_declarations (pending_statics->address (),
5144 pending_statics->length ()))
5145 reconsider = true;
5148 void *module_cookie = finish_module_processing (parse_in);
5150 lower_var_init ();
5152 generate_mangling_aliases ();
5154 /* All used inline functions must have a definition at this point. */
5155 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5157 if (/* Check online inline functions that were actually used. */
5158 DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
5159 /* If the definition actually was available here, then the
5160 fact that the function was not defined merely represents
5161 that for some reason (use of a template repository,
5162 #pragma interface, etc.) we decided not to emit the
5163 definition here. */
5164 && !DECL_INITIAL (decl)
5165 /* A defaulted fn in a header module can be synthesized on
5166 demand later. (In non-header modules we should have
5167 synthesized it above.) */
5168 && !(DECL_DEFAULTED_FN (decl) && header_module_p ())
5169 /* Don't complain if the template was defined. */
5170 && !(DECL_TEMPLATE_INSTANTIATION (decl)
5171 && DECL_INITIAL (DECL_TEMPLATE_RESULT
5172 (template_for_substitution (decl))))
5173 && warning_at (DECL_SOURCE_LOCATION (decl), 0,
5174 "inline function %qD used but never defined", decl))
5175 /* Avoid a duplicate warning from check_global_declaration. */
5176 suppress_warning (decl, OPT_Wunused);
5179 /* So must decls that use a type with no linkage. */
5180 FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
5181 no_linkage_error (decl);
5183 maybe_warn_sized_delete ();
5185 // Place the init fns in the right order. We need to do this now,
5186 // so that any module init will go at the start.
5187 if (static_init_fini_fns[true])
5188 for (auto iter : *static_init_fini_fns[true])
5189 iter.second = nreverse (iter.second);
5191 /* Then, do the Objective-C stuff. This is where all the
5192 Objective-C module stuff gets generated (symtab,
5193 class/protocol/selector lists etc). This must be done after C++
5194 templates, destructors etc. so that selectors used in C++
5195 templates are properly allocated. */
5196 if (c_dialect_objc ())
5197 objc_write_global_declarations ();
5199 bool has_module_inits = module_determine_import_inits ();
5200 bool has_objc_init = c_dialect_objc () && objc_static_init_needed_p ();
5201 if (has_module_inits || has_objc_init)
5203 input_location = locus_at_end_of_parsing;
5204 tree body = start_partial_init_fini_fn (true, DEFAULT_INIT_PRIORITY,
5205 ssdf_count++);
5206 /* For Objective-C++, we may need to initialize metadata found
5207 in this module. This must be done _before_ any other static
5208 initializations. */
5209 if (has_objc_init)
5210 objc_generate_static_init_call (NULL_TREE);
5211 if (has_module_inits)
5212 module_add_import_initializers ();
5213 input_location = locus_at_end_of_parsing;
5214 finish_partial_init_fini_fn (body);
5217 if (module_global_init_needed ())
5219 // Make sure there's a default priority entry.
5220 if (!static_init_fini_fns[true])
5221 static_init_fini_fns[true] = priority_map_t::create_ggc ();
5222 if (static_init_fini_fns[true]->get_or_insert (DEFAULT_INIT_PRIORITY))
5223 has_module_inits = true;
5226 /* Generate initialization and destruction functions for all
5227 priorities for which they are required. They have C-language
5228 linkage. */
5229 push_lang_context (lang_name_c);
5230 for (unsigned initp = 2; initp--;)
5231 if (static_init_fini_fns[initp])
5233 for (auto iter : *static_init_fini_fns[initp])
5234 generate_ctor_or_dtor_function (initp, iter.first, iter.second,
5235 locus_at_end_of_parsing);
5236 static_init_fini_fns[initp] = nullptr;
5238 pop_lang_context ();
5240 fini_modules (parse_in, module_cookie, has_module_inits);
5242 /* Generate any missing aliases. */
5243 maybe_apply_pending_pragma_weaks ();
5245 if (flag_vtable_verify)
5247 vtv_recover_class_info ();
5248 vtv_compute_class_hierarchy_transitive_closure ();
5249 vtv_build_vtable_verify_fndecl ();
5252 perform_deferred_noexcept_checks ();
5254 fini_constexpr ();
5255 cp_tree_c_finish_parsing ();
5256 clear_consteval_vfns (consteval_vtables);
5258 /* The entire file is now complete. If requested, dump everything
5259 to a file. */
5260 dump_tu ();
5262 if (flag_detailed_statistics)
5264 dump_tree_statistics ();
5265 dump_time_statistics ();
5268 timevar_stop (TV_PHASE_DEFERRED);
5269 timevar_start (TV_PHASE_PARSING);
5271 /* Indicate that we're done with front end processing. */
5272 at_eof = 2;
5275 /* Perform any post compilation-proper cleanups for the C++ front-end.
5276 This should really go away. No front-end should need to do
5277 anything past the compilation process. */
5279 void
5280 cxx_post_compilation_parsing_cleanups (void)
5282 timevar_start (TV_PHASE_LATE_PARSING_CLEANUPS);
5284 if (flag_vtable_verify)
5286 /* Generate the special constructor initialization function that
5287 calls __VLTRegisterPairs, and give it a very high
5288 initialization priority. This must be done after
5289 finalize_compilation_unit so that we have accurate
5290 information about which vtable will actually be emitted. */
5291 vtv_generate_init_routine ();
5294 input_location = locus_at_end_of_parsing;
5296 if (flag_checking)
5297 validate_conversion_obstack ();
5299 timevar_stop (TV_PHASE_LATE_PARSING_CLEANUPS);
5302 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
5303 function to call in parse-tree form; it has not yet been
5304 semantically analyzed. ARGS are the arguments to the function.
5305 They have already been semantically analyzed. This may change
5306 ARGS. */
5308 tree
5309 build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
5310 tsubst_flags_t complain)
5312 tree orig_fn;
5313 vec<tree, va_gc> *orig_args = NULL;
5314 tree expr;
5315 tree object;
5317 orig_fn = fn;
5318 object = TREE_OPERAND (fn, 0);
5320 if (processing_template_decl)
5322 gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
5323 || TREE_CODE (fn) == MEMBER_REF);
5324 if (type_dependent_expression_p (fn)
5325 || any_type_dependent_arguments_p (*args))
5326 return build_min_nt_call_vec (fn, *args);
5328 orig_args = make_tree_vector_copy (*args);
5330 /* Transform the arguments and add the implicit "this"
5331 parameter. That must be done before the FN is transformed
5332 because we depend on the form of FN. */
5333 make_args_non_dependent (*args);
5334 object = build_non_dependent_expr (object);
5335 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5337 if (TREE_CODE (fn) == DOTSTAR_EXPR)
5338 object = cp_build_addr_expr (object, complain);
5339 vec_safe_insert (*args, 0, object);
5341 /* Now that the arguments are done, transform FN. */
5342 fn = build_non_dependent_expr (fn);
5345 /* A qualified name corresponding to a bound pointer-to-member is
5346 represented as an OFFSET_REF:
5348 struct B { void g(); };
5349 void (B::*p)();
5350 void B::g() { (this->*p)(); } */
5351 if (TREE_CODE (fn) == OFFSET_REF)
5353 tree object_addr = cp_build_addr_expr (object, complain);
5354 fn = TREE_OPERAND (fn, 1);
5355 fn = get_member_function_from_ptrfunc (&object_addr, fn,
5356 complain);
5357 vec_safe_insert (*args, 0, object_addr);
5360 if (CLASS_TYPE_P (TREE_TYPE (fn)))
5361 expr = build_op_call (fn, args, complain);
5362 else
5363 expr = cp_build_function_call_vec (fn, args, complain);
5364 if (processing_template_decl && expr != error_mark_node)
5365 expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
5367 if (orig_args != NULL)
5368 release_tree_vector (orig_args);
5370 return expr;
5374 void
5375 check_default_args (tree x)
5377 tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
5378 bool saw_def = false;
5379 bool noted_first_def = false;
5380 int idx_of_first_default_arg = 0;
5381 location_t loc_of_first_default_arg = UNKNOWN_LOCATION;
5382 int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
5383 tree fndecl = STRIP_TEMPLATE (x);
5384 auto_diagnostic_group d;
5385 for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
5387 if (TREE_PURPOSE (arg))
5389 if (!saw_def)
5391 saw_def = true;
5392 idx_of_first_default_arg = i;
5393 location_t loc = get_fndecl_argument_location (fndecl, i);
5394 if (loc != DECL_SOURCE_LOCATION (x))
5395 loc_of_first_default_arg = loc;
5398 else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
5400 error_at (get_fndecl_argument_location (fndecl, i),
5401 "default argument missing for parameter %P of %q#D", i, x);
5402 if (loc_of_first_default_arg != UNKNOWN_LOCATION
5403 && !noted_first_def)
5405 inform (loc_of_first_default_arg,
5406 "...following parameter %P which has a default argument",
5407 idx_of_first_default_arg);
5408 noted_first_def = true;
5410 TREE_PURPOSE (arg) = error_mark_node;
5415 /* Return true if function DECL can be inlined. This is used to force
5416 instantiation of methods that might be interesting for inlining. */
5417 bool
5418 possibly_inlined_p (tree decl)
5420 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
5421 if (DECL_UNINLINABLE (decl))
5422 return false;
5423 if (!optimize)
5424 return DECL_DECLARED_INLINE_P (decl);
5425 /* When optimizing, we might inline everything when flatten
5426 attribute or heuristics inlining for size or autoinlining
5427 is used. */
5428 return true;
5431 /* If DECL is a function or variable template specialization, instantiate
5432 its definition now. */
5434 void
5435 maybe_instantiate_decl (tree decl)
5437 if (VAR_OR_FUNCTION_DECL_P (decl)
5438 && DECL_LANG_SPECIFIC (decl)
5439 && DECL_TEMPLATE_INFO (decl)
5440 && !DECL_DECLARED_CONCEPT_P (decl)
5441 && !uses_template_parms (DECL_TI_ARGS (decl)))
5443 /* Instantiating a function will result in garbage collection. We
5444 must treat this situation as if we were within the body of a
5445 function so as to avoid collecting live data only referenced from
5446 the stack (such as overload resolution candidates). */
5447 ++function_depth;
5448 instantiate_decl (decl, /*defer_ok=*/false,
5449 /*expl_inst_class_mem_p=*/false);
5450 --function_depth;
5454 /* Error if the DECL is unavailable (unless this is currently suppressed).
5455 Maybe warn if DECL is deprecated, subject to COMPLAIN. Returns true if
5456 an error or warning was emitted. */
5458 bool
5459 cp_handle_deprecated_or_unavailable (tree decl, tsubst_flags_t complain)
5461 if (!decl)
5462 return false;
5464 if ((complain & tf_error)
5465 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
5467 if (TREE_UNAVAILABLE (decl))
5469 error_unavailable_use (decl, NULL_TREE);
5470 return true;
5472 else
5474 /* Perhaps this is an unavailable typedef. */
5475 if (TYPE_P (decl)
5476 && TYPE_NAME (decl)
5477 && TREE_UNAVAILABLE (TYPE_NAME (decl)))
5479 decl = TYPE_NAME (decl);
5480 /* Don't error within members of a unavailable type. */
5481 if (TYPE_P (decl)
5482 && currently_open_class (decl))
5483 return false;
5485 error_unavailable_use (decl, NULL_TREE);
5486 return true;
5489 /* Carry on to consider deprecatedness. */
5492 if (!(complain & tf_warning)
5493 || deprecated_state == DEPRECATED_SUPPRESS
5494 || deprecated_state == UNAVAILABLE_DEPRECATED_SUPPRESS)
5495 return false;
5497 if (!TREE_DEPRECATED (decl))
5499 /* Perhaps this is a deprecated typedef. */
5500 if (TYPE_P (decl) && TYPE_NAME (decl))
5501 decl = TYPE_NAME (decl);
5503 if (!TREE_DEPRECATED (decl))
5504 return false;
5507 /* Don't warn within members of a deprecated type. */
5508 if (TYPE_P (decl)
5509 && currently_open_class (decl))
5510 return false;
5512 bool warned = false;
5513 if (cxx_dialect >= cxx11
5514 && DECL_P (decl)
5515 && DECL_ARTIFICIAL (decl)
5516 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5517 && copy_fn_p (decl))
5519 /* Don't warn if the flag was disabled around the class definition
5520 (c++/94492). */
5521 if (warning_enabled_at (DECL_SOURCE_LOCATION (decl),
5522 OPT_Wdeprecated_copy))
5524 auto_diagnostic_group d;
5525 tree ctx = DECL_CONTEXT (decl);
5526 tree other = classtype_has_depr_implicit_copy (ctx);
5527 int opt = (DECL_DESTRUCTOR_P (other)
5528 ? OPT_Wdeprecated_copy_dtor
5529 : OPT_Wdeprecated_copy);
5530 warned = warning (opt, "implicitly-declared %qD is deprecated",
5531 decl);
5532 if (warned)
5533 inform (DECL_SOURCE_LOCATION (other),
5534 "because %qT has user-provided %qD",
5535 ctx, other);
5538 else
5539 warned = warn_deprecated_use (decl, NULL_TREE);
5541 return warned;
5544 /* Like above, but takes into account outer scopes. */
5546 void
5547 cp_warn_deprecated_use_scopes (tree scope)
5549 while (scope
5550 && scope != error_mark_node
5551 && scope != global_namespace)
5553 if ((TREE_CODE (scope) == NAMESPACE_DECL || OVERLOAD_TYPE_P (scope))
5554 && cp_handle_deprecated_or_unavailable (scope))
5555 return;
5556 if (TYPE_P (scope))
5557 scope = CP_TYPE_CONTEXT (scope);
5558 else
5559 scope = CP_DECL_CONTEXT (scope);
5563 /* True if DECL or its enclosing scope have unbound template parameters. */
5565 bool
5566 decl_dependent_p (tree decl)
5568 if (DECL_FUNCTION_SCOPE_P (decl)
5569 || TREE_CODE (decl) == CONST_DECL
5570 || TREE_CODE (decl) == USING_DECL
5571 || TREE_CODE (decl) == FIELD_DECL)
5572 decl = CP_DECL_CONTEXT (decl);
5573 if (tree tinfo = get_template_info (decl))
5574 if (any_dependent_template_arguments_p (TI_ARGS (tinfo)))
5575 return true;
5576 if (LAMBDA_FUNCTION_P (decl)
5577 && dependent_type_p (DECL_CONTEXT (decl)))
5578 return true;
5579 return false;
5582 /* [basic.def.odr] A function is named [and therefore odr-used] by an
5583 expression or conversion if it is the selected member of an overload set in
5584 an overload resolution performed as part of forming that expression or
5585 conversion, unless it is a pure virtual function and either the expression
5586 is not an id-expression naming the function with an explicitly qualified
5587 name or the expression forms a pointer to member.
5589 Mostly, we call mark_used in places that actually do something with a
5590 function, like build_over_call. But in a few places we end up with a
5591 non-overloaded FUNCTION_DECL that we aren't going to do any more with, like
5592 convert_to_void. resolve_nondeduced_context is called in those places,
5593 but it's also called in too many other places. */
5595 bool
5596 mark_single_function (tree expr, tsubst_flags_t complain)
5598 expr = maybe_undo_parenthesized_ref (expr);
5599 expr = tree_strip_any_location_wrapper (expr);
5601 if (is_overloaded_fn (expr) == 1
5602 && !mark_used (expr, complain)
5603 && (complain & tf_error))
5604 return false;
5605 return true;
5608 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
5609 If DECL is a specialization or implicitly declared class member,
5610 generate the actual definition. Return false if something goes
5611 wrong, true otherwise. */
5613 bool
5614 mark_used (tree decl, tsubst_flags_t complain /* = tf_warning_or_error */)
5616 /* If we're just testing conversions or resolving overloads, we
5617 don't want any permanent effects like forcing functions to be
5618 output or instantiating templates. */
5619 if ((complain & tf_conv))
5620 return true;
5622 /* If DECL is a BASELINK for a single function, then treat it just
5623 like the DECL for the function. Otherwise, if the BASELINK is
5624 for an overloaded function, we don't know which function was
5625 actually used until after overload resolution. */
5626 if (BASELINK_P (decl))
5628 tree fns = BASELINK_FUNCTIONS (decl);
5629 if (really_overloaded_fn (fns))
5630 return true;
5631 fns = OVL_FIRST (fns);
5632 if (!mark_used (fns, complain))
5633 return false;
5634 /* We might have deduced its return type. */
5635 TREE_TYPE (decl) = TREE_TYPE (fns);
5636 return true;
5639 if (!DECL_P (decl))
5640 return true;
5642 /* Set TREE_USED for the benefit of -Wunused. */
5643 TREE_USED (decl) = true;
5645 /* And for structured bindings also the underlying decl. */
5646 if (DECL_DECOMPOSITION_P (decl) && DECL_DECOMP_BASE (decl))
5647 TREE_USED (DECL_DECOMP_BASE (decl)) = true;
5649 if (TREE_CODE (decl) == TEMPLATE_DECL)
5650 return true;
5652 if (DECL_CLONED_FUNCTION_P (decl))
5653 TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5655 /* Mark enumeration types as used. */
5656 if (TREE_CODE (decl) == CONST_DECL)
5657 used_types_insert (DECL_CONTEXT (decl));
5659 if (TREE_CODE (decl) == FUNCTION_DECL)
5661 if (DECL_MAYBE_DELETED (decl))
5663 ++function_depth;
5664 maybe_synthesize_method (decl);
5665 --function_depth;
5668 if (DECL_DELETED_FN (decl))
5670 if (DECL_ARTIFICIAL (decl)
5671 && DECL_CONV_FN_P (decl)
5672 && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
5673 /* We mark a lambda conversion op as deleted if we can't
5674 generate it properly; see maybe_add_lambda_conv_op. */
5675 sorry ("converting lambda that uses %<...%> to function pointer");
5676 else if (complain & tf_error)
5678 error ("use of deleted function %qD", decl);
5679 if (!maybe_explain_implicit_delete (decl))
5680 inform (DECL_SOURCE_LOCATION (decl), "declared here");
5682 return false;
5685 if (!maybe_instantiate_noexcept (decl, complain))
5686 return false;
5689 if (VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl))
5691 if (!DECL_LANG_SPECIFIC (decl))
5692 /* An unresolved dependent local extern. */
5693 return true;
5695 DECL_ODR_USED (decl) = 1;
5696 auto alias = DECL_LOCAL_DECL_ALIAS (decl);
5697 if (!alias || alias == error_mark_node)
5698 return true;
5700 /* Process the underlying decl. */
5701 decl = alias;
5702 TREE_USED (decl) = true;
5705 cp_handle_deprecated_or_unavailable (decl, complain);
5707 /* We can only check DECL_ODR_USED on variables or functions with
5708 DECL_LANG_SPECIFIC set, and these are also the only decls that we
5709 might need special handling for. */
5710 if (!VAR_OR_FUNCTION_DECL_P (decl)
5711 || DECL_LANG_SPECIFIC (decl) == NULL
5712 || DECL_THUNK_P (decl))
5714 if (!decl_dependent_p (decl)
5715 && !require_deduced_type (decl, complain))
5716 return false;
5717 return true;
5720 /* We only want to do this processing once. We don't need to keep trying
5721 to instantiate inline templates, because unit-at-a-time will make sure
5722 we get them compiled before functions that want to inline them. */
5723 if (DECL_ODR_USED (decl))
5724 return true;
5726 if (flag_concepts && TREE_CODE (decl) == FUNCTION_DECL
5727 && !constraints_satisfied_p (decl))
5729 if (complain & tf_error)
5731 auto_diagnostic_group d;
5732 error ("use of function %qD with unsatisfied constraints",
5733 decl);
5734 location_t loc = DECL_SOURCE_LOCATION (decl);
5735 inform (loc, "declared here");
5736 diagnose_constraints (loc, decl, NULL_TREE);
5738 return false;
5741 /* If DECL has a deduced return type, we need to instantiate it now to
5742 find out its type. For OpenMP user defined reductions, we need them
5743 instantiated for reduction clauses which inline them by hand directly. */
5744 if (undeduced_auto_decl (decl)
5745 || (TREE_CODE (decl) == FUNCTION_DECL
5746 && DECL_OMP_DECLARE_REDUCTION_P (decl)))
5747 maybe_instantiate_decl (decl);
5749 if (processing_template_decl || in_template_function ())
5750 return true;
5752 /* Check this too in case we're within instantiate_non_dependent_expr. */
5753 if (DECL_TEMPLATE_INFO (decl)
5754 && uses_template_parms (DECL_TI_ARGS (decl)))
5755 return true;
5757 if (!require_deduced_type (decl, complain))
5758 return false;
5760 if (builtin_pack_fn_p (decl))
5762 error ("use of built-in parameter pack %qD outside of a template",
5763 DECL_NAME (decl));
5764 return false;
5767 /* If we don't need a value, then we don't need to synthesize DECL. */
5768 if (cp_unevaluated_operand || in_discarded_stmt)
5769 return true;
5771 DECL_ODR_USED (decl) = 1;
5772 if (DECL_CLONED_FUNCTION_P (decl))
5773 DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5775 /* DR 757: A type without linkage shall not be used as the type of a
5776 variable or function with linkage, unless
5777 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
5778 o the variable or function is not used (3.2 [basic.def.odr]) or is
5779 defined in the same translation unit. */
5780 if (cxx_dialect > cxx98
5781 && decl_linkage (decl) != lk_none
5782 && !DECL_EXTERN_C_P (decl)
5783 && !DECL_ARTIFICIAL (decl)
5784 && !decl_defined_p (decl)
5785 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
5786 vec_safe_push (no_linkage_decls, decl);
5788 if (TREE_CODE (decl) == FUNCTION_DECL
5789 && DECL_DECLARED_INLINE_P (decl)
5790 && !DECL_INITIAL (decl)
5791 && !DECL_ARTIFICIAL (decl)
5792 && !DECL_PURE_VIRTUAL_P (decl))
5793 /* Remember it, so we can check it was defined. */
5794 note_vague_linkage_fn (decl);
5796 /* Is it a synthesized method that needs to be synthesized? */
5797 if (TREE_CODE (decl) == FUNCTION_DECL
5798 && DECL_DEFAULTED_FN (decl)
5799 /* A function defaulted outside the class is synthesized either by
5800 cp_finish_decl or instantiate_decl. */
5801 && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
5802 && ! DECL_INITIAL (decl))
5804 /* Remember the current location for a function we will end up
5805 synthesizing. Then we can inform the user where it was
5806 required in the case of error. */
5807 if (decl_remember_implicit_trigger_p (decl))
5808 DECL_SOURCE_LOCATION (decl) = input_location;
5810 /* Synthesizing an implicitly defined member function will result in
5811 garbage collection. We must treat this situation as if we were
5812 within the body of a function so as to avoid collecting live data
5813 on the stack (such as overload resolution candidates).
5815 We could just let c_parse_final_cleanups handle synthesizing
5816 this function by adding it to deferred_fns, but doing
5817 it at the use site produces better error messages. */
5818 ++function_depth;
5819 synthesize_method (decl);
5820 --function_depth;
5821 /* If this is a synthesized method we don't need to
5822 do the instantiation test below. */
5824 else if (VAR_OR_FUNCTION_DECL_P (decl)
5825 && DECL_TEMPLATE_INFO (decl)
5826 && !DECL_DECLARED_CONCEPT_P (decl)
5827 && (!DECL_EXPLICIT_INSTANTIATION (decl)
5828 || always_instantiate_p (decl)))
5829 /* If this is a function or variable that is an instance of some
5830 template, we now know that we will need to actually do the
5831 instantiation. We check that DECL is not an explicit
5832 instantiation because that is not checked in instantiate_decl.
5834 We put off instantiating functions in order to improve compile
5835 times. Maintaining a stack of active functions is expensive,
5836 and the inliner knows to instantiate any functions it might
5837 need. Therefore, we always try to defer instantiation. */
5839 ++function_depth;
5840 instantiate_decl (decl, /*defer_ok=*/true,
5841 /*expl_inst_class_mem_p=*/false);
5842 --function_depth;
5845 return true;
5848 tree
5849 vtv_start_verification_constructor_init_function (void)
5851 return start_objects (/*initp=*/true, MAX_RESERVED_INIT_PRIORITY - 1, true);
5854 tree
5855 vtv_finish_verification_constructor_init_function (tree body)
5857 return finish_objects (/*initp=*/true, MAX_RESERVED_INIT_PRIORITY - 1, body);
5860 #include "gt-cp-decl2.h"