c++: remove single-parameter version of mark_used
[official-gcc.git] / gcc / cp / decl2.cc
blob9f18466192f54500883b2c801ae7ddec3e2392da
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 tree arg;
1565 /* As we implement alignas using gnu::aligned attribute and
1566 alignas argument is a constant expression, force manifestly
1567 constant evaluation of aligned attribute argument. */
1568 bool manifestly_const_eval
1569 = is_attribute_p ("aligned", get_attribute_name (attr));
1570 for (arg = TREE_VALUE (attr); arg && TREE_CODE (arg) == TREE_LIST;
1571 arg = TREE_CHAIN (arg))
1573 tree expr = TREE_VALUE (arg);
1574 if (EXPR_P (expr))
1575 TREE_VALUE (arg)
1576 = fold_non_dependent_expr (expr, tf_warning_or_error,
1577 manifestly_const_eval);
1582 /* Return the last pushed declaration for the symbol DECL or NULL
1583 when no such declaration exists. */
1585 static tree
1586 find_last_decl (tree decl)
1588 tree last_decl = NULL_TREE;
1590 if (tree name = DECL_P (decl) ? DECL_NAME (decl) : NULL_TREE)
1592 /* Look up the declaration in its scope. */
1593 tree pushed_scope = NULL_TREE;
1594 if (tree ctype = DECL_CONTEXT (decl))
1595 pushed_scope = push_scope (ctype);
1597 last_decl = lookup_name (name);
1599 if (pushed_scope)
1600 pop_scope (pushed_scope);
1602 /* The declaration may be a member conversion operator
1603 or a bunch of overfloads (handle the latter below). */
1604 if (last_decl && BASELINK_P (last_decl))
1605 last_decl = BASELINK_FUNCTIONS (last_decl);
1608 if (!last_decl)
1609 return NULL_TREE;
1611 if (DECL_P (last_decl) || TREE_CODE (last_decl) == OVERLOAD)
1613 /* A set of overloads of the same function. */
1614 for (lkp_iterator iter (last_decl); iter; ++iter)
1616 if (TREE_CODE (*iter) == OVERLOAD)
1617 continue;
1619 tree d = *iter;
1621 /* We can't compare versions in the middle of processing the
1622 attribute that has the version. */
1623 if (TREE_CODE (d) == FUNCTION_DECL
1624 && DECL_FUNCTION_VERSIONED (d))
1625 return NULL_TREE;
1627 if (decls_match (decl, d, /*record_decls=*/false))
1628 return d;
1630 return NULL_TREE;
1633 return NULL_TREE;
1636 /* Like decl_attributes, but handle C++ complexity. */
1638 void
1639 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1641 if (*decl == NULL_TREE || *decl == void_type_node
1642 || *decl == error_mark_node || attributes == error_mark_node)
1643 return;
1645 /* Add implicit "omp declare target" attribute if requested. */
1646 if (vec_safe_length (scope_chain->omp_declare_target_attribute)
1647 && ((VAR_P (*decl)
1648 && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
1649 || TREE_CODE (*decl) == FUNCTION_DECL))
1651 if (VAR_P (*decl)
1652 && DECL_CLASS_SCOPE_P (*decl))
1653 error ("%q+D static data member inside of declare target directive",
1654 *decl);
1655 else if (VAR_P (*decl)
1656 && (processing_template_decl
1657 || !omp_mappable_type (TREE_TYPE (*decl))))
1658 attributes = tree_cons (get_identifier ("omp declare target implicit"),
1659 NULL_TREE, attributes);
1660 else
1662 attributes = tree_cons (get_identifier ("omp declare target"),
1663 NULL_TREE, attributes);
1664 attributes = tree_cons (get_identifier ("omp declare target block"),
1665 NULL_TREE, attributes);
1669 tree late_attrs = NULL_TREE;
1670 if (processing_template_decl)
1672 if (check_for_bare_parameter_packs (attributes))
1673 return;
1674 late_attrs = splice_template_attributes (&attributes, *decl);
1677 cp_check_const_attributes (attributes);
1679 if (flag_openmp || flag_openmp_simd)
1681 bool diagnosed = false;
1682 for (tree *pa = &attributes; *pa; )
1684 if (get_attribute_namespace (*pa) == omp_identifier)
1686 tree name = get_attribute_name (*pa);
1687 if (is_attribute_p ("directive", name)
1688 || is_attribute_p ("sequence", name))
1690 if (!diagnosed)
1692 error ("%<omp::%E%> not allowed to be specified in this "
1693 "context", name);
1694 diagnosed = true;
1696 *pa = TREE_CHAIN (*pa);
1697 continue;
1700 pa = &TREE_CHAIN (*pa);
1704 if (TREE_CODE (*decl) == TEMPLATE_DECL)
1705 decl = &DECL_TEMPLATE_RESULT (*decl);
1707 if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
1709 attributes
1710 = decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
1711 decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
1712 attributes, flags);
1714 else
1716 tree last_decl = find_last_decl (*decl);
1717 decl_attributes (decl, attributes, flags, last_decl);
1720 if (late_attrs)
1721 save_template_attributes (late_attrs, decl, flags);
1723 /* Propagate deprecation out to the template. */
1724 if (TREE_DEPRECATED (*decl))
1725 if (tree ti = get_template_info (*decl))
1727 tree tmpl = TI_TEMPLATE (ti);
1728 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1729 : DECL_TEMPLATE_RESULT (tmpl));
1730 if (*decl == pattern)
1731 TREE_DEPRECATED (tmpl) = true;
1734 /* Likewise, propagate unavailability out to the template. */
1735 if (TREE_UNAVAILABLE (*decl))
1736 if (tree ti = get_template_info (*decl))
1738 tree tmpl = TI_TEMPLATE (ti);
1739 tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1740 : DECL_TEMPLATE_RESULT (tmpl));
1741 if (*decl == pattern)
1742 TREE_UNAVAILABLE (tmpl) = true;
1746 /* Walks through the namespace- or function-scope anonymous union
1747 OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1748 Returns one of the fields for use in the mangled name. */
1750 static tree
1751 build_anon_union_vars (tree type, tree object)
1753 tree main_decl = NULL_TREE;
1754 tree field;
1756 /* Rather than write the code to handle the non-union case,
1757 just give an error. */
1758 if (TREE_CODE (type) != UNION_TYPE)
1760 error_at (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
1761 "anonymous struct not inside named type");
1762 return error_mark_node;
1765 for (field = TYPE_FIELDS (type);
1766 field != NULL_TREE;
1767 field = DECL_CHAIN (field))
1769 tree decl;
1770 tree ref;
1772 if (DECL_ARTIFICIAL (field))
1773 continue;
1774 if (TREE_CODE (field) != FIELD_DECL)
1776 permerror (DECL_SOURCE_LOCATION (field),
1777 "%q#D invalid; an anonymous union can only "
1778 "have non-static data members", field);
1779 continue;
1782 if (TREE_PRIVATE (field))
1783 permerror (DECL_SOURCE_LOCATION (field),
1784 "private member %q#D in anonymous union", field);
1785 else if (TREE_PROTECTED (field))
1786 permerror (DECL_SOURCE_LOCATION (field),
1787 "protected member %q#D in anonymous union", field);
1789 if (processing_template_decl)
1790 ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1791 DECL_NAME (field), NULL_TREE);
1792 else
1793 ref = build_class_member_access_expr (object, field, NULL_TREE,
1794 false, tf_warning_or_error);
1796 if (DECL_NAME (field))
1798 tree base;
1800 decl = build_decl (input_location,
1801 VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1802 DECL_ANON_UNION_VAR_P (decl) = 1;
1803 DECL_ARTIFICIAL (decl) = 1;
1805 base = get_base_address (object);
1806 TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1807 TREE_STATIC (decl) = TREE_STATIC (base);
1808 DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1810 SET_DECL_VALUE_EXPR (decl, ref);
1811 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1813 decl = pushdecl (decl);
1815 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1816 decl = build_anon_union_vars (TREE_TYPE (field), ref);
1817 else
1818 decl = 0;
1820 if (main_decl == NULL_TREE)
1821 main_decl = decl;
1824 return main_decl;
1827 /* Finish off the processing of a UNION_TYPE structure. If the union is an
1828 anonymous union, then all members must be laid out together. PUBLIC_P
1829 is nonzero if this union is not declared static. */
1831 void
1832 finish_anon_union (tree anon_union_decl)
1834 tree type;
1835 tree main_decl;
1836 bool public_p;
1838 if (anon_union_decl == error_mark_node)
1839 return;
1841 type = TREE_TYPE (anon_union_decl);
1842 public_p = TREE_PUBLIC (anon_union_decl);
1844 /* The VAR_DECL's context is the same as the TYPE's context. */
1845 DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1847 if (TYPE_FIELDS (type) == NULL_TREE)
1848 return;
1850 if (public_p)
1852 error ("namespace-scope anonymous aggregates must be static");
1853 return;
1856 main_decl = build_anon_union_vars (type, anon_union_decl);
1857 if (main_decl == error_mark_node)
1858 return;
1859 if (main_decl == NULL_TREE)
1861 pedwarn (input_location, 0, "anonymous union with no members");
1862 return;
1865 if (!processing_template_decl)
1867 /* Use main_decl to set the mangled name. */
1868 DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1869 maybe_commonize_var (anon_union_decl);
1870 if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1872 if (DECL_DISCRIMINATOR_P (anon_union_decl))
1873 determine_local_discriminator (anon_union_decl);
1874 mangle_decl (anon_union_decl);
1876 DECL_NAME (anon_union_decl) = NULL_TREE;
1879 pushdecl (anon_union_decl);
1880 cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
1883 /* Auxiliary functions to make type signatures for
1884 `operator new' and `operator delete' correspond to
1885 what compiler will be expecting. */
1887 tree
1888 coerce_new_type (tree type, location_t loc)
1890 int e = 0;
1891 tree args = TYPE_ARG_TYPES (type);
1893 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1895 if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1897 e = 1;
1898 error_at (loc, "%<operator new%> must return type %qT",
1899 ptr_type_node);
1902 if (args && args != void_list_node)
1904 if (TREE_PURPOSE (args))
1906 /* [basic.stc.dynamic.allocation]
1908 The first parameter shall not have an associated default
1909 argument. */
1910 error_at (loc, "the first parameter of %<operator new%> cannot "
1911 "have a default argument");
1912 /* Throw away the default argument. */
1913 TREE_PURPOSE (args) = NULL_TREE;
1916 if (!same_type_p (TREE_VALUE (args), size_type_node))
1918 e = 2;
1919 args = TREE_CHAIN (args);
1922 else
1923 e = 2;
1925 if (e == 2)
1926 permerror (loc, "%<operator new%> takes type %<size_t%> (%qT) "
1927 "as first parameter", size_type_node);
1929 switch (e)
1931 case 2:
1932 args = tree_cons (NULL_TREE, size_type_node, args);
1933 /* Fall through. */
1934 case 1:
1935 type = (cxx_copy_lang_qualifiers
1936 (build_function_type (ptr_type_node, args),
1937 type));
1938 /* Fall through. */
1939 default:;
1941 return type;
1944 void
1945 coerce_delete_type (tree decl, location_t loc)
1947 int e = 0;
1948 tree type = TREE_TYPE (decl);
1949 tree args = TYPE_ARG_TYPES (type);
1951 gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1953 if (!same_type_p (TREE_TYPE (type), void_type_node))
1955 e = 1;
1956 error_at (loc, "%<operator delete%> must return type %qT",
1957 void_type_node);
1960 tree ptrtype = ptr_type_node;
1961 if (destroying_delete_p (decl))
1963 if (DECL_CLASS_SCOPE_P (decl))
1964 /* If the function is a destroying operator delete declared in class
1965 type C, the type of its first parameter shall be C*. */
1966 ptrtype = build_pointer_type (DECL_CONTEXT (decl));
1967 else
1968 /* A destroying operator delete shall be a class member function named
1969 operator delete. */
1970 error_at (loc,
1971 "destroying %<operator delete%> must be a member function");
1972 const ovl_op_info_t *op = IDENTIFIER_OVL_OP_INFO (DECL_NAME (decl));
1973 if (op->flags & OVL_OP_FLAG_VEC)
1974 error_at (loc, "%<operator delete[]%> cannot be a destroying delete");
1975 if (!usual_deallocation_fn_p (decl))
1976 error_at (loc, "destroying %<operator delete%> must be a usual "
1977 "deallocation function");
1980 if (!args || args == void_list_node
1981 || !same_type_p (TREE_VALUE (args), ptrtype))
1983 e = 2;
1984 if (args && args != void_list_node)
1985 args = TREE_CHAIN (args);
1986 error_at (loc, "%<operator delete%> takes type %qT as first parameter",
1987 ptrtype);
1989 switch (e)
1991 case 2:
1992 args = tree_cons (NULL_TREE, ptrtype, args);
1993 /* Fall through. */
1994 case 1:
1995 type = (cxx_copy_lang_qualifiers
1996 (build_function_type (void_type_node, args),
1997 type));
1998 /* Fall through. */
1999 default:;
2002 TREE_TYPE (decl) = type;
2005 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
2006 and mark them as needed. */
2008 static void
2009 mark_vtable_entries (tree decl, vec<tree> &consteval_vtables)
2011 /* It's OK for the vtable to refer to deprecated virtual functions. */
2012 warning_sentinel w(warn_deprecated_decl);
2014 bool consteval_seen = false;
2016 for (auto &e: CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
2018 tree fnaddr = e.value;
2020 STRIP_NOPS (fnaddr);
2022 if (TREE_CODE (fnaddr) != ADDR_EXPR
2023 && TREE_CODE (fnaddr) != FDESC_EXPR)
2024 /* This entry is an offset: a virtual base class offset, a
2025 virtual call offset, an RTTI offset, etc. */
2026 continue;
2028 tree fn = TREE_OPERAND (fnaddr, 0);
2029 if (TREE_CODE (fn) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (fn))
2031 if (!consteval_seen)
2033 consteval_seen = true;
2034 consteval_vtables.safe_push (decl);
2036 continue;
2038 TREE_ADDRESSABLE (fn) = 1;
2039 /* When we don't have vcall offsets, we output thunks whenever
2040 we output the vtables that contain them. With vcall offsets,
2041 we know all the thunks we'll need when we emit a virtual
2042 function, so we emit the thunks there instead. */
2043 if (DECL_THUNK_P (fn))
2044 use_thunk (fn, /*emit_p=*/0);
2045 /* Set the location, as marking the function could cause
2046 instantiation. We do not need to preserve the incoming
2047 location, as we're called from c_parse_final_cleanups, which
2048 takes care of that. */
2049 input_location = DECL_SOURCE_LOCATION (fn);
2050 mark_used (fn);
2054 /* Replace any consteval functions in vtables with null pointers. */
2056 static void
2057 clear_consteval_vfns (vec<tree> &consteval_vtables)
2059 for (tree vtable : consteval_vtables)
2060 for (constructor_elt &elt : CONSTRUCTOR_ELTS (DECL_INITIAL (vtable)))
2062 tree fn = cp_get_fndecl_from_callee (elt.value, /*fold*/false);
2063 if (fn && DECL_IMMEDIATE_FUNCTION_P (fn))
2064 elt.value = build_zero_cst (vtable_entry_type);
2068 /* Adjust the TLS model on variable DECL if need be, typically after
2069 the linkage of DECL has been modified. */
2071 static void
2072 adjust_var_decl_tls_model (tree decl)
2074 if (CP_DECL_THREAD_LOCAL_P (decl)
2075 && !lookup_attribute ("tls_model", DECL_ATTRIBUTES (decl)))
2076 set_decl_tls_model (decl, decl_default_tls_model (decl));
2079 /* Set DECL up to have the closest approximation of "initialized common"
2080 linkage available. */
2082 void
2083 comdat_linkage (tree decl)
2085 if (flag_weak)
2086 make_decl_one_only (decl, cxx_comdat_group (decl));
2087 else if (TREE_CODE (decl) == FUNCTION_DECL
2088 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2089 /* We can just emit function and compiler-generated variables
2090 statically; having multiple copies is (for the most part) only
2091 a waste of space.
2093 There are two correctness issues, however: the address of a
2094 template instantiation with external linkage should be the
2095 same, independent of what translation unit asks for the
2096 address, and this will not hold when we emit multiple copies of
2097 the function. However, there's little else we can do.
2099 Also, by default, the typeinfo implementation assumes that
2100 there will be only one copy of the string used as the name for
2101 each type. Therefore, if weak symbols are unavailable, the
2102 run-time library should perform a more conservative check; it
2103 should perform a string comparison, rather than an address
2104 comparison. */
2105 TREE_PUBLIC (decl) = 0;
2106 else
2108 /* Static data member template instantiations, however, cannot
2109 have multiple copies. */
2110 if (DECL_INITIAL (decl) == 0
2111 || DECL_INITIAL (decl) == error_mark_node)
2112 DECL_COMMON (decl) = 1;
2113 else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
2115 DECL_COMMON (decl) = 1;
2116 DECL_INITIAL (decl) = error_mark_node;
2118 else if (!DECL_EXPLICIT_INSTANTIATION (decl))
2120 /* We can't do anything useful; leave vars for explicit
2121 instantiation. */
2122 DECL_EXTERNAL (decl) = 1;
2123 DECL_NOT_REALLY_EXTERN (decl) = 0;
2127 if (TREE_PUBLIC (decl))
2128 DECL_COMDAT (decl) = 1;
2130 if (VAR_P (decl))
2131 adjust_var_decl_tls_model (decl);
2134 /* For win32 we also want to put explicit instantiations in
2135 linkonce sections, so that they will be merged with implicit
2136 instantiations; otherwise we get duplicate symbol errors.
2137 For Darwin we do not want explicit instantiations to be
2138 linkonce. */
2140 void
2141 maybe_make_one_only (tree decl)
2143 /* We used to say that this was not necessary on targets that support weak
2144 symbols, because the implicit instantiations will defer to the explicit
2145 one. However, that's not actually the case in SVR4; a strong definition
2146 after a weak one is an error. Also, not making explicit
2147 instantiations one_only means that we can end up with two copies of
2148 some template instantiations. */
2149 if (! flag_weak)
2150 return;
2152 /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
2153 we can get away with not emitting them if they aren't used. We need
2154 to for variables so that cp_finish_decl will update their linkage,
2155 because their DECL_INITIAL may not have been set properly yet. */
2157 if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
2158 || (! DECL_EXPLICIT_INSTANTIATION (decl)
2159 && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
2161 make_decl_one_only (decl, cxx_comdat_group (decl));
2163 if (VAR_P (decl))
2165 varpool_node *node = varpool_node::get_create (decl);
2166 DECL_COMDAT (decl) = 1;
2167 /* Mark it needed so we don't forget to emit it. */
2168 node->forced_by_abi = true;
2169 TREE_USED (decl) = 1;
2171 adjust_var_decl_tls_model (decl);
2176 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
2177 This predicate will give the right answer during parsing of the
2178 function, which other tests may not. */
2180 bool
2181 vague_linkage_p (tree decl)
2183 if (!TREE_PUBLIC (decl))
2185 /* maybe_thunk_body clears TREE_PUBLIC and DECL_ABSTRACT_P on the
2186 maybe-in-charge 'tor variants; in that case we need to check one of
2187 the "clones" for the real linkage. But only in that case; before
2188 maybe_clone_body we haven't yet copied the linkage to the clones. */
2189 if (DECL_MAYBE_IN_CHARGE_CDTOR_P (decl)
2190 && !DECL_ABSTRACT_P (decl)
2191 && DECL_CHAIN (decl)
2192 && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)))
2193 return vague_linkage_p (DECL_CHAIN (decl));
2195 gcc_checking_assert (!DECL_COMDAT (decl));
2196 return false;
2198 /* Unfortunately, import_export_decl has not always been called
2199 before the function is processed, so we cannot simply check
2200 DECL_COMDAT. */
2201 if (DECL_COMDAT (decl)
2202 || (TREE_CODE (decl) == FUNCTION_DECL
2203 && DECL_DECLARED_INLINE_P (decl))
2204 || (DECL_LANG_SPECIFIC (decl)
2205 && DECL_TEMPLATE_INSTANTIATION (decl))
2206 || (VAR_P (decl) && DECL_INLINE_VAR_P (decl)))
2207 return true;
2208 else if (DECL_FUNCTION_SCOPE_P (decl))
2209 /* A local static in an inline effectively has vague linkage. */
2210 return (TREE_STATIC (decl)
2211 && vague_linkage_p (DECL_CONTEXT (decl)));
2212 else
2213 return false;
2216 /* Determine whether or not we want to specifically import or export CTYPE,
2217 using various heuristics. */
2219 static void
2220 import_export_class (tree ctype)
2222 /* -1 for imported, 1 for exported. */
2223 int import_export = 0;
2225 /* It only makes sense to call this function at EOF. The reason is
2226 that this function looks at whether or not the first non-inline
2227 non-abstract virtual member function has been defined in this
2228 translation unit. But, we can't possibly know that until we've
2229 seen the entire translation unit. */
2230 gcc_assert (at_eof);
2232 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
2233 return;
2235 /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
2236 we will have CLASSTYPE_INTERFACE_ONLY set but not
2237 CLASSTYPE_INTERFACE_KNOWN. In that case, we don't want to use this
2238 heuristic because someone will supply a #pragma implementation
2239 elsewhere, and deducing it here would produce a conflict. */
2240 if (CLASSTYPE_INTERFACE_ONLY (ctype))
2241 return;
2243 if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
2244 import_export = -1;
2245 else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
2246 import_export = 1;
2247 else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
2248 && !flag_implicit_templates)
2249 /* For a template class, without -fimplicit-templates, check the
2250 repository. If the virtual table is assigned to this
2251 translation unit, then export the class; otherwise, import
2252 it. */
2253 import_export = -1;
2254 else if (TYPE_POLYMORPHIC_P (ctype))
2256 /* The ABI specifies that the virtual table and associated
2257 information are emitted with the key method, if any. */
2258 tree method = CLASSTYPE_KEY_METHOD (ctype);
2259 /* If weak symbol support is not available, then we must be
2260 careful not to emit the vtable when the key function is
2261 inline. An inline function can be defined in multiple
2262 translation units. If we were to emit the vtable in each
2263 translation unit containing a definition, we would get
2264 multiple definition errors at link-time. */
2265 if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
2266 import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
2269 /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
2270 a definition anywhere else. */
2271 if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
2272 import_export = 0;
2274 /* Allow back ends the chance to overrule the decision. */
2275 if (targetm.cxx.import_export_class)
2276 import_export = targetm.cxx.import_export_class (ctype, import_export);
2278 if (import_export)
2280 SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
2281 CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
2285 /* Return true if VAR has already been provided to the back end; in that
2286 case VAR should not be modified further by the front end. */
2287 static bool
2288 var_finalized_p (tree var)
2290 return varpool_node::get_create (var)->definition;
2293 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
2294 must be emitted in this translation unit. Mark it as such. */
2296 void
2297 mark_needed (tree decl)
2299 TREE_USED (decl) = 1;
2300 if (TREE_CODE (decl) == FUNCTION_DECL)
2302 /* Extern inline functions don't become needed when referenced.
2303 If we know a method will be emitted in other TU and no new
2304 functions can be marked reachable, just use the external
2305 definition. */
2306 struct cgraph_node *node = cgraph_node::get_create (decl);
2307 node->forced_by_abi = true;
2309 /* #pragma interface can call mark_needed for
2310 maybe-in-charge 'tors; mark the clones as well. */
2311 tree clone;
2312 FOR_EACH_CLONE (clone, decl)
2313 mark_needed (clone);
2315 else if (VAR_P (decl))
2317 varpool_node *node = varpool_node::get_create (decl);
2318 /* C++ frontend use mark_decl_references to force COMDAT variables
2319 to be output that might appear dead otherwise. */
2320 node->forced_by_abi = true;
2324 /* DECL is either a FUNCTION_DECL or a VAR_DECL. This function
2325 returns true if a definition of this entity should be provided in
2326 this object file. Callers use this function to determine whether
2327 or not to let the back end know that a definition of DECL is
2328 available in this translation unit. */
2330 bool
2331 decl_needed_p (tree decl)
2333 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2334 /* This function should only be called at the end of the translation
2335 unit. We cannot be sure of whether or not something will be
2336 COMDAT until that point. */
2337 gcc_assert (at_eof);
2339 /* All entities with external linkage that are not COMDAT/EXTERN should be
2340 emitted; they may be referred to from other object files. */
2341 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
2342 return true;
2344 /* Functions marked "dllexport" must be emitted so that they are
2345 visible to other DLLs. */
2346 if (flag_keep_inline_dllexport
2347 && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
2348 return true;
2350 /* When not optimizing, do not bother to produce definitions for extern
2351 symbols. */
2352 if (DECL_REALLY_EXTERN (decl)
2353 && ((TREE_CODE (decl) != FUNCTION_DECL
2354 && !optimize)
2355 || (TREE_CODE (decl) == FUNCTION_DECL
2356 && !opt_for_fn (decl, optimize)))
2357 && !lookup_attribute ("always_inline", decl))
2358 return false;
2360 /* If this entity was used, let the back end see it; it will decide
2361 whether or not to emit it into the object file. */
2362 if (TREE_USED (decl))
2363 return true;
2365 /* Virtual functions might be needed for devirtualization. */
2366 if (flag_devirtualize
2367 && TREE_CODE (decl) == FUNCTION_DECL
2368 && DECL_VIRTUAL_P (decl))
2369 return true;
2371 /* Otherwise, DECL does not need to be emitted -- yet. A subsequent
2372 reference to DECL might cause it to be emitted later. */
2373 return false;
2376 /* If necessary, write out the vtables for the dynamic class CTYPE.
2377 Returns true if any vtables were emitted. */
2379 static bool
2380 maybe_emit_vtables (tree ctype, vec<tree> &consteval_vtables)
2382 tree vtbl;
2383 tree primary_vtbl;
2384 int needed = 0;
2385 varpool_node *current = NULL, *last = NULL;
2387 /* If the vtables for this class have already been emitted there is
2388 nothing more to do. */
2389 primary_vtbl = CLASSTYPE_VTABLES (ctype);
2390 if (var_finalized_p (primary_vtbl))
2391 return false;
2392 /* Ignore dummy vtables made by get_vtable_decl. */
2393 if (TREE_TYPE (primary_vtbl) == void_type_node)
2394 return false;
2396 /* On some targets, we cannot determine the key method until the end
2397 of the translation unit -- which is when this function is
2398 called. */
2399 if (!targetm.cxx.key_method_may_be_inline ())
2400 determine_key_method (ctype);
2402 /* See if any of the vtables are needed. */
2403 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2405 import_export_decl (vtbl);
2406 if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
2407 needed = 1;
2409 if (!needed)
2411 /* If the references to this class' vtables are optimized away,
2412 still emit the appropriate debugging information. See
2413 dfs_debug_mark. */
2414 if (DECL_COMDAT (primary_vtbl)
2415 && CLASSTYPE_DEBUG_REQUESTED (ctype))
2416 note_debug_info_needed (ctype);
2417 return false;
2420 /* The ABI requires that we emit all of the vtables if we emit any
2421 of them. */
2422 for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2424 /* Mark entities references from the virtual table as used. */
2425 mark_vtable_entries (vtbl, consteval_vtables);
2427 if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
2429 vec<tree, va_gc> *cleanups = NULL;
2430 tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
2431 LOOKUP_NORMAL);
2433 /* It had better be all done at compile-time. */
2434 gcc_assert (!expr && !cleanups);
2437 /* Write it out. */
2438 DECL_EXTERNAL (vtbl) = 0;
2439 rest_of_decl_compilation (vtbl, 1, 1);
2441 /* Because we're only doing syntax-checking, we'll never end up
2442 actually marking the variable as written. */
2443 if (flag_syntax_only)
2444 TREE_ASM_WRITTEN (vtbl) = 1;
2445 else if (DECL_ONE_ONLY (vtbl))
2447 current = varpool_node::get_create (vtbl);
2448 if (last)
2449 current->add_to_same_comdat_group (last);
2450 last = current;
2454 /* For abstract classes, the destructor has been removed from the
2455 vtable (in class.cc's build_vtbl_initializer). For a compiler-
2456 generated destructor, it hence might not have been generated in
2457 this translation unit - and with '#pragma interface' it might
2458 never get generated. */
2459 if (CLASSTYPE_PURE_VIRTUALS (ctype)
2460 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (ctype)
2461 && !CLASSTYPE_LAZY_DESTRUCTOR (ctype)
2462 && DECL_DEFAULTED_IN_CLASS_P (CLASSTYPE_DESTRUCTOR (ctype)))
2463 note_vague_linkage_fn (CLASSTYPE_DESTRUCTOR (ctype));
2465 /* Since we're writing out the vtable here, also write the debug
2466 info. */
2467 note_debug_info_needed (ctype);
2469 return true;
2472 /* A special return value from type_visibility meaning internal
2473 linkage. */
2475 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
2477 static int expr_visibility (tree);
2478 static int type_visibility (tree);
2480 /* walk_tree helper function for type_visibility. */
2482 static tree
2483 min_vis_r (tree *tp, int *walk_subtrees, void *data)
2485 int *vis_p = (int *)data;
2486 int this_vis = VISIBILITY_DEFAULT;
2487 if (! TYPE_P (*tp))
2488 *walk_subtrees = 0;
2489 else if (OVERLOAD_TYPE_P (*tp)
2490 && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
2492 this_vis = VISIBILITY_ANON;
2493 *walk_subtrees = 0;
2495 else if (CLASS_TYPE_P (*tp))
2497 this_vis = CLASSTYPE_VISIBILITY (*tp);
2498 *walk_subtrees = 0;
2500 else if (TREE_CODE (*tp) == ARRAY_TYPE
2501 && uses_template_parms (TYPE_DOMAIN (*tp)))
2502 this_vis = expr_visibility (TYPE_MAX_VALUE (TYPE_DOMAIN (*tp)));
2504 if (this_vis > *vis_p)
2505 *vis_p = this_vis;
2507 /* Tell cp_walk_subtrees to look through typedefs. */
2508 if (*walk_subtrees == 1)
2509 *walk_subtrees = 2;
2511 return NULL;
2514 /* walk_tree helper function for expr_visibility. */
2516 static tree
2517 min_vis_expr_r (tree *tp, int */*walk_subtrees*/, void *data)
2519 int *vis_p = (int *)data;
2520 int tpvis = VISIBILITY_DEFAULT;
2522 switch (TREE_CODE (*tp))
2524 case CAST_EXPR:
2525 case IMPLICIT_CONV_EXPR:
2526 case STATIC_CAST_EXPR:
2527 case REINTERPRET_CAST_EXPR:
2528 case CONST_CAST_EXPR:
2529 case DYNAMIC_CAST_EXPR:
2530 case NEW_EXPR:
2531 case CONSTRUCTOR:
2532 case LAMBDA_EXPR:
2533 tpvis = type_visibility (TREE_TYPE (*tp));
2534 break;
2536 case VAR_DECL:
2537 case FUNCTION_DECL:
2538 if (! TREE_PUBLIC (*tp))
2539 tpvis = VISIBILITY_ANON;
2540 else
2541 tpvis = DECL_VISIBILITY (*tp);
2542 break;
2544 default:
2545 break;
2548 if (tpvis > *vis_p)
2549 *vis_p = tpvis;
2551 return NULL_TREE;
2554 /* Returns the visibility of TYPE, which is the minimum visibility of its
2555 component types. */
2557 static int
2558 type_visibility (tree type)
2560 int vis = VISIBILITY_DEFAULT;
2561 cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
2562 return vis;
2565 /* Returns the visibility of an expression EXPR that appears in the signature
2566 of a function template, which is the minimum visibility of names that appear
2567 in its mangling. */
2569 static int
2570 expr_visibility (tree expr)
2572 int vis = VISIBILITY_DEFAULT;
2573 cp_walk_tree_without_duplicates (&expr, min_vis_expr_r, &vis);
2574 return vis;
2577 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
2578 specified (or if VISIBILITY is static). If TMPL is true, this
2579 constraint is for a template argument, and takes precedence
2580 over explicitly-specified visibility on the template. */
2582 static void
2583 constrain_visibility (tree decl, int visibility, bool tmpl)
2585 if (visibility == VISIBILITY_ANON)
2587 /* extern "C" declarations aren't affected by the anonymous
2588 namespace. */
2589 if (!DECL_EXTERN_C_P (decl))
2591 TREE_PUBLIC (decl) = 0;
2592 DECL_WEAK (decl) = 0;
2593 DECL_COMMON (decl) = 0;
2594 DECL_COMDAT (decl) = false;
2595 if (VAR_OR_FUNCTION_DECL_P (decl))
2597 struct symtab_node *snode = symtab_node::get (decl);
2599 if (snode)
2600 snode->set_comdat_group (NULL);
2602 DECL_INTERFACE_KNOWN (decl) = 1;
2603 if (DECL_LANG_SPECIFIC (decl))
2604 DECL_NOT_REALLY_EXTERN (decl) = 1;
2607 else if (visibility > DECL_VISIBILITY (decl)
2608 && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
2610 DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
2611 /* This visibility was not specified. */
2612 DECL_VISIBILITY_SPECIFIED (decl) = false;
2616 /* Constrain the visibility of DECL based on the visibility of its template
2617 arguments. */
2619 static void
2620 constrain_visibility_for_template (tree decl, tree targs)
2622 /* If this is a template instantiation, check the innermost
2623 template args for visibility constraints. The outer template
2624 args are covered by the class check. */
2625 tree args = INNERMOST_TEMPLATE_ARGS (targs);
2626 int i;
2627 for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2629 int vis = 0;
2631 tree arg = TREE_VEC_ELT (args, i-1);
2632 if (TYPE_P (arg))
2633 vis = type_visibility (arg);
2634 else
2635 vis = expr_visibility (arg);
2636 if (vis)
2637 constrain_visibility (decl, vis, true);
2641 /* Like c_determine_visibility, but with additional C++-specific
2642 behavior.
2644 Function-scope entities can rely on the function's visibility because
2645 it is set in start_preparsed_function.
2647 Class-scope entities cannot rely on the class's visibility until the end
2648 of the enclosing class definition.
2650 Note that because namespaces have multiple independent definitions,
2651 namespace visibility is handled elsewhere using the #pragma visibility
2652 machinery rather than by decorating the namespace declaration.
2654 The goal is for constraints from the type to give a diagnostic, and
2655 other constraints to be applied silently. */
2657 void
2658 determine_visibility (tree decl)
2660 /* Remember that all decls get VISIBILITY_DEFAULT when built. */
2662 /* Only relevant for names with external linkage. */
2663 if (!TREE_PUBLIC (decl))
2664 return;
2666 /* Cloned constructors and destructors get the same visibility as
2667 the underlying function. That should be set up in
2668 maybe_clone_body. */
2669 gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2671 bool orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2672 enum symbol_visibility orig_visibility = DECL_VISIBILITY (decl);
2674 /* The decl may be a template instantiation, which could influence
2675 visibilty. */
2676 tree template_decl = NULL_TREE;
2677 if (TREE_CODE (decl) == TYPE_DECL)
2679 if (CLASS_TYPE_P (TREE_TYPE (decl)))
2681 if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
2682 template_decl = decl;
2684 else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2685 template_decl = decl;
2687 else if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
2688 template_decl = decl;
2690 if (TREE_CODE (decl) == TYPE_DECL
2691 && LAMBDA_TYPE_P (TREE_TYPE (decl))
2692 && CLASSTYPE_LAMBDA_EXPR (TREE_TYPE (decl)) != error_mark_node)
2693 if (tree extra = LAMBDA_TYPE_EXTRA_SCOPE (TREE_TYPE (decl)))
2695 /* The lambda's visibility is limited by that of its extra
2696 scope. */
2697 int vis = 0;
2698 if (TYPE_P (extra))
2699 vis = type_visibility (extra);
2700 else
2701 vis = expr_visibility (extra);
2702 constrain_visibility (decl, vis, false);
2705 /* If DECL is a member of a class, visibility specifiers on the
2706 class can influence the visibility of the DECL. */
2707 tree class_type = NULL_TREE;
2708 if (DECL_CLASS_SCOPE_P (decl))
2709 class_type = DECL_CONTEXT (decl);
2710 else
2712 /* Not a class member. */
2714 /* Virtual tables have DECL_CONTEXT set to their associated class,
2715 so they are automatically handled above. */
2716 gcc_assert (!VAR_P (decl)
2717 || !DECL_VTABLE_OR_VTT_P (decl));
2719 if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2721 /* Local statics and classes get the visibility of their
2722 containing function by default, except that
2723 -fvisibility-inlines-hidden doesn't affect them. */
2724 tree fn = DECL_CONTEXT (decl);
2725 if (DECL_VISIBILITY_SPECIFIED (fn))
2727 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2728 DECL_VISIBILITY_SPECIFIED (decl) =
2729 DECL_VISIBILITY_SPECIFIED (fn);
2731 else
2733 if (DECL_CLASS_SCOPE_P (fn))
2734 determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2735 else if (determine_hidden_inline (fn))
2737 DECL_VISIBILITY (decl) = default_visibility;
2738 DECL_VISIBILITY_SPECIFIED (decl) =
2739 visibility_options.inpragma;
2741 else
2743 DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2744 DECL_VISIBILITY_SPECIFIED (decl) =
2745 DECL_VISIBILITY_SPECIFIED (fn);
2749 /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2750 but have no TEMPLATE_INFO, so don't try to check it. */
2751 template_decl = NULL_TREE;
2753 else if (VAR_P (decl) && DECL_TINFO_P (decl)
2754 && flag_visibility_ms_compat)
2756 /* Under -fvisibility-ms-compat, types are visible by default,
2757 even though their contents aren't. */
2758 tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2759 int underlying_vis = type_visibility (underlying_type);
2760 if (underlying_vis == VISIBILITY_ANON
2761 || (CLASS_TYPE_P (underlying_type)
2762 && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2763 constrain_visibility (decl, underlying_vis, false);
2764 else
2765 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2767 else if (VAR_P (decl) && DECL_TINFO_P (decl))
2769 /* tinfo visibility is based on the type it's for. */
2770 constrain_visibility
2771 (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2773 /* Give the target a chance to override the visibility associated
2774 with DECL. */
2775 if (TREE_PUBLIC (decl)
2776 && !DECL_REALLY_EXTERN (decl)
2777 && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2778 && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2779 targetm.cxx.determine_class_data_visibility (decl);
2781 else if (template_decl)
2782 /* Template instantiations and specializations get visibility based
2783 on their template unless they override it with an attribute. */;
2784 else if (! DECL_VISIBILITY_SPECIFIED (decl))
2786 if (determine_hidden_inline (decl))
2787 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2788 else
2790 /* Set default visibility to whatever the user supplied with
2791 #pragma GCC visibility or a namespace visibility attribute. */
2792 DECL_VISIBILITY (decl) = default_visibility;
2793 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2798 if (template_decl)
2800 /* If the specialization doesn't specify visibility, use the
2801 visibility from the template. */
2802 tree tinfo = get_template_info (template_decl);
2803 tree args = TI_ARGS (tinfo);
2804 tree attribs = (TREE_CODE (decl) == TYPE_DECL
2805 ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2806 : DECL_ATTRIBUTES (decl));
2807 tree attr = lookup_attribute ("visibility", attribs);
2809 if (args != error_mark_node)
2811 tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2813 if (!DECL_VISIBILITY_SPECIFIED (decl))
2815 if (!attr
2816 && determine_hidden_inline (decl))
2817 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2818 else
2820 DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2821 DECL_VISIBILITY_SPECIFIED (decl)
2822 = DECL_VISIBILITY_SPECIFIED (pattern);
2826 if (args
2827 /* Template argument visibility outweighs #pragma or namespace
2828 visibility, but not an explicit attribute. */
2829 && !attr)
2831 int depth = TMPL_ARGS_DEPTH (args);
2832 if (DECL_VISIBILITY_SPECIFIED (decl))
2834 /* A class template member with explicit visibility
2835 overrides the class visibility, so we need to apply
2836 all the levels of template args directly. */
2837 int i;
2838 for (i = 1; i <= depth; ++i)
2840 tree lev = TMPL_ARGS_LEVEL (args, i);
2841 constrain_visibility_for_template (decl, lev);
2844 else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2845 /* Limit visibility based on its template arguments. */
2846 constrain_visibility_for_template (decl, args);
2851 if (class_type)
2852 determine_visibility_from_class (decl, class_type);
2854 if (decl_internal_context_p (decl))
2855 /* Names in an anonymous namespace get internal linkage. */
2856 constrain_visibility (decl, VISIBILITY_ANON, false);
2857 else if (TREE_CODE (decl) != TYPE_DECL)
2859 /* Propagate anonymity from type to decl. */
2860 int tvis = type_visibility (TREE_TYPE (decl));
2861 if (tvis == VISIBILITY_ANON
2862 || ! DECL_VISIBILITY_SPECIFIED (decl))
2863 constrain_visibility (decl, tvis, false);
2865 else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2866 /* DR 757: A type without linkage shall not be used as the type of a
2867 variable or function with linkage, unless
2868 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2869 o the variable or function is not used (3.2 [basic.def.odr]) or is
2870 defined in the same translation unit.
2872 Since non-extern "C" decls need to be defined in the same
2873 translation unit, we can make the type internal. */
2874 constrain_visibility (decl, VISIBILITY_ANON, false);
2876 /* If visibility changed and DECL already has DECL_RTL, ensure
2877 symbol flags are updated. */
2878 if ((DECL_VISIBILITY (decl) != orig_visibility
2879 || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2880 && ((VAR_P (decl) && TREE_STATIC (decl))
2881 || TREE_CODE (decl) == FUNCTION_DECL)
2882 && DECL_RTL_SET_P (decl))
2883 make_decl_rtl (decl);
2886 /* By default, static data members and function members receive
2887 the visibility of their containing class. */
2889 static void
2890 determine_visibility_from_class (tree decl, tree class_type)
2892 if (DECL_VISIBILITY_SPECIFIED (decl))
2893 return;
2895 if (determine_hidden_inline (decl))
2896 DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2897 else
2899 /* Default to the class visibility. */
2900 DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2901 DECL_VISIBILITY_SPECIFIED (decl)
2902 = CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2905 /* Give the target a chance to override the visibility associated
2906 with DECL. */
2907 if (VAR_P (decl)
2908 && TREE_PUBLIC (decl)
2909 && (DECL_TINFO_P (decl) || DECL_VTABLE_OR_VTT_P (decl))
2910 && !DECL_REALLY_EXTERN (decl)
2911 && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2912 targetm.cxx.determine_class_data_visibility (decl);
2915 /* Returns true iff DECL is an inline that should get hidden visibility
2916 because of -fvisibility-inlines-hidden. */
2918 static bool
2919 determine_hidden_inline (tree decl)
2921 return (visibility_options.inlines_hidden
2922 /* Don't do this for inline templates; specializations might not be
2923 inline, and we don't want them to inherit the hidden
2924 visibility. We'll set it here for all inline instantiations. */
2925 && !processing_template_decl
2926 && TREE_CODE (decl) == FUNCTION_DECL
2927 && DECL_DECLARED_INLINE_P (decl)
2928 && (! DECL_LANG_SPECIFIC (decl)
2929 || ! DECL_EXPLICIT_INSTANTIATION (decl)));
2932 /* Constrain the visibility of a class TYPE based on the visibility of its
2933 field types. Warn if any fields require lesser visibility. */
2935 void
2936 constrain_class_visibility (tree type)
2938 tree binfo;
2939 tree t;
2940 int i;
2942 int vis = type_visibility (type);
2944 if (vis == VISIBILITY_ANON
2945 || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2946 return;
2948 /* Don't warn about visibility if the class has explicit visibility. */
2949 if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2950 vis = VISIBILITY_INTERNAL;
2952 for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
2953 if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node
2954 && !DECL_ARTIFICIAL (t))
2956 tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2957 int subvis = type_visibility (ftype);
2959 if (subvis == VISIBILITY_ANON)
2961 if (!in_main_input_context())
2963 tree nlt = no_linkage_check (ftype, /*relaxed_p=*/false);
2964 if (nlt)
2966 if (same_type_p (TREE_TYPE (t), nlt))
2967 warning (OPT_Wsubobject_linkage, "\
2968 %qT has a field %q#D whose type has no linkage",
2969 type, t);
2970 else
2971 warning (OPT_Wsubobject_linkage, "\
2972 %qT has a field %qD whose type depends on the type %qT which has no linkage",
2973 type, t, nlt);
2975 else if (cxx_dialect > cxx98
2976 && !decl_anon_ns_mem_p (ftype))
2977 warning (OPT_Wsubobject_linkage, "\
2978 %qT has a field %q#D whose type has internal linkage",
2979 type, t);
2980 else // In C++98 this can only happen with unnamed namespaces.
2981 warning (OPT_Wsubobject_linkage, "\
2982 %qT has a field %q#D whose type uses the anonymous namespace",
2983 type, t);
2986 else if (MAYBE_CLASS_TYPE_P (ftype)
2987 && vis < VISIBILITY_HIDDEN
2988 && subvis >= VISIBILITY_HIDDEN)
2989 warning (OPT_Wattributes, "\
2990 %qT declared with greater visibility than the type of its field %qD",
2991 type, t);
2994 binfo = TYPE_BINFO (type);
2995 for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
2997 tree btype = BINFO_TYPE (t);
2998 int subvis = type_visibility (btype);
3000 if (subvis == VISIBILITY_ANON)
3002 if (!in_main_input_context())
3004 tree nlt = no_linkage_check (btype, /*relaxed_p=*/false);
3005 if (nlt)
3007 if (same_type_p (btype, nlt))
3008 warning (OPT_Wsubobject_linkage, "\
3009 %qT has a base %qT which has no linkage",
3010 type, btype);
3011 else
3012 warning (OPT_Wsubobject_linkage, "\
3013 %qT has a base %qT which depends on the type %qT which has no linkage",
3014 type, btype, nlt);
3016 else if (cxx_dialect > cxx98
3017 && !decl_anon_ns_mem_p (btype))
3018 warning (OPT_Wsubobject_linkage, "\
3019 %qT has a base %qT which has internal linkage",
3020 type, btype);
3021 else // In C++98 this can only happen with unnamed namespaces.
3022 warning (OPT_Wsubobject_linkage, "\
3023 %qT has a base %qT which uses the anonymous namespace",
3024 type, btype);
3027 else if (vis < VISIBILITY_HIDDEN
3028 && subvis >= VISIBILITY_HIDDEN)
3029 warning (OPT_Wattributes, "\
3030 %qT declared with greater visibility than its base %qT",
3031 type, TREE_TYPE (t));
3035 /* Functions for adjusting the visibility of a tagged type and its nested
3036 types and declarations when it gets a name for linkage purposes from a
3037 typedef. */
3038 // FIXME: It is now a DR for such a class type to contain anything
3039 // other than C. So at minium most of this can probably be deleted.
3041 /* First reset the visibility of all the types. */
3043 static void
3044 reset_type_linkage_1 (tree type)
3046 set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
3047 if (CLASS_TYPE_P (type))
3048 for (tree member = TYPE_FIELDS (type); member; member = DECL_CHAIN (member))
3049 if (DECL_IMPLICIT_TYPEDEF_P (member))
3050 reset_type_linkage_1 (TREE_TYPE (member));
3053 /* Then reset the visibility of any static data members or member
3054 functions that use those types. */
3056 static void
3057 reset_decl_linkage (tree decl)
3059 if (TREE_PUBLIC (decl))
3060 return;
3061 if (DECL_CLONED_FUNCTION_P (decl))
3062 return;
3063 TREE_PUBLIC (decl) = true;
3064 DECL_INTERFACE_KNOWN (decl) = false;
3065 determine_visibility (decl);
3066 tentative_decl_linkage (decl);
3069 void
3070 reset_type_linkage (tree type)
3072 reset_type_linkage_1 (type);
3073 if (CLASS_TYPE_P (type))
3075 if (tree vt = CLASSTYPE_VTABLES (type))
3077 tree name = mangle_vtbl_for_type (type);
3078 DECL_NAME (vt) = name;
3079 SET_DECL_ASSEMBLER_NAME (vt, name);
3080 reset_decl_linkage (vt);
3082 if (!ANON_AGGR_TYPE_P (type))
3083 if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
3085 tree name = mangle_typeinfo_for_type (type);
3086 DECL_NAME (ti) = name;
3087 SET_DECL_ASSEMBLER_NAME (ti, name);
3088 TREE_TYPE (name) = type;
3089 reset_decl_linkage (ti);
3091 for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
3093 tree mem = STRIP_TEMPLATE (m);
3094 if (TREE_CODE (mem) == VAR_DECL || TREE_CODE (mem) == FUNCTION_DECL)
3095 reset_decl_linkage (mem);
3096 else if (DECL_IMPLICIT_TYPEDEF_P (mem))
3097 reset_type_linkage (TREE_TYPE (mem));
3102 /* Set up our initial idea of what the linkage of DECL should be. */
3104 void
3105 tentative_decl_linkage (tree decl)
3107 if (DECL_INTERFACE_KNOWN (decl))
3108 /* We've already made a decision as to how this function will
3109 be handled. */;
3110 else if (vague_linkage_p (decl))
3112 if (TREE_CODE (decl) == FUNCTION_DECL
3113 && decl_defined_p (decl))
3115 DECL_EXTERNAL (decl) = 1;
3116 DECL_NOT_REALLY_EXTERN (decl) = 1;
3117 note_vague_linkage_fn (decl);
3118 /* A non-template inline function with external linkage will
3119 always be COMDAT. As we must eventually determine the
3120 linkage of all functions, and as that causes writes to
3121 the data mapped in from the PCH file, it's advantageous
3122 to mark the functions at this point. */
3123 if (DECL_DECLARED_INLINE_P (decl)
3124 && (!DECL_IMPLICIT_INSTANTIATION (decl)
3125 || DECL_DEFAULTED_FN (decl)))
3127 /* This function must have external linkage, as
3128 otherwise DECL_INTERFACE_KNOWN would have been
3129 set. */
3130 gcc_assert (TREE_PUBLIC (decl));
3131 comdat_linkage (decl);
3132 DECL_INTERFACE_KNOWN (decl) = 1;
3135 else if (VAR_P (decl))
3136 maybe_commonize_var (decl);
3140 /* DECL is a FUNCTION_DECL or VAR_DECL. If the object file linkage
3141 for DECL has not already been determined, do so now by setting
3142 DECL_EXTERNAL, DECL_COMDAT and other related flags. Until this
3143 function is called entities with vague linkage whose definitions
3144 are available must have TREE_PUBLIC set.
3146 If this function decides to place DECL in COMDAT, it will set
3147 appropriate flags -- but will not clear DECL_EXTERNAL. It is up to
3148 the caller to decide whether or not to clear DECL_EXTERNAL. Some
3149 callers defer that decision until it is clear that DECL is actually
3150 required. */
3152 void
3153 import_export_decl (tree decl)
3155 bool comdat_p;
3156 bool import_p;
3157 tree class_type = NULL_TREE;
3159 if (DECL_INTERFACE_KNOWN (decl))
3160 return;
3162 /* We cannot determine what linkage to give to an entity with vague
3163 linkage until the end of the file. For example, a virtual table
3164 for a class will be defined if and only if the key method is
3165 defined in this translation unit. */
3166 gcc_assert (at_eof);
3167 /* Object file linkage for explicit instantiations is handled in
3168 mark_decl_instantiated. For static variables in functions with
3169 vague linkage, maybe_commonize_var is used.
3171 Therefore, the only declarations that should be provided to this
3172 function are those with external linkage that are:
3174 * implicit instantiations of function templates
3176 * inline function
3178 * implicit instantiations of static data members of class
3179 templates
3181 * virtual tables
3183 * typeinfo objects
3185 Furthermore, all entities that reach this point must have a
3186 definition available in this translation unit.
3188 The following assertions check these conditions. */
3189 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
3190 /* Any code that creates entities with TREE_PUBLIC cleared should
3191 also set DECL_INTERFACE_KNOWN. */
3192 gcc_assert (TREE_PUBLIC (decl));
3193 if (TREE_CODE (decl) == FUNCTION_DECL)
3194 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3195 || DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
3196 || DECL_DECLARED_INLINE_P (decl));
3197 else
3198 gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
3199 || DECL_VTABLE_OR_VTT_P (decl)
3200 || DECL_TINFO_P (decl));
3201 /* Check that a definition of DECL is available in this translation
3202 unit. */
3203 gcc_assert (!DECL_REALLY_EXTERN (decl));
3205 /* Assume that DECL will not have COMDAT linkage. */
3206 comdat_p = false;
3207 /* Assume that DECL will not be imported into this translation
3208 unit. */
3209 import_p = false;
3211 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
3213 class_type = DECL_CONTEXT (decl);
3214 import_export_class (class_type);
3215 if (CLASSTYPE_INTERFACE_KNOWN (class_type)
3216 && CLASSTYPE_INTERFACE_ONLY (class_type))
3217 import_p = true;
3218 else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
3219 && !CLASSTYPE_USE_TEMPLATE (class_type)
3220 && CLASSTYPE_KEY_METHOD (class_type)
3221 && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
3222 /* The ABI requires that all virtual tables be emitted with
3223 COMDAT linkage. However, on systems where COMDAT symbols
3224 don't show up in the table of contents for a static
3225 archive, or on systems without weak symbols (where we
3226 approximate COMDAT linkage by using internal linkage), the
3227 linker will report errors about undefined symbols because
3228 it will not see the virtual table definition. Therefore,
3229 in the case that we know that the virtual table will be
3230 emitted in only one translation unit, we make the virtual
3231 table an ordinary definition with external linkage. */
3232 DECL_EXTERNAL (decl) = 0;
3233 else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
3235 /* CLASS_TYPE is being exported from this translation unit,
3236 so DECL should be defined here. */
3237 if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
3238 /* If a class is declared in a header with the "extern
3239 template" extension, then it will not be instantiated,
3240 even in translation units that would normally require
3241 it. Often such classes are explicitly instantiated in
3242 one translation unit. Therefore, the explicit
3243 instantiation must be made visible to other translation
3244 units. */
3245 DECL_EXTERNAL (decl) = 0;
3246 else
3248 /* The generic C++ ABI says that class data is always
3249 COMDAT, even if there is a key function. Some
3250 variants (e.g., the ARM EABI) says that class data
3251 only has COMDAT linkage if the class data might be
3252 emitted in more than one translation unit. When the
3253 key method can be inline and is inline, we still have
3254 to arrange for comdat even though
3255 class_data_always_comdat is false. */
3256 if (!CLASSTYPE_KEY_METHOD (class_type)
3257 || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
3258 || targetm.cxx.class_data_always_comdat ())
3260 /* The ABI requires COMDAT linkage. Normally, we
3261 only emit COMDAT things when they are needed;
3262 make sure that we realize that this entity is
3263 indeed needed. */
3264 comdat_p = true;
3265 mark_needed (decl);
3269 else if (!flag_implicit_templates
3270 && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
3271 import_p = true;
3272 else
3273 comdat_p = true;
3275 else if (VAR_P (decl) && DECL_TINFO_P (decl))
3277 tree type = TREE_TYPE (DECL_NAME (decl));
3278 if (CLASS_TYPE_P (type))
3280 class_type = type;
3281 import_export_class (type);
3282 if (CLASSTYPE_INTERFACE_KNOWN (type)
3283 && TYPE_POLYMORPHIC_P (type)
3284 && CLASSTYPE_INTERFACE_ONLY (type)
3285 /* If -fno-rtti was specified, then we cannot be sure
3286 that RTTI information will be emitted with the
3287 virtual table of the class, so we must emit it
3288 wherever it is used. */
3289 && flag_rtti)
3290 import_p = true;
3291 else
3293 if (CLASSTYPE_INTERFACE_KNOWN (type)
3294 && !CLASSTYPE_INTERFACE_ONLY (type))
3296 comdat_p = (targetm.cxx.class_data_always_comdat ()
3297 || (CLASSTYPE_KEY_METHOD (type)
3298 && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
3299 mark_needed (decl);
3300 if (!flag_weak)
3302 comdat_p = false;
3303 DECL_EXTERNAL (decl) = 0;
3306 else
3307 comdat_p = true;
3310 else
3311 comdat_p = true;
3313 else if (DECL_TEMPLOID_INSTANTIATION (decl))
3315 /* DECL is an implicit instantiation of a function or static
3316 data member. */
3317 if (flag_implicit_templates
3318 || (flag_implicit_inline_templates
3319 && TREE_CODE (decl) == FUNCTION_DECL
3320 && DECL_DECLARED_INLINE_P (decl)))
3321 comdat_p = true;
3322 else
3323 /* If we are not implicitly generating templates, then mark
3324 this entity as undefined in this translation unit. */
3325 import_p = true;
3327 else if (DECL_FUNCTION_MEMBER_P (decl))
3329 if (!DECL_DECLARED_INLINE_P (decl))
3331 tree ctype = DECL_CONTEXT (decl);
3332 import_export_class (ctype);
3333 if (CLASSTYPE_INTERFACE_KNOWN (ctype))
3335 DECL_NOT_REALLY_EXTERN (decl)
3336 = ! (CLASSTYPE_INTERFACE_ONLY (ctype)
3337 || (DECL_DECLARED_INLINE_P (decl)
3338 && ! flag_implement_inlines
3339 && !DECL_VINDEX (decl)));
3341 if (!DECL_NOT_REALLY_EXTERN (decl))
3342 DECL_EXTERNAL (decl) = 1;
3344 /* Always make artificials weak. */
3345 if (DECL_ARTIFICIAL (decl) && flag_weak)
3346 comdat_p = true;
3347 else
3348 maybe_make_one_only (decl);
3351 else
3352 comdat_p = true;
3354 else
3355 comdat_p = true;
3357 if (import_p)
3359 /* If we are importing DECL into this translation unit, mark is
3360 an undefined here. */
3361 DECL_EXTERNAL (decl) = 1;
3362 DECL_NOT_REALLY_EXTERN (decl) = 0;
3364 else if (comdat_p)
3366 /* If we decided to put DECL in COMDAT, mark it accordingly at
3367 this point. */
3368 comdat_linkage (decl);
3371 DECL_INTERFACE_KNOWN (decl) = 1;
3374 /* Return an expression that performs the destruction of DECL, which
3375 must be a VAR_DECL whose type has a non-trivial destructor, or is
3376 an array whose (innermost) elements have a non-trivial destructor. */
3378 tree
3379 build_cleanup (tree decl)
3381 tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
3382 gcc_assert (clean != NULL_TREE);
3383 return clean;
3386 /* GUARD is a helper variable for DECL; make them have the same linkage and
3387 visibility. */
3389 void
3390 copy_linkage (tree guard, tree decl)
3392 TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
3393 TREE_STATIC (guard) = TREE_STATIC (decl);
3394 DECL_COMMON (guard) = DECL_COMMON (decl);
3395 DECL_COMDAT (guard) = DECL_COMDAT (decl);
3396 if (TREE_STATIC (guard))
3398 CP_DECL_THREAD_LOCAL_P (guard) = CP_DECL_THREAD_LOCAL_P (decl);
3399 set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
3400 if (DECL_ONE_ONLY (decl))
3401 make_decl_one_only (guard, cxx_comdat_group (guard));
3402 if (TREE_PUBLIC (decl))
3403 DECL_WEAK (guard) = DECL_WEAK (decl);
3404 /* Also check vague_linkage_p, as DECL_WEAK and DECL_ONE_ONLY might not
3405 be set until import_export_decl at EOF. */
3406 if (vague_linkage_p (decl))
3407 comdat_linkage (guard);
3408 DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
3409 DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
3413 /* Returns the initialization guard variable for the variable DECL,
3414 which has static storage duration. */
3416 tree
3417 get_guard (tree decl)
3419 tree sname = mangle_guard_variable (decl);
3420 tree guard = get_global_binding (sname);
3421 if (! guard)
3423 tree guard_type;
3425 /* We use a type that is big enough to contain a mutex as well
3426 as an integer counter. */
3427 guard_type = targetm.cxx.guard_type ();
3428 guard = build_decl (DECL_SOURCE_LOCATION (decl),
3429 VAR_DECL, sname, guard_type);
3431 /* The guard should have the same linkage as what it guards. */
3432 copy_linkage (guard, decl);
3434 DECL_ARTIFICIAL (guard) = 1;
3435 DECL_IGNORED_P (guard) = 1;
3436 TREE_USED (guard) = 1;
3437 pushdecl_top_level_and_finish (guard, NULL_TREE);
3439 return guard;
3442 /* Returns true if accessing the GUARD atomic is expensive,
3443 i.e. involves a call to __sync_synchronize or similar.
3444 In this case let __cxa_guard_acquire handle the atomics. */
3446 static bool
3447 is_atomic_expensive_p (machine_mode mode)
3449 if (!flag_inline_atomics)
3450 return true;
3452 if (!can_compare_and_swap_p (mode, false) || !can_atomic_load_p (mode))
3453 return true;
3455 return false;
3458 /* Return an atomic load of src with the appropriate memory model. */
3460 static tree
3461 build_atomic_load_type (tree src, HOST_WIDE_INT model, tree type)
3463 tree ptr_type = build_pointer_type (type);
3464 tree mem_model = build_int_cst (integer_type_node, model);
3465 tree t, addr, val;
3466 unsigned int size;
3467 int fncode;
3469 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
3471 fncode = BUILT_IN_ATOMIC_LOAD_N + exact_log2 (size) + 1;
3472 t = builtin_decl_implicit ((enum built_in_function) fncode);
3474 addr = build1 (ADDR_EXPR, ptr_type, src);
3475 val = build_call_expr (t, 2, addr, mem_model);
3476 return val;
3479 /* Return those bits of the GUARD variable that should be set when the
3480 guarded entity is actually initialized. */
3482 static tree
3483 get_guard_bits (tree guard)
3485 if (!targetm.cxx.guard_mask_bit ())
3487 /* We only set the first byte of the guard, in order to leave room
3488 for a mutex in the high-order bits. */
3489 guard = build1 (ADDR_EXPR,
3490 build_pointer_type (TREE_TYPE (guard)),
3491 guard);
3492 guard = build1 (NOP_EXPR,
3493 build_pointer_type (char_type_node),
3494 guard);
3495 guard = build1 (INDIRECT_REF, char_type_node, guard);
3498 return guard;
3501 /* Return an expression which determines whether or not the GUARD
3502 variable has already been initialized. */
3504 tree
3505 get_guard_cond (tree guard, bool thread_safe)
3507 tree guard_value;
3509 if (!thread_safe)
3510 guard = get_guard_bits (guard);
3511 else
3513 tree type = targetm.cxx.guard_mask_bit ()
3514 ? TREE_TYPE (guard) : char_type_node;
3516 if (is_atomic_expensive_p (TYPE_MODE (type)))
3517 guard = integer_zero_node;
3518 else
3519 guard = build_atomic_load_type (guard, MEMMODEL_ACQUIRE, type);
3522 /* Mask off all but the low bit. */
3523 if (targetm.cxx.guard_mask_bit ())
3525 guard_value = integer_one_node;
3526 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3527 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3528 guard = cp_build_binary_op (input_location,
3529 BIT_AND_EXPR, guard, guard_value,
3530 tf_warning_or_error);
3533 guard_value = integer_zero_node;
3534 if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3535 guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3536 return cp_build_binary_op (input_location,
3537 EQ_EXPR, guard, guard_value,
3538 tf_warning_or_error);
3541 /* Return an expression which sets the GUARD variable, indicating that
3542 the variable being guarded has been initialized. */
3544 tree
3545 set_guard (tree guard)
3547 tree guard_init;
3549 /* Set the GUARD to one. */
3550 guard = get_guard_bits (guard);
3551 guard_init = integer_one_node;
3552 if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
3553 guard_init = fold_convert (TREE_TYPE (guard), guard_init);
3554 return cp_build_modify_expr (input_location, guard, NOP_EXPR, guard_init,
3555 tf_warning_or_error);
3558 /* Returns true iff we can tell that VAR does not have a dynamic
3559 initializer. */
3561 static bool
3562 var_defined_without_dynamic_init (tree var)
3564 /* constinit vars are guaranteed to not have dynamic initializer,
3565 but still registering the destructor counts as dynamic initialization. */
3566 if (DECL_DECLARED_CONSTINIT_P (var)
3567 && COMPLETE_TYPE_P (TREE_TYPE (var))
3568 && !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3569 return true;
3570 /* If it's defined in another TU, we can't tell. */
3571 if (DECL_EXTERNAL (var))
3572 return false;
3573 /* If it has a non-trivial destructor, registering the destructor
3574 counts as dynamic initialization. */
3575 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3576 return false;
3577 /* If it's in this TU, its initializer has been processed, unless
3578 it's a case of self-initialization, then DECL_INITIALIZED_P is
3579 false while the initializer is handled by finish_id_expression. */
3580 if (!DECL_INITIALIZED_P (var))
3581 return false;
3582 /* If it has no initializer or a constant one, it's not dynamic. */
3583 return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
3584 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
3587 /* Returns true iff VAR is a variable that needs uses to be
3588 wrapped for possible dynamic initialization. */
3590 static bool
3591 var_needs_tls_wrapper (tree var)
3593 return (!error_operand_p (var)
3594 && CP_DECL_THREAD_LOCAL_P (var)
3595 && !DECL_GNU_TLS_P (var)
3596 && !DECL_FUNCTION_SCOPE_P (var)
3597 && !var_defined_without_dynamic_init (var));
3600 /* Get the FUNCTION_DECL for the shared TLS init function for this
3601 translation unit. */
3603 static tree
3604 get_local_tls_init_fn (location_t loc)
3606 tree sname = get_identifier ("__tls_init");
3607 tree fn = get_global_binding (sname);
3608 if (!fn)
3610 fn = build_lang_decl_loc (loc, FUNCTION_DECL, sname,
3611 build_function_type (void_type_node,
3612 void_list_node));
3613 SET_DECL_LANGUAGE (fn, lang_c);
3614 TREE_PUBLIC (fn) = false;
3615 DECL_ARTIFICIAL (fn) = true;
3616 mark_used (fn);
3617 set_global_binding (fn);
3619 return fn;
3622 /* Get a FUNCTION_DECL for the init function for the thread_local
3623 variable VAR. The init function will be an alias to the function
3624 that initializes all the non-local TLS variables in the translation
3625 unit. The init function is only used by the wrapper function. */
3627 static tree
3628 get_tls_init_fn (tree var)
3630 /* Only C++11 TLS vars need this init fn. */
3631 if (!var_needs_tls_wrapper (var))
3632 return NULL_TREE;
3634 /* If -fno-extern-tls-init, assume that we don't need to call
3635 a tls init function for a variable defined in another TU. */
3636 if (!flag_extern_tls_init && DECL_EXTERNAL (var))
3637 return NULL_TREE;
3639 /* If the variable is internal, or if we can't generate aliases,
3640 call the local init function directly. */
3641 if (!TREE_PUBLIC (var) || !TARGET_SUPPORTS_ALIASES)
3642 return get_local_tls_init_fn (DECL_SOURCE_LOCATION (var));
3644 tree sname = mangle_tls_init_fn (var);
3645 tree fn = get_global_binding (sname);
3646 if (!fn)
3648 fn = build_lang_decl (FUNCTION_DECL, sname,
3649 build_function_type (void_type_node,
3650 void_list_node));
3651 SET_DECL_LANGUAGE (fn, lang_c);
3652 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3653 DECL_ARTIFICIAL (fn) = true;
3654 DECL_COMDAT (fn) = DECL_COMDAT (var);
3655 DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
3656 if (DECL_ONE_ONLY (var))
3657 make_decl_one_only (fn, cxx_comdat_group (fn));
3658 if (TREE_PUBLIC (var))
3660 tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
3661 /* If the variable is defined somewhere else and might have static
3662 initialization, make the init function a weak reference. */
3663 if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
3664 || TYPE_HAS_CONSTEXPR_CTOR (obtype)
3665 || TYPE_HAS_TRIVIAL_DFLT (obtype))
3666 && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
3667 && DECL_EXTERNAL (var))
3668 declare_weak (fn);
3669 else
3670 DECL_WEAK (fn) = DECL_WEAK (var);
3672 DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
3673 DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
3674 DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
3675 DECL_IGNORED_P (fn) = 1;
3676 mark_used (fn);
3678 DECL_BEFRIENDING_CLASSES (fn) = var;
3680 set_global_binding (fn);
3682 return fn;
3685 /* Get a FUNCTION_DECL for the init wrapper function for the thread_local
3686 variable VAR. The wrapper function calls the init function (if any) for
3687 VAR and then returns a reference to VAR. The wrapper function is used
3688 in place of VAR everywhere VAR is mentioned. */
3690 static tree
3691 get_tls_wrapper_fn (tree var)
3693 /* Only C++11 TLS vars need this wrapper fn. */
3694 if (!var_needs_tls_wrapper (var))
3695 return NULL_TREE;
3697 tree sname = mangle_tls_wrapper_fn (var);
3698 tree fn = get_global_binding (sname);
3699 if (!fn)
3701 /* A named rvalue reference is an lvalue, so the wrapper should
3702 always return an lvalue reference. */
3703 tree type = non_reference (TREE_TYPE (var));
3704 type = build_reference_type (type);
3705 tree fntype = build_function_type (type, void_list_node);
3707 fn = build_lang_decl_loc (DECL_SOURCE_LOCATION (var),
3708 FUNCTION_DECL, sname, fntype);
3709 SET_DECL_LANGUAGE (fn, lang_c);
3710 TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3711 DECL_ARTIFICIAL (fn) = true;
3712 DECL_IGNORED_P (fn) = 1;
3713 /* The wrapper is inline and emitted everywhere var is used. */
3714 DECL_DECLARED_INLINE_P (fn) = true;
3715 if (TREE_PUBLIC (var))
3717 comdat_linkage (fn);
3718 #ifdef HAVE_GAS_HIDDEN
3719 /* Make the wrapper bind locally; there's no reason to share
3720 the wrapper between multiple shared objects. */
3721 DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
3722 DECL_VISIBILITY_SPECIFIED (fn) = true;
3723 #endif
3725 if (!TREE_PUBLIC (fn))
3726 DECL_INTERFACE_KNOWN (fn) = true;
3727 mark_used (fn);
3728 note_vague_linkage_fn (fn);
3730 #if 0
3731 /* We want CSE to commonize calls to the wrapper, but marking it as
3732 pure is unsafe since it has side-effects. I guess we need a new
3733 ECF flag even weaker than ECF_PURE. FIXME! */
3734 DECL_PURE_P (fn) = true;
3735 #endif
3737 DECL_BEFRIENDING_CLASSES (fn) = var;
3739 set_global_binding (fn);
3741 return fn;
3744 /* If EXPR is a thread_local variable that should be wrapped by init
3745 wrapper function, return a call to that function, otherwise return
3746 NULL. */
3748 tree
3749 maybe_get_tls_wrapper_call (tree expr)
3751 if (VAR_P (expr)
3752 && !processing_template_decl
3753 && !cp_unevaluated_operand
3754 && CP_DECL_THREAD_LOCAL_P (expr))
3755 if (tree wrap = get_tls_wrapper_fn (expr))
3756 return build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
3757 return NULL;
3760 /* At EOF, generate the definition for the TLS wrapper function FN:
3762 T& var_wrapper() {
3763 if (init_fn) init_fn();
3764 return var;
3765 } */
3767 static void
3768 generate_tls_wrapper (tree fn)
3770 tree var = DECL_BEFRIENDING_CLASSES (fn);
3772 start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
3773 tree body = begin_function_body ();
3774 /* Only call the init fn if there might be one. */
3775 if (tree init_fn = get_tls_init_fn (var))
3777 tree if_stmt = NULL_TREE;
3778 /* If init_fn is a weakref, make sure it exists before calling. */
3779 if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
3781 if_stmt = begin_if_stmt ();
3782 tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
3783 tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
3784 NE_EXPR, addr, nullptr_node,
3785 tf_warning_or_error);
3786 finish_if_stmt_cond (cond, if_stmt);
3788 finish_expr_stmt (build_cxx_call
3789 (init_fn, 0, NULL, tf_warning_or_error));
3790 if (if_stmt)
3792 finish_then_clause (if_stmt);
3793 finish_if_stmt (if_stmt);
3796 else
3797 /* If there's no initialization, the wrapper is a constant function. */
3798 TREE_READONLY (fn) = true;
3799 finish_return_stmt (convert_from_reference (var));
3800 finish_function_body (body);
3801 expand_or_defer_fn (finish_function (/*inline_p=*/false));
3804 /* Start a global constructor or destructor function. */
3806 static tree
3807 start_objects (bool initp, unsigned priority, bool has_body)
3809 bool default_init = initp && priority == DEFAULT_INIT_PRIORITY;
3810 bool is_module_init = default_init && module_global_init_needed ();
3811 tree name = NULL_TREE;
3813 if (is_module_init)
3814 name = mangle_module_global_init (0);
3815 else
3817 char type[14];
3819 /* We use `I' to indicate initialization and `D' to indicate
3820 destruction. */
3821 unsigned len = sprintf (type, "sub_%c", initp ? 'I' : 'D');
3822 if (priority != DEFAULT_INIT_PRIORITY)
3824 char joiner = '_';
3825 #ifdef JOINER
3826 joiner = JOINER;
3827 #endif
3828 type[len++] = joiner;
3829 sprintf (type + len, "%.5u", priority);
3831 name = get_file_function_name (type);
3834 tree fntype = build_function_type (void_type_node, void_list_node);
3835 tree fndecl = build_lang_decl (FUNCTION_DECL, name, fntype);
3836 DECL_CONTEXT (fndecl) = FROB_CONTEXT (global_namespace);
3837 if (is_module_init)
3839 SET_DECL_ASSEMBLER_NAME (fndecl, name);
3840 TREE_PUBLIC (fndecl) = true;
3841 determine_visibility (fndecl);
3843 else
3844 TREE_PUBLIC (fndecl) = 0;
3845 start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3847 /* Mark as artificial because it's not explicitly in the user's
3848 source code. */
3849 DECL_ARTIFICIAL (current_function_decl) = 1;
3851 /* Mark this declaration as used to avoid spurious warnings. */
3852 TREE_USED (current_function_decl) = 1;
3854 /* Mark this function as a global constructor or destructor. */
3855 if (initp)
3856 DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3857 else
3858 DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3860 tree body = begin_compound_stmt (BCS_FN_BODY);
3862 if (is_module_init && has_body)
3864 // If the function is going to be empty, don't emit idempotency.
3865 // 'static bool __in_chrg = false;
3866 // if (__inchrg) return;
3867 // __inchrg = true
3868 tree var = build_lang_decl (VAR_DECL, in_charge_identifier,
3869 boolean_type_node);
3870 DECL_CONTEXT (var) = fndecl;
3871 DECL_ARTIFICIAL (var) = true;
3872 TREE_STATIC (var) = true;
3873 pushdecl (var);
3874 cp_finish_decl (var, NULL_TREE, false, NULL_TREE, 0);
3876 tree if_stmt = begin_if_stmt ();
3877 finish_if_stmt_cond (var, if_stmt);
3878 finish_return_stmt (NULL_TREE);
3879 finish_then_clause (if_stmt);
3880 finish_if_stmt (if_stmt);
3882 tree assign = build2 (MODIFY_EXPR, boolean_type_node,
3883 var, boolean_true_node);
3884 TREE_SIDE_EFFECTS (assign) = true;
3885 finish_expr_stmt (assign);
3888 return body;
3891 /* Finish a global constructor or destructor. Add it to the global
3892 ctors or dtors, if STARTP is true. */
3894 static tree
3895 finish_objects (bool initp, unsigned priority, tree body, bool startp)
3897 /* Finish up. */
3898 finish_compound_stmt (body);
3899 tree fn = finish_function (/*inline_p=*/false);
3901 if (!startp)
3902 ; // Neither ctor nor dtor I be.
3903 else if (initp)
3905 DECL_STATIC_CONSTRUCTOR (fn) = 1;
3906 decl_init_priority_insert (fn, priority);
3908 else
3910 DECL_STATIC_DESTRUCTOR (fn) = 1;
3911 decl_fini_priority_insert (fn, priority);
3914 return fn;
3917 /* The name of the function we create to handle initializations and
3918 destructions for objects with static storage duration. */
3919 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
3921 /* Begins the generation of the function that will handle all
3922 initialization or destruction of objects with static storage
3923 duration at PRIORITY.
3925 It is assumed that this function will only be called once. */
3927 static tree
3928 start_partial_init_fini_fn (bool initp, unsigned priority, unsigned count)
3930 char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
3932 /* Create the identifier for this function. It will be of the form
3933 SSDF_IDENTIFIER_<number>. */
3934 sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
3936 tree type = build_function_type (void_type_node, void_list_node);
3938 /* Create the FUNCTION_DECL itself. */
3939 tree fn = build_lang_decl (FUNCTION_DECL, get_identifier (id), type);
3940 TREE_PUBLIC (fn) = 0;
3941 DECL_ARTIFICIAL (fn) = 1;
3943 /* Put this function in the list of functions to be called from the
3944 static constructors and destructors. */
3945 if (!static_init_fini_fns[initp])
3946 static_init_fini_fns[initp] = priority_map_t::create_ggc ();
3947 auto &slot = static_init_fini_fns[initp]->get_or_insert (priority);
3948 slot = tree_cons (fn, NULL_TREE, slot);
3950 /* Put the function in the global scope. */
3951 pushdecl (fn);
3953 /* Start the function itself. This is equivalent to declaring the
3954 function as:
3956 static void __ssdf (int __initialize_p, init __priority_p);
3958 It is static because we only need to call this function from the
3959 various constructor and destructor functions for this module. */
3960 start_preparsed_function (fn, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3962 /* Set up the scope of the outermost block in the function. */
3963 return begin_compound_stmt (BCS_FN_BODY);
3966 /* Finish the generation of the function which performs initialization
3967 or destruction of objects with static storage duration. */
3969 static void
3970 finish_partial_init_fini_fn (tree body)
3972 /* Close out the function. */
3973 finish_compound_stmt (body);
3974 expand_or_defer_fn (finish_function (/*inline_p=*/false));
3977 /* The effective initialization priority of a DECL. */
3979 #define DECL_EFFECTIVE_INIT_PRIORITY(decl) \
3980 ((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
3981 ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
3983 /* Whether a DECL needs a guard to protect it against multiple
3984 initialization. */
3986 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl) \
3987 || DECL_ONE_ONLY (decl) \
3988 || DECL_WEAK (decl)))
3990 /* Walks the initializer list of a global variable and looks for
3991 temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
3992 and that have their DECL_CONTEXT() == NULL. For each such
3993 temporary variable, set their DECL_CONTEXT() to CTX -- the
3994 initializing function. This is necessary because otherwise some
3995 optimizers (enabled by -O2 -fprofile-arcs) might crash when trying
3996 to refer to a temporary variable that does not have its
3997 DECL_CONTEXT() properly set. */
3999 static tree
4000 fix_temporary_vars_context_r (tree *node,
4001 int * /*unused*/,
4002 void *ctx)
4004 if (TREE_CODE (*node) == BIND_EXPR)
4005 for (tree var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
4006 if (VAR_P (var) && !DECL_NAME (var)
4007 && DECL_ARTIFICIAL (var) && !DECL_CONTEXT (var))
4008 DECL_CONTEXT (var) = tree (ctx);
4010 return NULL_TREE;
4013 /* Set up to handle the initialization or destruction of DECL. If
4014 INITP is nonzero, we are initializing the variable. Otherwise, we
4015 are destroying it. */
4017 static void
4018 one_static_initialization_or_destruction (bool initp, tree decl, tree init)
4020 /* If we are supposed to destruct and there's a trivial destructor,
4021 nothing has to be done. */
4022 gcc_checking_assert (init || !TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)));
4024 /* Trick the compiler into thinking we are at the file and line
4025 where DECL was declared so that error-messages make sense, and so
4026 that the debugger will show somewhat sensible file and line
4027 information. */
4028 input_location = DECL_SOURCE_LOCATION (decl);
4030 /* Make sure temporary variables in the initialiser all have
4031 their DECL_CONTEXT() set to a value different from NULL_TREE.
4032 This can happen when global variables initializers are built.
4033 In that case, the DECL_CONTEXT() of the global variables _AND_ of all
4034 the temporary variables that might have been generated in the
4035 accompanying initializers is NULL_TREE, meaning the variables have been
4036 declared in the global namespace.
4037 What we want to do here is to fix that and make sure the DECL_CONTEXT()
4038 of the temporaries are set to the current function decl. */
4039 cp_walk_tree_without_duplicates (&init,
4040 fix_temporary_vars_context_r,
4041 current_function_decl);
4043 /* Because of:
4045 [class.access.spec]
4047 Access control for implicit calls to the constructors,
4048 the conversion functions, or the destructor called to
4049 create and destroy a static data member is performed as
4050 if these calls appeared in the scope of the member's
4051 class.
4053 we pretend we are in a static member function of the class of
4054 which the DECL is a member. */
4055 if (member_p (decl))
4057 DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
4058 DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
4061 /* Assume we don't need a guard. */
4062 tree guard_if_stmt = NULL_TREE;
4064 /* We need a guard if this is an object with external linkage that
4065 might be initialized in more than one place. (For example, a
4066 static data member of a template, when the data member requires
4067 construction.) */
4068 if (NEEDS_GUARD_P (decl))
4070 tree guard = get_guard (decl);
4071 tree guard_cond;
4073 if (flag_use_cxa_atexit)
4075 /* When using __cxa_atexit, we just check the GUARD as we
4076 would for a local static. We never try to destroy
4077 anything from a static destructor. */
4078 gcc_assert (initp);
4079 guard_cond = get_guard_cond (guard, false);
4081 else
4083 /* If we don't have __cxa_atexit, then we will be running
4084 destructors from .fini sections, or their equivalents.
4085 So, we need to know how many times we've tried to
4086 initialize this object. We do initializations only if
4087 the GUARD was or becomes zero (initp vs !initp
4088 respectively). */
4089 guard_cond = cp_build_unary_op (initp ? POSTINCREMENT_EXPR
4090 : PREDECREMENT_EXPR,
4091 guard,
4092 /*noconvert=*/true,
4093 tf_warning_or_error);
4094 guard_cond = cp_build_binary_op (input_location, EQ_EXPR, guard_cond,
4095 integer_zero_node,
4096 tf_warning_or_error);
4099 guard_if_stmt = begin_if_stmt ();
4100 finish_if_stmt_cond (guard_cond, guard_if_stmt);
4102 if (flag_use_cxa_atexit)
4103 /* Set the GUARD now. */
4104 finish_expr_stmt (set_guard (guard));
4107 /* Perform the initialization or destruction. */
4108 if (initp)
4110 if (init)
4112 finish_expr_stmt (init);
4113 if (sanitize_flags_p (SANITIZE_ADDRESS, decl))
4114 if (varpool_node *vnode = varpool_node::get (decl))
4115 vnode->dynamically_initialized = 1;
4118 /* If we're using __cxa_atexit, register a function that calls the
4119 destructor for the object. */
4120 if (flag_use_cxa_atexit)
4121 finish_expr_stmt (register_dtor_fn (decl));
4123 else
4124 finish_expr_stmt (build_cleanup (decl));
4126 /* Finish the guard if-stmt, if necessary. */
4127 if (guard_if_stmt)
4129 finish_then_clause (guard_if_stmt);
4130 finish_if_stmt (guard_if_stmt);
4133 /* Now that we're done with DECL we don't need to pretend to be a
4134 member of its class any longer. */
4135 DECL_CONTEXT (current_function_decl) = NULL_TREE;
4136 DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
4139 /* Generate code to do the initialization or destruction of the decls in VARS,
4140 a TREE_LIST of VAR_DECL with static storage duration.
4141 Whether initialization or destruction is performed is specified by INITP. */
4143 static void
4144 emit_partial_init_fini_fn (bool initp, unsigned priority, tree vars,
4145 unsigned counter, location_t locus)
4147 input_location = locus;
4148 tree body = start_partial_init_fini_fn (initp, priority, counter);
4150 for (tree node = vars; node; node = TREE_CHAIN (node))
4151 /* Do one initialization or destruction. */
4152 one_static_initialization_or_destruction (initp, TREE_VALUE (node),
4153 TREE_PURPOSE (node));
4155 /* Finish up the static storage duration function for this
4156 round. */
4157 input_location = locus;
4158 finish_partial_init_fini_fn (body);
4161 /* VARS is a list of variables with static storage duration which may
4162 need initialization and/or finalization. Remove those variables
4163 that don't really need to be initialized or finalized, and return
4164 the resulting list. The order in which the variables appear in
4165 VARS is in reverse order of the order in which they should actually
4166 be initialized. That order is preserved. */
4168 static tree
4169 prune_vars_needing_no_initialization (tree *vars)
4171 tree *var = vars;
4172 tree result = NULL_TREE;
4174 while (*var)
4176 tree t = *var;
4177 tree decl = TREE_VALUE (t);
4178 tree init = TREE_PURPOSE (t);
4180 /* Deal gracefully with error. */
4181 if (error_operand_p (decl))
4183 var = &TREE_CHAIN (t);
4184 continue;
4187 /* The only things that can be initialized are variables. */
4188 gcc_assert (VAR_P (decl));
4190 /* If this object is not defined, we don't need to do anything
4191 here. */
4192 if (DECL_EXTERNAL (decl))
4194 var = &TREE_CHAIN (t);
4195 continue;
4198 /* Also, if the initializer already contains errors, we can bail
4199 out now. */
4200 if (init && TREE_CODE (init) == TREE_LIST
4201 && value_member (error_mark_node, init))
4203 var = &TREE_CHAIN (t);
4204 continue;
4207 /* This variable is going to need initialization and/or
4208 finalization, so we add it to the list. */
4209 *var = TREE_CHAIN (t);
4210 TREE_CHAIN (t) = result;
4211 result = t;
4214 return result;
4217 /* Split VAR_LIST by init priority and add into PARTS hash table.
4218 This reverses the variable ordering. */
4220 void
4221 partition_vars_for_init_fini (tree var_list, priority_map_t *(&parts)[2])
4223 for (auto node = var_list; node; node = TREE_CHAIN (node))
4225 tree decl = TREE_VALUE (node);
4226 tree init = TREE_PURPOSE (node);
4227 bool has_cleanup = !TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl));
4228 unsigned priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
4230 if (init || (flag_use_cxa_atexit && has_cleanup))
4232 // Add to initialization list.
4233 if (!parts[true])
4234 parts[true] = priority_map_t::create_ggc ();
4235 auto &slot = parts[true]->get_or_insert (priority);
4236 slot = tree_cons (init, decl, slot);
4239 if (!flag_use_cxa_atexit && has_cleanup)
4241 // Add to finalization list.
4242 if (!parts[false])
4243 parts[false] = priority_map_t::create_ggc ();
4244 auto &slot = parts[false]->get_or_insert (priority);
4245 slot = tree_cons (NULL_TREE, decl, slot);
4250 /* Make sure we have told the back end about all the variables in
4251 VARS. */
4253 static void
4254 write_out_vars (tree vars)
4256 tree v;
4258 for (v = vars; v; v = TREE_CHAIN (v))
4260 tree var = TREE_VALUE (v);
4261 if (!var_finalized_p (var))
4263 import_export_decl (var);
4264 rest_of_decl_compilation (var, 1, 1);
4269 /* Generate a static constructor or destructor that calls the given
4270 init/fini fns at the indicated priority. */
4272 static void
4273 generate_ctor_or_dtor_function (bool initp, unsigned priority,
4274 tree fns, location_t locus)
4276 input_location = locus;
4277 tree body = start_objects (initp, priority, bool (fns));
4279 if (fns)
4281 /* To make sure dynamic construction doesn't access globals from
4282 other compilation units where they might not be yet
4283 constructed, for -fsanitize=address insert
4284 __asan_before_dynamic_init call that prevents access to
4285 either all global variables that need construction in other
4286 compilation units, or at least those that haven't been
4287 initialized yet. Variables that need dynamic construction in
4288 the current compilation unit are kept accessible. */
4289 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4290 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
4292 /* Call the static init/fini functions. */
4293 for (tree node = fns; node; node = TREE_CHAIN (node))
4295 tree fn = TREE_PURPOSE (node);
4297 // We should never find a pure or constant cdtor.
4298 gcc_checking_assert (!(flags_from_decl_or_type (fn)
4299 & (ECF_CONST | ECF_PURE)));
4301 tree call = cp_build_function_call_nary (fn, tf_warning_or_error,
4302 NULL_TREE);
4303 finish_expr_stmt (call);
4306 /* Revert what __asan_before_dynamic_init did by calling
4307 __asan_after_dynamic_init. */
4308 if (initp && (flag_sanitize & SANITIZE_ADDRESS))
4309 finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
4312 /* Close out the function, and arrange for it to be called at init
4313 or fini time, if non-empty. (Even non-nop module initializer
4314 functions need this, as we cannot guarantee the module is
4315 imported somewhere in the program.) */
4316 expand_or_defer_fn (finish_objects (initp, priority, body, fns != NULL_TREE));
4319 /* Return C++ property of T, based on given operation OP. */
4321 static int
4322 cpp_check (tree t, cpp_operation op)
4324 switch (op)
4326 case HAS_DEPENDENT_TEMPLATE_ARGS:
4328 tree ti = CLASSTYPE_TEMPLATE_INFO (t);
4329 if (!ti)
4330 return 0;
4331 ++processing_template_decl;
4332 const bool dep = any_dependent_template_arguments_p (TI_ARGS (ti));
4333 --processing_template_decl;
4334 return dep;
4336 case IS_ABSTRACT:
4337 return DECL_PURE_VIRTUAL_P (t);
4338 case IS_ASSIGNMENT_OPERATOR:
4339 return DECL_ASSIGNMENT_OPERATOR_P (t);
4340 case IS_CONSTRUCTOR:
4341 return DECL_CONSTRUCTOR_P (t);
4342 case IS_DESTRUCTOR:
4343 return DECL_DESTRUCTOR_P (t);
4344 case IS_COPY_CONSTRUCTOR:
4345 return DECL_COPY_CONSTRUCTOR_P (t);
4346 case IS_MOVE_CONSTRUCTOR:
4347 return DECL_MOVE_CONSTRUCTOR_P (t);
4348 case IS_TEMPLATE:
4349 return TREE_CODE (t) == TEMPLATE_DECL;
4350 case IS_TRIVIAL:
4351 return trivial_type_p (t);
4352 default:
4353 return 0;
4357 /* Collect source file references recursively, starting from NAMESPC. */
4359 static void
4360 collect_source_refs (tree namespc)
4362 /* Iterate over names in this name space. */
4363 for (tree t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
4364 if (DECL_IS_UNDECLARED_BUILTIN (t))
4366 else if (TREE_CODE (t) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (t))
4367 collect_source_refs (t);
4368 else
4369 collect_source_ref (DECL_SOURCE_FILE (t));
4372 /* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
4373 starting from NAMESPC. */
4375 static void
4376 collect_ada_namespace (tree namespc, const char *source_file)
4378 tree decl = NAMESPACE_LEVEL (namespc)->names;
4380 /* Collect decls from this namespace. This will skip
4381 NAMESPACE_DECLs (both aliases and regular, it cannot tell). */
4382 collect_ada_nodes (decl, source_file);
4384 /* Now scan for namespace children, and dump them. */
4385 for (; decl; decl = TREE_CHAIN (decl))
4386 if (TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl))
4387 collect_ada_namespace (decl, source_file);
4390 /* Returns true iff there is a definition available for variable or
4391 function DECL. */
4393 bool
4394 decl_defined_p (tree decl)
4396 if (TREE_CODE (decl) == FUNCTION_DECL)
4397 return (DECL_INITIAL (decl) != NULL_TREE
4398 /* A pending instantiation of a friend temploid is defined. */
4399 || (DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
4400 && DECL_INITIAL (DECL_TEMPLATE_RESULT
4401 (DECL_TI_TEMPLATE (decl)))));
4402 else
4404 gcc_assert (VAR_P (decl));
4405 return !DECL_EXTERNAL (decl);
4409 /* Nonzero for a VAR_DECL whose value can be used in a constant expression.
4411 [expr.const]
4413 An integral constant-expression can only involve ... const
4414 variables of integral or enumeration types initialized with
4415 constant expressions ...
4417 C++0x also allows constexpr variables and temporaries initialized
4418 with constant expressions. We handle the former here, but the latter
4419 are just folded away in cxx_eval_constant_expression.
4421 The standard does not require that the expression be non-volatile.
4422 G++ implements the proposed correction in DR 457. */
4424 bool
4425 decl_constant_var_p (tree decl)
4427 if (!decl_maybe_constant_var_p (decl))
4428 return false;
4430 /* We don't know if a template static data member is initialized with
4431 a constant expression until we instantiate its initializer. Even
4432 in the case of a constexpr variable, we can't treat it as a
4433 constant until its initializer is complete in case it's used in
4434 its own initializer. */
4435 maybe_instantiate_decl (decl);
4436 return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
4439 /* Returns true if DECL could be a symbolic constant variable, depending on
4440 its initializer. */
4442 bool
4443 decl_maybe_constant_var_p (tree decl)
4445 tree type = TREE_TYPE (decl);
4446 if (!VAR_P (decl))
4447 return false;
4448 if (DECL_DECLARED_CONSTEXPR_P (decl) && !TREE_THIS_VOLATILE (decl))
4449 return true;
4450 if (DECL_HAS_VALUE_EXPR_P (decl))
4451 /* A proxy isn't constant. */
4452 return false;
4453 if (TYPE_REF_P (type))
4454 /* References can be constant. */;
4455 else if (CP_TYPE_CONST_NON_VOLATILE_P (type)
4456 && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4457 /* And const integers. */;
4458 else
4459 return false;
4461 if (DECL_INITIAL (decl)
4462 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
4463 /* We know the initializer, and it isn't constant. */
4464 return false;
4465 else
4466 return true;
4469 /* Complain that DECL uses a type with no linkage. In C++98 mode this is
4470 called from grokfndecl and grokvardecl; in all modes it is called from
4471 cp_write_global_declarations. */
4473 void
4474 no_linkage_error (tree decl)
4476 if (cxx_dialect >= cxx11
4477 && (decl_defined_p (decl)
4478 /* Treat templates which limit_bad_template_recursion decided
4479 not to instantiate as if they were defined. */
4480 || (errorcount + sorrycount > 0
4481 && DECL_LANG_SPECIFIC (decl)
4482 && DECL_TEMPLATE_INFO (decl)
4483 && warning_suppressed_p (decl /* What warning? */))))
4484 /* In C++11 it's ok if the decl is defined. */
4485 return;
4487 if (DECL_LANG_SPECIFIC (decl) && DECL_MODULE_IMPORT_P (decl))
4488 /* An imported decl is ok. */
4489 return;
4491 tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
4492 if (t == NULL_TREE)
4493 /* The type that got us on no_linkage_decls must have gotten a name for
4494 linkage purposes. */;
4495 else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
4496 // FIXME: This is now invalid, as a DR to c++98
4497 /* The type might end up having a typedef name for linkage purposes. */
4498 vec_safe_push (no_linkage_decls, decl);
4499 else if (TYPE_UNNAMED_P (t))
4501 bool d = false;
4502 auto_diagnostic_group grp;
4503 if (cxx_dialect >= cxx11)
4504 d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
4505 "unnamed type, is used but never defined", decl);
4506 else if (DECL_EXTERN_C_P (decl))
4507 /* Allow this; it's pretty common in C. */;
4508 else if (VAR_P (decl))
4509 /* DRs 132, 319 and 389 seem to indicate types with
4510 no linkage can only be used to declare extern "C"
4511 entities. Since it's not always an error in the
4512 ISO C++ 90 Standard, we only issue a warning. */
4513 d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "unnamed type "
4514 "with no linkage used to declare variable %q#D with "
4515 "linkage", decl);
4516 else
4517 d = permerror (DECL_SOURCE_LOCATION (decl), "unnamed type with no "
4518 "linkage used to declare function %q#D with linkage",
4519 decl);
4520 if (d && is_typedef_decl (TYPE_NAME (t)))
4521 inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
4522 "to the unqualified type, so it is not used for linkage",
4523 TYPE_NAME (t));
4525 else if (cxx_dialect >= cxx11)
4527 if (VAR_P (decl) || !DECL_PURE_VIRTUAL_P (decl))
4528 permerror (DECL_SOURCE_LOCATION (decl),
4529 "%q#D, declared using local type "
4530 "%qT, is used but never defined", decl, t);
4532 else if (VAR_P (decl))
4533 warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
4534 "used to declare variable %q#D with linkage", t, decl);
4535 else
4536 permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
4537 "to declare function %q#D with linkage", t, decl);
4540 /* Collect declarations from all namespaces relevant to SOURCE_FILE. */
4542 static void
4543 collect_all_refs (const char *source_file)
4545 collect_ada_namespace (global_namespace, source_file);
4548 /* Clear DECL_EXTERNAL for NODE. */
4550 static bool
4551 clear_decl_external (struct cgraph_node *node, void * /*data*/)
4553 DECL_EXTERNAL (node->decl) = 0;
4554 return false;
4557 /* Build up the function to run dynamic initializers for thread_local
4558 variables in this translation unit and alias the init functions for the
4559 individual variables to it. */
4561 static void
4562 handle_tls_init (void)
4564 tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
4565 if (vars == NULL_TREE)
4566 return;
4568 location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
4570 write_out_vars (vars);
4572 tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
4573 boolean_type_node);
4574 TREE_PUBLIC (guard) = false;
4575 TREE_STATIC (guard) = true;
4576 DECL_ARTIFICIAL (guard) = true;
4577 DECL_IGNORED_P (guard) = true;
4578 TREE_USED (guard) = true;
4579 CP_DECL_THREAD_LOCAL_P (guard) = true;
4580 set_decl_tls_model (guard, decl_default_tls_model (guard));
4581 pushdecl_top_level_and_finish (guard, NULL_TREE);
4583 tree fn = get_local_tls_init_fn (loc);
4584 start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
4585 tree body = begin_function_body ();
4586 tree if_stmt = begin_if_stmt ();
4587 tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
4588 tf_warning_or_error);
4589 finish_if_stmt_cond (cond, if_stmt);
4590 finish_expr_stmt (cp_build_modify_expr (loc, guard, NOP_EXPR,
4591 boolean_true_node,
4592 tf_warning_or_error));
4593 for (; vars; vars = TREE_CHAIN (vars))
4595 tree var = TREE_VALUE (vars);
4596 tree init = TREE_PURPOSE (vars);
4597 one_static_initialization_or_destruction (/*initp=*/true, var, init);
4599 /* Output init aliases even with -fno-extern-tls-init. */
4600 if (TARGET_SUPPORTS_ALIASES && TREE_PUBLIC (var))
4602 tree single_init_fn = get_tls_init_fn (var);
4603 if (single_init_fn == NULL_TREE)
4604 continue;
4605 cgraph_node *alias
4606 = cgraph_node::get_create (fn)->create_same_body_alias
4607 (single_init_fn, fn);
4608 gcc_assert (alias != NULL);
4612 finish_then_clause (if_stmt);
4613 finish_if_stmt (if_stmt);
4614 finish_function_body (body);
4615 expand_or_defer_fn (finish_function (/*inline_p=*/false));
4618 /* We're at the end of compilation, so generate any mangling aliases that
4619 we've been saving up, if DECL is going to be output and ID2 isn't
4620 already taken by another declaration. */
4622 static void
4623 generate_mangling_alias (tree decl, tree id2)
4625 struct cgraph_node *n = NULL;
4627 if (TREE_CODE (decl) == FUNCTION_DECL)
4629 n = cgraph_node::get (decl);
4630 if (!n)
4631 /* Don't create an alias to an unreferenced function. */
4632 return;
4635 tree *slot
4636 = mangled_decls->find_slot_with_hash (id2, IDENTIFIER_HASH_VALUE (id2),
4637 INSERT);
4639 /* If there's a declaration already using this mangled name,
4640 don't create a compatibility alias that conflicts. */
4641 if (*slot)
4642 return;
4644 tree alias = make_alias_for (decl, id2);
4645 *slot = alias;
4647 DECL_IGNORED_P (alias) = 1;
4648 TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
4649 DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
4650 if (vague_linkage_p (decl))
4651 DECL_WEAK (alias) = 1;
4653 if (n)
4654 n->create_same_body_alias (alias, decl);
4655 else
4656 varpool_node::create_extra_name_alias (alias, decl);
4659 /* Note that we might want to emit an alias with the symbol ID2 for DECL at
4660 the end of translation, for compatibility across bugs in the mangling
4661 implementation. */
4663 void
4664 note_mangling_alias (tree decl, tree id2)
4666 if (TARGET_SUPPORTS_ALIASES)
4668 if (!defer_mangling_aliases)
4669 generate_mangling_alias (decl, id2);
4670 else
4672 vec_safe_push (mangling_aliases, decl);
4673 vec_safe_push (mangling_aliases, id2);
4678 /* Emit all mangling aliases that were deferred up to this point. */
4680 void
4681 generate_mangling_aliases ()
4683 while (!vec_safe_is_empty (mangling_aliases))
4685 tree id2 = mangling_aliases->pop();
4686 tree decl = mangling_aliases->pop();
4687 generate_mangling_alias (decl, id2);
4689 defer_mangling_aliases = false;
4692 /* Record a mangling of DECL, whose DECL_ASSEMBLER_NAME has just been
4693 set. NEED_WARNING is true if we must warn about collisions. We do
4694 this to spot changes in mangling that may require compatibility
4695 aliases. */
4697 void
4698 record_mangling (tree decl, bool need_warning)
4700 if (!mangled_decls)
4701 mangled_decls = hash_table<mangled_decl_hash>::create_ggc (499);
4703 gcc_checking_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
4704 tree id = DECL_ASSEMBLER_NAME_RAW (decl);
4705 tree *slot
4706 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4707 INSERT);
4709 /* If this is already an alias, remove the alias, because the real
4710 decl takes precedence. */
4711 if (*slot && DECL_ARTIFICIAL (*slot) && DECL_IGNORED_P (*slot))
4712 if (symtab_node *n = symtab_node::get (*slot))
4713 if (n->cpp_implicit_alias)
4715 n->remove ();
4716 *slot = NULL_TREE;
4719 if (!*slot)
4720 *slot = decl;
4721 else if (need_warning)
4723 error_at (DECL_SOURCE_LOCATION (decl),
4724 "mangling of %q#D as %qE conflicts with a previous mangle",
4725 decl, id);
4726 inform (DECL_SOURCE_LOCATION (*slot),
4727 "previous mangling %q#D", *slot);
4728 inform (DECL_SOURCE_LOCATION (decl),
4729 "a later %<-fabi-version=%> (or =0)"
4730 " avoids this error with a change in mangling");
4731 *slot = decl;
4735 /* The mangled name of DECL is being forcibly changed to NAME. Remove
4736 any existing knowledge of DECL's mangled name meaning DECL. */
4738 void
4739 overwrite_mangling (tree decl, tree name)
4741 if (tree id = DECL_ASSEMBLER_NAME_RAW (decl))
4742 if ((TREE_CODE (decl) == VAR_DECL
4743 || TREE_CODE (decl) == FUNCTION_DECL)
4744 && mangled_decls)
4745 if (tree *slot
4746 = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4747 NO_INSERT))
4748 if (*slot == decl)
4750 mangled_decls->clear_slot (slot);
4752 /* If this is an alias, remove it from the symbol table. */
4753 if (DECL_ARTIFICIAL (decl) && DECL_IGNORED_P (decl))
4754 if (symtab_node *n = symtab_node::get (decl))
4755 if (n->cpp_implicit_alias)
4756 n->remove ();
4759 DECL_ASSEMBLER_NAME_RAW (decl) = name;
4762 /* The entire file is now complete. If requested, dump everything
4763 to a file. */
4765 static void
4766 dump_tu (void)
4768 dump_flags_t flags;
4769 if (FILE *stream = dump_begin (raw_dump_id, &flags))
4771 dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4772 dump_end (raw_dump_id, stream);
4776 static location_t locus_at_end_of_parsing;
4778 /* Check the deallocation functions for CODE to see if we want to warn that
4779 only one was defined. */
4781 static void
4782 maybe_warn_sized_delete (enum tree_code code)
4784 tree sized = NULL_TREE;
4785 tree unsized = NULL_TREE;
4787 for (ovl_iterator iter (get_global_binding (ovl_op_identifier (false, code)));
4788 iter; ++iter)
4790 tree fn = *iter;
4791 /* We're only interested in usual deallocation functions. */
4792 if (!usual_deallocation_fn_p (fn))
4793 continue;
4794 if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4795 unsized = fn;
4796 else
4797 sized = fn;
4799 if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
4800 warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
4801 "the program should also define %qD", sized);
4802 else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
4803 warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
4804 "the program should also define %qD", unsized);
4807 /* Check the global deallocation functions to see if we want to warn about
4808 defining unsized without sized (or vice versa). */
4810 static void
4811 maybe_warn_sized_delete ()
4813 if (!flag_sized_deallocation || !warn_sized_deallocation)
4814 return;
4815 maybe_warn_sized_delete (DELETE_EXPR);
4816 maybe_warn_sized_delete (VEC_DELETE_EXPR);
4819 /* Earlier we left PTRMEM_CST in variable initializers alone so that we could
4820 look them up when evaluating non-type template parameters. Now we need to
4821 lower them to something the back end can understand. */
4823 static void
4824 lower_var_init ()
4826 varpool_node *node;
4827 FOR_EACH_VARIABLE (node)
4829 tree d = node->decl;
4830 if (tree init = DECL_INITIAL (d))
4831 DECL_INITIAL (d) = cplus_expand_constant (init);
4835 /* This routine is called at the end of compilation.
4836 Its job is to create all the code needed to initialize and
4837 destroy the global aggregates. We do the destruction
4838 first, since that way we only need to reverse the decls once. */
4840 void
4841 c_parse_final_cleanups (void)
4843 size_t i;
4844 tree decl;
4846 locus_at_end_of_parsing = input_location;
4847 at_eof = 1;
4849 /* Bad parse errors. Just forget about it. */
4850 if (! global_bindings_p () || current_class_type
4851 || !vec_safe_is_empty (decl_namespace_list))
4852 return;
4854 /* This is the point to write out a PCH if we're doing that.
4855 In that case we do not want to do anything else. */
4856 if (pch_file)
4858 /* Mangle all symbols at PCH creation time. */
4859 symtab_node *node;
4860 FOR_EACH_SYMBOL (node)
4861 if (! is_a <varpool_node *> (node)
4862 || ! DECL_HARD_REGISTER (node->decl))
4863 DECL_ASSEMBLER_NAME (node->decl);
4864 c_common_write_pch ();
4865 dump_tu ();
4866 /* Ensure even the callers don't try to finalize the CU. */
4867 flag_syntax_only = 1;
4868 return;
4871 timevar_stop (TV_PHASE_PARSING);
4872 timevar_start (TV_PHASE_DEFERRED);
4874 symtab->process_same_body_aliases ();
4876 /* Handle -fdump-ada-spec[-slim] */
4877 if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
4879 collect_source_ref (main_input_filename);
4880 if (!flag_dump_ada_spec_slim)
4881 collect_source_refs (global_namespace);
4883 dump_ada_specs (collect_all_refs, cpp_check);
4886 /* FIXME - huh? was input_line -= 1;*/
4888 /* We now have to write out all the stuff we put off writing out.
4889 These include:
4891 o Template specializations that we have not yet instantiated,
4892 but which are needed.
4893 o Initialization and destruction for non-local objects with
4894 static storage duration. (Local objects with static storage
4895 duration are initialized when their scope is first entered,
4896 and are cleaned up via atexit.)
4897 o Virtual function tables.
4899 All of these may cause others to be needed. For example,
4900 instantiating one function may cause another to be needed, and
4901 generating the initializer for an object may cause templates to be
4902 instantiated, etc., etc. */
4904 emit_support_tinfos ();
4906 /* Track vtables we want to emit that refer to consteval functions. */
4907 auto_vec<tree> consteval_vtables;
4909 int retries = 0;
4910 unsigned ssdf_count = 0;
4911 for (bool reconsider = true; reconsider; retries++)
4913 reconsider = false;
4915 /* If there are templates that we've put off instantiating, do
4916 them now. */
4917 instantiate_pending_templates (retries);
4918 ggc_collect ();
4920 if (header_module_p ())
4921 /* A header modules initializations are handled in its
4922 importer. */
4923 continue;
4925 /* Write out virtual tables as required. Writing out the
4926 virtual table for a template class may cause the
4927 instantiation of members of that class. If we write out
4928 vtables then we remove the class from our list so we don't
4929 have to look at it again. */
4930 tree t;
4931 for (i = keyed_classes->length ();
4932 keyed_classes->iterate (--i, &t);)
4933 if (maybe_emit_vtables (t, consteval_vtables))
4935 reconsider = true;
4936 keyed_classes->unordered_remove (i);
4938 /* The input_location may have been changed during marking of
4939 vtable entries. */
4940 input_location = locus_at_end_of_parsing;
4942 /* Write out needed type info variables. We have to be careful
4943 looping through unemitted decls, because emit_tinfo_decl may
4944 cause other variables to be needed. New elements will be
4945 appended, and we remove from the vector those that actually
4946 get emitted. */
4947 for (i = unemitted_tinfo_decls->length ();
4948 unemitted_tinfo_decls->iterate (--i, &t);)
4949 if (emit_tinfo_decl (t))
4951 reconsider = true;
4952 unemitted_tinfo_decls->unordered_remove (i);
4955 /* The list of objects with static storage duration is built up
4956 in reverse order. We clear STATIC_AGGREGATES so that any new
4957 aggregates added during the initialization of these will be
4958 initialized in the correct order when we next come around the
4959 loop. */
4960 if (tree vars = prune_vars_needing_no_initialization (&static_aggregates))
4962 if (flag_openmp)
4963 /* Add initializer information from VARS into
4964 DYNAMIC_INITIALIZERS. */
4965 for (t = vars; t; t = TREE_CHAIN (t))
4966 hash_map_safe_put<hm_ggc> (dynamic_initializers,
4967 TREE_VALUE (t), TREE_PURPOSE (t));
4969 /* Make sure the back end knows about all the variables. */
4970 write_out_vars (vars);
4972 function_depth++; // Disable GC
4973 priority_map_t *parts[2] = {nullptr, nullptr};
4974 partition_vars_for_init_fini (vars, parts);
4976 for (unsigned initp = 2; initp--;)
4977 if (parts[initp])
4978 for (auto iter : *parts[initp])
4980 auto list = iter.second;
4981 if (initp)
4982 // Partitioning kept the vars in reverse order.
4983 // We only want that for dtors.
4984 list = nreverse (list);
4985 emit_partial_init_fini_fn (initp, iter.first, list,
4986 ssdf_count++,
4987 locus_at_end_of_parsing);
4989 function_depth--; // Re-enable GC
4991 /* All those initializations and finalizations might cause
4992 us to need more inline functions, more template
4993 instantiations, etc. */
4994 reconsider = true;
4997 /* Now do the same for thread_local variables. */
4998 handle_tls_init ();
5000 /* Go through the set of inline functions whose bodies have not
5001 been emitted yet. If out-of-line copies of these functions
5002 are required, emit them. */
5003 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5005 /* Does it need synthesizing? */
5006 if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
5007 && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
5009 /* Even though we're already at the top-level, we push
5010 there again. That way, when we pop back a few lines
5011 hence, all of our state is restored. Otherwise,
5012 finish_function doesn't clean things up, and we end
5013 up with CURRENT_FUNCTION_DECL set. */
5014 push_to_top_level ();
5015 /* The decl's location will mark where it was first
5016 needed. Save that so synthesize method can indicate
5017 where it was needed from, in case of error */
5018 input_location = DECL_SOURCE_LOCATION (decl);
5019 synthesize_method (decl);
5020 pop_from_top_level ();
5021 reconsider = true;
5024 if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
5025 generate_tls_wrapper (decl);
5027 if (!DECL_SAVED_TREE (decl))
5028 continue;
5030 cgraph_node *node = cgraph_node::get_create (decl);
5032 /* We lie to the back end, pretending that some functions
5033 are not defined when they really are. This keeps these
5034 functions from being put out unnecessarily. But, we must
5035 stop lying when the functions are referenced, or if they
5036 are not comdat since they need to be put out now. If
5037 DECL_INTERFACE_KNOWN, then we have already set
5038 DECL_EXTERNAL appropriately, so there's no need to check
5039 again, and we do not want to clear DECL_EXTERNAL if a
5040 previous call to import_export_decl set it.
5042 This is done in a separate for cycle, because if some
5043 deferred function is contained in another deferred
5044 function later in deferred_fns varray,
5045 rest_of_compilation would skip this function and we
5046 really cannot expand the same function twice. */
5047 import_export_decl (decl);
5048 if (DECL_NOT_REALLY_EXTERN (decl)
5049 && DECL_INITIAL (decl)
5050 && decl_needed_p (decl))
5052 if (node->cpp_implicit_alias)
5053 node = node->get_alias_target ();
5055 node->call_for_symbol_thunks_and_aliases (clear_decl_external,
5056 NULL, true);
5057 /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
5058 group, we need to mark all symbols in the same comdat group
5059 that way. */
5060 if (node->same_comdat_group)
5061 for (cgraph_node *next
5062 = dyn_cast<cgraph_node *> (node->same_comdat_group);
5063 next != node;
5064 next = dyn_cast<cgraph_node *> (next->same_comdat_group))
5065 next->call_for_symbol_thunks_and_aliases (clear_decl_external,
5066 NULL, true);
5069 /* If we're going to need to write this function out, and
5070 there's already a body for it, create RTL for it now.
5071 (There might be no body if this is a method we haven't
5072 gotten around to synthesizing yet.) */
5073 if (!DECL_EXTERNAL (decl)
5074 && decl_needed_p (decl)
5075 && !TREE_ASM_WRITTEN (decl)
5076 && !DECL_IMMEDIATE_FUNCTION_P (decl)
5077 && !node->definition)
5079 /* We will output the function; no longer consider it in this
5080 loop. */
5081 DECL_DEFER_OUTPUT (decl) = 0;
5082 /* Generate RTL for this function now that we know we
5083 need it. */
5084 expand_or_defer_fn (decl);
5085 reconsider = true;
5089 if (wrapup_namespace_globals ())
5090 reconsider = true;
5092 /* Static data members are just like namespace-scope globals. */
5093 FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
5095 if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
5096 /* Don't write it out if we haven't seen a definition. */
5097 || DECL_IN_AGGR_P (decl))
5098 continue;
5099 import_export_decl (decl);
5100 /* If this static data member is needed, provide it to the
5101 back end. */
5102 if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
5103 DECL_EXTERNAL (decl) = 0;
5106 if (vec_safe_length (pending_statics) != 0
5107 && wrapup_global_declarations (pending_statics->address (),
5108 pending_statics->length ()))
5109 reconsider = true;
5112 void *module_cookie = finish_module_processing (parse_in);
5114 lower_var_init ();
5116 generate_mangling_aliases ();
5118 /* All used inline functions must have a definition at this point. */
5119 FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
5121 if (/* Check online inline functions that were actually used. */
5122 DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
5123 /* If the definition actually was available here, then the
5124 fact that the function was not defined merely represents
5125 that for some reason (use of a template repository,
5126 #pragma interface, etc.) we decided not to emit the
5127 definition here. */
5128 && !DECL_INITIAL (decl)
5129 /* A defaulted fn in a header module can be synthesized on
5130 demand later. (In non-header modules we should have
5131 synthesized it above.) */
5132 && !(DECL_DEFAULTED_FN (decl) && header_module_p ())
5133 /* Don't complain if the template was defined. */
5134 && !(DECL_TEMPLATE_INSTANTIATION (decl)
5135 && DECL_INITIAL (DECL_TEMPLATE_RESULT
5136 (template_for_substitution (decl))))
5137 && warning_at (DECL_SOURCE_LOCATION (decl), 0,
5138 "inline function %qD used but never defined", decl))
5139 /* Avoid a duplicate warning from check_global_declaration. */
5140 suppress_warning (decl, OPT_Wunused);
5143 /* So must decls that use a type with no linkage. */
5144 FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
5145 no_linkage_error (decl);
5147 maybe_warn_sized_delete ();
5149 // Place the init fns in the right order. We need to do this now,
5150 // so that any module init will go at the start.
5151 if (static_init_fini_fns[true])
5152 for (auto iter : *static_init_fini_fns[true])
5153 iter.second = nreverse (iter.second);
5155 /* Then, do the Objective-C stuff. This is where all the
5156 Objective-C module stuff gets generated (symtab,
5157 class/protocol/selector lists etc). This must be done after C++
5158 templates, destructors etc. so that selectors used in C++
5159 templates are properly allocated. */
5160 if (c_dialect_objc ())
5161 objc_write_global_declarations ();
5163 bool has_module_inits = module_determine_import_inits ();
5164 bool has_objc_init = c_dialect_objc () && objc_static_init_needed_p ();
5165 if (has_module_inits || has_objc_init)
5167 input_location = locus_at_end_of_parsing;
5168 tree body = start_partial_init_fini_fn (true, DEFAULT_INIT_PRIORITY,
5169 ssdf_count++);
5170 /* For Objective-C++, we may need to initialize metadata found
5171 in this module. This must be done _before_ any other static
5172 initializations. */
5173 if (has_objc_init)
5174 objc_generate_static_init_call (NULL_TREE);
5175 if (has_module_inits)
5176 module_add_import_initializers ();
5177 input_location = locus_at_end_of_parsing;
5178 finish_partial_init_fini_fn (body);
5181 if (module_global_init_needed ())
5183 // Make sure there's a default priority entry.
5184 if (!static_init_fini_fns[true])
5185 static_init_fini_fns[true] = priority_map_t::create_ggc ();
5186 if (static_init_fini_fns[true]->get_or_insert (DEFAULT_INIT_PRIORITY))
5187 has_module_inits = true;
5190 /* Generate initialization and destruction functions for all
5191 priorities for which they are required. They have C-language
5192 linkage. */
5193 push_lang_context (lang_name_c);
5194 for (unsigned initp = 2; initp--;)
5195 if (static_init_fini_fns[initp])
5197 for (auto iter : *static_init_fini_fns[initp])
5198 generate_ctor_or_dtor_function (initp, iter.first, iter.second,
5199 locus_at_end_of_parsing);
5200 static_init_fini_fns[initp] = nullptr;
5202 pop_lang_context ();
5204 fini_modules (parse_in, module_cookie, has_module_inits);
5206 /* Generate any missing aliases. */
5207 maybe_apply_pending_pragma_weaks ();
5209 if (flag_vtable_verify)
5211 vtv_recover_class_info ();
5212 vtv_compute_class_hierarchy_transitive_closure ();
5213 vtv_build_vtable_verify_fndecl ();
5216 perform_deferred_noexcept_checks ();
5218 fini_constexpr ();
5219 cp_tree_c_finish_parsing ();
5220 clear_consteval_vfns (consteval_vtables);
5222 /* The entire file is now complete. If requested, dump everything
5223 to a file. */
5224 dump_tu ();
5226 if (flag_detailed_statistics)
5228 dump_tree_statistics ();
5229 dump_time_statistics ();
5232 timevar_stop (TV_PHASE_DEFERRED);
5233 timevar_start (TV_PHASE_PARSING);
5235 /* Indicate that we're done with front end processing. */
5236 at_eof = 2;
5239 /* Perform any post compilation-proper cleanups for the C++ front-end.
5240 This should really go away. No front-end should need to do
5241 anything past the compilation process. */
5243 void
5244 cxx_post_compilation_parsing_cleanups (void)
5246 timevar_start (TV_PHASE_LATE_PARSING_CLEANUPS);
5248 if (flag_vtable_verify)
5250 /* Generate the special constructor initialization function that
5251 calls __VLTRegisterPairs, and give it a very high
5252 initialization priority. This must be done after
5253 finalize_compilation_unit so that we have accurate
5254 information about which vtable will actually be emitted. */
5255 vtv_generate_init_routine ();
5258 input_location = locus_at_end_of_parsing;
5260 if (flag_checking)
5261 validate_conversion_obstack ();
5263 timevar_stop (TV_PHASE_LATE_PARSING_CLEANUPS);
5266 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
5267 function to call in parse-tree form; it has not yet been
5268 semantically analyzed. ARGS are the arguments to the function.
5269 They have already been semantically analyzed. This may change
5270 ARGS. */
5272 tree
5273 build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
5274 tsubst_flags_t complain)
5276 tree orig_fn;
5277 vec<tree, va_gc> *orig_args = NULL;
5278 tree expr;
5279 tree object;
5281 orig_fn = fn;
5282 object = TREE_OPERAND (fn, 0);
5284 if (processing_template_decl)
5286 gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
5287 || TREE_CODE (fn) == MEMBER_REF);
5288 if (type_dependent_expression_p (fn)
5289 || any_type_dependent_arguments_p (*args))
5290 return build_min_nt_call_vec (fn, *args);
5292 orig_args = make_tree_vector_copy (*args);
5294 /* Transform the arguments and add the implicit "this"
5295 parameter. That must be done before the FN is transformed
5296 because we depend on the form of FN. */
5297 make_args_non_dependent (*args);
5298 object = build_non_dependent_expr (object);
5299 if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5301 if (TREE_CODE (fn) == DOTSTAR_EXPR)
5302 object = cp_build_addr_expr (object, complain);
5303 vec_safe_insert (*args, 0, object);
5305 /* Now that the arguments are done, transform FN. */
5306 fn = build_non_dependent_expr (fn);
5309 /* A qualified name corresponding to a bound pointer-to-member is
5310 represented as an OFFSET_REF:
5312 struct B { void g(); };
5313 void (B::*p)();
5314 void B::g() { (this->*p)(); } */
5315 if (TREE_CODE (fn) == OFFSET_REF)
5317 tree object_addr = cp_build_addr_expr (object, complain);
5318 fn = TREE_OPERAND (fn, 1);
5319 fn = get_member_function_from_ptrfunc (&object_addr, fn,
5320 complain);
5321 vec_safe_insert (*args, 0, object_addr);
5324 if (CLASS_TYPE_P (TREE_TYPE (fn)))
5325 expr = build_op_call (fn, args, complain);
5326 else
5327 expr = cp_build_function_call_vec (fn, args, complain);
5328 if (processing_template_decl && expr != error_mark_node)
5329 expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
5331 if (orig_args != NULL)
5332 release_tree_vector (orig_args);
5334 return expr;
5338 void
5339 check_default_args (tree x)
5341 tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
5342 bool saw_def = false;
5343 bool noted_first_def = false;
5344 int idx_of_first_default_arg = 0;
5345 location_t loc_of_first_default_arg = UNKNOWN_LOCATION;
5346 int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
5347 tree fndecl = STRIP_TEMPLATE (x);
5348 auto_diagnostic_group d;
5349 for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
5351 if (TREE_PURPOSE (arg))
5353 if (!saw_def)
5355 saw_def = true;
5356 idx_of_first_default_arg = i;
5357 location_t loc = get_fndecl_argument_location (fndecl, i);
5358 if (loc != DECL_SOURCE_LOCATION (x))
5359 loc_of_first_default_arg = loc;
5362 else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
5364 error_at (get_fndecl_argument_location (fndecl, i),
5365 "default argument missing for parameter %P of %q#D", i, x);
5366 if (loc_of_first_default_arg != UNKNOWN_LOCATION
5367 && !noted_first_def)
5369 inform (loc_of_first_default_arg,
5370 "...following parameter %P which has a default argument",
5371 idx_of_first_default_arg);
5372 noted_first_def = true;
5374 TREE_PURPOSE (arg) = error_mark_node;
5379 /* Return true if function DECL can be inlined. This is used to force
5380 instantiation of methods that might be interesting for inlining. */
5381 bool
5382 possibly_inlined_p (tree decl)
5384 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
5385 if (DECL_UNINLINABLE (decl))
5386 return false;
5387 if (!optimize)
5388 return DECL_DECLARED_INLINE_P (decl);
5389 /* When optimizing, we might inline everything when flatten
5390 attribute or heuristics inlining for size or autoinlining
5391 is used. */
5392 return true;
5395 /* If DECL is a function or variable template specialization, instantiate
5396 its definition now. */
5398 void
5399 maybe_instantiate_decl (tree decl)
5401 if (VAR_OR_FUNCTION_DECL_P (decl)
5402 && DECL_LANG_SPECIFIC (decl)
5403 && DECL_TEMPLATE_INFO (decl)
5404 && !DECL_DECLARED_CONCEPT_P (decl)
5405 && !uses_template_parms (DECL_TI_ARGS (decl)))
5407 /* Instantiating a function will result in garbage collection. We
5408 must treat this situation as if we were within the body of a
5409 function so as to avoid collecting live data only referenced from
5410 the stack (such as overload resolution candidates). */
5411 ++function_depth;
5412 instantiate_decl (decl, /*defer_ok=*/false,
5413 /*expl_inst_class_mem_p=*/false);
5414 --function_depth;
5418 /* Error if the DECL is unavailable (unless this is currently suppressed).
5419 Maybe warn if DECL is deprecated, subject to COMPLAIN. Returns true if
5420 an error or warning was emitted. */
5422 bool
5423 cp_handle_deprecated_or_unavailable (tree decl, tsubst_flags_t complain)
5425 if (!decl)
5426 return false;
5428 if ((complain & tf_error)
5429 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
5431 if (TREE_UNAVAILABLE (decl))
5433 error_unavailable_use (decl, NULL_TREE);
5434 return true;
5436 else
5438 /* Perhaps this is an unavailable typedef. */
5439 if (TYPE_P (decl)
5440 && TYPE_NAME (decl)
5441 && TREE_UNAVAILABLE (TYPE_NAME (decl)))
5443 decl = TYPE_NAME (decl);
5444 /* Don't error within members of a unavailable type. */
5445 if (TYPE_P (decl)
5446 && currently_open_class (decl))
5447 return false;
5449 error_unavailable_use (decl, NULL_TREE);
5450 return true;
5453 /* Carry on to consider deprecatedness. */
5456 if (!(complain & tf_warning)
5457 || deprecated_state == DEPRECATED_SUPPRESS
5458 || deprecated_state == UNAVAILABLE_DEPRECATED_SUPPRESS)
5459 return false;
5461 if (!TREE_DEPRECATED (decl))
5463 /* Perhaps this is a deprecated typedef. */
5464 if (TYPE_P (decl) && TYPE_NAME (decl))
5465 decl = TYPE_NAME (decl);
5467 if (!TREE_DEPRECATED (decl))
5468 return false;
5471 /* Don't warn within members of a deprecated type. */
5472 if (TYPE_P (decl)
5473 && currently_open_class (decl))
5474 return false;
5476 bool warned = false;
5477 if (cxx_dialect >= cxx11
5478 && DECL_P (decl)
5479 && DECL_ARTIFICIAL (decl)
5480 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5481 && copy_fn_p (decl))
5483 /* Don't warn if the flag was disabled around the class definition
5484 (c++/94492). */
5485 if (warning_enabled_at (DECL_SOURCE_LOCATION (decl),
5486 OPT_Wdeprecated_copy))
5488 auto_diagnostic_group d;
5489 tree ctx = DECL_CONTEXT (decl);
5490 tree other = classtype_has_depr_implicit_copy (ctx);
5491 int opt = (DECL_DESTRUCTOR_P (other)
5492 ? OPT_Wdeprecated_copy_dtor
5493 : OPT_Wdeprecated_copy);
5494 warned = warning (opt, "implicitly-declared %qD is deprecated",
5495 decl);
5496 if (warned)
5497 inform (DECL_SOURCE_LOCATION (other),
5498 "because %qT has user-provided %qD",
5499 ctx, other);
5502 else
5503 warned = warn_deprecated_use (decl, NULL_TREE);
5505 return warned;
5508 /* Like above, but takes into account outer scopes. */
5510 void
5511 cp_warn_deprecated_use_scopes (tree scope)
5513 while (scope
5514 && scope != error_mark_node
5515 && scope != global_namespace)
5517 if ((TREE_CODE (scope) == NAMESPACE_DECL || OVERLOAD_TYPE_P (scope))
5518 && cp_handle_deprecated_or_unavailable (scope))
5519 return;
5520 if (TYPE_P (scope))
5521 scope = CP_TYPE_CONTEXT (scope);
5522 else
5523 scope = CP_DECL_CONTEXT (scope);
5527 /* True if DECL or its enclosing scope have unbound template parameters. */
5529 bool
5530 decl_dependent_p (tree decl)
5532 if (DECL_FUNCTION_SCOPE_P (decl)
5533 || TREE_CODE (decl) == CONST_DECL
5534 || TREE_CODE (decl) == USING_DECL
5535 || TREE_CODE (decl) == FIELD_DECL)
5536 decl = CP_DECL_CONTEXT (decl);
5537 if (tree tinfo = get_template_info (decl))
5538 if (any_dependent_template_arguments_p (TI_ARGS (tinfo)))
5539 return true;
5540 if (LAMBDA_FUNCTION_P (decl)
5541 && dependent_type_p (DECL_CONTEXT (decl)))
5542 return true;
5543 return false;
5546 /* [basic.def.odr] A function is named [and therefore odr-used] by an
5547 expression or conversion if it is the selected member of an overload set in
5548 an overload resolution performed as part of forming that expression or
5549 conversion, unless it is a pure virtual function and either the expression
5550 is not an id-expression naming the function with an explicitly qualified
5551 name or the expression forms a pointer to member.
5553 Mostly, we call mark_used in places that actually do something with a
5554 function, like build_over_call. But in a few places we end up with a
5555 non-overloaded FUNCTION_DECL that we aren't going to do any more with, like
5556 convert_to_void. resolve_nondeduced_context is called in those places,
5557 but it's also called in too many other places. */
5559 bool
5560 mark_single_function (tree expr, tsubst_flags_t complain)
5562 expr = maybe_undo_parenthesized_ref (expr);
5563 expr = tree_strip_any_location_wrapper (expr);
5565 if (is_overloaded_fn (expr) == 1
5566 && !mark_used (expr, complain)
5567 && (complain & tf_error))
5568 return false;
5569 return true;
5572 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
5573 If DECL is a specialization or implicitly declared class member,
5574 generate the actual definition. Return false if something goes
5575 wrong, true otherwise. */
5577 bool
5578 mark_used (tree decl, tsubst_flags_t complain /* = tf_warning_or_error */)
5580 /* If we're just testing conversions or resolving overloads, we
5581 don't want any permanent effects like forcing functions to be
5582 output or instantiating templates. */
5583 if ((complain & tf_conv))
5584 return true;
5586 /* If DECL is a BASELINK for a single function, then treat it just
5587 like the DECL for the function. Otherwise, if the BASELINK is
5588 for an overloaded function, we don't know which function was
5589 actually used until after overload resolution. */
5590 if (BASELINK_P (decl))
5592 tree fns = BASELINK_FUNCTIONS (decl);
5593 if (really_overloaded_fn (fns))
5594 return true;
5595 fns = OVL_FIRST (fns);
5596 if (!mark_used (fns, complain))
5597 return false;
5598 /* We might have deduced its return type. */
5599 TREE_TYPE (decl) = TREE_TYPE (fns);
5600 return true;
5603 if (!DECL_P (decl))
5604 return true;
5606 /* Set TREE_USED for the benefit of -Wunused. */
5607 TREE_USED (decl) = true;
5609 /* And for structured bindings also the underlying decl. */
5610 if (DECL_DECOMPOSITION_P (decl) && DECL_DECOMP_BASE (decl))
5611 TREE_USED (DECL_DECOMP_BASE (decl)) = true;
5613 if (TREE_CODE (decl) == TEMPLATE_DECL)
5614 return true;
5616 if (DECL_CLONED_FUNCTION_P (decl))
5617 TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5619 /* Mark enumeration types as used. */
5620 if (TREE_CODE (decl) == CONST_DECL)
5621 used_types_insert (DECL_CONTEXT (decl));
5623 if (TREE_CODE (decl) == FUNCTION_DECL)
5625 if (DECL_MAYBE_DELETED (decl))
5627 ++function_depth;
5628 maybe_synthesize_method (decl);
5629 --function_depth;
5632 if (DECL_DELETED_FN (decl))
5634 if (DECL_ARTIFICIAL (decl)
5635 && DECL_CONV_FN_P (decl)
5636 && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
5637 /* We mark a lambda conversion op as deleted if we can't
5638 generate it properly; see maybe_add_lambda_conv_op. */
5639 sorry ("converting lambda that uses %<...%> to function pointer");
5640 else if (complain & tf_error)
5642 error ("use of deleted function %qD", decl);
5643 if (!maybe_explain_implicit_delete (decl))
5644 inform (DECL_SOURCE_LOCATION (decl), "declared here");
5646 return false;
5649 if (!maybe_instantiate_noexcept (decl, complain))
5650 return false;
5653 if (VAR_OR_FUNCTION_DECL_P (decl) && DECL_LOCAL_DECL_P (decl))
5655 if (!DECL_LANG_SPECIFIC (decl))
5656 /* An unresolved dependent local extern. */
5657 return true;
5659 DECL_ODR_USED (decl) = 1;
5660 auto alias = DECL_LOCAL_DECL_ALIAS (decl);
5661 if (!alias || alias == error_mark_node)
5662 return true;
5664 /* Process the underlying decl. */
5665 decl = alias;
5666 TREE_USED (decl) = true;
5669 cp_handle_deprecated_or_unavailable (decl, complain);
5671 /* We can only check DECL_ODR_USED on variables or functions with
5672 DECL_LANG_SPECIFIC set, and these are also the only decls that we
5673 might need special handling for. */
5674 if (!VAR_OR_FUNCTION_DECL_P (decl)
5675 || DECL_LANG_SPECIFIC (decl) == NULL
5676 || DECL_THUNK_P (decl))
5678 if (!decl_dependent_p (decl)
5679 && !require_deduced_type (decl, complain))
5680 return false;
5681 return true;
5684 /* We only want to do this processing once. We don't need to keep trying
5685 to instantiate inline templates, because unit-at-a-time will make sure
5686 we get them compiled before functions that want to inline them. */
5687 if (DECL_ODR_USED (decl))
5688 return true;
5690 if (flag_concepts && TREE_CODE (decl) == FUNCTION_DECL
5691 && !constraints_satisfied_p (decl))
5693 if (complain & tf_error)
5695 auto_diagnostic_group d;
5696 error ("use of function %qD with unsatisfied constraints",
5697 decl);
5698 location_t loc = DECL_SOURCE_LOCATION (decl);
5699 inform (loc, "declared here");
5700 diagnose_constraints (loc, decl, NULL_TREE);
5702 return false;
5705 /* If DECL has a deduced return type, we need to instantiate it now to
5706 find out its type. For OpenMP user defined reductions, we need them
5707 instantiated for reduction clauses which inline them by hand directly. */
5708 if (undeduced_auto_decl (decl)
5709 || (TREE_CODE (decl) == FUNCTION_DECL
5710 && DECL_OMP_DECLARE_REDUCTION_P (decl)))
5711 maybe_instantiate_decl (decl);
5713 if (processing_template_decl || in_template_function ())
5714 return true;
5716 /* Check this too in case we're within instantiate_non_dependent_expr. */
5717 if (DECL_TEMPLATE_INFO (decl)
5718 && uses_template_parms (DECL_TI_ARGS (decl)))
5719 return true;
5721 if (!require_deduced_type (decl, complain))
5722 return false;
5724 if (builtin_pack_fn_p (decl))
5726 error ("use of built-in parameter pack %qD outside of a template",
5727 DECL_NAME (decl));
5728 return false;
5731 /* If we don't need a value, then we don't need to synthesize DECL. */
5732 if (cp_unevaluated_operand || in_discarded_stmt)
5733 return true;
5735 DECL_ODR_USED (decl) = 1;
5736 if (DECL_CLONED_FUNCTION_P (decl))
5737 DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5739 /* DR 757: A type without linkage shall not be used as the type of a
5740 variable or function with linkage, unless
5741 o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
5742 o the variable or function is not used (3.2 [basic.def.odr]) or is
5743 defined in the same translation unit. */
5744 if (cxx_dialect > cxx98
5745 && decl_linkage (decl) != lk_none
5746 && !DECL_EXTERN_C_P (decl)
5747 && !DECL_ARTIFICIAL (decl)
5748 && !decl_defined_p (decl)
5749 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
5750 vec_safe_push (no_linkage_decls, decl);
5752 if (TREE_CODE (decl) == FUNCTION_DECL
5753 && DECL_DECLARED_INLINE_P (decl)
5754 && !DECL_INITIAL (decl)
5755 && !DECL_ARTIFICIAL (decl)
5756 && !DECL_PURE_VIRTUAL_P (decl))
5757 /* Remember it, so we can check it was defined. */
5758 note_vague_linkage_fn (decl);
5760 /* Is it a synthesized method that needs to be synthesized? */
5761 if (TREE_CODE (decl) == FUNCTION_DECL
5762 && DECL_DEFAULTED_FN (decl)
5763 /* A function defaulted outside the class is synthesized either by
5764 cp_finish_decl or instantiate_decl. */
5765 && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
5766 && ! DECL_INITIAL (decl))
5768 /* Defer virtual destructors so that thunks get the right
5769 linkage. */
5770 if (DECL_VIRTUAL_P (decl) && !at_eof)
5772 note_vague_linkage_fn (decl);
5773 return true;
5776 /* Remember the current location for a function we will end up
5777 synthesizing. Then we can inform the user where it was
5778 required in the case of error. */
5779 if (decl_remember_implicit_trigger_p (decl))
5780 DECL_SOURCE_LOCATION (decl) = input_location;
5782 /* Synthesizing an implicitly defined member function will result in
5783 garbage collection. We must treat this situation as if we were
5784 within the body of a function so as to avoid collecting live data
5785 on the stack (such as overload resolution candidates).
5787 We could just let c_parse_final_cleanups handle synthesizing
5788 this function by adding it to deferred_fns, but doing
5789 it at the use site produces better error messages. */
5790 ++function_depth;
5791 synthesize_method (decl);
5792 --function_depth;
5793 /* If this is a synthesized method we don't need to
5794 do the instantiation test below. */
5796 else if (VAR_OR_FUNCTION_DECL_P (decl)
5797 && DECL_TEMPLATE_INFO (decl)
5798 && !DECL_DECLARED_CONCEPT_P (decl)
5799 && (!DECL_EXPLICIT_INSTANTIATION (decl)
5800 || always_instantiate_p (decl)))
5801 /* If this is a function or variable that is an instance of some
5802 template, we now know that we will need to actually do the
5803 instantiation. We check that DECL is not an explicit
5804 instantiation because that is not checked in instantiate_decl.
5806 We put off instantiating functions in order to improve compile
5807 times. Maintaining a stack of active functions is expensive,
5808 and the inliner knows to instantiate any functions it might
5809 need. Therefore, we always try to defer instantiation. */
5811 ++function_depth;
5812 instantiate_decl (decl, /*defer_ok=*/true,
5813 /*expl_inst_class_mem_p=*/false);
5814 --function_depth;
5817 return true;
5820 tree
5821 vtv_start_verification_constructor_init_function (void)
5823 return start_objects (/*initp=*/true, MAX_RESERVED_INIT_PRIORITY - 1, true);
5826 tree
5827 vtv_finish_verification_constructor_init_function (tree body)
5829 return finish_objects (/*initp=*/true, MAX_RESERVED_INIT_PRIORITY - 1, body);
5832 #include "gt-cp-decl2.h"