xref: /dragonfly/contrib/gcc-8.0/gcc/cp/decl2.c (revision aefcce89)
1 /* Process declarations and variables for C++ compiler.
2    Copyright (C) 1988-2018 Free Software Foundation, Inc.
3    Hacked by Michael Tiemann (tiemann@cygnus.com)
4 
5 This file is part of GCC.
6 
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.
11 
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.
16 
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/>.  */
20 
21 
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.  */
25 
26 /* ??? not all decl nodes are given the most useful possible
27    line numbers.  For example, the CONST_DECLs for enum values.  */
28 
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 
52 /* Id for dumping the raw trees.  */
53 int raw_dump_id;
54 
55 extern cpp_reader *parse_in;
56 
57 /* This structure contains information about the initializations
58    and/or destructions required for a particular priority level.  */
59 typedef struct priority_info_s {
60   /* Nonzero if there have been any initializations at this priority
61      throughout the translation unit.  */
62   int initializations_p;
63   /* Nonzero if there have been any destructions at this priority
64      throughout the translation unit.  */
65   int destructions_p;
66 } *priority_info;
67 
68 static void mark_vtable_entries (tree);
69 static bool maybe_emit_vtables (tree);
70 static tree start_objects (int, int);
71 static void finish_objects (int, int, tree);
72 static tree start_static_storage_duration_function (unsigned);
73 static void finish_static_storage_duration_function (tree);
74 static priority_info get_priority_info (int);
75 static void do_static_initialization_or_destruction (tree, bool);
76 static void one_static_initialization_or_destruction (tree, tree, bool);
77 static void generate_ctor_or_dtor_function (bool, int, location_t *);
78 static int generate_ctor_and_dtor_functions_for_priority (splay_tree_node,
79 							  void *);
80 static tree prune_vars_needing_no_initialization (tree *);
81 static void write_out_vars (tree);
82 static void import_export_class (tree);
83 static tree get_guard_bits (tree);
84 static void determine_visibility_from_class (tree, tree);
85 static bool determine_hidden_inline (tree);
86 static void maybe_instantiate_decl (tree);
87 
88 /* A list of static class variables.  This is needed, because a
89    static class variable can be declared inside the class without
90    an initializer, and then initialized, statically, outside the class.  */
91 static GTY(()) vec<tree, va_gc> *pending_statics;
92 
93 /* A list of functions which were declared inline, but which we
94    may need to emit outline anyway.  */
95 static GTY(()) vec<tree, va_gc> *deferred_fns;
96 
97 /* A list of decls that use types with no linkage, which we need to make
98    sure are defined.  */
99 static GTY(()) vec<tree, va_gc> *no_linkage_decls;
100 
101 /* A vector of alternating decls and identifiers, where the latter
102    is to be an alias for the former if the former is defined.  */
103 static GTY(()) vec<tree, va_gc> *mangling_aliases;
104 
105 /* hash traits for declarations.  Hashes single decls via
106    DECL_ASSEMBLER_NAME_RAW.  */
107 
108 struct mangled_decl_hash : ggc_remove <tree>
109 {
110   typedef tree value_type; /* A DECL.  */
111   typedef tree compare_type; /* An identifier.  */
112 
113   static hashval_t hash (const value_type decl)
114   {
115     return IDENTIFIER_HASH_VALUE (DECL_ASSEMBLER_NAME_RAW (decl));
116   }
117   static bool equal (const value_type existing, compare_type candidate)
118   {
119     tree name = DECL_ASSEMBLER_NAME_RAW (existing);
120     return candidate == name;
121   }
122 
123   static inline void mark_empty (value_type &p) {p = NULL_TREE;}
124   static inline bool is_empty (value_type p) {return !p;}
125 
126   static bool is_deleted (value_type e)
127   {
128     return e == reinterpret_cast <value_type> (1);
129   }
130   static void mark_deleted (value_type &e)
131   {
132     e = reinterpret_cast <value_type> (1);
133   }
134 };
135 
136 /* A hash table of decls keyed by mangled name.  Used to figure out if
137    we need compatibility aliases.  */
138 static GTY(()) hash_table<mangled_decl_hash> *mangled_decls;
139 
140 /* Nonzero if we're done parsing and into end-of-file activities.  */
141 
142 int at_eof;
143 
144 /* True if note_mangling_alias should enqueue mangling aliases for
145    later generation, rather than emitting them right away.  */
146 
147 bool defer_mangling_aliases = true;
148 
149 
150 /* Return a member function type (a METHOD_TYPE), given FNTYPE (a
151    FUNCTION_TYPE), CTYPE (class type), and QUALS (the cv-qualifiers
152    that apply to the function).  */
153 
154 tree
155 build_memfn_type (tree fntype, tree ctype, cp_cv_quals quals,
156 		  cp_ref_qualifier rqual)
157 {
158   tree raises;
159   tree attrs;
160   int type_quals;
161   bool late_return_type_p;
162 
163   if (fntype == error_mark_node || ctype == error_mark_node)
164     return error_mark_node;
165 
166   gcc_assert (TREE_CODE (fntype) == FUNCTION_TYPE
167 	      || TREE_CODE (fntype) == METHOD_TYPE);
168 
169   type_quals = quals & ~TYPE_QUAL_RESTRICT;
170   ctype = cp_build_qualified_type (ctype, type_quals);
171   raises = TYPE_RAISES_EXCEPTIONS (fntype);
172   attrs = TYPE_ATTRIBUTES (fntype);
173   late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype);
174   fntype = build_method_type_directly (ctype, TREE_TYPE (fntype),
175 				       (TREE_CODE (fntype) == METHOD_TYPE
176 					? TREE_CHAIN (TYPE_ARG_TYPES (fntype))
177 					: TYPE_ARG_TYPES (fntype)));
178   if (attrs)
179     fntype = cp_build_type_attribute_variant (fntype, attrs);
180   if (rqual)
181     fntype = build_ref_qualified_type (fntype, rqual);
182   if (raises)
183     fntype = build_exception_variant (fntype, raises);
184   if (late_return_type_p)
185     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
186 
187   return fntype;
188 }
189 
190 /* Return a variant of FNTYPE, a FUNCTION_TYPE or METHOD_TYPE, with its
191    return type changed to NEW_RET.  */
192 
193 tree
194 change_return_type (tree new_ret, tree fntype)
195 {
196   tree newtype;
197   tree args = TYPE_ARG_TYPES (fntype);
198   tree raises = TYPE_RAISES_EXCEPTIONS (fntype);
199   tree attrs = TYPE_ATTRIBUTES (fntype);
200   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (fntype);
201 
202   if (new_ret == error_mark_node)
203     return fntype;
204 
205   if (same_type_p (new_ret, TREE_TYPE (fntype)))
206     return fntype;
207 
208   if (TREE_CODE (fntype) == FUNCTION_TYPE)
209     {
210       newtype = build_function_type (new_ret, args);
211       newtype = apply_memfn_quals (newtype,
212 				   type_memfn_quals (fntype),
213 				   type_memfn_rqual (fntype));
214     }
215   else
216     newtype = build_method_type_directly
217       (class_of_this_parm (fntype), new_ret, TREE_CHAIN (args));
218   if (FUNCTION_REF_QUALIFIED (fntype))
219     newtype = build_ref_qualified_type (newtype, type_memfn_rqual (fntype));
220   if (raises)
221     newtype = build_exception_variant (newtype, raises);
222   if (attrs)
223     newtype = cp_build_type_attribute_variant (newtype, attrs);
224   if (late_return_type_p)
225     TYPE_HAS_LATE_RETURN_TYPE (newtype) = 1;
226 
227   return newtype;
228 }
229 
230 /* Build a PARM_DECL of FN with NAME and TYPE, and set DECL_ARG_TYPE
231    appropriately.  */
232 
233 tree
234 cp_build_parm_decl (tree fn, tree name, tree type)
235 {
236   tree parm = build_decl (input_location,
237 			  PARM_DECL, name, type);
238   DECL_CONTEXT (parm) = fn;
239 
240   /* DECL_ARG_TYPE is only used by the back end and the back end never
241      sees templates.  */
242   if (!processing_template_decl)
243     DECL_ARG_TYPE (parm) = type_passed_as (type);
244 
245   return parm;
246 }
247 
248 /* Returns a PARM_DECL of FN for a parameter of the indicated TYPE, with the
249    indicated NAME.  */
250 
251 tree
252 build_artificial_parm (tree fn, tree name, tree type)
253 {
254   tree parm = cp_build_parm_decl (fn, name, type);
255   DECL_ARTIFICIAL (parm) = 1;
256   /* All our artificial parms are implicitly `const'; they cannot be
257      assigned to.  */
258   TREE_READONLY (parm) = 1;
259   return parm;
260 }
261 
262 /* Constructors for types with virtual baseclasses need an "in-charge" flag
263    saying whether this constructor is responsible for initialization of
264    virtual baseclasses or not.  All destructors also need this "in-charge"
265    flag, which additionally determines whether or not the destructor should
266    free the memory for the object.
267 
268    This function adds the "in-charge" flag to member function FN if
269    appropriate.  It is called from grokclassfn and tsubst.
270    FN must be either a constructor or destructor.
271 
272    The in-charge flag follows the 'this' parameter, and is followed by the
273    VTT parm (if any), then the user-written parms.  */
274 
275 void
276 maybe_retrofit_in_chrg (tree fn)
277 {
278   tree basetype, arg_types, parms, parm, fntype;
279 
280   /* If we've already add the in-charge parameter don't do it again.  */
281   if (DECL_HAS_IN_CHARGE_PARM_P (fn))
282     return;
283 
284   /* When processing templates we can't know, in general, whether or
285      not we're going to have virtual baseclasses.  */
286   if (processing_template_decl)
287     return;
288 
289   /* We don't need an in-charge parameter for constructors that don't
290      have virtual bases.  */
291   if (DECL_CONSTRUCTOR_P (fn)
292       && !CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
293     return;
294 
295   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
296   basetype = TREE_TYPE (TREE_VALUE (arg_types));
297   arg_types = TREE_CHAIN (arg_types);
298 
299   parms = DECL_CHAIN (DECL_ARGUMENTS (fn));
300 
301   /* If this is a subobject constructor or destructor, our caller will
302      pass us a pointer to our VTT.  */
303   if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fn)))
304     {
305       parm = build_artificial_parm (fn, vtt_parm_identifier, vtt_parm_type);
306 
307       /* First add it to DECL_ARGUMENTS between 'this' and the real args...  */
308       DECL_CHAIN (parm) = parms;
309       parms = parm;
310 
311       /* ...and then to TYPE_ARG_TYPES.  */
312       arg_types = hash_tree_chain (vtt_parm_type, arg_types);
313 
314       DECL_HAS_VTT_PARM_P (fn) = 1;
315     }
316 
317   /* Then add the in-charge parm (before the VTT parm).  */
318   parm = build_artificial_parm (fn, in_charge_identifier, integer_type_node);
319   DECL_CHAIN (parm) = parms;
320   parms = parm;
321   arg_types = hash_tree_chain (integer_type_node, arg_types);
322 
323   /* Insert our new parameter(s) into the list.  */
324   DECL_CHAIN (DECL_ARGUMENTS (fn)) = parms;
325 
326   /* And rebuild the function type.  */
327   fntype = build_method_type_directly (basetype, TREE_TYPE (TREE_TYPE (fn)),
328 				       arg_types);
329   if (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)))
330     fntype = build_exception_variant (fntype,
331 				      TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn)));
332   if (TYPE_ATTRIBUTES (TREE_TYPE (fn)))
333     fntype = (cp_build_type_attribute_variant
334 	      (fntype, TYPE_ATTRIBUTES (TREE_TYPE (fn))));
335   TREE_TYPE (fn) = fntype;
336 
337   /* Now we've got the in-charge parameter.  */
338   DECL_HAS_IN_CHARGE_PARM_P (fn) = 1;
339 }
340 
341 /* Classes overload their constituent function names automatically.
342    When a function name is declared in a record structure,
343    its name is changed to it overloaded name.  Since names for
344    constructors and destructors can conflict, we place a leading
345    '$' for destructors.
346 
347    CNAME is the name of the class we are grokking for.
348 
349    FUNCTION is a FUNCTION_DECL.  It was created by `grokdeclarator'.
350 
351    FLAGS contains bits saying what's special about today's
352    arguments.  DTOR_FLAG == DESTRUCTOR.
353 
354    If FUNCTION is a destructor, then we must add the `auto-delete' field
355    as a second parameter.  There is some hair associated with the fact
356    that we must "declare" this variable in the manner consistent with the
357    way the rest of the arguments were declared.
358 
359    QUALS are the qualifiers for the this pointer.  */
360 
361 void
362 grokclassfn (tree ctype, tree function, enum overload_flags flags)
363 {
364   tree fn_name = DECL_NAME (function);
365 
366   /* Even within an `extern "C"' block, members get C++ linkage.  See
367      [dcl.link] for details.  */
368   SET_DECL_LANGUAGE (function, lang_cplusplus);
369 
370   if (fn_name == NULL_TREE)
371     {
372       error ("name missing for member function");
373       fn_name = get_identifier ("<anonymous>");
374       DECL_NAME (function) = fn_name;
375     }
376 
377   DECL_CONTEXT (function) = ctype;
378 
379   if (flags == DTOR_FLAG)
380     DECL_CXX_DESTRUCTOR_P (function) = 1;
381 
382   if (flags == DTOR_FLAG || DECL_CONSTRUCTOR_P (function))
383     maybe_retrofit_in_chrg (function);
384 }
385 
386 /* Create an ARRAY_REF, checking for the user doing things backwards
387    along the way.  DECLTYPE_P is for N3276, as in the parser.  */
388 
389 tree
390 grok_array_decl (location_t loc, tree array_expr, tree index_exp,
391 		 bool decltype_p)
392 {
393   tree type;
394   tree expr;
395   tree orig_array_expr = array_expr;
396   tree orig_index_exp = index_exp;
397   tree overload = NULL_TREE;
398 
399   if (error_operand_p (array_expr) || error_operand_p (index_exp))
400     return error_mark_node;
401 
402   if (processing_template_decl)
403     {
404       if (type_dependent_expression_p (array_expr)
405 	  || type_dependent_expression_p (index_exp))
406 	return build_min_nt_loc (loc, ARRAY_REF, array_expr, index_exp,
407 				 NULL_TREE, NULL_TREE);
408       array_expr = build_non_dependent_expr (array_expr);
409       index_exp = build_non_dependent_expr (index_exp);
410     }
411 
412   type = TREE_TYPE (array_expr);
413   gcc_assert (type);
414   type = non_reference (type);
415 
416   /* If they have an `operator[]', use that.  */
417   if (MAYBE_CLASS_TYPE_P (type) || MAYBE_CLASS_TYPE_P (TREE_TYPE (index_exp)))
418     {
419       tsubst_flags_t complain = tf_warning_or_error;
420       if (decltype_p)
421 	complain |= tf_decltype;
422       expr = build_new_op (loc, ARRAY_REF, LOOKUP_NORMAL, array_expr,
423 			   index_exp, NULL_TREE, &overload, complain);
424     }
425   else
426     {
427       tree p1, p2, i1, i2;
428 
429       /* Otherwise, create an ARRAY_REF for a pointer or array type.
430 	 It is a little-known fact that, if `a' is an array and `i' is
431 	 an int, you can write `i[a]', which means the same thing as
432 	 `a[i]'.  */
433       if (TREE_CODE (type) == ARRAY_TYPE || VECTOR_TYPE_P (type))
434 	p1 = array_expr;
435       else
436 	p1 = build_expr_type_conversion (WANT_POINTER, array_expr, false);
437 
438       if (TREE_CODE (TREE_TYPE (index_exp)) == ARRAY_TYPE)
439 	p2 = index_exp;
440       else
441 	p2 = build_expr_type_conversion (WANT_POINTER, index_exp, false);
442 
443       i1 = build_expr_type_conversion (WANT_INT | WANT_ENUM, array_expr,
444 				       false);
445       i2 = build_expr_type_conversion (WANT_INT | WANT_ENUM, index_exp,
446 				       false);
447 
448       if ((p1 && i2) && (i1 && p2))
449 	error ("ambiguous conversion for array subscript");
450 
451       if (p1 && i2)
452 	array_expr = p1, index_exp = i2;
453       else if (i1 && p2)
454 	array_expr = p2, index_exp = i1;
455       else
456 	{
457 	  error ("invalid types %<%T[%T]%> for array subscript",
458 		 type, TREE_TYPE (index_exp));
459 	  return error_mark_node;
460 	}
461 
462       if (array_expr == error_mark_node || index_exp == error_mark_node)
463 	error ("ambiguous conversion for array subscript");
464 
465       if (TREE_CODE (TREE_TYPE (array_expr)) == POINTER_TYPE)
466 	array_expr = mark_rvalue_use (array_expr);
467       else
468 	array_expr = mark_lvalue_use_nonread (array_expr);
469       index_exp = mark_rvalue_use (index_exp);
470       expr = build_array_ref (input_location, array_expr, index_exp);
471     }
472   if (processing_template_decl && expr != error_mark_node)
473     {
474       if (overload != NULL_TREE)
475 	return (build_min_non_dep_op_overload
476 		(ARRAY_REF, expr, overload, orig_array_expr, orig_index_exp));
477 
478       return build_min_non_dep (ARRAY_REF, expr, orig_array_expr, orig_index_exp,
479 				NULL_TREE, NULL_TREE);
480     }
481   return expr;
482 }
483 
484 /* Given the cast expression EXP, checking out its validity.   Either return
485    an error_mark_node if there was an unavoidable error, return a cast to
486    void for trying to delete a pointer w/ the value 0, or return the
487    call to delete.  If DOING_VEC is true, we handle things differently
488    for doing an array delete.
489    Implements ARM $5.3.4.  This is called from the parser.  */
490 
491 tree
492 delete_sanity (tree exp, tree size, bool doing_vec, int use_global_delete,
493 	       tsubst_flags_t complain)
494 {
495   tree t, type;
496 
497   if (exp == error_mark_node)
498     return exp;
499 
500   if (processing_template_decl)
501     {
502       t = build_min (DELETE_EXPR, void_type_node, exp, size);
503       DELETE_EXPR_USE_GLOBAL (t) = use_global_delete;
504       DELETE_EXPR_USE_VEC (t) = doing_vec;
505       TREE_SIDE_EFFECTS (t) = 1;
506       return t;
507     }
508 
509   /* An array can't have been allocated by new, so complain.  */
510   if (TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE)
511     warning (0, "deleting array %q#E", exp);
512 
513   t = build_expr_type_conversion (WANT_POINTER, exp, true);
514 
515   if (t == NULL_TREE || t == error_mark_node)
516     {
517       error ("type %q#T argument given to %<delete%>, expected pointer",
518 	     TREE_TYPE (exp));
519       return error_mark_node;
520     }
521 
522   type = TREE_TYPE (t);
523 
524   /* As of Valley Forge, you can delete a pointer to const.  */
525 
526   /* You can't delete functions.  */
527   if (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
528     {
529       error ("cannot delete a function.  Only pointer-to-objects are "
530 	     "valid arguments to %<delete%>");
531       return error_mark_node;
532     }
533 
534   /* Deleting ptr to void is undefined behavior [expr.delete/3].  */
535   if (VOID_TYPE_P (TREE_TYPE (type)))
536     {
537       warning (OPT_Wdelete_incomplete, "deleting %qT is undefined", type);
538       doing_vec = 0;
539     }
540 
541   /* Deleting a pointer with the value zero is valid and has no effect.  */
542   if (integer_zerop (t))
543     return build1 (NOP_EXPR, void_type_node, t);
544 
545   if (doing_vec)
546     return build_vec_delete (t, /*maxindex=*/NULL_TREE,
547 			     sfk_deleting_destructor,
548 			     use_global_delete, complain);
549   else
550     return build_delete (type, t, sfk_deleting_destructor,
551 			 LOOKUP_NORMAL, use_global_delete,
552 			 complain);
553 }
554 
555 /* Report an error if the indicated template declaration is not the
556    sort of thing that should be a member template.  */
557 
558 void
559 check_member_template (tree tmpl)
560 {
561   tree decl;
562 
563   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
564   decl = DECL_TEMPLATE_RESULT (tmpl);
565 
566   if (TREE_CODE (decl) == FUNCTION_DECL
567       || DECL_ALIAS_TEMPLATE_P (tmpl)
568       || (TREE_CODE (decl) == TYPE_DECL
569 	  && MAYBE_CLASS_TYPE_P (TREE_TYPE (decl))))
570     {
571       /* The parser rejects template declarations in local classes
572 	 (with the exception of generic lambdas).  */
573       gcc_assert (!current_function_decl || LAMBDA_FUNCTION_P (decl));
574       /* The parser rejects any use of virtual in a function template.  */
575       gcc_assert (!(TREE_CODE (decl) == FUNCTION_DECL
576 		    && DECL_VIRTUAL_P (decl)));
577 
578       /* The debug-information generating code doesn't know what to do
579 	 with member templates.  */
580       DECL_IGNORED_P (tmpl) = 1;
581     }
582   else if (variable_template_p (tmpl))
583     /* OK */;
584   else
585     error ("template declaration of %q#D", decl);
586 }
587 
588 /* Sanity check: report error if this function FUNCTION is not
589    really a member of the class (CTYPE) it is supposed to belong to.
590    TEMPLATE_PARMS is used to specify the template parameters of a member
591    template passed as FUNCTION_DECL. If the member template is passed as a
592    TEMPLATE_DECL, it can be NULL since the parameters can be extracted
593    from the declaration. If the function is not a function template, it
594    must be NULL.
595    It returns the original declaration for the function, NULL_TREE if
596    no declaration was found, error_mark_node if an error was emitted.  */
597 
598 tree
599 check_classfn (tree ctype, tree function, tree template_parms)
600 {
601   if (DECL_USE_TEMPLATE (function)
602       && !(TREE_CODE (function) == TEMPLATE_DECL
603 	   && DECL_TEMPLATE_SPECIALIZATION (function))
604       && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (function)))
605     /* Since this is a specialization of a member template,
606        we're not going to find the declaration in the class.
607        For example, in:
608 
609 	 struct S { template <typename T> void f(T); };
610 	 template <> void S::f(int);
611 
612        we're not going to find `S::f(int)', but there's no
613        reason we should, either.  We let our callers know we didn't
614        find the method, but we don't complain.  */
615     return NULL_TREE;
616 
617   /* Basic sanity check: for a template function, the template parameters
618      either were not passed, or they are the same of DECL_TEMPLATE_PARMS.  */
619   if (TREE_CODE (function) == TEMPLATE_DECL)
620     {
621       if (template_parms
622 	  && !comp_template_parms (template_parms,
623 				   DECL_TEMPLATE_PARMS (function)))
624 	{
625 	  error ("template parameter lists provided don%'t match the "
626 		 "template parameters of %qD", function);
627 	  return error_mark_node;
628 	}
629       template_parms = DECL_TEMPLATE_PARMS (function);
630     }
631 
632   /* OK, is this a definition of a member template?  */
633   bool is_template = (template_parms != NULL_TREE);
634 
635   /* [temp.mem]
636 
637      A destructor shall not be a member template.  */
638   if (DECL_DESTRUCTOR_P (function) && is_template)
639     {
640       error ("destructor %qD declared as member template", function);
641       return error_mark_node;
642     }
643 
644   /* We must enter the scope here, because conversion operators are
645      named by target type, and type equivalence relies on typenames
646      resolving within the scope of CTYPE.  */
647   tree pushed_scope = push_scope (ctype);
648   tree matched = NULL_TREE;
649   tree fns = get_class_binding (ctype, DECL_NAME (function));
650 
651   for (ovl_iterator iter (fns); !matched && iter; ++iter)
652     {
653       tree fndecl = *iter;
654 
655       /* A member template definition only matches a member template
656 	 declaration.  */
657       if (is_template != (TREE_CODE (fndecl) == TEMPLATE_DECL))
658 	continue;
659 
660       if (!DECL_DECLARES_FUNCTION_P (fndecl))
661 	continue;
662 
663       tree p1 = TYPE_ARG_TYPES (TREE_TYPE (function));
664       tree p2 = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
665 
666       /* We cannot simply call decls_match because this doesn't work
667 	 for static member functions that are pretending to be
668 	 methods, and because the name may have been changed by
669 	 asm("new_name").  */
670 
671       /* Get rid of the this parameter on functions that become
672 	 static.  */
673       if (DECL_STATIC_FUNCTION_P (fndecl)
674 	  && TREE_CODE (TREE_TYPE (function)) == METHOD_TYPE)
675 	p1 = TREE_CHAIN (p1);
676 
677       /* ref-qualifier or absence of same must match.  */
678       if (type_memfn_rqual (TREE_TYPE (function))
679 	  != type_memfn_rqual (TREE_TYPE (fndecl)))
680 	continue;
681 
682       // Include constraints in the match.
683       tree c1 = get_constraints (function);
684       tree c2 = get_constraints (fndecl);
685 
686       /* While finding a match, same types and params are not enough
687 	 if the function is versioned.  Also check version ("target")
688 	 attributes.  */
689       if (same_type_p (TREE_TYPE (TREE_TYPE (function)),
690 		       TREE_TYPE (TREE_TYPE (fndecl)))
691 	  && compparms (p1, p2)
692 	  && !targetm.target_option.function_versions (function, fndecl)
693 	  && (!is_template
694 	      || comp_template_parms (template_parms,
695 				      DECL_TEMPLATE_PARMS (fndecl)))
696 	  && equivalent_constraints (c1, c2)
697 	  && (DECL_TEMPLATE_SPECIALIZATION (function)
698 	      == DECL_TEMPLATE_SPECIALIZATION (fndecl))
699 	  && (!DECL_TEMPLATE_SPECIALIZATION (function)
700 	      || (DECL_TI_TEMPLATE (function) == DECL_TI_TEMPLATE (fndecl))))
701 	matched = fndecl;
702     }
703 
704   if (!matched)
705     {
706       if (!COMPLETE_TYPE_P (ctype))
707 	cxx_incomplete_type_error (function, ctype);
708       else
709 	{
710 	  if (DECL_CONV_FN_P (function))
711 	    fns = get_class_binding (ctype, conv_op_identifier);
712 
713 	  error_at (DECL_SOURCE_LOCATION (function),
714 		    "no declaration matches %q#D", function);
715 	  if (fns)
716 	    print_candidates (fns);
717 	  else if (DECL_CONV_FN_P (function))
718 	    inform (DECL_SOURCE_LOCATION (function),
719 		    "no conversion operators declared");
720 	  else
721 	    inform (DECL_SOURCE_LOCATION (function),
722 		    "no functions named %qD", function);
723 	  inform (DECL_SOURCE_LOCATION (TYPE_NAME (ctype)),
724 		  "%#qT defined here", ctype);
725 	}
726       matched = error_mark_node;
727     }
728 
729   if (pushed_scope)
730     pop_scope (pushed_scope);
731 
732   return matched;
733 }
734 
735 /* DECL is a function with vague linkage.  Remember it so that at the
736    end of the translation unit we can decide whether or not to emit
737    it.  */
738 
739 void
740 note_vague_linkage_fn (tree decl)
741 {
742   if (processing_template_decl)
743     return;
744 
745   DECL_DEFER_OUTPUT (decl) = 1;
746   vec_safe_push (deferred_fns, decl);
747 }
748 
749 /* As above, but for variable template instantiations.  */
750 
751 void
752 note_variable_template_instantiation (tree decl)
753 {
754   vec_safe_push (pending_statics, decl);
755 }
756 
757 /* We have just processed the DECL, which is a static data member.
758    The other parameters are as for cp_finish_decl.  */
759 
760 void
761 finish_static_data_member_decl (tree decl,
762 				tree init, bool init_const_expr_p,
763 				tree asmspec_tree,
764 				int flags)
765 {
766   DECL_CONTEXT (decl) = current_class_type;
767 
768   /* We cannot call pushdecl here, because that would fill in the
769      TREE_CHAIN of our decl.  Instead, we modify cp_finish_decl to do
770      the right thing, namely, to put this decl out straight away.  */
771 
772   if (! processing_template_decl)
773     vec_safe_push (pending_statics, decl);
774 
775   if (LOCAL_CLASS_P (current_class_type)
776       /* We already complained about the template definition.  */
777       && !DECL_TEMPLATE_INSTANTIATION (decl))
778     permerror (input_location, "local class %q#T shall not have static data member %q#D",
779 	       current_class_type, decl);
780   else
781     for (tree t = current_class_type; TYPE_P (t);
782 	 t = CP_TYPE_CONTEXT (t))
783       if (TYPE_UNNAMED_P (t))
784 	{
785 	  if (permerror (DECL_SOURCE_LOCATION (decl),
786 			 "static data member %qD in unnamed class", decl))
787 	    inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)),
788 		    "unnamed class defined here");
789 	  break;
790 	}
791 
792   DECL_IN_AGGR_P (decl) = 1;
793 
794   if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
795       && TYPE_DOMAIN (TREE_TYPE (decl)) == NULL_TREE)
796     SET_VAR_HAD_UNKNOWN_BOUND (decl);
797 
798   if (init)
799     {
800       /* Similarly to start_decl_1, we want to complete the type in order
801 	 to do the right thing in cp_apply_type_quals_to_decl, possibly
802 	 clear TYPE_QUAL_CONST (c++/65579).  */
803       tree type = TREE_TYPE (decl) = complete_type (TREE_TYPE (decl));
804       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
805     }
806 
807   cp_finish_decl (decl, init, init_const_expr_p, asmspec_tree, flags);
808 }
809 
810 /* DECLARATOR and DECLSPECS correspond to a class member.  The other
811    parameters are as for cp_finish_decl.  Return the DECL for the
812    class member declared.  */
813 
814 tree
815 grokfield (const cp_declarator *declarator,
816 	   cp_decl_specifier_seq *declspecs,
817 	   tree init, bool init_const_expr_p,
818 	   tree asmspec_tree,
819 	   tree attrlist)
820 {
821   tree value;
822   const char *asmspec = 0;
823   int flags;
824   tree name;
825 
826   if (init
827       && TREE_CODE (init) == TREE_LIST
828       && TREE_VALUE (init) == error_mark_node
829       && TREE_CHAIN (init) == NULL_TREE)
830     init = NULL_TREE;
831 
832   value = grokdeclarator (declarator, declspecs, FIELD, init != 0, &attrlist);
833   if (! value || value == error_mark_node)
834     /* friend or constructor went bad.  */
835     return error_mark_node;
836   if (TREE_TYPE (value) == error_mark_node)
837     return value;
838 
839   if (TREE_CODE (value) == TYPE_DECL && init)
840     {
841       error ("typedef %qD is initialized (use decltype instead)", value);
842       init = NULL_TREE;
843     }
844 
845   /* Pass friendly classes back.  */
846   if (value == void_type_node)
847     return value;
848 
849 
850   name = DECL_NAME (value);
851 
852   if (name != NULL_TREE)
853     {
854       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
855 	{
856 	  error ("explicit template argument list not allowed");
857 	  return error_mark_node;
858 	}
859 
860       if (IDENTIFIER_POINTER (name)[0] == '_'
861 	  && id_equal (name, "_vptr"))
862 	error ("member %qD conflicts with virtual function table field name",
863 	       value);
864     }
865 
866   /* Stash away type declarations.  */
867   if (TREE_CODE (value) == TYPE_DECL)
868     {
869       DECL_NONLOCAL (value) = 1;
870       DECL_CONTEXT (value) = current_class_type;
871 
872       if (attrlist)
873 	{
874 	  int attrflags = 0;
875 
876 	  /* If this is a typedef that names the class for linkage purposes
877 	     (7.1.3p8), apply any attributes directly to the type.  */
878 	  if (OVERLOAD_TYPE_P (TREE_TYPE (value))
879 	      && value == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))))
880 	    attrflags = ATTR_FLAG_TYPE_IN_PLACE;
881 
882 	  cplus_decl_attributes (&value, attrlist, attrflags);
883 	}
884 
885       if (decl_spec_seq_has_spec_p (declspecs, ds_typedef)
886           && TREE_TYPE (value) != error_mark_node
887           && TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (value))) != value)
888 	set_underlying_type (value);
889 
890       /* It's important that push_template_decl below follows
891 	 set_underlying_type above so that the created template
892 	 carries the properly set type of VALUE.  */
893       if (processing_template_decl)
894 	value = push_template_decl (value);
895 
896       record_locally_defined_typedef (value);
897       return value;
898     }
899 
900   int friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
901 
902   if (!friendp && DECL_IN_AGGR_P (value))
903     {
904       error ("%qD is already defined in %qT", value, DECL_CONTEXT (value));
905       return void_type_node;
906     }
907 
908   if (asmspec_tree && asmspec_tree != error_mark_node)
909     asmspec = TREE_STRING_POINTER (asmspec_tree);
910 
911   if (init)
912     {
913       if (TREE_CODE (value) == FUNCTION_DECL)
914 	{
915 	  if (init == ridpointers[(int)RID_DELETE])
916 	    {
917 	      if (friendp && decl_defined_p (value))
918 		{
919 		  error ("redefinition of %q#D", value);
920 		  inform (DECL_SOURCE_LOCATION (value),
921 			  "%q#D previously defined here", value);
922 		}
923 	      else
924 		{
925 		  DECL_DELETED_FN (value) = 1;
926 		  DECL_DECLARED_INLINE_P (value) = 1;
927 		  DECL_INITIAL (value) = error_mark_node;
928 		}
929 	    }
930 	  else if (init == ridpointers[(int)RID_DEFAULT])
931 	    {
932 	      if (defaultable_fn_check (value))
933 		{
934 		  DECL_DEFAULTED_FN (value) = 1;
935 		  DECL_INITIALIZED_IN_CLASS_P (value) = 1;
936 		  DECL_DECLARED_INLINE_P (value) = 1;
937 		}
938 	    }
939 	  else if (TREE_CODE (init) == DEFAULT_ARG)
940 	    error ("invalid initializer for member function %qD", value);
941 	  else if (TREE_CODE (TREE_TYPE (value)) == METHOD_TYPE)
942 	    {
943 	      if (integer_zerop (init))
944 		DECL_PURE_VIRTUAL_P (value) = 1;
945 	      else if (error_operand_p (init))
946 		; /* An error has already been reported.  */
947 	      else
948 		error ("invalid initializer for member function %qD",
949 		       value);
950 	    }
951 	  else
952 	    {
953 	      gcc_assert (TREE_CODE (TREE_TYPE (value)) == FUNCTION_TYPE);
954 	      if (friendp)
955 		error ("initializer specified for friend function %qD",
956 		       value);
957 	      else
958 		error ("initializer specified for static member function %qD",
959 		       value);
960 	    }
961 	}
962       else if (TREE_CODE (value) == FIELD_DECL)
963 	/* C++11 NSDMI, keep going.  */;
964       else if (!VAR_P (value))
965 	gcc_unreachable ();
966     }
967 
968   /* Pass friend decls back.  */
969   if ((TREE_CODE (value) == FUNCTION_DECL
970        || TREE_CODE (value) == TEMPLATE_DECL)
971       && DECL_CONTEXT (value) != current_class_type)
972     return value;
973 
974   /* Need to set this before push_template_decl.  */
975   if (VAR_P (value))
976     DECL_CONTEXT (value) = current_class_type;
977 
978   if (processing_template_decl && VAR_OR_FUNCTION_DECL_P (value))
979     {
980       value = push_template_decl (value);
981       if (error_operand_p (value))
982 	return error_mark_node;
983     }
984 
985   if (attrlist)
986     cplus_decl_attributes (&value, attrlist, 0);
987 
988   if (init && DIRECT_LIST_INIT_P (init))
989     flags = LOOKUP_NORMAL;
990   else
991     flags = LOOKUP_IMPLICIT;
992 
993   switch (TREE_CODE (value))
994     {
995     case VAR_DECL:
996       finish_static_data_member_decl (value, init, init_const_expr_p,
997 				      asmspec_tree, flags);
998       return value;
999 
1000     case FIELD_DECL:
1001       if (asmspec)
1002 	error ("%<asm%> specifiers are not permitted on non-static data members");
1003       if (DECL_INITIAL (value) == error_mark_node)
1004 	init = error_mark_node;
1005       cp_finish_decl (value, init, /*init_const_expr_p=*/false,
1006 		      NULL_TREE, flags);
1007       DECL_IN_AGGR_P (value) = 1;
1008       return value;
1009 
1010     case  FUNCTION_DECL:
1011       if (asmspec)
1012 	set_user_assembler_name (value, asmspec);
1013 
1014       cp_finish_decl (value,
1015 		      /*init=*/NULL_TREE,
1016 		      /*init_const_expr_p=*/false,
1017 		      asmspec_tree, flags);
1018 
1019       /* Pass friends back this way.  */
1020       if (DECL_FRIEND_P (value))
1021 	return void_type_node;
1022 
1023       DECL_IN_AGGR_P (value) = 1;
1024       return value;
1025 
1026     default:
1027       gcc_unreachable ();
1028     }
1029   return NULL_TREE;
1030 }
1031 
1032 /* Like `grokfield', but for bitfields.
1033    WIDTH is the width of the bitfield, a constant expression.
1034    The other parameters are as for grokfield.  */
1035 
1036 tree
1037 grokbitfield (const cp_declarator *declarator,
1038 	      cp_decl_specifier_seq *declspecs, tree width, tree init,
1039 	      tree attrlist)
1040 {
1041   tree value = grokdeclarator (declarator, declspecs, BITFIELD,
1042 			       init != NULL_TREE, &attrlist);
1043 
1044   if (value == error_mark_node)
1045     return NULL_TREE; /* friends went bad.  */
1046   if (TREE_TYPE (value) == error_mark_node)
1047     return value;
1048 
1049   /* Pass friendly classes back.  */
1050   if (VOID_TYPE_P (value))
1051     return void_type_node;
1052 
1053   if (!INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (value))
1054       && (POINTER_TYPE_P (value)
1055           || !dependent_type_p (TREE_TYPE (value))))
1056     {
1057       error ("bit-field %qD with non-integral type", value);
1058       return error_mark_node;
1059     }
1060 
1061   if (TREE_CODE (value) == TYPE_DECL)
1062     {
1063       error ("cannot declare %qD to be a bit-field type", value);
1064       return NULL_TREE;
1065     }
1066 
1067   /* Usually, finish_struct_1 catches bitfields with invalid types.
1068      But, in the case of bitfields with function type, we confuse
1069      ourselves into thinking they are member functions, so we must
1070      check here.  */
1071   if (TREE_CODE (value) == FUNCTION_DECL)
1072     {
1073       error ("cannot declare bit-field %qD with function type",
1074 	     DECL_NAME (value));
1075       return NULL_TREE;
1076     }
1077 
1078   if (width && TYPE_WARN_IF_NOT_ALIGN (TREE_TYPE (value)))
1079     {
1080       error ("cannot declare bit-field %qD with %<warn_if_not_aligned%> type",
1081 	     DECL_NAME (value));
1082       return NULL_TREE;
1083     }
1084 
1085   if (DECL_IN_AGGR_P (value))
1086     {
1087       error ("%qD is already defined in the class %qT", value,
1088 	     DECL_CONTEXT (value));
1089       return void_type_node;
1090     }
1091 
1092   if (TREE_STATIC (value))
1093     {
1094       error ("static member %qD cannot be a bit-field", value);
1095       return NULL_TREE;
1096     }
1097 
1098   int flags = LOOKUP_IMPLICIT;
1099   if (init && DIRECT_LIST_INIT_P (init))
1100     flags = LOOKUP_NORMAL;
1101   cp_finish_decl (value, init, false, NULL_TREE, flags);
1102 
1103   if (width != error_mark_node)
1104     {
1105       /* The width must be an integer type.  */
1106       if (!type_dependent_expression_p (width)
1107 	  && !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (width)))
1108 	error ("width of bit-field %qD has non-integral type %qT", value,
1109 	       TREE_TYPE (width));
1110       else
1111 	{
1112 	  /* Temporarily stash the width in DECL_BIT_FIELD_REPRESENTATIVE.
1113 	     check_bitfield_decl picks it from there later and sets DECL_SIZE
1114 	     accordingly.  */
1115 	  DECL_BIT_FIELD_REPRESENTATIVE (value) = width;
1116 	  SET_DECL_C_BIT_FIELD (value);
1117 	}
1118     }
1119 
1120   DECL_IN_AGGR_P (value) = 1;
1121 
1122   if (attrlist)
1123     cplus_decl_attributes (&value, attrlist, /*flags=*/0);
1124 
1125   return value;
1126 }
1127 
1128 
1129 /* Returns true iff ATTR is an attribute which needs to be applied at
1130    instantiation time rather than template definition time.  */
1131 
1132 static bool
1133 is_late_template_attribute (tree attr, tree decl)
1134 {
1135   tree name = get_attribute_name (attr);
1136   tree args = TREE_VALUE (attr);
1137   const struct attribute_spec *spec = lookup_attribute_spec (name);
1138   tree arg;
1139 
1140   if (!spec)
1141     /* Unknown attribute.  */
1142     return false;
1143 
1144   /* Attribute weak handling wants to write out assembly right away.  */
1145   if (is_attribute_p ("weak", name))
1146     return true;
1147 
1148   /* Attributes used and unused are applied directly to typedefs for the
1149      benefit of maybe_warn_unused_local_typedefs.  */
1150   if (TREE_CODE (decl) == TYPE_DECL
1151       && (is_attribute_p ("unused", name)
1152 	  || is_attribute_p ("used", name)))
1153     return false;
1154 
1155   /* Attribute tls_model wants to modify the symtab.  */
1156   if (is_attribute_p ("tls_model", name))
1157     return true;
1158 
1159   /* #pragma omp declare simd attribute needs to be always deferred.  */
1160   if (flag_openmp
1161       && is_attribute_p ("omp declare simd", name))
1162     return true;
1163 
1164   /* An attribute pack is clearly dependent.  */
1165   if (args && PACK_EXPANSION_P (args))
1166     return true;
1167 
1168   /* If any of the arguments are dependent expressions, we can't evaluate
1169      the attribute until instantiation time.  */
1170   for (arg = args; arg; arg = TREE_CHAIN (arg))
1171     {
1172       tree t = TREE_VALUE (arg);
1173 
1174       /* If the first attribute argument is an identifier, only consider
1175 	 second and following arguments.  Attributes like mode, format,
1176 	 cleanup and several target specific attributes aren't late
1177 	 just because they have an IDENTIFIER_NODE as first argument.  */
1178       if (arg == args && attribute_takes_identifier_p (name)
1179 	  && identifier_p (t))
1180 	continue;
1181 
1182       if (value_dependent_expression_p (t)
1183 	  || type_dependent_expression_p (t))
1184 	return true;
1185     }
1186 
1187   if (TREE_CODE (decl) == TYPE_DECL
1188       || TYPE_P (decl)
1189       || spec->type_required)
1190     {
1191       tree type = TYPE_P (decl) ? decl : TREE_TYPE (decl);
1192 
1193       /* We can't apply any attributes to a completely unknown type until
1194 	 instantiation time.  */
1195       enum tree_code code = TREE_CODE (type);
1196       if (code == TEMPLATE_TYPE_PARM
1197 	  || code == BOUND_TEMPLATE_TEMPLATE_PARM
1198 	  || code == TYPENAME_TYPE)
1199 	return true;
1200       /* Also defer most attributes on dependent types.  This is not
1201 	 necessary in all cases, but is the better default.  */
1202       else if (dependent_type_p (type)
1203 	       /* But some attributes specifically apply to templates.  */
1204 	       && !is_attribute_p ("abi_tag", name)
1205 	       && !is_attribute_p ("deprecated", name)
1206 	       && !is_attribute_p ("visibility", name))
1207 	return true;
1208       else
1209 	return false;
1210     }
1211   else
1212     return false;
1213 }
1214 
1215 /* ATTR_P is a list of attributes.  Remove any attributes which need to be
1216    applied at instantiation time and return them.  If IS_DEPENDENT is true,
1217    the declaration itself is dependent, so all attributes should be applied
1218    at instantiation time.  */
1219 
1220 static tree
1221 splice_template_attributes (tree *attr_p, tree decl)
1222 {
1223   tree *p = attr_p;
1224   tree late_attrs = NULL_TREE;
1225   tree *q = &late_attrs;
1226 
1227   if (!p)
1228     return NULL_TREE;
1229 
1230   for (; *p; )
1231     {
1232       if (is_late_template_attribute (*p, decl))
1233 	{
1234 	  ATTR_IS_DEPENDENT (*p) = 1;
1235 	  *q = *p;
1236 	  *p = TREE_CHAIN (*p);
1237 	  q = &TREE_CHAIN (*q);
1238 	  *q = NULL_TREE;
1239 	}
1240       else
1241 	p = &TREE_CHAIN (*p);
1242     }
1243 
1244   return late_attrs;
1245 }
1246 
1247 /* Remove any late attributes from the list in ATTR_P and attach them to
1248    DECL_P.  */
1249 
1250 static void
1251 save_template_attributes (tree *attr_p, tree *decl_p, int flags)
1252 {
1253   tree *q;
1254 
1255   if (attr_p && *attr_p == error_mark_node)
1256     return;
1257 
1258   tree late_attrs = splice_template_attributes (attr_p, *decl_p);
1259   if (!late_attrs)
1260     return;
1261 
1262   if (DECL_P (*decl_p))
1263     q = &DECL_ATTRIBUTES (*decl_p);
1264   else
1265     q = &TYPE_ATTRIBUTES (*decl_p);
1266 
1267   tree old_attrs = *q;
1268 
1269   /* Merge the late attributes at the beginning with the attribute
1270      list.  */
1271   late_attrs = merge_attributes (late_attrs, *q);
1272   if (*q != late_attrs
1273       && !DECL_P (*decl_p)
1274       && !(flags & ATTR_FLAG_TYPE_IN_PLACE))
1275     {
1276       if (!dependent_type_p (*decl_p))
1277 	*decl_p = cp_build_type_attribute_variant (*decl_p, late_attrs);
1278       else
1279 	{
1280 	  *decl_p = build_variant_type_copy (*decl_p);
1281 	  TYPE_ATTRIBUTES (*decl_p) = late_attrs;
1282 	}
1283     }
1284   else
1285     *q = late_attrs;
1286 
1287   if (!DECL_P (*decl_p) && *decl_p == TYPE_MAIN_VARIANT (*decl_p))
1288     {
1289       /* We've added new attributes directly to the main variant, so
1290 	 now we need to update all of the other variants to include
1291 	 these new attributes.  */
1292       tree variant;
1293       for (variant = TYPE_NEXT_VARIANT (*decl_p); variant;
1294 	   variant = TYPE_NEXT_VARIANT (variant))
1295 	{
1296 	  gcc_assert (TYPE_ATTRIBUTES (variant) == old_attrs);
1297 	  TYPE_ATTRIBUTES (variant) = TYPE_ATTRIBUTES (*decl_p);
1298 	}
1299     }
1300 }
1301 
1302 /* True if ATTRS contains any dependent attributes that affect type
1303    identity.  */
1304 
1305 bool
1306 any_dependent_type_attributes_p (tree attrs)
1307 {
1308   for (tree a = attrs; a; a = TREE_CHAIN (a))
1309     if (ATTR_IS_DEPENDENT (a))
1310       {
1311 	const attribute_spec *as = lookup_attribute_spec (TREE_PURPOSE (a));
1312 	if (as && as->affects_type_identity)
1313 	  return true;
1314       }
1315   return false;
1316 }
1317 
1318 /* Return true iff ATTRS are acceptable attributes to be applied in-place
1319    to a typedef which gives a previously unnamed class or enum a name for
1320    linkage purposes.  */
1321 
1322 bool
1323 attributes_naming_typedef_ok (tree attrs)
1324 {
1325   for (; attrs; attrs = TREE_CHAIN (attrs))
1326     {
1327       tree name = get_attribute_name (attrs);
1328       if (is_attribute_p ("vector_size", name))
1329 	return false;
1330     }
1331   return true;
1332 }
1333 
1334 /* Like reconstruct_complex_type, but handle also template trees.  */
1335 
1336 tree
1337 cp_reconstruct_complex_type (tree type, tree bottom)
1338 {
1339   tree inner, outer;
1340   bool late_return_type_p = false;
1341 
1342   if (TYPE_PTR_P (type))
1343     {
1344       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1345       outer = build_pointer_type_for_mode (inner, TYPE_MODE (type),
1346 					   TYPE_REF_CAN_ALIAS_ALL (type));
1347     }
1348   else if (TREE_CODE (type) == REFERENCE_TYPE)
1349     {
1350       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1351       outer = build_reference_type_for_mode (inner, TYPE_MODE (type),
1352 					     TYPE_REF_CAN_ALIAS_ALL (type));
1353     }
1354   else if (TREE_CODE (type) == ARRAY_TYPE)
1355     {
1356       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1357       outer = build_cplus_array_type (inner, TYPE_DOMAIN (type));
1358       /* Don't call cp_build_qualified_type on ARRAY_TYPEs, the
1359 	 element type qualification will be handled by the recursive
1360 	 cp_reconstruct_complex_type call and cp_build_qualified_type
1361 	 for ARRAY_TYPEs changes the element type.  */
1362       return outer;
1363     }
1364   else if (TREE_CODE (type) == FUNCTION_TYPE)
1365     {
1366       late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type);
1367       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1368       outer = build_function_type (inner, TYPE_ARG_TYPES (type));
1369       outer = apply_memfn_quals (outer,
1370 				 type_memfn_quals (type),
1371 				 type_memfn_rqual (type));
1372     }
1373   else if (TREE_CODE (type) == METHOD_TYPE)
1374     {
1375       late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (type);
1376       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1377       /* The build_method_type_directly() routine prepends 'this' to argument list,
1378 	 so we must compensate by getting rid of it.  */
1379       outer
1380 	= build_method_type_directly
1381 	    (class_of_this_parm (type), inner,
1382 	     TREE_CHAIN (TYPE_ARG_TYPES (type)));
1383     }
1384   else if (TREE_CODE (type) == OFFSET_TYPE)
1385     {
1386       inner = cp_reconstruct_complex_type (TREE_TYPE (type), bottom);
1387       outer = build_offset_type (TYPE_OFFSET_BASETYPE (type), inner);
1388     }
1389   else
1390     return bottom;
1391 
1392   if (TYPE_ATTRIBUTES (type))
1393     outer = cp_build_type_attribute_variant (outer, TYPE_ATTRIBUTES (type));
1394   outer = cp_build_qualified_type (outer, cp_type_quals (type));
1395 
1396   if (late_return_type_p)
1397     TYPE_HAS_LATE_RETURN_TYPE (outer) = 1;
1398 
1399   return outer;
1400 }
1401 
1402 /* Replaces any constexpr expression that may be into the attributes
1403    arguments with their reduced value.  */
1404 
1405 static void
1406 cp_check_const_attributes (tree attributes)
1407 {
1408   if (attributes == error_mark_node)
1409     return;
1410 
1411   tree attr;
1412   for (attr = attributes; attr; attr = TREE_CHAIN (attr))
1413     {
1414       tree arg;
1415       for (arg = TREE_VALUE (attr); arg; arg = TREE_CHAIN (arg))
1416 	{
1417 	  tree expr = TREE_VALUE (arg);
1418 	  if (EXPR_P (expr))
1419 	    TREE_VALUE (arg) = fold_non_dependent_expr (expr);
1420 	}
1421     }
1422 }
1423 
1424 /* Return true if TYPE is an OpenMP mappable type.  */
1425 bool
1426 cp_omp_mappable_type (tree type)
1427 {
1428   /* Mappable type has to be complete.  */
1429   if (type == error_mark_node || !COMPLETE_TYPE_P (type))
1430     return false;
1431   /* Arrays have mappable type if the elements have mappable type.  */
1432   while (TREE_CODE (type) == ARRAY_TYPE)
1433     type = TREE_TYPE (type);
1434   /* A mappable type cannot contain virtual members.  */
1435   if (CLASS_TYPE_P (type) && CLASSTYPE_VTABLES (type))
1436     return false;
1437   /* All data members must be non-static.  */
1438   if (CLASS_TYPE_P (type))
1439     {
1440       tree field;
1441       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1442 	if (VAR_P (field))
1443 	  return false;
1444 	/* All fields must have mappable types.  */
1445 	else if (TREE_CODE (field) == FIELD_DECL
1446 		 && !cp_omp_mappable_type (TREE_TYPE (field)))
1447 	  return false;
1448     }
1449   return true;
1450 }
1451 
1452 /* Return the last pushed declaration for the symbol DECL or NULL
1453    when no such declaration exists.  */
1454 
1455 static tree
1456 find_last_decl (tree decl)
1457 {
1458   tree last_decl = NULL_TREE;
1459 
1460   if (tree name = DECL_P (decl) ? DECL_NAME (decl) : NULL_TREE)
1461     {
1462       /* Look up the declaration in its scope.  */
1463       tree pushed_scope = NULL_TREE;
1464       if (tree ctype = DECL_CONTEXT (decl))
1465 	pushed_scope = push_scope (ctype);
1466 
1467       last_decl = lookup_name (name);
1468 
1469       if (pushed_scope)
1470 	pop_scope (pushed_scope);
1471 
1472       /* The declaration may be a member conversion operator
1473 	 or a bunch of overfloads (handle the latter below).  */
1474       if (last_decl && BASELINK_P (last_decl))
1475 	last_decl = BASELINK_FUNCTIONS (last_decl);
1476     }
1477 
1478   if (!last_decl)
1479     return NULL_TREE;
1480 
1481   if (DECL_P (last_decl) || TREE_CODE (last_decl) == OVERLOAD)
1482     {
1483       /* A set of overloads of the same function.  */
1484       for (lkp_iterator iter (last_decl); iter; ++iter)
1485 	{
1486 	  if (TREE_CODE (*iter) == OVERLOAD)
1487 	    continue;
1488 
1489 	  if (decls_match (decl, *iter, /*record_decls=*/false))
1490 	    return *iter;
1491 	}
1492       return NULL_TREE;
1493     }
1494 
1495   return NULL_TREE;
1496 }
1497 
1498 /* Like decl_attributes, but handle C++ complexity.  */
1499 
1500 void
1501 cplus_decl_attributes (tree *decl, tree attributes, int flags)
1502 {
1503   if (*decl == NULL_TREE || *decl == void_type_node
1504       || *decl == error_mark_node)
1505     return;
1506 
1507   /* Add implicit "omp declare target" attribute if requested.  */
1508   if (scope_chain->omp_declare_target_attribute
1509       && ((VAR_P (*decl)
1510 	   && (TREE_STATIC (*decl) || DECL_EXTERNAL (*decl)))
1511 	  || TREE_CODE (*decl) == FUNCTION_DECL))
1512     {
1513       if (VAR_P (*decl)
1514 	  && DECL_CLASS_SCOPE_P (*decl))
1515 	error ("%q+D static data member inside of declare target directive",
1516 	       *decl);
1517       else if (VAR_P (*decl)
1518 	       && (processing_template_decl
1519 		   || !cp_omp_mappable_type (TREE_TYPE (*decl))))
1520 	attributes = tree_cons (get_identifier ("omp declare target implicit"),
1521 				NULL_TREE, attributes);
1522       else
1523 	attributes = tree_cons (get_identifier ("omp declare target"),
1524 				NULL_TREE, attributes);
1525     }
1526 
1527   if (processing_template_decl)
1528     {
1529       if (check_for_bare_parameter_packs (attributes))
1530 	return;
1531 
1532       save_template_attributes (&attributes, decl, flags);
1533     }
1534 
1535   cp_check_const_attributes (attributes);
1536 
1537   if (TREE_CODE (*decl) == TEMPLATE_DECL)
1538     decl = &DECL_TEMPLATE_RESULT (*decl);
1539 
1540   if (TREE_TYPE (*decl) && TYPE_PTRMEMFUNC_P (TREE_TYPE (*decl)))
1541     {
1542       attributes
1543 	= decl_attributes (decl, attributes, flags | ATTR_FLAG_FUNCTION_NEXT);
1544       decl_attributes (&TYPE_PTRMEMFUNC_FN_TYPE_RAW (TREE_TYPE (*decl)),
1545 		       attributes, flags);
1546     }
1547   else
1548     {
1549       tree last_decl = find_last_decl (*decl);
1550       decl_attributes (decl, attributes, flags, last_decl);
1551     }
1552 
1553   if (TREE_CODE (*decl) == TYPE_DECL)
1554     SET_IDENTIFIER_TYPE_VALUE (DECL_NAME (*decl), TREE_TYPE (*decl));
1555 
1556   /* Propagate deprecation out to the template.  */
1557   if (TREE_DEPRECATED (*decl))
1558     if (tree ti = get_template_info (*decl))
1559       {
1560 	tree tmpl = TI_TEMPLATE (ti);
1561 	tree pattern = (TYPE_P (*decl) ? TREE_TYPE (tmpl)
1562 			: DECL_TEMPLATE_RESULT (tmpl));
1563 	if (*decl == pattern)
1564 	  TREE_DEPRECATED (tmpl) = true;
1565       }
1566 }
1567 
1568 /* Walks through the namespace- or function-scope anonymous union
1569    OBJECT, with the indicated TYPE, building appropriate VAR_DECLs.
1570    Returns one of the fields for use in the mangled name.  */
1571 
1572 static tree
1573 build_anon_union_vars (tree type, tree object)
1574 {
1575   tree main_decl = NULL_TREE;
1576   tree field;
1577 
1578   /* Rather than write the code to handle the non-union case,
1579      just give an error.  */
1580   if (TREE_CODE (type) != UNION_TYPE)
1581     {
1582       error ("anonymous struct not inside named type");
1583       return error_mark_node;
1584     }
1585 
1586   for (field = TYPE_FIELDS (type);
1587        field != NULL_TREE;
1588        field = DECL_CHAIN (field))
1589     {
1590       tree decl;
1591       tree ref;
1592 
1593       if (DECL_ARTIFICIAL (field))
1594 	continue;
1595       if (TREE_CODE (field) != FIELD_DECL)
1596 	{
1597 	  permerror (DECL_SOURCE_LOCATION (field),
1598 		     "%q#D invalid; an anonymous union can only "
1599 		     "have non-static data members", field);
1600 	  continue;
1601 	}
1602 
1603       if (TREE_PRIVATE (field))
1604 	permerror (DECL_SOURCE_LOCATION (field),
1605 		   "private member %q#D in anonymous union", field);
1606       else if (TREE_PROTECTED (field))
1607 	permerror (DECL_SOURCE_LOCATION (field),
1608 		   "protected member %q#D in anonymous union", field);
1609 
1610       if (processing_template_decl)
1611 	ref = build_min_nt_loc (UNKNOWN_LOCATION, COMPONENT_REF, object,
1612 				DECL_NAME (field), NULL_TREE);
1613       else
1614 	ref = build_class_member_access_expr (object, field, NULL_TREE,
1615 					      false, tf_warning_or_error);
1616 
1617       if (DECL_NAME (field))
1618 	{
1619 	  tree base;
1620 
1621 	  decl = build_decl (input_location,
1622 			     VAR_DECL, DECL_NAME (field), TREE_TYPE (field));
1623 	  DECL_ANON_UNION_VAR_P (decl) = 1;
1624 	  DECL_ARTIFICIAL (decl) = 1;
1625 
1626 	  base = get_base_address (object);
1627 	  TREE_PUBLIC (decl) = TREE_PUBLIC (base);
1628 	  TREE_STATIC (decl) = TREE_STATIC (base);
1629 	  DECL_EXTERNAL (decl) = DECL_EXTERNAL (base);
1630 
1631 	  SET_DECL_VALUE_EXPR (decl, ref);
1632 	  DECL_HAS_VALUE_EXPR_P (decl) = 1;
1633 
1634 	  decl = pushdecl (decl);
1635 	}
1636       else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1637 	decl = build_anon_union_vars (TREE_TYPE (field), ref);
1638       else
1639 	decl = 0;
1640 
1641       if (main_decl == NULL_TREE)
1642 	main_decl = decl;
1643     }
1644 
1645   return main_decl;
1646 }
1647 
1648 /* Finish off the processing of a UNION_TYPE structure.  If the union is an
1649    anonymous union, then all members must be laid out together.  PUBLIC_P
1650    is nonzero if this union is not declared static.  */
1651 
1652 void
1653 finish_anon_union (tree anon_union_decl)
1654 {
1655   tree type;
1656   tree main_decl;
1657   bool public_p;
1658 
1659   if (anon_union_decl == error_mark_node)
1660     return;
1661 
1662   type = TREE_TYPE (anon_union_decl);
1663   public_p = TREE_PUBLIC (anon_union_decl);
1664 
1665   /* The VAR_DECL's context is the same as the TYPE's context.  */
1666   DECL_CONTEXT (anon_union_decl) = DECL_CONTEXT (TYPE_NAME (type));
1667 
1668   if (TYPE_FIELDS (type) == NULL_TREE)
1669     return;
1670 
1671   if (public_p)
1672     {
1673       error ("namespace-scope anonymous aggregates must be static");
1674       return;
1675     }
1676 
1677   main_decl = build_anon_union_vars (type, anon_union_decl);
1678   if (main_decl == error_mark_node)
1679     return;
1680   if (main_decl == NULL_TREE)
1681     {
1682       pedwarn (input_location, 0, "anonymous union with no members");
1683       return;
1684     }
1685 
1686   if (!processing_template_decl)
1687     {
1688       /* Use main_decl to set the mangled name.  */
1689       DECL_NAME (anon_union_decl) = DECL_NAME (main_decl);
1690       maybe_commonize_var (anon_union_decl);
1691       if (TREE_STATIC (anon_union_decl) || DECL_EXTERNAL (anon_union_decl))
1692 	mangle_decl (anon_union_decl);
1693       DECL_NAME (anon_union_decl) = NULL_TREE;
1694     }
1695 
1696   pushdecl (anon_union_decl);
1697   cp_finish_decl (anon_union_decl, NULL_TREE, false, NULL_TREE, 0);
1698 }
1699 
1700 /* Auxiliary functions to make type signatures for
1701    `operator new' and `operator delete' correspond to
1702    what compiler will be expecting.  */
1703 
1704 tree
1705 coerce_new_type (tree type)
1706 {
1707   int e = 0;
1708   tree args = TYPE_ARG_TYPES (type);
1709 
1710   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1711 
1712   if (!same_type_p (TREE_TYPE (type), ptr_type_node))
1713     {
1714       e = 1;
1715       error ("%<operator new%> must return type %qT", ptr_type_node);
1716     }
1717 
1718   if (args && args != void_list_node)
1719     {
1720       if (TREE_PURPOSE (args))
1721 	{
1722 	  /* [basic.stc.dynamic.allocation]
1723 
1724 	     The first parameter shall not have an associated default
1725 	     argument.  */
1726 	  error ("the first parameter of %<operator new%> cannot "
1727 		 "have a default argument");
1728 	  /* Throw away the default argument.  */
1729 	  TREE_PURPOSE (args) = NULL_TREE;
1730 	}
1731 
1732       if (!same_type_p (TREE_VALUE (args), size_type_node))
1733 	{
1734 	  e = 2;
1735 	  args = TREE_CHAIN (args);
1736 	}
1737     }
1738   else
1739     e = 2;
1740 
1741   if (e == 2)
1742     permerror (input_location, "%<operator new%> takes type %<size_t%> (%qT) "
1743 	       "as first parameter", size_type_node);
1744 
1745   switch (e)
1746   {
1747     case 2:
1748       args = tree_cons (NULL_TREE, size_type_node, args);
1749       /* Fall through.  */
1750     case 1:
1751       type = build_exception_variant
1752 	      (build_function_type (ptr_type_node, args),
1753 	       TYPE_RAISES_EXCEPTIONS (type));
1754       /* Fall through.  */
1755     default:;
1756   }
1757   return type;
1758 }
1759 
1760 tree
1761 coerce_delete_type (tree type)
1762 {
1763   int e = 0;
1764   tree args = TYPE_ARG_TYPES (type);
1765 
1766   gcc_assert (TREE_CODE (type) == FUNCTION_TYPE);
1767 
1768   if (!same_type_p (TREE_TYPE (type), void_type_node))
1769     {
1770       e = 1;
1771       error ("%<operator delete%> must return type %qT", void_type_node);
1772     }
1773 
1774   if (!args || args == void_list_node
1775       || !same_type_p (TREE_VALUE (args), ptr_type_node))
1776     {
1777       e = 2;
1778       if (args && args != void_list_node)
1779 	args = TREE_CHAIN (args);
1780       error ("%<operator delete%> takes type %qT as first parameter",
1781 	     ptr_type_node);
1782     }
1783   switch (e)
1784   {
1785     case 2:
1786       args = tree_cons (NULL_TREE, ptr_type_node, args);
1787       /* Fall through.  */
1788     case 1:
1789       type = build_exception_variant
1790 	      (build_function_type (void_type_node, args),
1791 	       TYPE_RAISES_EXCEPTIONS (type));
1792       /* Fall through.  */
1793     default:;
1794   }
1795 
1796   return type;
1797 }
1798 
1799 /* DECL is a VAR_DECL for a vtable: walk through the entries in the vtable
1800    and mark them as needed.  */
1801 
1802 static void
1803 mark_vtable_entries (tree decl)
1804 {
1805   tree fnaddr;
1806   unsigned HOST_WIDE_INT idx;
1807 
1808   /* It's OK for the vtable to refer to deprecated virtual functions.  */
1809   warning_sentinel w(warn_deprecated_decl);
1810 
1811   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)),
1812 			      idx, fnaddr)
1813     {
1814       tree fn;
1815 
1816       STRIP_NOPS (fnaddr);
1817 
1818       if (TREE_CODE (fnaddr) != ADDR_EXPR
1819 	  && TREE_CODE (fnaddr) != FDESC_EXPR)
1820 	/* This entry is an offset: a virtual base class offset, a
1821 	   virtual call offset, an RTTI offset, etc.  */
1822 	continue;
1823 
1824       fn = TREE_OPERAND (fnaddr, 0);
1825       TREE_ADDRESSABLE (fn) = 1;
1826       /* When we don't have vcall offsets, we output thunks whenever
1827 	 we output the vtables that contain them.  With vcall offsets,
1828 	 we know all the thunks we'll need when we emit a virtual
1829 	 function, so we emit the thunks there instead.  */
1830       if (DECL_THUNK_P (fn))
1831 	use_thunk (fn, /*emit_p=*/0);
1832       /* Set the location, as marking the function could cause
1833          instantiation.  We do not need to preserve the incoming
1834          location, as we're called from c_parse_final_cleanups, which
1835          takes care of that.  */
1836       input_location = DECL_SOURCE_LOCATION (fn);
1837       mark_used (fn);
1838     }
1839 }
1840 
1841 /* Set DECL up to have the closest approximation of "initialized common"
1842    linkage available.  */
1843 
1844 void
1845 comdat_linkage (tree decl)
1846 {
1847   if (flag_weak)
1848     make_decl_one_only (decl, cxx_comdat_group (decl));
1849   else if (TREE_CODE (decl) == FUNCTION_DECL
1850 	   || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
1851     /* We can just emit function and compiler-generated variables
1852        statically; having multiple copies is (for the most part) only
1853        a waste of space.
1854 
1855        There are two correctness issues, however: the address of a
1856        template instantiation with external linkage should be the
1857        same, independent of what translation unit asks for the
1858        address, and this will not hold when we emit multiple copies of
1859        the function.  However, there's little else we can do.
1860 
1861        Also, by default, the typeinfo implementation assumes that
1862        there will be only one copy of the string used as the name for
1863        each type.  Therefore, if weak symbols are unavailable, the
1864        run-time library should perform a more conservative check; it
1865        should perform a string comparison, rather than an address
1866        comparison.  */
1867     TREE_PUBLIC (decl) = 0;
1868   else
1869     {
1870       /* Static data member template instantiations, however, cannot
1871 	 have multiple copies.  */
1872       if (DECL_INITIAL (decl) == 0
1873 	  || DECL_INITIAL (decl) == error_mark_node)
1874 	DECL_COMMON (decl) = 1;
1875       else if (EMPTY_CONSTRUCTOR_P (DECL_INITIAL (decl)))
1876 	{
1877 	  DECL_COMMON (decl) = 1;
1878 	  DECL_INITIAL (decl) = error_mark_node;
1879 	}
1880       else if (!DECL_EXPLICIT_INSTANTIATION (decl))
1881 	{
1882 	  /* We can't do anything useful; leave vars for explicit
1883 	     instantiation.  */
1884 	  DECL_EXTERNAL (decl) = 1;
1885 	  DECL_NOT_REALLY_EXTERN (decl) = 0;
1886 	}
1887     }
1888 
1889   if (TREE_PUBLIC (decl))
1890     DECL_COMDAT (decl) = 1;
1891 }
1892 
1893 /* For win32 we also want to put explicit instantiations in
1894    linkonce sections, so that they will be merged with implicit
1895    instantiations; otherwise we get duplicate symbol errors.
1896    For Darwin we do not want explicit instantiations to be
1897    linkonce.  */
1898 
1899 void
1900 maybe_make_one_only (tree decl)
1901 {
1902   /* We used to say that this was not necessary on targets that support weak
1903      symbols, because the implicit instantiations will defer to the explicit
1904      one.  However, that's not actually the case in SVR4; a strong definition
1905      after a weak one is an error.  Also, not making explicit
1906      instantiations one_only means that we can end up with two copies of
1907      some template instantiations.  */
1908   if (! flag_weak)
1909     return;
1910 
1911   /* We can't set DECL_COMDAT on functions, or cp_finish_file will think
1912      we can get away with not emitting them if they aren't used.  We need
1913      to for variables so that cp_finish_decl will update their linkage,
1914      because their DECL_INITIAL may not have been set properly yet.  */
1915 
1916   if (!TARGET_WEAK_NOT_IN_ARCHIVE_TOC
1917       || (! DECL_EXPLICIT_INSTANTIATION (decl)
1918 	  && ! DECL_TEMPLATE_SPECIALIZATION (decl)))
1919     {
1920       make_decl_one_only (decl, cxx_comdat_group (decl));
1921 
1922       if (VAR_P (decl))
1923 	{
1924 	  varpool_node *node = varpool_node::get_create (decl);
1925 	  DECL_COMDAT (decl) = 1;
1926 	  /* Mark it needed so we don't forget to emit it.  */
1927           node->forced_by_abi = true;
1928 	  TREE_USED (decl) = 1;
1929 	}
1930     }
1931 }
1932 
1933 /* Returns true iff DECL, a FUNCTION_DECL or VAR_DECL, has vague linkage.
1934    This predicate will give the right answer during parsing of the
1935    function, which other tests may not.  */
1936 
1937 bool
1938 vague_linkage_p (tree decl)
1939 {
1940   if (!TREE_PUBLIC (decl))
1941     {
1942       /* maybe_thunk_body clears TREE_PUBLIC and DECL_ABSTRACT_P on the
1943 	 maybe-in-charge 'tor variants; in that case we need to check one of
1944 	 the "clones" for the real linkage.  But only in that case; before
1945 	 maybe_clone_body we haven't yet copied the linkage to the clones.  */
1946       if ((DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (decl)
1947 	   || DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl))
1948 	  && !DECL_ABSTRACT_P (decl)
1949 	  && DECL_CHAIN (decl)
1950 	  && DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)))
1951 	return vague_linkage_p (DECL_CHAIN (decl));
1952 
1953       gcc_checking_assert (!DECL_COMDAT (decl));
1954       return false;
1955     }
1956   /* Unfortunately, import_export_decl has not always been called
1957      before the function is processed, so we cannot simply check
1958      DECL_COMDAT.  */
1959   if (DECL_COMDAT (decl)
1960       || (TREE_CODE (decl) == FUNCTION_DECL
1961 	  && DECL_DECLARED_INLINE_P (decl))
1962       || (DECL_LANG_SPECIFIC (decl)
1963 	  && DECL_TEMPLATE_INSTANTIATION (decl))
1964       || (VAR_P (decl) && DECL_INLINE_VAR_P (decl)))
1965     return true;
1966   else if (DECL_FUNCTION_SCOPE_P (decl))
1967     /* A local static in an inline effectively has vague linkage.  */
1968     return (TREE_STATIC (decl)
1969 	    && vague_linkage_p (DECL_CONTEXT (decl)));
1970   else
1971     return false;
1972 }
1973 
1974 /* Determine whether or not we want to specifically import or export CTYPE,
1975    using various heuristics.  */
1976 
1977 static void
1978 import_export_class (tree ctype)
1979 {
1980   /* -1 for imported, 1 for exported.  */
1981   int import_export = 0;
1982 
1983   /* It only makes sense to call this function at EOF.  The reason is
1984      that this function looks at whether or not the first non-inline
1985      non-abstract virtual member function has been defined in this
1986      translation unit.  But, we can't possibly know that until we've
1987      seen the entire translation unit.  */
1988   gcc_assert (at_eof);
1989 
1990   if (CLASSTYPE_INTERFACE_KNOWN (ctype))
1991     return;
1992 
1993   /* If MULTIPLE_SYMBOL_SPACES is set and we saw a #pragma interface,
1994      we will have CLASSTYPE_INTERFACE_ONLY set but not
1995      CLASSTYPE_INTERFACE_KNOWN.  In that case, we don't want to use this
1996      heuristic because someone will supply a #pragma implementation
1997      elsewhere, and deducing it here would produce a conflict.  */
1998   if (CLASSTYPE_INTERFACE_ONLY (ctype))
1999     return;
2000 
2001   if (lookup_attribute ("dllimport", TYPE_ATTRIBUTES (ctype)))
2002     import_export = -1;
2003   else if (lookup_attribute ("dllexport", TYPE_ATTRIBUTES (ctype)))
2004     import_export = 1;
2005   else if (CLASSTYPE_IMPLICIT_INSTANTIATION (ctype)
2006 	   && !flag_implicit_templates)
2007     /* For a template class, without -fimplicit-templates, check the
2008        repository.  If the virtual table is assigned to this
2009        translation unit, then export the class; otherwise, import
2010        it.  */
2011       import_export = repo_export_class_p (ctype) ? 1 : -1;
2012   else if (TYPE_POLYMORPHIC_P (ctype))
2013     {
2014       /* The ABI specifies that the virtual table and associated
2015 	 information are emitted with the key method, if any.  */
2016       tree method = CLASSTYPE_KEY_METHOD (ctype);
2017       /* If weak symbol support is not available, then we must be
2018 	 careful not to emit the vtable when the key function is
2019 	 inline.  An inline function can be defined in multiple
2020 	 translation units.  If we were to emit the vtable in each
2021 	 translation unit containing a definition, we would get
2022 	 multiple definition errors at link-time.  */
2023       if (method && (flag_weak || ! DECL_DECLARED_INLINE_P (method)))
2024 	import_export = (DECL_REALLY_EXTERN (method) ? -1 : 1);
2025     }
2026 
2027   /* When MULTIPLE_SYMBOL_SPACES is set, we cannot count on seeing
2028      a definition anywhere else.  */
2029   if (MULTIPLE_SYMBOL_SPACES && import_export == -1)
2030     import_export = 0;
2031 
2032   /* Allow back ends the chance to overrule the decision.  */
2033   if (targetm.cxx.import_export_class)
2034     import_export = targetm.cxx.import_export_class (ctype, import_export);
2035 
2036   if (import_export)
2037     {
2038       SET_CLASSTYPE_INTERFACE_KNOWN (ctype);
2039       CLASSTYPE_INTERFACE_ONLY (ctype) = (import_export < 0);
2040     }
2041 }
2042 
2043 /* Return true if VAR has already been provided to the back end; in that
2044    case VAR should not be modified further by the front end.  */
2045 static bool
2046 var_finalized_p (tree var)
2047 {
2048   return varpool_node::get_create (var)->definition;
2049 }
2050 
2051 /* DECL is a VAR_DECL or FUNCTION_DECL which, for whatever reason,
2052    must be emitted in this translation unit.  Mark it as such.  */
2053 
2054 void
2055 mark_needed (tree decl)
2056 {
2057   TREE_USED (decl) = 1;
2058   if (TREE_CODE (decl) == FUNCTION_DECL)
2059     {
2060       /* Extern inline functions don't become needed when referenced.
2061 	 If we know a method will be emitted in other TU and no new
2062 	 functions can be marked reachable, just use the external
2063 	 definition.  */
2064       struct cgraph_node *node = cgraph_node::get_create (decl);
2065       node->forced_by_abi = true;
2066 
2067       /* #pragma interface and -frepo code can call mark_needed for
2068           maybe-in-charge 'tors; mark the clones as well.  */
2069       tree clone;
2070       FOR_EACH_CLONE (clone, decl)
2071 	mark_needed (clone);
2072     }
2073   else if (VAR_P (decl))
2074     {
2075       varpool_node *node = varpool_node::get_create (decl);
2076       /* C++ frontend use mark_decl_references to force COMDAT variables
2077          to be output that might appear dead otherwise.  */
2078       node->forced_by_abi = true;
2079     }
2080 }
2081 
2082 /* DECL is either a FUNCTION_DECL or a VAR_DECL.  This function
2083    returns true if a definition of this entity should be provided in
2084    this object file.  Callers use this function to determine whether
2085    or not to let the back end know that a definition of DECL is
2086    available in this translation unit.  */
2087 
2088 bool
2089 decl_needed_p (tree decl)
2090 {
2091   gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2092   /* This function should only be called at the end of the translation
2093      unit.  We cannot be sure of whether or not something will be
2094      COMDAT until that point.  */
2095   gcc_assert (at_eof);
2096 
2097   /* All entities with external linkage that are not COMDAT/EXTERN should be
2098      emitted; they may be referred to from other object files.  */
2099   if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl) && !DECL_REALLY_EXTERN (decl))
2100     return true;
2101   /* Functions marked "dllexport" must be emitted so that they are
2102      visible to other DLLs.  */
2103   if (flag_keep_inline_dllexport
2104       && lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
2105     return true;
2106 
2107   /* When not optimizing, do not bother to produce definitions for extern
2108      symbols.  */
2109   if (DECL_REALLY_EXTERN (decl)
2110       && ((TREE_CODE (decl) != FUNCTION_DECL
2111 	   && !optimize)
2112 	  || (TREE_CODE (decl) == FUNCTION_DECL
2113 	      && !opt_for_fn (decl, optimize)))
2114       && !lookup_attribute ("always_inline", decl))
2115     return false;
2116 
2117   /* If this entity was used, let the back end see it; it will decide
2118      whether or not to emit it into the object file.  */
2119   if (TREE_USED (decl))
2120     return true;
2121 
2122   /* Virtual functions might be needed for devirtualization.  */
2123   if (flag_devirtualize
2124       && TREE_CODE (decl) == FUNCTION_DECL
2125       && DECL_VIRTUAL_P (decl))
2126     return true;
2127 
2128   /* Otherwise, DECL does not need to be emitted -- yet.  A subsequent
2129      reference to DECL might cause it to be emitted later.  */
2130   return false;
2131 }
2132 
2133 /* If necessary, write out the vtables for the dynamic class CTYPE.
2134    Returns true if any vtables were emitted.  */
2135 
2136 static bool
2137 maybe_emit_vtables (tree ctype)
2138 {
2139   tree vtbl;
2140   tree primary_vtbl;
2141   int needed = 0;
2142   varpool_node *current = NULL, *last = NULL;
2143 
2144   /* If the vtables for this class have already been emitted there is
2145      nothing more to do.  */
2146   primary_vtbl = CLASSTYPE_VTABLES (ctype);
2147   if (var_finalized_p (primary_vtbl))
2148     return false;
2149   /* Ignore dummy vtables made by get_vtable_decl.  */
2150   if (TREE_TYPE (primary_vtbl) == void_type_node)
2151     return false;
2152 
2153   /* On some targets, we cannot determine the key method until the end
2154      of the translation unit -- which is when this function is
2155      called.  */
2156   if (!targetm.cxx.key_method_may_be_inline ())
2157     determine_key_method (ctype);
2158 
2159   /* See if any of the vtables are needed.  */
2160   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2161     {
2162       import_export_decl (vtbl);
2163       if (DECL_NOT_REALLY_EXTERN (vtbl) && decl_needed_p (vtbl))
2164 	needed = 1;
2165     }
2166   if (!needed)
2167     {
2168       /* If the references to this class' vtables are optimized away,
2169 	 still emit the appropriate debugging information.  See
2170 	 dfs_debug_mark.  */
2171       if (DECL_COMDAT (primary_vtbl)
2172 	  && CLASSTYPE_DEBUG_REQUESTED (ctype))
2173 	note_debug_info_needed (ctype);
2174       return false;
2175     }
2176 
2177   /* The ABI requires that we emit all of the vtables if we emit any
2178      of them.  */
2179   for (vtbl = CLASSTYPE_VTABLES (ctype); vtbl; vtbl = DECL_CHAIN (vtbl))
2180     {
2181       /* Mark entities references from the virtual table as used.  */
2182       mark_vtable_entries (vtbl);
2183 
2184       if (TREE_TYPE (DECL_INITIAL (vtbl)) == 0)
2185 	{
2186 	  vec<tree, va_gc> *cleanups = NULL;
2187 	  tree expr = store_init_value (vtbl, DECL_INITIAL (vtbl), &cleanups,
2188 					LOOKUP_NORMAL);
2189 
2190 	  /* It had better be all done at compile-time.  */
2191 	  gcc_assert (!expr && !cleanups);
2192 	}
2193 
2194       /* Write it out.  */
2195       DECL_EXTERNAL (vtbl) = 0;
2196       rest_of_decl_compilation (vtbl, 1, 1);
2197 
2198       /* Because we're only doing syntax-checking, we'll never end up
2199 	 actually marking the variable as written.  */
2200       if (flag_syntax_only)
2201 	TREE_ASM_WRITTEN (vtbl) = 1;
2202       else if (DECL_ONE_ONLY (vtbl))
2203 	{
2204 	  current = varpool_node::get_create (vtbl);
2205 	  if (last)
2206 	    current->add_to_same_comdat_group (last);
2207 	  last = current;
2208 	}
2209     }
2210 
2211   /* Since we're writing out the vtable here, also write the debug
2212      info.  */
2213   note_debug_info_needed (ctype);
2214 
2215   return true;
2216 }
2217 
2218 /* A special return value from type_visibility meaning internal
2219    linkage.  */
2220 
2221 enum { VISIBILITY_ANON = VISIBILITY_INTERNAL+1 };
2222 
2223 /* walk_tree helper function for type_visibility.  */
2224 
2225 static tree
2226 min_vis_r (tree *tp, int *walk_subtrees, void *data)
2227 {
2228   int *vis_p = (int *)data;
2229   if (! TYPE_P (*tp))
2230     {
2231       *walk_subtrees = 0;
2232     }
2233   else if (OVERLOAD_TYPE_P (*tp)
2234 	   && !TREE_PUBLIC (TYPE_MAIN_DECL (*tp)))
2235     {
2236       *vis_p = VISIBILITY_ANON;
2237       return *tp;
2238     }
2239   else if (CLASS_TYPE_P (*tp)
2240 	   && CLASSTYPE_VISIBILITY (*tp) > *vis_p)
2241     *vis_p = CLASSTYPE_VISIBILITY (*tp);
2242   return NULL;
2243 }
2244 
2245 /* Returns the visibility of TYPE, which is the minimum visibility of its
2246    component types.  */
2247 
2248 static int
2249 type_visibility (tree type)
2250 {
2251   int vis = VISIBILITY_DEFAULT;
2252   cp_walk_tree_without_duplicates (&type, min_vis_r, &vis);
2253   return vis;
2254 }
2255 
2256 /* Limit the visibility of DECL to VISIBILITY, if not explicitly
2257    specified (or if VISIBILITY is static).  If TMPL is true, this
2258    constraint is for a template argument, and takes precedence
2259    over explicitly-specified visibility on the template.  */
2260 
2261 static void
2262 constrain_visibility (tree decl, int visibility, bool tmpl)
2263 {
2264   if (visibility == VISIBILITY_ANON)
2265     {
2266       /* extern "C" declarations aren't affected by the anonymous
2267 	 namespace.  */
2268       if (!DECL_EXTERN_C_P (decl))
2269 	{
2270 	  TREE_PUBLIC (decl) = 0;
2271 	  DECL_WEAK (decl) = 0;
2272 	  DECL_COMMON (decl) = 0;
2273 	  DECL_COMDAT (decl) = false;
2274 	  if (VAR_OR_FUNCTION_DECL_P (decl))
2275 	    {
2276 	      struct symtab_node *snode = symtab_node::get (decl);
2277 
2278 	      if (snode)
2279 	        snode->set_comdat_group (NULL);
2280 	    }
2281 	  DECL_INTERFACE_KNOWN (decl) = 1;
2282 	  if (DECL_LANG_SPECIFIC (decl))
2283 	    DECL_NOT_REALLY_EXTERN (decl) = 1;
2284 	}
2285     }
2286   else if (visibility > DECL_VISIBILITY (decl)
2287 	   && (tmpl || !DECL_VISIBILITY_SPECIFIED (decl)))
2288     {
2289       DECL_VISIBILITY (decl) = (enum symbol_visibility) visibility;
2290       /* This visibility was not specified.  */
2291       DECL_VISIBILITY_SPECIFIED (decl) = false;
2292     }
2293 }
2294 
2295 /* Constrain the visibility of DECL based on the visibility of its template
2296    arguments.  */
2297 
2298 static void
2299 constrain_visibility_for_template (tree decl, tree targs)
2300 {
2301   /* If this is a template instantiation, check the innermost
2302      template args for visibility constraints.  The outer template
2303      args are covered by the class check.  */
2304   tree args = INNERMOST_TEMPLATE_ARGS (targs);
2305   int i;
2306   for (i = TREE_VEC_LENGTH (args); i > 0; --i)
2307     {
2308       int vis = 0;
2309 
2310       tree arg = TREE_VEC_ELT (args, i-1);
2311       if (TYPE_P (arg))
2312 	vis = type_visibility (arg);
2313       else
2314 	{
2315 	  if (REFERENCE_REF_P (arg))
2316 	    arg = TREE_OPERAND (arg, 0);
2317 	  if (TREE_TYPE (arg))
2318 	    STRIP_NOPS (arg);
2319 	  if (TREE_CODE (arg) == ADDR_EXPR)
2320 	    arg = TREE_OPERAND (arg, 0);
2321 	  if (VAR_OR_FUNCTION_DECL_P (arg))
2322 	    {
2323 	      if (! TREE_PUBLIC (arg))
2324 		vis = VISIBILITY_ANON;
2325 	      else
2326 		vis = DECL_VISIBILITY (arg);
2327 	    }
2328 	}
2329       if (vis)
2330 	constrain_visibility (decl, vis, true);
2331     }
2332 }
2333 
2334 /* Like c_determine_visibility, but with additional C++-specific
2335    behavior.
2336 
2337    Function-scope entities can rely on the function's visibility because
2338    it is set in start_preparsed_function.
2339 
2340    Class-scope entities cannot rely on the class's visibility until the end
2341    of the enclosing class definition.
2342 
2343    Note that because namespaces have multiple independent definitions,
2344    namespace visibility is handled elsewhere using the #pragma visibility
2345    machinery rather than by decorating the namespace declaration.
2346 
2347    The goal is for constraints from the type to give a diagnostic, and
2348    other constraints to be applied silently.  */
2349 
2350 void
2351 determine_visibility (tree decl)
2352 {
2353   /* Remember that all decls get VISIBILITY_DEFAULT when built.  */
2354 
2355   /* Only relevant for names with external linkage.  */
2356   if (!TREE_PUBLIC (decl))
2357     return;
2358 
2359   /* Cloned constructors and destructors get the same visibility as
2360      the underlying function.  That should be set up in
2361      maybe_clone_body.  */
2362   gcc_assert (!DECL_CLONED_FUNCTION_P (decl));
2363 
2364   bool orig_visibility_specified = DECL_VISIBILITY_SPECIFIED (decl);
2365   enum symbol_visibility orig_visibility = DECL_VISIBILITY (decl);
2366 
2367   /* The decl may be a template instantiation, which could influence
2368      visibilty.  */
2369   tree template_decl = NULL_TREE;
2370   if (TREE_CODE (decl) == TYPE_DECL)
2371     {
2372       if (CLASS_TYPE_P (TREE_TYPE (decl)))
2373 	{
2374 	  if (CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)))
2375 	    template_decl = decl;
2376 	}
2377       else if (TYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
2378 	template_decl = decl;
2379     }
2380   else if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
2381     template_decl = decl;
2382 
2383   /* If DECL is a member of a class, visibility specifiers on the
2384      class can influence the visibility of the DECL.  */
2385   tree class_type = NULL_TREE;
2386   if (DECL_CLASS_SCOPE_P (decl))
2387     class_type = DECL_CONTEXT (decl);
2388   else
2389     {
2390       /* Not a class member.  */
2391 
2392       /* Virtual tables have DECL_CONTEXT set to their associated class,
2393 	 so they are automatically handled above.  */
2394       gcc_assert (!VAR_P (decl)
2395 		  || !DECL_VTABLE_OR_VTT_P (decl));
2396 
2397       if (DECL_FUNCTION_SCOPE_P (decl) && ! DECL_VISIBILITY_SPECIFIED (decl))
2398 	{
2399 	  /* Local statics and classes get the visibility of their
2400 	     containing function by default, except that
2401 	     -fvisibility-inlines-hidden doesn't affect them.  */
2402 	  tree fn = DECL_CONTEXT (decl);
2403 	  if (DECL_VISIBILITY_SPECIFIED (fn))
2404 	    {
2405 	      DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2406 	      DECL_VISIBILITY_SPECIFIED (decl) =
2407 		DECL_VISIBILITY_SPECIFIED (fn);
2408 	    }
2409 	  else
2410 	    {
2411 	      if (DECL_CLASS_SCOPE_P (fn))
2412 		determine_visibility_from_class (decl, DECL_CONTEXT (fn));
2413 	      else if (determine_hidden_inline (fn))
2414 		{
2415 		  DECL_VISIBILITY (decl) = default_visibility;
2416 		  DECL_VISIBILITY_SPECIFIED (decl) =
2417 		    visibility_options.inpragma;
2418 		}
2419 	      else
2420 		{
2421 	          DECL_VISIBILITY (decl) = DECL_VISIBILITY (fn);
2422 	          DECL_VISIBILITY_SPECIFIED (decl) =
2423 		    DECL_VISIBILITY_SPECIFIED (fn);
2424 		}
2425 	    }
2426 
2427 	  /* Local classes in templates have CLASSTYPE_USE_TEMPLATE set,
2428 	     but have no TEMPLATE_INFO, so don't try to check it.  */
2429 	  template_decl = NULL_TREE;
2430 	}
2431       else if (VAR_P (decl) && DECL_TINFO_P (decl)
2432 	       && flag_visibility_ms_compat)
2433 	{
2434 	  /* Under -fvisibility-ms-compat, types are visible by default,
2435 	     even though their contents aren't.  */
2436 	  tree underlying_type = TREE_TYPE (DECL_NAME (decl));
2437 	  int underlying_vis = type_visibility (underlying_type);
2438 	  if (underlying_vis == VISIBILITY_ANON
2439 	      || (CLASS_TYPE_P (underlying_type)
2440 		  && CLASSTYPE_VISIBILITY_SPECIFIED (underlying_type)))
2441 	    constrain_visibility (decl, underlying_vis, false);
2442 	  else
2443 	    DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
2444 	}
2445       else if (VAR_P (decl) && DECL_TINFO_P (decl))
2446 	{
2447 	  /* tinfo visibility is based on the type it's for.  */
2448 	  constrain_visibility
2449 	    (decl, type_visibility (TREE_TYPE (DECL_NAME (decl))), false);
2450 
2451 	  /* Give the target a chance to override the visibility associated
2452 	     with DECL.  */
2453 	  if (TREE_PUBLIC (decl)
2454 	      && !DECL_REALLY_EXTERN (decl)
2455 	      && CLASS_TYPE_P (TREE_TYPE (DECL_NAME (decl)))
2456 	      && !CLASSTYPE_VISIBILITY_SPECIFIED (TREE_TYPE (DECL_NAME (decl))))
2457 	    targetm.cxx.determine_class_data_visibility (decl);
2458 	}
2459       else if (template_decl)
2460 	/* Template instantiations and specializations get visibility based
2461 	   on their template unless they override it with an attribute.  */;
2462       else if (! DECL_VISIBILITY_SPECIFIED (decl))
2463 	{
2464           if (determine_hidden_inline (decl))
2465 	    DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2466 	  else
2467             {
2468 	      /* Set default visibility to whatever the user supplied with
2469 	         #pragma GCC visibility or a namespace visibility attribute.  */
2470 	      DECL_VISIBILITY (decl) = default_visibility;
2471 	      DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
2472             }
2473 	}
2474     }
2475 
2476   if (template_decl)
2477     {
2478       /* If the specialization doesn't specify visibility, use the
2479 	 visibility from the template.  */
2480       tree tinfo = get_template_info (template_decl);
2481       tree args = TI_ARGS (tinfo);
2482       tree attribs = (TREE_CODE (decl) == TYPE_DECL
2483 		      ? TYPE_ATTRIBUTES (TREE_TYPE (decl))
2484 		      : DECL_ATTRIBUTES (decl));
2485 
2486       if (args != error_mark_node)
2487 	{
2488 	  tree pattern = DECL_TEMPLATE_RESULT (TI_TEMPLATE (tinfo));
2489 
2490 	  if (!DECL_VISIBILITY_SPECIFIED (decl))
2491 	    {
2492 	      if (!DECL_VISIBILITY_SPECIFIED (pattern)
2493 		  && determine_hidden_inline (decl))
2494 		DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2495 	      else
2496 		{
2497 	          DECL_VISIBILITY (decl) = DECL_VISIBILITY (pattern);
2498 	          DECL_VISIBILITY_SPECIFIED (decl)
2499 		    = DECL_VISIBILITY_SPECIFIED (pattern);
2500 		}
2501 	    }
2502 
2503 	  if (args
2504 	      /* Template argument visibility outweighs #pragma or namespace
2505 		 visibility, but not an explicit attribute.  */
2506 	      && !lookup_attribute ("visibility", attribs))
2507 	    {
2508 	      int depth = TMPL_ARGS_DEPTH (args);
2509 	      if (DECL_VISIBILITY_SPECIFIED (decl))
2510 		{
2511 		  /* A class template member with explicit visibility
2512 		     overrides the class visibility, so we need to apply
2513 		     all the levels of template args directly.  */
2514 		  int i;
2515 		  for (i = 1; i <= depth; ++i)
2516 		    {
2517 		      tree lev = TMPL_ARGS_LEVEL (args, i);
2518 		      constrain_visibility_for_template (decl, lev);
2519 		    }
2520 		}
2521 	      else if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
2522 		/* Limit visibility based on its template arguments.  */
2523 		constrain_visibility_for_template (decl, args);
2524 	    }
2525 	}
2526     }
2527 
2528   if (class_type)
2529     determine_visibility_from_class (decl, class_type);
2530 
2531   if (decl_anon_ns_mem_p (decl))
2532     /* Names in an anonymous namespace get internal linkage.
2533        This might change once we implement export.  */
2534     constrain_visibility (decl, VISIBILITY_ANON, false);
2535   else if (TREE_CODE (decl) != TYPE_DECL)
2536     {
2537       /* Propagate anonymity from type to decl.  */
2538       int tvis = type_visibility (TREE_TYPE (decl));
2539       if (tvis == VISIBILITY_ANON
2540 	  || ! DECL_VISIBILITY_SPECIFIED (decl))
2541 	constrain_visibility (decl, tvis, false);
2542     }
2543   else if (no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/true))
2544     /* DR 757: A type without linkage shall not be used as the type of a
2545        variable or function with linkage, unless
2546        o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
2547        o the variable or function is not used (3.2 [basic.def.odr]) or is
2548        defined in the same translation unit.
2549 
2550        Since non-extern "C" decls need to be defined in the same
2551        translation unit, we can make the type internal.  */
2552     constrain_visibility (decl, VISIBILITY_ANON, false);
2553 
2554   /* If visibility changed and DECL already has DECL_RTL, ensure
2555      symbol flags are updated.  */
2556   if ((DECL_VISIBILITY (decl) != orig_visibility
2557        || DECL_VISIBILITY_SPECIFIED (decl) != orig_visibility_specified)
2558       && ((VAR_P (decl) && TREE_STATIC (decl))
2559 	  || TREE_CODE (decl) == FUNCTION_DECL)
2560       && DECL_RTL_SET_P (decl))
2561     make_decl_rtl (decl);
2562 }
2563 
2564 /* By default, static data members and function members receive
2565    the visibility of their containing class.  */
2566 
2567 static void
2568 determine_visibility_from_class (tree decl, tree class_type)
2569 {
2570   if (DECL_VISIBILITY_SPECIFIED (decl))
2571     return;
2572 
2573   if (determine_hidden_inline (decl))
2574     DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
2575   else
2576     {
2577       /* Default to the class visibility.  */
2578       DECL_VISIBILITY (decl) = CLASSTYPE_VISIBILITY (class_type);
2579       DECL_VISIBILITY_SPECIFIED (decl)
2580 	= CLASSTYPE_VISIBILITY_SPECIFIED (class_type);
2581     }
2582 
2583   /* Give the target a chance to override the visibility associated
2584      with DECL.  */
2585   if (VAR_P (decl)
2586       && (DECL_TINFO_P (decl)
2587 	  || (DECL_VTABLE_OR_VTT_P (decl)
2588 	      /* Construction virtual tables are not exported because
2589 		 they cannot be referred to from other object files;
2590 		 their name is not standardized by the ABI.  */
2591 	      && !DECL_CONSTRUCTION_VTABLE_P (decl)))
2592       && TREE_PUBLIC (decl)
2593       && !DECL_REALLY_EXTERN (decl)
2594       && !CLASSTYPE_VISIBILITY_SPECIFIED (class_type))
2595     targetm.cxx.determine_class_data_visibility (decl);
2596 }
2597 
2598 /* Returns true iff DECL is an inline that should get hidden visibility
2599    because of -fvisibility-inlines-hidden.  */
2600 
2601 static bool
2602 determine_hidden_inline (tree decl)
2603 {
2604   return (visibility_options.inlines_hidden
2605 	  /* Don't do this for inline templates; specializations might not be
2606 	     inline, and we don't want them to inherit the hidden
2607 	     visibility.  We'll set it here for all inline instantiations.  */
2608 	  && !processing_template_decl
2609 	  && TREE_CODE (decl) == FUNCTION_DECL
2610 	  && DECL_DECLARED_INLINE_P (decl)
2611 	  && (! DECL_LANG_SPECIFIC (decl)
2612 	      || ! DECL_EXPLICIT_INSTANTIATION (decl)));
2613 }
2614 
2615 /* Constrain the visibility of a class TYPE based on the visibility of its
2616    field types.  Warn if any fields require lesser visibility.  */
2617 
2618 void
2619 constrain_class_visibility (tree type)
2620 {
2621   tree binfo;
2622   tree t;
2623   int i;
2624 
2625   int vis = type_visibility (type);
2626 
2627   if (vis == VISIBILITY_ANON
2628       || DECL_IN_SYSTEM_HEADER (TYPE_MAIN_DECL (type)))
2629     return;
2630 
2631   /* Don't warn about visibility if the class has explicit visibility.  */
2632   if (CLASSTYPE_VISIBILITY_SPECIFIED (type))
2633     vis = VISIBILITY_INTERNAL;
2634 
2635   for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
2636     if (TREE_CODE (t) == FIELD_DECL && TREE_TYPE (t) != error_mark_node
2637 	&& !DECL_ARTIFICIAL (t))
2638       {
2639 	tree ftype = strip_pointer_or_array_types (TREE_TYPE (t));
2640 	int subvis = type_visibility (ftype);
2641 
2642 	if (subvis == VISIBILITY_ANON)
2643 	  {
2644 	    if (!in_main_input_context())
2645 	      {
2646 		tree nlt = no_linkage_check (ftype, /*relaxed_p=*/false);
2647 		if (nlt)
2648 		  {
2649 		    if (same_type_p (TREE_TYPE (t), nlt))
2650 		      warning (OPT_Wsubobject_linkage, "\
2651 %qT has a field %qD whose type has no linkage",
2652 			       type, t);
2653 		    else
2654 		      warning (OPT_Wsubobject_linkage, "\
2655 %qT has a field %qD whose type depends on the type %qT which has no linkage",
2656 			       type, t, nlt);
2657 		  }
2658 		else
2659 		  warning (OPT_Wsubobject_linkage, "\
2660 %qT has a field %qD whose type uses the anonymous namespace",
2661 			   type, t);
2662 	      }
2663 	  }
2664 	else if (MAYBE_CLASS_TYPE_P (ftype)
2665 		 && vis < VISIBILITY_HIDDEN
2666 		 && subvis >= VISIBILITY_HIDDEN)
2667 	  warning (OPT_Wattributes, "\
2668 %qT declared with greater visibility than the type of its field %qD",
2669 		   type, t);
2670       }
2671 
2672   binfo = TYPE_BINFO (type);
2673   for (i = 0; BINFO_BASE_ITERATE (binfo, i, t); ++i)
2674     {
2675       int subvis = type_visibility (TREE_TYPE (t));
2676 
2677       if (subvis == VISIBILITY_ANON)
2678         {
2679 	  if (!in_main_input_context())
2680 	    {
2681 	      tree nlt = no_linkage_check (TREE_TYPE (t), /*relaxed_p=*/false);
2682 	      if (nlt)
2683 		{
2684 		  if (same_type_p (TREE_TYPE (t), nlt))
2685 		    warning (OPT_Wsubobject_linkage, "\
2686 %qT has a base %qT whose type has no linkage",
2687 			     type, TREE_TYPE (t));
2688 		  else
2689 		    warning (OPT_Wsubobject_linkage, "\
2690 %qT has a base %qT whose type depends on the type %qT which has no linkage",
2691 			     type, TREE_TYPE (t), nlt);
2692 		}
2693 	      else
2694 		warning (OPT_Wsubobject_linkage, "\
2695 %qT has a base %qT whose type uses the anonymous namespace",
2696 			 type, TREE_TYPE (t));
2697 	    }
2698 	}
2699       else if (vis < VISIBILITY_HIDDEN
2700 	       && subvis >= VISIBILITY_HIDDEN)
2701 	warning (OPT_Wattributes, "\
2702 %qT declared with greater visibility than its base %qT",
2703 		 type, TREE_TYPE (t));
2704     }
2705 }
2706 
2707 /* Functions for adjusting the visibility of a tagged type and its nested
2708    types and declarations when it gets a name for linkage purposes from a
2709    typedef.  */
2710 
2711 static void bt_reset_linkage_1 (binding_entry, void *);
2712 static void bt_reset_linkage_2 (binding_entry, void *);
2713 
2714 /* First reset the visibility of all the types.  */
2715 
2716 static void
2717 reset_type_linkage_1 (tree type)
2718 {
2719   set_linkage_according_to_type (type, TYPE_MAIN_DECL (type));
2720   if (CLASS_TYPE_P (type))
2721     binding_table_foreach (CLASSTYPE_NESTED_UTDS (type),
2722 			   bt_reset_linkage_1, NULL);
2723 }
2724 static void
2725 bt_reset_linkage_1 (binding_entry b, void */*data*/)
2726 {
2727   reset_type_linkage_1 (b->type);
2728 }
2729 
2730 /* Then reset the visibility of any static data members or member
2731    functions that use those types.  */
2732 
2733 static void
2734 reset_decl_linkage (tree decl)
2735 {
2736   if (TREE_PUBLIC (decl))
2737     return;
2738   if (DECL_CLONED_FUNCTION_P (decl))
2739     return;
2740   TREE_PUBLIC (decl) = true;
2741   DECL_INTERFACE_KNOWN (decl) = false;
2742   determine_visibility (decl);
2743   tentative_decl_linkage (decl);
2744 }
2745 
2746 static void
2747 reset_type_linkage_2 (tree type)
2748 {
2749   if (CLASS_TYPE_P (type))
2750     {
2751       if (tree vt = CLASSTYPE_VTABLES (type))
2752 	{
2753 	  tree name = mangle_vtbl_for_type (type);
2754 	  DECL_NAME (vt) = name;
2755 	  SET_DECL_ASSEMBLER_NAME (vt, name);
2756 	  reset_decl_linkage (vt);
2757 	}
2758       if (tree ti = CLASSTYPE_TYPEINFO_VAR (type))
2759 	{
2760 	  tree name = mangle_typeinfo_for_type (type);
2761 	  DECL_NAME (ti) = name;
2762 	  SET_DECL_ASSEMBLER_NAME (ti, name);
2763 	  TREE_TYPE (name) = type;
2764 	  reset_decl_linkage (ti);
2765 	}
2766       for (tree m = TYPE_FIELDS (type); m; m = DECL_CHAIN (m))
2767 	{
2768 	  tree mem = STRIP_TEMPLATE (m);
2769 	  if (TREE_CODE (mem) == VAR_DECL || TREE_CODE (mem) == FUNCTION_DECL)
2770 	    reset_decl_linkage (mem);
2771 	}
2772       binding_table_foreach (CLASSTYPE_NESTED_UTDS (type),
2773 			     bt_reset_linkage_2, NULL);
2774     }
2775 }
2776 
2777 static void
2778 bt_reset_linkage_2 (binding_entry b, void */*data*/)
2779 {
2780   reset_type_linkage_2 (b->type);
2781 }
2782 void
2783 reset_type_linkage (tree type)
2784 {
2785   reset_type_linkage_1 (type);
2786   reset_type_linkage_2 (type);
2787 }
2788 
2789 /* Set up our initial idea of what the linkage of DECL should be.  */
2790 
2791 void
2792 tentative_decl_linkage (tree decl)
2793 {
2794   if (DECL_INTERFACE_KNOWN (decl))
2795     /* We've already made a decision as to how this function will
2796        be handled.  */;
2797   else if (vague_linkage_p (decl))
2798     {
2799       if (TREE_CODE (decl) == FUNCTION_DECL
2800 	  && decl_defined_p (decl))
2801 	{
2802 	  DECL_EXTERNAL (decl) = 1;
2803 	  DECL_NOT_REALLY_EXTERN (decl) = 1;
2804 	  note_vague_linkage_fn (decl);
2805 	  /* A non-template inline function with external linkage will
2806 	     always be COMDAT.  As we must eventually determine the
2807 	     linkage of all functions, and as that causes writes to
2808 	     the data mapped in from the PCH file, it's advantageous
2809 	     to mark the functions at this point.  */
2810 	  if (DECL_DECLARED_INLINE_P (decl)
2811 	      && (!DECL_IMPLICIT_INSTANTIATION (decl)
2812 		  || DECL_DEFAULTED_FN (decl)))
2813 	    {
2814 	      /* This function must have external linkage, as
2815 		 otherwise DECL_INTERFACE_KNOWN would have been
2816 		 set.  */
2817 	      gcc_assert (TREE_PUBLIC (decl));
2818 	      comdat_linkage (decl);
2819 	      DECL_INTERFACE_KNOWN (decl) = 1;
2820 	    }
2821 	}
2822       else if (VAR_P (decl))
2823 	maybe_commonize_var (decl);
2824     }
2825 }
2826 
2827 /* DECL is a FUNCTION_DECL or VAR_DECL.  If the object file linkage
2828    for DECL has not already been determined, do so now by setting
2829    DECL_EXTERNAL, DECL_COMDAT and other related flags.  Until this
2830    function is called entities with vague linkage whose definitions
2831    are available must have TREE_PUBLIC set.
2832 
2833    If this function decides to place DECL in COMDAT, it will set
2834    appropriate flags -- but will not clear DECL_EXTERNAL.  It is up to
2835    the caller to decide whether or not to clear DECL_EXTERNAL.  Some
2836    callers defer that decision until it is clear that DECL is actually
2837    required.  */
2838 
2839 void
2840 import_export_decl (tree decl)
2841 {
2842   int emit_p;
2843   bool comdat_p;
2844   bool import_p;
2845   tree class_type = NULL_TREE;
2846 
2847   if (DECL_INTERFACE_KNOWN (decl))
2848     return;
2849 
2850   /* We cannot determine what linkage to give to an entity with vague
2851      linkage until the end of the file.  For example, a virtual table
2852      for a class will be defined if and only if the key method is
2853      defined in this translation unit.  As a further example, consider
2854      that when compiling a translation unit that uses PCH file with
2855      "-frepo" it would be incorrect to make decisions about what
2856      entities to emit when building the PCH; those decisions must be
2857      delayed until the repository information has been processed.  */
2858   gcc_assert (at_eof);
2859   /* Object file linkage for explicit instantiations is handled in
2860      mark_decl_instantiated.  For static variables in functions with
2861      vague linkage, maybe_commonize_var is used.
2862 
2863      Therefore, the only declarations that should be provided to this
2864      function are those with external linkage that are:
2865 
2866      * implicit instantiations of function templates
2867 
2868      * inline function
2869 
2870      * implicit instantiations of static data members of class
2871        templates
2872 
2873      * virtual tables
2874 
2875      * typeinfo objects
2876 
2877      Furthermore, all entities that reach this point must have a
2878      definition available in this translation unit.
2879 
2880      The following assertions check these conditions.  */
2881   gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
2882   /* Any code that creates entities with TREE_PUBLIC cleared should
2883      also set DECL_INTERFACE_KNOWN.  */
2884   gcc_assert (TREE_PUBLIC (decl));
2885   if (TREE_CODE (decl) == FUNCTION_DECL)
2886     gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2887 		|| DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
2888 		|| DECL_DECLARED_INLINE_P (decl));
2889   else
2890     gcc_assert (DECL_IMPLICIT_INSTANTIATION (decl)
2891 		|| DECL_VTABLE_OR_VTT_P (decl)
2892 		|| DECL_TINFO_P (decl));
2893   /* Check that a definition of DECL is available in this translation
2894      unit.  */
2895   gcc_assert (!DECL_REALLY_EXTERN (decl));
2896 
2897   /* Assume that DECL will not have COMDAT linkage.  */
2898   comdat_p = false;
2899   /* Assume that DECL will not be imported into this translation
2900      unit.  */
2901   import_p = false;
2902 
2903   /* See if the repository tells us whether or not to emit DECL in
2904      this translation unit.  */
2905   emit_p = repo_emit_p (decl);
2906   if (emit_p == 0)
2907     import_p = true;
2908   else if (emit_p == 1)
2909     {
2910       /* The repository indicates that this entity should be defined
2911 	 here.  Make sure the back end honors that request.  */
2912       mark_needed (decl);
2913       /* Output the definition as an ordinary strong definition.  */
2914       DECL_EXTERNAL (decl) = 0;
2915       DECL_INTERFACE_KNOWN (decl) = 1;
2916       return;
2917     }
2918 
2919   if (import_p)
2920     /* We have already decided what to do with this DECL; there is no
2921        need to check anything further.  */
2922     ;
2923   else if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
2924     {
2925       class_type = DECL_CONTEXT (decl);
2926       import_export_class (class_type);
2927       if (CLASSTYPE_INTERFACE_KNOWN (class_type)
2928 	  && CLASSTYPE_INTERFACE_ONLY (class_type))
2929 	import_p = true;
2930       else if ((!flag_weak || TARGET_WEAK_NOT_IN_ARCHIVE_TOC)
2931 	       && !CLASSTYPE_USE_TEMPLATE (class_type)
2932 	       && CLASSTYPE_KEY_METHOD (class_type)
2933 	       && !DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type)))
2934 	/* The ABI requires that all virtual tables be emitted with
2935 	   COMDAT linkage.  However, on systems where COMDAT symbols
2936 	   don't show up in the table of contents for a static
2937 	   archive, or on systems without weak symbols (where we
2938 	   approximate COMDAT linkage by using internal linkage), the
2939 	   linker will report errors about undefined symbols because
2940 	   it will not see the virtual table definition.  Therefore,
2941 	   in the case that we know that the virtual table will be
2942 	   emitted in only one translation unit, we make the virtual
2943 	   table an ordinary definition with external linkage.  */
2944 	DECL_EXTERNAL (decl) = 0;
2945       else if (CLASSTYPE_INTERFACE_KNOWN (class_type))
2946 	{
2947 	  /* CLASS_TYPE is being exported from this translation unit,
2948 	     so DECL should be defined here.  */
2949 	  if (!flag_weak && CLASSTYPE_EXPLICIT_INSTANTIATION (class_type))
2950 	    /* If a class is declared in a header with the "extern
2951 	       template" extension, then it will not be instantiated,
2952 	       even in translation units that would normally require
2953 	       it.  Often such classes are explicitly instantiated in
2954 	       one translation unit.  Therefore, the explicit
2955 	       instantiation must be made visible to other translation
2956 	       units.  */
2957 	    DECL_EXTERNAL (decl) = 0;
2958 	  else
2959 	    {
2960 	      /* The generic C++ ABI says that class data is always
2961 		 COMDAT, even if there is a key function.  Some
2962 		 variants (e.g., the ARM EABI) says that class data
2963 		 only has COMDAT linkage if the class data might be
2964 		 emitted in more than one translation unit.  When the
2965 		 key method can be inline and is inline, we still have
2966 		 to arrange for comdat even though
2967 		 class_data_always_comdat is false.  */
2968 	      if (!CLASSTYPE_KEY_METHOD (class_type)
2969 		  || DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (class_type))
2970 		  || targetm.cxx.class_data_always_comdat ())
2971 		{
2972 		  /* The ABI requires COMDAT linkage.  Normally, we
2973 		     only emit COMDAT things when they are needed;
2974 		     make sure that we realize that this entity is
2975 		     indeed needed.  */
2976 		  comdat_p = true;
2977 		  mark_needed (decl);
2978 		}
2979 	    }
2980 	}
2981       else if (!flag_implicit_templates
2982 	       && CLASSTYPE_IMPLICIT_INSTANTIATION (class_type))
2983 	import_p = true;
2984       else
2985 	comdat_p = true;
2986     }
2987   else if (VAR_P (decl) && DECL_TINFO_P (decl))
2988     {
2989       tree type = TREE_TYPE (DECL_NAME (decl));
2990       if (CLASS_TYPE_P (type))
2991 	{
2992 	  class_type = type;
2993 	  import_export_class (type);
2994 	  if (CLASSTYPE_INTERFACE_KNOWN (type)
2995 	      && TYPE_POLYMORPHIC_P (type)
2996 	      && CLASSTYPE_INTERFACE_ONLY (type)
2997 	      /* If -fno-rtti was specified, then we cannot be sure
2998 		 that RTTI information will be emitted with the
2999 		 virtual table of the class, so we must emit it
3000 		 wherever it is used.  */
3001 	      && flag_rtti)
3002 	    import_p = true;
3003 	  else
3004 	    {
3005 	      if (CLASSTYPE_INTERFACE_KNOWN (type)
3006 		  && !CLASSTYPE_INTERFACE_ONLY (type))
3007 		{
3008 		  comdat_p = (targetm.cxx.class_data_always_comdat ()
3009 			      || (CLASSTYPE_KEY_METHOD (type)
3010 				  && DECL_DECLARED_INLINE_P (CLASSTYPE_KEY_METHOD (type))));
3011 		  mark_needed (decl);
3012 		  if (!flag_weak)
3013 		    {
3014 		      comdat_p = false;
3015 		      DECL_EXTERNAL (decl) = 0;
3016 		    }
3017 		}
3018 	      else
3019 		comdat_p = true;
3020 	    }
3021 	}
3022       else
3023 	comdat_p = true;
3024     }
3025   else if (DECL_TEMPLOID_INSTANTIATION (decl))
3026     {
3027       /* DECL is an implicit instantiation of a function or static
3028 	 data member.  */
3029       if ((flag_implicit_templates
3030 	   && !flag_use_repository)
3031 	  || (flag_implicit_inline_templates
3032 	      && TREE_CODE (decl) == FUNCTION_DECL
3033 	      && DECL_DECLARED_INLINE_P (decl)))
3034 	comdat_p = true;
3035       else
3036 	/* If we are not implicitly generating templates, then mark
3037 	   this entity as undefined in this translation unit.  */
3038 	import_p = true;
3039     }
3040   else if (DECL_FUNCTION_MEMBER_P (decl))
3041     {
3042       if (!DECL_DECLARED_INLINE_P (decl))
3043 	{
3044 	  tree ctype = DECL_CONTEXT (decl);
3045 	  import_export_class (ctype);
3046 	  if (CLASSTYPE_INTERFACE_KNOWN (ctype))
3047 	    {
3048 	      DECL_NOT_REALLY_EXTERN (decl)
3049 		= ! (CLASSTYPE_INTERFACE_ONLY (ctype)
3050 		     || (DECL_DECLARED_INLINE_P (decl)
3051 			 && ! flag_implement_inlines
3052 			 && !DECL_VINDEX (decl)));
3053 
3054 	      if (!DECL_NOT_REALLY_EXTERN (decl))
3055 		DECL_EXTERNAL (decl) = 1;
3056 
3057 	      /* Always make artificials weak.  */
3058 	      if (DECL_ARTIFICIAL (decl) && flag_weak)
3059 		comdat_p = true;
3060 	      else
3061 		maybe_make_one_only (decl);
3062 	    }
3063 	}
3064       else
3065 	comdat_p = true;
3066     }
3067   else
3068     comdat_p = true;
3069 
3070   if (import_p)
3071     {
3072       /* If we are importing DECL into this translation unit, mark is
3073 	 an undefined here.  */
3074       DECL_EXTERNAL (decl) = 1;
3075       DECL_NOT_REALLY_EXTERN (decl) = 0;
3076     }
3077   else if (comdat_p)
3078     {
3079       /* If we decided to put DECL in COMDAT, mark it accordingly at
3080 	 this point.  */
3081       comdat_linkage (decl);
3082     }
3083 
3084   DECL_INTERFACE_KNOWN (decl) = 1;
3085 }
3086 
3087 /* Return an expression that performs the destruction of DECL, which
3088    must be a VAR_DECL whose type has a non-trivial destructor, or is
3089    an array whose (innermost) elements have a non-trivial destructor.  */
3090 
3091 tree
3092 build_cleanup (tree decl)
3093 {
3094   tree clean = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
3095   gcc_assert (clean != NULL_TREE);
3096   return clean;
3097 }
3098 
3099 /* Returns the initialization guard variable for the variable DECL,
3100    which has static storage duration.  */
3101 
3102 tree
3103 get_guard (tree decl)
3104 {
3105   tree sname;
3106   tree guard;
3107 
3108   sname = mangle_guard_variable (decl);
3109   guard = get_global_binding (sname);
3110   if (! guard)
3111     {
3112       tree guard_type;
3113 
3114       /* We use a type that is big enough to contain a mutex as well
3115 	 as an integer counter.  */
3116       guard_type = targetm.cxx.guard_type ();
3117       guard = build_decl (DECL_SOURCE_LOCATION (decl),
3118 			  VAR_DECL, sname, guard_type);
3119 
3120       /* The guard should have the same linkage as what it guards.  */
3121       TREE_PUBLIC (guard) = TREE_PUBLIC (decl);
3122       TREE_STATIC (guard) = TREE_STATIC (decl);
3123       DECL_COMMON (guard) = DECL_COMMON (decl);
3124       DECL_COMDAT (guard) = DECL_COMDAT (decl);
3125       CP_DECL_THREAD_LOCAL_P (guard) = CP_DECL_THREAD_LOCAL_P (decl);
3126       set_decl_tls_model (guard, DECL_TLS_MODEL (decl));
3127       if (DECL_ONE_ONLY (decl))
3128 	make_decl_one_only (guard, cxx_comdat_group (guard));
3129       if (TREE_PUBLIC (decl))
3130 	DECL_WEAK (guard) = DECL_WEAK (decl);
3131       DECL_VISIBILITY (guard) = DECL_VISIBILITY (decl);
3132       DECL_VISIBILITY_SPECIFIED (guard) = DECL_VISIBILITY_SPECIFIED (decl);
3133 
3134       DECL_ARTIFICIAL (guard) = 1;
3135       DECL_IGNORED_P (guard) = 1;
3136       TREE_USED (guard) = 1;
3137       pushdecl_top_level_and_finish (guard, NULL_TREE);
3138     }
3139   return guard;
3140 }
3141 
3142 /* Return an atomic load of src with the appropriate memory model.  */
3143 
3144 static tree
3145 build_atomic_load_byte (tree src, HOST_WIDE_INT model)
3146 {
3147   tree ptr_type = build_pointer_type (char_type_node);
3148   tree mem_model = build_int_cst (integer_type_node, model);
3149   tree t, addr, val;
3150   unsigned int size;
3151   int fncode;
3152 
3153   size = tree_to_uhwi (TYPE_SIZE_UNIT (char_type_node));
3154 
3155   fncode = BUILT_IN_ATOMIC_LOAD_N + exact_log2 (size) + 1;
3156   t = builtin_decl_implicit ((enum built_in_function) fncode);
3157 
3158   addr = build1 (ADDR_EXPR, ptr_type, src);
3159   val = build_call_expr (t, 2, addr, mem_model);
3160   return val;
3161 }
3162 
3163 /* Return those bits of the GUARD variable that should be set when the
3164    guarded entity is actually initialized.  */
3165 
3166 static tree
3167 get_guard_bits (tree guard)
3168 {
3169   if (!targetm.cxx.guard_mask_bit ())
3170     {
3171       /* We only set the first byte of the guard, in order to leave room
3172 	 for a mutex in the high-order bits.  */
3173       guard = build1 (ADDR_EXPR,
3174 		      build_pointer_type (TREE_TYPE (guard)),
3175 		      guard);
3176       guard = build1 (NOP_EXPR,
3177 		      build_pointer_type (char_type_node),
3178 		      guard);
3179       guard = build1 (INDIRECT_REF, char_type_node, guard);
3180     }
3181 
3182   return guard;
3183 }
3184 
3185 /* Return an expression which determines whether or not the GUARD
3186    variable has already been initialized.  */
3187 
3188 tree
3189 get_guard_cond (tree guard, bool thread_safe)
3190 {
3191   tree guard_value;
3192 
3193   if (!thread_safe)
3194     guard = get_guard_bits (guard);
3195   else
3196     guard = build_atomic_load_byte (guard, MEMMODEL_ACQUIRE);
3197 
3198   /* Mask off all but the low bit.  */
3199   if (targetm.cxx.guard_mask_bit ())
3200     {
3201       guard_value = integer_one_node;
3202       if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3203 	guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3204       guard = cp_build_binary_op (input_location,
3205 				  BIT_AND_EXPR, guard, guard_value,
3206 				  tf_warning_or_error);
3207     }
3208 
3209   guard_value = integer_zero_node;
3210   if (!same_type_p (TREE_TYPE (guard_value), TREE_TYPE (guard)))
3211     guard_value = fold_convert (TREE_TYPE (guard), guard_value);
3212   return cp_build_binary_op (input_location,
3213 			     EQ_EXPR, guard, guard_value,
3214 			     tf_warning_or_error);
3215 }
3216 
3217 /* Return an expression which sets the GUARD variable, indicating that
3218    the variable being guarded has been initialized.  */
3219 
3220 tree
3221 set_guard (tree guard)
3222 {
3223   tree guard_init;
3224 
3225   /* Set the GUARD to one.  */
3226   guard = get_guard_bits (guard);
3227   guard_init = integer_one_node;
3228   if (!same_type_p (TREE_TYPE (guard_init), TREE_TYPE (guard)))
3229     guard_init = fold_convert (TREE_TYPE (guard), guard_init);
3230   return cp_build_modify_expr (input_location, guard, NOP_EXPR, guard_init,
3231 			       tf_warning_or_error);
3232 }
3233 
3234 /* Returns true iff we can tell that VAR does not have a dynamic
3235    initializer.  */
3236 
3237 static bool
3238 var_defined_without_dynamic_init (tree var)
3239 {
3240   /* If it's defined in another TU, we can't tell.  */
3241   if (DECL_EXTERNAL (var))
3242     return false;
3243   /* If it has a non-trivial destructor, registering the destructor
3244      counts as dynamic initialization.  */
3245   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (var)))
3246     return false;
3247   /* If it's in this TU, its initializer has been processed, unless
3248      it's a case of self-initialization, then DECL_INITIALIZED_P is
3249      false while the initializer is handled by finish_id_expression.  */
3250   if (!DECL_INITIALIZED_P (var))
3251     return false;
3252   /* If it has no initializer or a constant one, it's not dynamic.  */
3253   return (!DECL_NONTRIVIALLY_INITIALIZED_P (var)
3254 	  || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (var));
3255 }
3256 
3257 /* Returns true iff VAR is a variable that needs uses to be
3258    wrapped for possible dynamic initialization.  */
3259 
3260 static bool
3261 var_needs_tls_wrapper (tree var)
3262 {
3263   return (!error_operand_p (var)
3264 	  && CP_DECL_THREAD_LOCAL_P (var)
3265 	  && !DECL_GNU_TLS_P (var)
3266 	  && !DECL_FUNCTION_SCOPE_P (var)
3267 	  && !var_defined_without_dynamic_init (var));
3268 }
3269 
3270 /* Get the FUNCTION_DECL for the shared TLS init function for this
3271    translation unit.  */
3272 
3273 static tree
3274 get_local_tls_init_fn (void)
3275 {
3276   tree sname = get_identifier ("__tls_init");
3277   tree fn = get_global_binding (sname);
3278   if (!fn)
3279     {
3280       fn = build_lang_decl (FUNCTION_DECL, sname,
3281 			     build_function_type (void_type_node,
3282 						  void_list_node));
3283       SET_DECL_LANGUAGE (fn, lang_c);
3284       TREE_PUBLIC (fn) = false;
3285       DECL_ARTIFICIAL (fn) = true;
3286       mark_used (fn);
3287       set_global_binding (fn);
3288     }
3289   return fn;
3290 }
3291 
3292 /* Get a FUNCTION_DECL for the init function for the thread_local
3293    variable VAR.  The init function will be an alias to the function
3294    that initializes all the non-local TLS variables in the translation
3295    unit.  The init function is only used by the wrapper function.  */
3296 
3297 static tree
3298 get_tls_init_fn (tree var)
3299 {
3300   /* Only C++11 TLS vars need this init fn.  */
3301   if (!var_needs_tls_wrapper (var))
3302     return NULL_TREE;
3303 
3304   /* If -fno-extern-tls-init, assume that we don't need to call
3305      a tls init function for a variable defined in another TU.  */
3306   if (!flag_extern_tls_init && DECL_EXTERNAL (var))
3307     return NULL_TREE;
3308 
3309   /* If the variable is internal, or if we can't generate aliases,
3310      call the local init function directly.  */
3311   if (!TREE_PUBLIC (var) || !TARGET_SUPPORTS_ALIASES)
3312     return get_local_tls_init_fn ();
3313 
3314   tree sname = mangle_tls_init_fn (var);
3315   tree fn = get_global_binding (sname);
3316   if (!fn)
3317     {
3318       fn = build_lang_decl (FUNCTION_DECL, sname,
3319 			    build_function_type (void_type_node,
3320 						 void_list_node));
3321       SET_DECL_LANGUAGE (fn, lang_c);
3322       TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3323       DECL_ARTIFICIAL (fn) = true;
3324       DECL_COMDAT (fn) = DECL_COMDAT (var);
3325       DECL_EXTERNAL (fn) = DECL_EXTERNAL (var);
3326       if (DECL_ONE_ONLY (var))
3327 	make_decl_one_only (fn, cxx_comdat_group (fn));
3328       if (TREE_PUBLIC (var))
3329 	{
3330 	  tree obtype = strip_array_types (non_reference (TREE_TYPE (var)));
3331 	  /* If the variable is defined somewhere else and might have static
3332 	     initialization, make the init function a weak reference.  */
3333 	  if ((!TYPE_NEEDS_CONSTRUCTING (obtype)
3334 	       || TYPE_HAS_CONSTEXPR_CTOR (obtype)
3335 	       || TYPE_HAS_TRIVIAL_DFLT (obtype))
3336 	      && TYPE_HAS_TRIVIAL_DESTRUCTOR (obtype)
3337 	      && DECL_EXTERNAL (var))
3338 	    declare_weak (fn);
3339 	  else
3340 	    DECL_WEAK (fn) = DECL_WEAK (var);
3341 	}
3342       DECL_VISIBILITY (fn) = DECL_VISIBILITY (var);
3343       DECL_VISIBILITY_SPECIFIED (fn) = DECL_VISIBILITY_SPECIFIED (var);
3344       DECL_DLLIMPORT_P (fn) = DECL_DLLIMPORT_P (var);
3345       DECL_IGNORED_P (fn) = 1;
3346       mark_used (fn);
3347 
3348       DECL_BEFRIENDING_CLASSES (fn) = var;
3349 
3350       set_global_binding (fn);
3351     }
3352   return fn;
3353 }
3354 
3355 /* Get a FUNCTION_DECL for the init wrapper function for the thread_local
3356    variable VAR.  The wrapper function calls the init function (if any) for
3357    VAR and then returns a reference to VAR.  The wrapper function is used
3358    in place of VAR everywhere VAR is mentioned.  */
3359 
3360 tree
3361 get_tls_wrapper_fn (tree var)
3362 {
3363   /* Only C++11 TLS vars need this wrapper fn.  */
3364   if (!var_needs_tls_wrapper (var))
3365     return NULL_TREE;
3366 
3367   tree sname = mangle_tls_wrapper_fn (var);
3368   tree fn = get_global_binding (sname);
3369   if (!fn)
3370     {
3371       /* A named rvalue reference is an lvalue, so the wrapper should
3372 	 always return an lvalue reference.  */
3373       tree type = non_reference (TREE_TYPE (var));
3374       type = build_reference_type (type);
3375       tree fntype = build_function_type (type, void_list_node);
3376       fn = build_lang_decl (FUNCTION_DECL, sname, fntype);
3377       SET_DECL_LANGUAGE (fn, lang_c);
3378       TREE_PUBLIC (fn) = TREE_PUBLIC (var);
3379       DECL_ARTIFICIAL (fn) = true;
3380       DECL_IGNORED_P (fn) = 1;
3381       /* The wrapper is inline and emitted everywhere var is used.  */
3382       DECL_DECLARED_INLINE_P (fn) = true;
3383       if (TREE_PUBLIC (var))
3384 	{
3385 	  comdat_linkage (fn);
3386 #ifdef HAVE_GAS_HIDDEN
3387 	  /* Make the wrapper bind locally; there's no reason to share
3388 	     the wrapper between multiple shared objects.  */
3389 	  DECL_VISIBILITY (fn) = VISIBILITY_INTERNAL;
3390 	  DECL_VISIBILITY_SPECIFIED (fn) = true;
3391 #endif
3392 	}
3393       if (!TREE_PUBLIC (fn))
3394 	DECL_INTERFACE_KNOWN (fn) = true;
3395       mark_used (fn);
3396       note_vague_linkage_fn (fn);
3397 
3398 #if 0
3399       /* We want CSE to commonize calls to the wrapper, but marking it as
3400 	 pure is unsafe since it has side-effects.  I guess we need a new
3401 	 ECF flag even weaker than ECF_PURE.  FIXME!  */
3402       DECL_PURE_P (fn) = true;
3403 #endif
3404 
3405       DECL_BEFRIENDING_CLASSES (fn) = var;
3406 
3407       set_global_binding (fn);
3408     }
3409   return fn;
3410 }
3411 
3412 /* At EOF, generate the definition for the TLS wrapper function FN:
3413 
3414    T& var_wrapper() {
3415      if (init_fn) init_fn();
3416      return var;
3417    }  */
3418 
3419 static void
3420 generate_tls_wrapper (tree fn)
3421 {
3422   tree var = DECL_BEFRIENDING_CLASSES (fn);
3423 
3424   start_preparsed_function (fn, NULL_TREE, SF_DEFAULT | SF_PRE_PARSED);
3425   tree body = begin_function_body ();
3426   /* Only call the init fn if there might be one.  */
3427   if (tree init_fn = get_tls_init_fn (var))
3428     {
3429       tree if_stmt = NULL_TREE;
3430       /* If init_fn is a weakref, make sure it exists before calling.  */
3431       if (lookup_attribute ("weak", DECL_ATTRIBUTES (init_fn)))
3432 	{
3433 	  if_stmt = begin_if_stmt ();
3434 	  tree addr = cp_build_addr_expr (init_fn, tf_warning_or_error);
3435 	  tree cond = cp_build_binary_op (DECL_SOURCE_LOCATION (var),
3436 					  NE_EXPR, addr, nullptr_node,
3437 					  tf_warning_or_error);
3438 	  finish_if_stmt_cond (cond, if_stmt);
3439 	}
3440       finish_expr_stmt (build_cxx_call
3441 			(init_fn, 0, NULL, tf_warning_or_error));
3442       if (if_stmt)
3443 	{
3444 	  finish_then_clause (if_stmt);
3445 	  finish_if_stmt (if_stmt);
3446 	}
3447     }
3448   else
3449     /* If there's no initialization, the wrapper is a constant function.  */
3450     TREE_READONLY (fn) = true;
3451   finish_return_stmt (convert_from_reference (var));
3452   finish_function_body (body);
3453   expand_or_defer_fn (finish_function (/*inline_p=*/false));
3454 }
3455 
3456 /* Start the process of running a particular set of global constructors
3457    or destructors.  Subroutine of do_[cd]tors.  Also called from
3458    vtv_start_verification_constructor_init_function.  */
3459 
3460 static tree
3461 start_objects (int method_type, int initp)
3462 {
3463   tree body;
3464   tree fndecl;
3465   char type[14];
3466 
3467   /* Make ctor or dtor function.  METHOD_TYPE may be 'I' or 'D'.  */
3468 
3469   if (initp != DEFAULT_INIT_PRIORITY)
3470     {
3471       char joiner;
3472 
3473 #ifdef JOINER
3474       joiner = JOINER;
3475 #else
3476       joiner = '_';
3477 #endif
3478 
3479       sprintf (type, "sub_%c%c%.5u", method_type, joiner, initp);
3480     }
3481   else
3482     sprintf (type, "sub_%c", method_type);
3483 
3484   fndecl = build_lang_decl (FUNCTION_DECL,
3485 			    get_file_function_name (type),
3486 			    build_function_type_list (void_type_node,
3487 						      NULL_TREE));
3488   start_preparsed_function (fndecl, /*attrs=*/NULL_TREE, SF_PRE_PARSED);
3489 
3490   TREE_PUBLIC (current_function_decl) = 0;
3491 
3492   /* Mark as artificial because it's not explicitly in the user's
3493      source code.  */
3494   DECL_ARTIFICIAL (current_function_decl) = 1;
3495 
3496   /* Mark this declaration as used to avoid spurious warnings.  */
3497   TREE_USED (current_function_decl) = 1;
3498 
3499   /* Mark this function as a global constructor or destructor.  */
3500   if (method_type == 'I')
3501     DECL_GLOBAL_CTOR_P (current_function_decl) = 1;
3502   else
3503     DECL_GLOBAL_DTOR_P (current_function_decl) = 1;
3504 
3505   body = begin_compound_stmt (BCS_FN_BODY);
3506 
3507   return body;
3508 }
3509 
3510 /* Finish the process of running a particular set of global constructors
3511    or destructors.  Subroutine of do_[cd]tors.  */
3512 
3513 static void
3514 finish_objects (int method_type, int initp, tree body)
3515 {
3516   tree fn;
3517 
3518   /* Finish up.  */
3519   finish_compound_stmt (body);
3520   fn = finish_function (/*inline_p=*/false);
3521 
3522   if (method_type == 'I')
3523     {
3524       DECL_STATIC_CONSTRUCTOR (fn) = 1;
3525       decl_init_priority_insert (fn, initp);
3526     }
3527   else
3528     {
3529       DECL_STATIC_DESTRUCTOR (fn) = 1;
3530       decl_fini_priority_insert (fn, initp);
3531     }
3532 
3533   expand_or_defer_fn (fn);
3534 }
3535 
3536 /* The names of the parameters to the function created to handle
3537    initializations and destructions for objects with static storage
3538    duration.  */
3539 #define INITIALIZE_P_IDENTIFIER "__initialize_p"
3540 #define PRIORITY_IDENTIFIER "__priority"
3541 
3542 /* The name of the function we create to handle initializations and
3543    destructions for objects with static storage duration.  */
3544 #define SSDF_IDENTIFIER "__static_initialization_and_destruction"
3545 
3546 /* The declaration for the __INITIALIZE_P argument.  */
3547 static GTY(()) tree initialize_p_decl;
3548 
3549 /* The declaration for the __PRIORITY argument.  */
3550 static GTY(()) tree priority_decl;
3551 
3552 /* The declaration for the static storage duration function.  */
3553 static GTY(()) tree ssdf_decl;
3554 
3555 /* All the static storage duration functions created in this
3556    translation unit.  */
3557 static GTY(()) vec<tree, va_gc> *ssdf_decls;
3558 
3559 /* A map from priority levels to information about that priority
3560    level.  There may be many such levels, so efficient lookup is
3561    important.  */
3562 static splay_tree priority_info_map;
3563 
3564 /* Begins the generation of the function that will handle all
3565    initialization and destruction of objects with static storage
3566    duration.  The function generated takes two parameters of type
3567    `int': __INITIALIZE_P and __PRIORITY.  If __INITIALIZE_P is
3568    nonzero, it performs initializations.  Otherwise, it performs
3569    destructions.  It only performs those initializations or
3570    destructions with the indicated __PRIORITY.  The generated function
3571    returns no value.
3572 
3573    It is assumed that this function will only be called once per
3574    translation unit.  */
3575 
3576 static tree
3577 start_static_storage_duration_function (unsigned count)
3578 {
3579   tree type;
3580   tree body;
3581   char id[sizeof (SSDF_IDENTIFIER) + 1 /* '\0' */ + 32];
3582 
3583   /* Create the identifier for this function.  It will be of the form
3584      SSDF_IDENTIFIER_<number>.  */
3585   sprintf (id, "%s_%u", SSDF_IDENTIFIER, count);
3586 
3587   type = build_function_type_list (void_type_node,
3588 				   integer_type_node, integer_type_node,
3589 				   NULL_TREE);
3590 
3591   /* Create the FUNCTION_DECL itself.  */
3592   ssdf_decl = build_lang_decl (FUNCTION_DECL,
3593 			       get_identifier (id),
3594 			       type);
3595   TREE_PUBLIC (ssdf_decl) = 0;
3596   DECL_ARTIFICIAL (ssdf_decl) = 1;
3597 
3598   /* Put this function in the list of functions to be called from the
3599      static constructors and destructors.  */
3600   if (!ssdf_decls)
3601     {
3602       vec_alloc (ssdf_decls, 32);
3603 
3604       /* Take this opportunity to initialize the map from priority
3605 	 numbers to information about that priority level.  */
3606       priority_info_map = splay_tree_new (splay_tree_compare_ints,
3607 					  /*delete_key_fn=*/0,
3608 					  /*delete_value_fn=*/
3609 					  (splay_tree_delete_value_fn)
3610 					  (void (*) (void)) free);
3611 
3612       /* We always need to generate functions for the
3613 	 DEFAULT_INIT_PRIORITY so enter it now.  That way when we walk
3614 	 priorities later, we'll be sure to find the
3615 	 DEFAULT_INIT_PRIORITY.  */
3616       get_priority_info (DEFAULT_INIT_PRIORITY);
3617     }
3618 
3619   vec_safe_push (ssdf_decls, ssdf_decl);
3620 
3621   /* Create the argument list.  */
3622   initialize_p_decl = cp_build_parm_decl
3623     (ssdf_decl, get_identifier (INITIALIZE_P_IDENTIFIER), integer_type_node);
3624   TREE_USED (initialize_p_decl) = 1;
3625   priority_decl = cp_build_parm_decl
3626     (ssdf_decl, get_identifier (PRIORITY_IDENTIFIER), integer_type_node);
3627   TREE_USED (priority_decl) = 1;
3628 
3629   DECL_CHAIN (initialize_p_decl) = priority_decl;
3630   DECL_ARGUMENTS (ssdf_decl) = initialize_p_decl;
3631 
3632   /* Put the function in the global scope.  */
3633   pushdecl (ssdf_decl);
3634 
3635   /* Start the function itself.  This is equivalent to declaring the
3636      function as:
3637 
3638        static void __ssdf (int __initialize_p, init __priority_p);
3639 
3640      It is static because we only need to call this function from the
3641      various constructor and destructor functions for this module.  */
3642   start_preparsed_function (ssdf_decl,
3643 			    /*attrs=*/NULL_TREE,
3644 			    SF_PRE_PARSED);
3645 
3646   /* Set up the scope of the outermost block in the function.  */
3647   body = begin_compound_stmt (BCS_FN_BODY);
3648 
3649   return body;
3650 }
3651 
3652 /* Finish the generation of the function which performs initialization
3653    and destruction of objects with static storage duration.  After
3654    this point, no more such objects can be created.  */
3655 
3656 static void
3657 finish_static_storage_duration_function (tree body)
3658 {
3659   /* Close out the function.  */
3660   finish_compound_stmt (body);
3661   expand_or_defer_fn (finish_function (/*inline_p=*/false));
3662 }
3663 
3664 /* Return the information about the indicated PRIORITY level.  If no
3665    code to handle this level has yet been generated, generate the
3666    appropriate prologue.  */
3667 
3668 static priority_info
3669 get_priority_info (int priority)
3670 {
3671   priority_info pi;
3672   splay_tree_node n;
3673 
3674   n = splay_tree_lookup (priority_info_map,
3675 			 (splay_tree_key) priority);
3676   if (!n)
3677     {
3678       /* Create a new priority information structure, and insert it
3679 	 into the map.  */
3680       pi = XNEW (struct priority_info_s);
3681       pi->initializations_p = 0;
3682       pi->destructions_p = 0;
3683       splay_tree_insert (priority_info_map,
3684 			 (splay_tree_key) priority,
3685 			 (splay_tree_value) pi);
3686     }
3687   else
3688     pi = (priority_info) n->value;
3689 
3690   return pi;
3691 }
3692 
3693 /* The effective initialization priority of a DECL.  */
3694 
3695 #define DECL_EFFECTIVE_INIT_PRIORITY(decl)				      \
3696 	((!DECL_HAS_INIT_PRIORITY_P (decl) || DECL_INIT_PRIORITY (decl) == 0) \
3697 	 ? DEFAULT_INIT_PRIORITY : DECL_INIT_PRIORITY (decl))
3698 
3699 /* Whether a DECL needs a guard to protect it against multiple
3700    initialization.  */
3701 
3702 #define NEEDS_GUARD_P(decl) (TREE_PUBLIC (decl) && (DECL_COMMON (decl)      \
3703 						    || DECL_ONE_ONLY (decl) \
3704 						    || DECL_WEAK (decl)))
3705 
3706 /* Called from one_static_initialization_or_destruction(),
3707    via walk_tree.
3708    Walks the initializer list of a global variable and looks for
3709    temporary variables (DECL_NAME() == NULL and DECL_ARTIFICIAL != 0)
3710    and that have their DECL_CONTEXT() == NULL.
3711    For each such temporary variable, set their DECL_CONTEXT() to
3712    the current function. This is necessary because otherwise
3713    some optimizers (enabled by -O2 -fprofile-arcs) might crash
3714    when trying to refer to a temporary variable that does not have
3715    it's DECL_CONTECT() properly set.  */
3716 static tree
3717 fix_temporary_vars_context_r (tree *node,
3718 			      int  * /*unused*/,
3719 			      void * /*unused1*/)
3720 {
3721   gcc_assert (current_function_decl);
3722 
3723   if (TREE_CODE (*node) == BIND_EXPR)
3724     {
3725       tree var;
3726 
3727       for (var = BIND_EXPR_VARS (*node); var; var = DECL_CHAIN (var))
3728 	if (VAR_P (var)
3729 	  && !DECL_NAME (var)
3730 	  && DECL_ARTIFICIAL (var)
3731 	  && !DECL_CONTEXT (var))
3732 	  DECL_CONTEXT (var) = current_function_decl;
3733     }
3734 
3735   return NULL_TREE;
3736 }
3737 
3738 /* Set up to handle the initialization or destruction of DECL.  If
3739    INITP is nonzero, we are initializing the variable.  Otherwise, we
3740    are destroying it.  */
3741 
3742 static void
3743 one_static_initialization_or_destruction (tree decl, tree init, bool initp)
3744 {
3745   tree guard_if_stmt = NULL_TREE;
3746   tree guard;
3747 
3748   /* If we are supposed to destruct and there's a trivial destructor,
3749      nothing has to be done.  */
3750   if (!initp
3751       && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3752     return;
3753 
3754   /* Trick the compiler into thinking we are at the file and line
3755      where DECL was declared so that error-messages make sense, and so
3756      that the debugger will show somewhat sensible file and line
3757      information.  */
3758   input_location = DECL_SOURCE_LOCATION (decl);
3759 
3760   /* Make sure temporary variables in the initialiser all have
3761      their DECL_CONTEXT() set to a value different from NULL_TREE.
3762      This can happen when global variables initializers are built.
3763      In that case, the DECL_CONTEXT() of the global variables _AND_ of all
3764      the temporary variables that might have been generated in the
3765      accompanying initializers is NULL_TREE, meaning the variables have been
3766      declared in the global namespace.
3767      What we want to do here is to fix that and make sure the DECL_CONTEXT()
3768      of the temporaries are set to the current function decl.  */
3769   cp_walk_tree_without_duplicates (&init,
3770 				   fix_temporary_vars_context_r,
3771 				   NULL);
3772 
3773   /* Because of:
3774 
3775        [class.access.spec]
3776 
3777        Access control for implicit calls to the constructors,
3778        the conversion functions, or the destructor called to
3779        create and destroy a static data member is performed as
3780        if these calls appeared in the scope of the member's
3781        class.
3782 
3783      we pretend we are in a static member function of the class of
3784      which the DECL is a member.  */
3785   if (member_p (decl))
3786     {
3787       DECL_CONTEXT (current_function_decl) = DECL_CONTEXT (decl);
3788       DECL_STATIC_FUNCTION_P (current_function_decl) = 1;
3789     }
3790 
3791   /* Assume we don't need a guard.  */
3792   guard = NULL_TREE;
3793   /* We need a guard if this is an object with external linkage that
3794      might be initialized in more than one place.  (For example, a
3795      static data member of a template, when the data member requires
3796      construction.)  */
3797   if (NEEDS_GUARD_P (decl))
3798     {
3799       tree guard_cond;
3800 
3801       guard = get_guard (decl);
3802 
3803       /* When using __cxa_atexit, we just check the GUARD as we would
3804 	 for a local static.  */
3805       if (flag_use_cxa_atexit)
3806 	{
3807 	  /* When using __cxa_atexit, we never try to destroy
3808 	     anything from a static destructor.  */
3809 	  gcc_assert (initp);
3810 	  guard_cond = get_guard_cond (guard, false);
3811 	}
3812       /* If we don't have __cxa_atexit, then we will be running
3813 	 destructors from .fini sections, or their equivalents.  So,
3814 	 we need to know how many times we've tried to initialize this
3815 	 object.  We do initializations only if the GUARD is zero,
3816 	 i.e., if we are the first to initialize the variable.  We do
3817 	 destructions only if the GUARD is one, i.e., if we are the
3818 	 last to destroy the variable.  */
3819       else if (initp)
3820 	guard_cond
3821 	  = cp_build_binary_op (input_location,
3822 				EQ_EXPR,
3823 				cp_build_unary_op (PREINCREMENT_EXPR,
3824 						   guard,
3825 						   /*noconvert=*/true,
3826 						   tf_warning_or_error),
3827 				integer_one_node,
3828 				tf_warning_or_error);
3829       else
3830 	guard_cond
3831 	  = cp_build_binary_op (input_location,
3832 				EQ_EXPR,
3833 				cp_build_unary_op (PREDECREMENT_EXPR,
3834 						   guard,
3835 						   /*noconvert=*/true,
3836 						   tf_warning_or_error),
3837 				integer_zero_node,
3838 				tf_warning_or_error);
3839 
3840       guard_if_stmt = begin_if_stmt ();
3841       finish_if_stmt_cond (guard_cond, guard_if_stmt);
3842     }
3843 
3844 
3845   /* If we're using __cxa_atexit, we have not already set the GUARD,
3846      so we must do so now.  */
3847   if (guard && initp && flag_use_cxa_atexit)
3848     finish_expr_stmt (set_guard (guard));
3849 
3850   /* Perform the initialization or destruction.  */
3851   if (initp)
3852     {
3853       if (init)
3854 	{
3855 	  finish_expr_stmt (init);
3856 	  if (sanitize_flags_p (SANITIZE_ADDRESS, decl))
3857 	    {
3858 	      varpool_node *vnode = varpool_node::get (decl);
3859 	      if (vnode)
3860 		vnode->dynamically_initialized = 1;
3861 	    }
3862 	}
3863 
3864       /* If we're using __cxa_atexit, register a function that calls the
3865 	 destructor for the object.  */
3866       if (flag_use_cxa_atexit)
3867 	finish_expr_stmt (register_dtor_fn (decl));
3868     }
3869   else
3870     finish_expr_stmt (build_cleanup (decl));
3871 
3872   /* Finish the guard if-stmt, if necessary.  */
3873   if (guard)
3874     {
3875       finish_then_clause (guard_if_stmt);
3876       finish_if_stmt (guard_if_stmt);
3877     }
3878 
3879   /* Now that we're done with DECL we don't need to pretend to be a
3880      member of its class any longer.  */
3881   DECL_CONTEXT (current_function_decl) = NULL_TREE;
3882   DECL_STATIC_FUNCTION_P (current_function_decl) = 0;
3883 }
3884 
3885 /* Generate code to do the initialization or destruction of the decls in VARS,
3886    a TREE_LIST of VAR_DECL with static storage duration.
3887    Whether initialization or destruction is performed is specified by INITP.  */
3888 
3889 static void
3890 do_static_initialization_or_destruction (tree vars, bool initp)
3891 {
3892   tree node, init_if_stmt, cond;
3893 
3894   /* Build the outer if-stmt to check for initialization or destruction.  */
3895   init_if_stmt = begin_if_stmt ();
3896   cond = initp ? integer_one_node : integer_zero_node;
3897   cond = cp_build_binary_op (input_location,
3898 			     EQ_EXPR,
3899 			     initialize_p_decl,
3900 			     cond,
3901 			     tf_warning_or_error);
3902   finish_if_stmt_cond (cond, init_if_stmt);
3903 
3904   /* To make sure dynamic construction doesn't access globals from other
3905      compilation units where they might not be yet constructed, for
3906      -fsanitize=address insert __asan_before_dynamic_init call that
3907      prevents access to either all global variables that need construction
3908      in other compilation units, or at least those that haven't been
3909      initialized yet.  Variables that need dynamic construction in
3910      the current compilation unit are kept accessible.  */
3911   if (initp && (flag_sanitize & SANITIZE_ADDRESS))
3912     finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/false));
3913 
3914   node = vars;
3915   do {
3916     tree decl = TREE_VALUE (node);
3917     tree priority_if_stmt;
3918     int priority;
3919     priority_info pi;
3920 
3921     /* If we don't need a destructor, there's nothing to do.  Avoid
3922        creating a possibly empty if-stmt.  */
3923     if (!initp && TYPE_HAS_TRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3924       {
3925 	node = TREE_CHAIN (node);
3926 	continue;
3927       }
3928 
3929     /* Remember that we had an initialization or finalization at this
3930        priority.  */
3931     priority = DECL_EFFECTIVE_INIT_PRIORITY (decl);
3932     pi = get_priority_info (priority);
3933     if (initp)
3934       pi->initializations_p = 1;
3935     else
3936       pi->destructions_p = 1;
3937 
3938     /* Conditionalize this initialization on being in the right priority
3939        and being initializing/finalizing appropriately.  */
3940     priority_if_stmt = begin_if_stmt ();
3941     cond = cp_build_binary_op (input_location,
3942 			       EQ_EXPR,
3943 			       priority_decl,
3944 			       build_int_cst (NULL_TREE, priority),
3945 			       tf_warning_or_error);
3946     finish_if_stmt_cond (cond, priority_if_stmt);
3947 
3948     /* Process initializers with same priority.  */
3949     for (; node
3950 	   && DECL_EFFECTIVE_INIT_PRIORITY (TREE_VALUE (node)) == priority;
3951 	 node = TREE_CHAIN (node))
3952       /* Do one initialization or destruction.  */
3953       one_static_initialization_or_destruction (TREE_VALUE (node),
3954 						TREE_PURPOSE (node), initp);
3955 
3956     /* Finish up the priority if-stmt body.  */
3957     finish_then_clause (priority_if_stmt);
3958     finish_if_stmt (priority_if_stmt);
3959 
3960   } while (node);
3961 
3962   /* Revert what __asan_before_dynamic_init did by calling
3963      __asan_after_dynamic_init.  */
3964   if (initp && (flag_sanitize & SANITIZE_ADDRESS))
3965     finish_expr_stmt (asan_dynamic_init_call (/*after_p=*/true));
3966 
3967   /* Finish up the init/destruct if-stmt body.  */
3968   finish_then_clause (init_if_stmt);
3969   finish_if_stmt (init_if_stmt);
3970 }
3971 
3972 /* VARS is a list of variables with static storage duration which may
3973    need initialization and/or finalization.  Remove those variables
3974    that don't really need to be initialized or finalized, and return
3975    the resulting list.  The order in which the variables appear in
3976    VARS is in reverse order of the order in which they should actually
3977    be initialized.  The list we return is in the unreversed order;
3978    i.e., the first variable should be initialized first.  */
3979 
3980 static tree
3981 prune_vars_needing_no_initialization (tree *vars)
3982 {
3983   tree *var = vars;
3984   tree result = NULL_TREE;
3985 
3986   while (*var)
3987     {
3988       tree t = *var;
3989       tree decl = TREE_VALUE (t);
3990       tree init = TREE_PURPOSE (t);
3991 
3992       /* Deal gracefully with error.  */
3993       if (error_operand_p (decl))
3994 	{
3995 	  var = &TREE_CHAIN (t);
3996 	  continue;
3997 	}
3998 
3999       /* The only things that can be initialized are variables.  */
4000       gcc_assert (VAR_P (decl));
4001 
4002       /* If this object is not defined, we don't need to do anything
4003 	 here.  */
4004       if (DECL_EXTERNAL (decl))
4005 	{
4006 	  var = &TREE_CHAIN (t);
4007 	  continue;
4008 	}
4009 
4010       /* Also, if the initializer already contains errors, we can bail
4011 	 out now.  */
4012       if (init && TREE_CODE (init) == TREE_LIST
4013 	  && value_member (error_mark_node, init))
4014 	{
4015 	  var = &TREE_CHAIN (t);
4016 	  continue;
4017 	}
4018 
4019       /* This variable is going to need initialization and/or
4020 	 finalization, so we add it to the list.  */
4021       *var = TREE_CHAIN (t);
4022       TREE_CHAIN (t) = result;
4023       result = t;
4024     }
4025 
4026   return result;
4027 }
4028 
4029 /* Make sure we have told the back end about all the variables in
4030    VARS.  */
4031 
4032 static void
4033 write_out_vars (tree vars)
4034 {
4035   tree v;
4036 
4037   for (v = vars; v; v = TREE_CHAIN (v))
4038     {
4039       tree var = TREE_VALUE (v);
4040       if (!var_finalized_p (var))
4041 	{
4042 	  import_export_decl (var);
4043 	  rest_of_decl_compilation (var, 1, 1);
4044 	}
4045     }
4046 }
4047 
4048 /* Generate a static constructor (if CONSTRUCTOR_P) or destructor
4049    (otherwise) that will initialize all global objects with static
4050    storage duration having the indicated PRIORITY.  */
4051 
4052 static void
4053 generate_ctor_or_dtor_function (bool constructor_p, int priority,
4054 				location_t *locus)
4055 {
4056   char function_key;
4057   tree fndecl;
4058   tree body;
4059   size_t i;
4060 
4061   input_location = *locus;
4062   /* ??? */
4063   /* Was: locus->line++; */
4064 
4065   /* We use `I' to indicate initialization and `D' to indicate
4066      destruction.  */
4067   function_key = constructor_p ? 'I' : 'D';
4068 
4069   /* We emit the function lazily, to avoid generating empty
4070      global constructors and destructors.  */
4071   body = NULL_TREE;
4072 
4073   /* For Objective-C++, we may need to initialize metadata found in this module.
4074      This must be done _before_ any other static initializations.  */
4075   if (c_dialect_objc () && (priority == DEFAULT_INIT_PRIORITY)
4076       && constructor_p && objc_static_init_needed_p ())
4077     {
4078       body = start_objects (function_key, priority);
4079       objc_generate_static_init_call (NULL_TREE);
4080     }
4081 
4082   /* Call the static storage duration function with appropriate
4083      arguments.  */
4084   FOR_EACH_VEC_SAFE_ELT (ssdf_decls, i, fndecl)
4085     {
4086       /* Calls to pure or const functions will expand to nothing.  */
4087       if (! (flags_from_decl_or_type (fndecl) & (ECF_CONST | ECF_PURE)))
4088 	{
4089 	  tree call;
4090 
4091 	  if (! body)
4092 	    body = start_objects (function_key, priority);
4093 
4094 	  call = cp_build_function_call_nary (fndecl, tf_warning_or_error,
4095 					      build_int_cst (NULL_TREE,
4096 							     constructor_p),
4097 					      build_int_cst (NULL_TREE,
4098 							     priority),
4099 					      NULL_TREE);
4100 	  finish_expr_stmt (call);
4101 	}
4102     }
4103 
4104   /* Close out the function.  */
4105   if (body)
4106     finish_objects (function_key, priority, body);
4107 }
4108 
4109 /* Generate constructor and destructor functions for the priority
4110    indicated by N.  */
4111 
4112 static int
4113 generate_ctor_and_dtor_functions_for_priority (splay_tree_node n, void * data)
4114 {
4115   location_t *locus = (location_t *) data;
4116   int priority = (int) n->key;
4117   priority_info pi = (priority_info) n->value;
4118 
4119   /* Generate the functions themselves, but only if they are really
4120      needed.  */
4121   if (pi->initializations_p)
4122     generate_ctor_or_dtor_function (/*constructor_p=*/true, priority, locus);
4123   if (pi->destructions_p)
4124     generate_ctor_or_dtor_function (/*constructor_p=*/false, priority, locus);
4125 
4126   /* Keep iterating.  */
4127   return 0;
4128 }
4129 
4130 /* Return C++ property of T, based on given operation OP.  */
4131 
4132 static int
4133 cpp_check (tree t, cpp_operation op)
4134 {
4135   switch (op)
4136     {
4137       case HAS_DEPENDENT_TEMPLATE_ARGS:
4138 	{
4139 	  tree ti = CLASSTYPE_TEMPLATE_INFO (t);
4140 	  if (!ti)
4141 	    return 0;
4142 	  ++processing_template_decl;
4143 	  const bool dep = any_dependent_template_arguments_p (TI_ARGS (ti));
4144 	  --processing_template_decl;
4145 	  return dep;
4146 	}
4147       case IS_ABSTRACT:
4148 	return DECL_PURE_VIRTUAL_P (t);
4149       case IS_CONSTRUCTOR:
4150 	return DECL_CONSTRUCTOR_P (t);
4151       case IS_DESTRUCTOR:
4152 	return DECL_DESTRUCTOR_P (t);
4153       case IS_COPY_CONSTRUCTOR:
4154 	return DECL_COPY_CONSTRUCTOR_P (t);
4155       case IS_MOVE_CONSTRUCTOR:
4156 	return DECL_MOVE_CONSTRUCTOR_P (t);
4157       case IS_TEMPLATE:
4158 	return TREE_CODE (t) == TEMPLATE_DECL;
4159       case IS_TRIVIAL:
4160 	return trivial_type_p (t);
4161       default:
4162         return 0;
4163     }
4164 }
4165 
4166 /* Collect source file references recursively, starting from NAMESPC.  */
4167 
4168 static void
4169 collect_source_refs (tree namespc)
4170 {
4171   /* Iterate over names in this name space.  */
4172   for (tree t = NAMESPACE_LEVEL (namespc)->names; t; t = TREE_CHAIN (t))
4173     if (DECL_IS_BUILTIN (t))
4174       ;
4175     else if (TREE_CODE (t) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (t))
4176       collect_source_refs (t);
4177     else
4178       collect_source_ref (DECL_SOURCE_FILE (t));
4179 }
4180 
4181 /* Collect decls relevant to SOURCE_FILE from all namespaces recursively,
4182    starting from NAMESPC.  */
4183 
4184 static void
4185 collect_ada_namespace (tree namespc, const char *source_file)
4186 {
4187   tree decl = NAMESPACE_LEVEL (namespc)->names;
4188 
4189   /* Collect decls from this namespace.  This will skip
4190      NAMESPACE_DECLs (both aliases and regular, it cannot tell).  */
4191   collect_ada_nodes (decl, source_file);
4192 
4193   /* Now scan for namespace children, and dump them.  */
4194   for (; decl; decl = TREE_CHAIN (decl))
4195     if (TREE_CODE (decl) == NAMESPACE_DECL && !DECL_NAMESPACE_ALIAS (decl))
4196       collect_ada_namespace (decl, source_file);
4197 }
4198 
4199 /* Returns true iff there is a definition available for variable or
4200    function DECL.  */
4201 
4202 bool
4203 decl_defined_p (tree decl)
4204 {
4205   if (TREE_CODE (decl) == FUNCTION_DECL)
4206     return (DECL_INITIAL (decl) != NULL_TREE
4207 	    /* A pending instantiation of a friend temploid is defined.  */
4208 	    || (DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
4209 		&& DECL_INITIAL (DECL_TEMPLATE_RESULT
4210 				 (DECL_TI_TEMPLATE (decl)))));
4211   else
4212     {
4213       gcc_assert (VAR_P (decl));
4214       return !DECL_EXTERNAL (decl);
4215     }
4216 }
4217 
4218 /* Nonzero for a VAR_DECL whose value can be used in a constant expression.
4219 
4220       [expr.const]
4221 
4222       An integral constant-expression can only involve ... const
4223       variables of integral or enumeration types initialized with
4224       constant expressions ...
4225 
4226       C++0x also allows constexpr variables and temporaries initialized
4227       with constant expressions.  We handle the former here, but the latter
4228       are just folded away in cxx_eval_constant_expression.
4229 
4230    The standard does not require that the expression be non-volatile.
4231    G++ implements the proposed correction in DR 457.  */
4232 
4233 bool
4234 decl_constant_var_p (tree decl)
4235 {
4236   if (!decl_maybe_constant_var_p (decl))
4237     return false;
4238 
4239   /* We don't know if a template static data member is initialized with
4240      a constant expression until we instantiate its initializer.  Even
4241      in the case of a constexpr variable, we can't treat it as a
4242      constant until its initializer is complete in case it's used in
4243      its own initializer.  */
4244   maybe_instantiate_decl (decl);
4245   return DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl);
4246 }
4247 
4248 /* Returns true if DECL could be a symbolic constant variable, depending on
4249    its initializer.  */
4250 
4251 bool
4252 decl_maybe_constant_var_p (tree decl)
4253 {
4254   tree type = TREE_TYPE (decl);
4255   if (!VAR_P (decl))
4256     return false;
4257   if (DECL_DECLARED_CONSTEXPR_P (decl))
4258     return true;
4259   if (DECL_HAS_VALUE_EXPR_P (decl))
4260     /* A proxy isn't constant.  */
4261     return false;
4262   if (TREE_CODE (type) == REFERENCE_TYPE)
4263     /* References can be constant.  */;
4264   else if (CP_TYPE_CONST_NON_VOLATILE_P (type)
4265 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4266     /* And const integers.  */;
4267   else
4268     return false;
4269 
4270   if (DECL_INITIAL (decl)
4271       && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
4272     /* We know the initializer, and it isn't constant.  */
4273     return false;
4274   else
4275     return true;
4276 }
4277 
4278 /* Complain that DECL uses a type with no linkage.  In C++98 mode this is
4279    called from grokfndecl and grokvardecl; in all modes it is called from
4280    cp_write_global_declarations.  */
4281 
4282 void
4283 no_linkage_error (tree decl)
4284 {
4285   if (cxx_dialect >= cxx11 && decl_defined_p (decl))
4286     /* In C++11 it's ok if the decl is defined.  */
4287     return;
4288   tree t = no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false);
4289   if (t == NULL_TREE)
4290     /* The type that got us on no_linkage_decls must have gotten a name for
4291        linkage purposes.  */;
4292   else if (CLASS_TYPE_P (t) && TYPE_BEING_DEFINED (t))
4293     /* The type might end up having a typedef name for linkage purposes.  */
4294     vec_safe_push (no_linkage_decls, decl);
4295   else if (TYPE_UNNAMED_P (t))
4296     {
4297       bool d = false;
4298       if (cxx_dialect >= cxx11)
4299 	d = permerror (DECL_SOURCE_LOCATION (decl), "%q#D, declared using "
4300 		       "unnamed type, is used but never defined", decl);
4301       else if (DECL_EXTERN_C_P (decl))
4302 	/* Allow this; it's pretty common in C.  */;
4303       else if (VAR_P (decl))
4304 	/* DRs 132, 319 and 389 seem to indicate types with
4305 	   no linkage can only be used to declare extern "C"
4306 	   entities.  Since it's not always an error in the
4307 	   ISO C++ 90 Standard, we only issue a warning.  */
4308 	d = warning_at (DECL_SOURCE_LOCATION (decl), 0, "unnamed type "
4309 			"with no linkage used to declare variable %q#D with "
4310 			"linkage", decl);
4311       else
4312 	d = permerror (DECL_SOURCE_LOCATION (decl), "unnamed type with no "
4313 		       "linkage used to declare function %q#D with linkage",
4314 		       decl);
4315       if (d && is_typedef_decl (TYPE_NAME (t)))
4316 	inform (DECL_SOURCE_LOCATION (TYPE_NAME (t)), "%q#D does not refer "
4317 		"to the unqualified type, so it is not used for linkage",
4318 		TYPE_NAME (t));
4319     }
4320   else if (cxx_dialect >= cxx11)
4321     {
4322       if (VAR_P (decl) || !DECL_PURE_VIRTUAL_P (decl))
4323 	permerror (DECL_SOURCE_LOCATION (decl),
4324 		   "%q#D, declared using local type "
4325 		   "%qT, is used but never defined", decl, t);
4326     }
4327   else if (VAR_P (decl))
4328     warning_at (DECL_SOURCE_LOCATION (decl), 0, "type %qT with no linkage "
4329 		"used to declare variable %q#D with linkage", t, decl);
4330   else
4331     permerror (DECL_SOURCE_LOCATION (decl), "type %qT with no linkage used "
4332 	       "to declare function %q#D with linkage", t, decl);
4333 }
4334 
4335 /* Collect declarations from all namespaces relevant to SOURCE_FILE.  */
4336 
4337 static void
4338 collect_all_refs (const char *source_file)
4339 {
4340   collect_ada_namespace (global_namespace, source_file);
4341 }
4342 
4343 /* Clear DECL_EXTERNAL for NODE.  */
4344 
4345 static bool
4346 clear_decl_external (struct cgraph_node *node, void * /*data*/)
4347 {
4348   DECL_EXTERNAL (node->decl) = 0;
4349   return false;
4350 }
4351 
4352 /* Build up the function to run dynamic initializers for thread_local
4353    variables in this translation unit and alias the init functions for the
4354    individual variables to it.  */
4355 
4356 static void
4357 handle_tls_init (void)
4358 {
4359   tree vars = prune_vars_needing_no_initialization (&tls_aggregates);
4360   if (vars == NULL_TREE)
4361     return;
4362 
4363   location_t loc = DECL_SOURCE_LOCATION (TREE_VALUE (vars));
4364 
4365   write_out_vars (vars);
4366 
4367   tree guard = build_decl (loc, VAR_DECL, get_identifier ("__tls_guard"),
4368 			   boolean_type_node);
4369   TREE_PUBLIC (guard) = false;
4370   TREE_STATIC (guard) = true;
4371   DECL_ARTIFICIAL (guard) = true;
4372   DECL_IGNORED_P (guard) = true;
4373   TREE_USED (guard) = true;
4374   CP_DECL_THREAD_LOCAL_P (guard) = true;
4375   set_decl_tls_model (guard, decl_default_tls_model (guard));
4376   pushdecl_top_level_and_finish (guard, NULL_TREE);
4377 
4378   tree fn = get_local_tls_init_fn ();
4379   start_preparsed_function (fn, NULL_TREE, SF_PRE_PARSED);
4380   tree body = begin_function_body ();
4381   tree if_stmt = begin_if_stmt ();
4382   tree cond = cp_build_unary_op (TRUTH_NOT_EXPR, guard, false,
4383 				 tf_warning_or_error);
4384   finish_if_stmt_cond (cond, if_stmt);
4385   finish_expr_stmt (cp_build_modify_expr (loc, guard, NOP_EXPR,
4386 					  boolean_true_node,
4387 					  tf_warning_or_error));
4388   for (; vars; vars = TREE_CHAIN (vars))
4389     {
4390       tree var = TREE_VALUE (vars);
4391       tree init = TREE_PURPOSE (vars);
4392       one_static_initialization_or_destruction (var, init, true);
4393 
4394       /* Output init aliases even with -fno-extern-tls-init.  */
4395       if (TARGET_SUPPORTS_ALIASES && TREE_PUBLIC (var))
4396 	{
4397           tree single_init_fn = get_tls_init_fn (var);
4398 	  if (single_init_fn == NULL_TREE)
4399 	    continue;
4400 	  cgraph_node *alias
4401 	    = cgraph_node::get_create (fn)->create_same_body_alias
4402 		(single_init_fn, fn);
4403 	  gcc_assert (alias != NULL);
4404 	}
4405     }
4406 
4407   finish_then_clause (if_stmt);
4408   finish_if_stmt (if_stmt);
4409   finish_function_body (body);
4410   expand_or_defer_fn (finish_function (/*inline_p=*/false));
4411 }
4412 
4413 /* We're at the end of compilation, so generate any mangling aliases that
4414    we've been saving up, if DECL is going to be output and ID2 isn't
4415    already taken by another declaration.  */
4416 
4417 static void
4418 generate_mangling_alias (tree decl, tree id2)
4419 {
4420   struct cgraph_node *n = NULL;
4421 
4422   if (TREE_CODE (decl) == FUNCTION_DECL)
4423     {
4424       n = cgraph_node::get (decl);
4425       if (!n)
4426 	/* Don't create an alias to an unreferenced function.  */
4427 	return;
4428     }
4429 
4430   tree *slot
4431     = mangled_decls->find_slot_with_hash (id2, IDENTIFIER_HASH_VALUE (id2),
4432 					  INSERT);
4433 
4434   /* If there's a declaration already using this mangled name,
4435      don't create a compatibility alias that conflicts.  */
4436   if (*slot)
4437     return;
4438 
4439   tree alias = make_alias_for (decl, id2);
4440   *slot = alias;
4441 
4442   DECL_IGNORED_P (alias) = 1;
4443   TREE_PUBLIC (alias) = TREE_PUBLIC (decl);
4444   DECL_VISIBILITY (alias) = DECL_VISIBILITY (decl);
4445   if (vague_linkage_p (decl))
4446     DECL_WEAK (alias) = 1;
4447 
4448   if (n)
4449     n->create_same_body_alias (alias, decl);
4450   else
4451     varpool_node::create_extra_name_alias (alias, decl);
4452 }
4453 
4454 /* Note that we might want to emit an alias with the symbol ID2 for DECL at
4455    the end of translation, for compatibility across bugs in the mangling
4456    implementation.  */
4457 
4458 void
4459 note_mangling_alias (tree decl, tree id2)
4460 {
4461   if (TARGET_SUPPORTS_ALIASES)
4462     {
4463       if (!defer_mangling_aliases)
4464 	generate_mangling_alias (decl, id2);
4465       else
4466 	{
4467 	  vec_safe_push (mangling_aliases, decl);
4468 	  vec_safe_push (mangling_aliases, id2);
4469 	}
4470     }
4471 }
4472 
4473 /* Emit all mangling aliases that were deferred up to this point.  */
4474 
4475 void
4476 generate_mangling_aliases ()
4477 {
4478   while (!vec_safe_is_empty (mangling_aliases))
4479     {
4480       tree id2 = mangling_aliases->pop();
4481       tree decl = mangling_aliases->pop();
4482       generate_mangling_alias (decl, id2);
4483     }
4484   defer_mangling_aliases = false;
4485 }
4486 
4487 /* Record a mangling of DECL, whose DECL_ASSEMBLER_NAME has just been
4488    set.  NEED_WARNING is true if we must warn about collisions.  We do
4489    this to spot changes in mangling that may require compatibility
4490    aliases.  */
4491 
4492 void
4493 record_mangling (tree decl, bool need_warning)
4494 {
4495   if (!mangled_decls)
4496     mangled_decls = hash_table<mangled_decl_hash>::create_ggc (499);
4497 
4498   gcc_checking_assert (DECL_ASSEMBLER_NAME_SET_P (decl));
4499   tree id = DECL_ASSEMBLER_NAME_RAW (decl);
4500   tree *slot
4501     = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4502 					  INSERT);
4503 
4504   /* If this is already an alias, remove the alias, because the real
4505      decl takes precedence.  */
4506   if (*slot && DECL_ARTIFICIAL (*slot) && DECL_IGNORED_P (*slot))
4507     if (symtab_node *n = symtab_node::get (*slot))
4508       if (n->cpp_implicit_alias)
4509 	{
4510 	  n->remove ();
4511 	  *slot = NULL_TREE;
4512 	}
4513 
4514   if (!*slot)
4515     *slot = decl;
4516   else if (need_warning)
4517     {
4518       error_at (DECL_SOURCE_LOCATION (decl),
4519 		"mangling of %q#D as %qE conflicts with a previous mangle",
4520 		decl, id);
4521       inform (DECL_SOURCE_LOCATION (*slot),
4522 	      "previous mangling %q#D", *slot);
4523       inform (DECL_SOURCE_LOCATION (decl),
4524 	      "a later -fabi-version= (or =0)"
4525 	      " avoids this error with a change in mangling");
4526       *slot = decl;
4527     }
4528 }
4529 
4530 /* The mangled name of DECL is being forcibly changed to NAME.  Remove
4531    any existing knowledge of DECL's mangled name meaning DECL.  */
4532 
4533 void
4534 overwrite_mangling (tree decl, tree name)
4535 {
4536   if (tree id = DECL_ASSEMBLER_NAME_RAW (decl))
4537     if ((TREE_CODE (decl) == VAR_DECL
4538 	 || TREE_CODE (decl) == FUNCTION_DECL)
4539 	&& mangled_decls)
4540       if (tree *slot
4541 	  = mangled_decls->find_slot_with_hash (id, IDENTIFIER_HASH_VALUE (id),
4542 						NO_INSERT))
4543 	if (*slot == decl)
4544 	  {
4545 	    mangled_decls->clear_slot (slot);
4546 
4547 	    /* If this is an alias, remove it from the symbol table.  */
4548 	    if (DECL_ARTIFICIAL (decl) && DECL_IGNORED_P (decl))
4549 	      if (symtab_node *n = symtab_node::get (decl))
4550 		if (n->cpp_implicit_alias)
4551 		  n->remove ();
4552 	  }
4553 
4554   DECL_ASSEMBLER_NAME_RAW (decl) = name;
4555 }
4556 
4557 /* The entire file is now complete.  If requested, dump everything
4558    to a file.  */
4559 
4560 static void
4561 dump_tu (void)
4562 {
4563   dump_flags_t flags;
4564   if (FILE *stream = dump_begin (raw_dump_id, &flags))
4565     {
4566       dump_node (global_namespace, flags & ~TDF_SLIM, stream);
4567       dump_end (raw_dump_id, stream);
4568     }
4569 }
4570 
4571 static location_t locus_at_end_of_parsing;
4572 
4573 /* Check the deallocation functions for CODE to see if we want to warn that
4574    only one was defined.  */
4575 
4576 static void
4577 maybe_warn_sized_delete (enum tree_code code)
4578 {
4579   tree sized = NULL_TREE;
4580   tree unsized = NULL_TREE;
4581 
4582   for (ovl_iterator iter (get_global_binding (ovl_op_identifier (false, code)));
4583        iter; ++iter)
4584     {
4585       tree fn = *iter;
4586       /* We're only interested in usual deallocation functions.  */
4587       if (!usual_deallocation_fn_p (fn))
4588 	continue;
4589       if (FUNCTION_ARG_CHAIN (fn) == void_list_node)
4590 	unsized = fn;
4591       else
4592 	sized = fn;
4593     }
4594   if (DECL_INITIAL (unsized) && !DECL_INITIAL (sized))
4595     warning_at (DECL_SOURCE_LOCATION (unsized), OPT_Wsized_deallocation,
4596 		"the program should also define %qD", sized);
4597   else if (!DECL_INITIAL (unsized) && DECL_INITIAL (sized))
4598     warning_at (DECL_SOURCE_LOCATION (sized), OPT_Wsized_deallocation,
4599 		"the program should also define %qD", unsized);
4600 }
4601 
4602 /* Check the global deallocation functions to see if we want to warn about
4603    defining unsized without sized (or vice versa).  */
4604 
4605 static void
4606 maybe_warn_sized_delete ()
4607 {
4608   if (!flag_sized_deallocation || !warn_sized_deallocation)
4609     return;
4610   maybe_warn_sized_delete (DELETE_EXPR);
4611   maybe_warn_sized_delete (VEC_DELETE_EXPR);
4612 }
4613 
4614 /* Earlier we left PTRMEM_CST in variable initializers alone so that we could
4615    look them up when evaluating non-type template parameters.  Now we need to
4616    lower them to something the back end can understand.  */
4617 
4618 static void
4619 lower_var_init ()
4620 {
4621   varpool_node *node;
4622   FOR_EACH_VARIABLE (node)
4623     {
4624       tree d = node->decl;
4625       if (tree init = DECL_INITIAL (d))
4626 	DECL_INITIAL (d) = cplus_expand_constant (init);
4627     }
4628 }
4629 
4630 /* This routine is called at the end of compilation.
4631    Its job is to create all the code needed to initialize and
4632    destroy the global aggregates.  We do the destruction
4633    first, since that way we only need to reverse the decls once.  */
4634 
4635 void
4636 c_parse_final_cleanups (void)
4637 {
4638   tree vars;
4639   bool reconsider;
4640   size_t i;
4641   unsigned ssdf_count = 0;
4642   int retries = 0;
4643   tree decl;
4644 
4645   locus_at_end_of_parsing = input_location;
4646   at_eof = 1;
4647 
4648   /* Bad parse errors.  Just forget about it.  */
4649   if (! global_bindings_p () || current_class_type
4650       || !vec_safe_is_empty (decl_namespace_list))
4651     return;
4652 
4653   /* This is the point to write out a PCH if we're doing that.
4654      In that case we do not want to do anything else.  */
4655   if (pch_file)
4656     {
4657       /* Mangle all symbols at PCH creation time.  */
4658       symtab_node *node;
4659       FOR_EACH_SYMBOL (node)
4660 	if (! is_a <varpool_node *> (node)
4661 	    || ! DECL_HARD_REGISTER (node->decl))
4662 	  DECL_ASSEMBLER_NAME (node->decl);
4663       c_common_write_pch ();
4664       dump_tu ();
4665       /* Ensure even the callers don't try to finalize the CU.  */
4666       flag_syntax_only = 1;
4667       return;
4668     }
4669 
4670   timevar_stop (TV_PHASE_PARSING);
4671   timevar_start (TV_PHASE_DEFERRED);
4672 
4673   symtab->process_same_body_aliases ();
4674 
4675   /* Handle -fdump-ada-spec[-slim] */
4676   if (flag_dump_ada_spec || flag_dump_ada_spec_slim)
4677     {
4678       if (flag_dump_ada_spec_slim)
4679 	collect_source_ref (main_input_filename);
4680       else
4681 	collect_source_refs (global_namespace);
4682 
4683       dump_ada_specs (collect_all_refs, cpp_check);
4684     }
4685 
4686   /* FIXME - huh?  was  input_line -= 1;*/
4687 
4688   /* We now have to write out all the stuff we put off writing out.
4689      These include:
4690 
4691        o Template specializations that we have not yet instantiated,
4692 	 but which are needed.
4693        o Initialization and destruction for non-local objects with
4694 	 static storage duration.  (Local objects with static storage
4695 	 duration are initialized when their scope is first entered,
4696 	 and are cleaned up via atexit.)
4697        o Virtual function tables.
4698 
4699      All of these may cause others to be needed.  For example,
4700      instantiating one function may cause another to be needed, and
4701      generating the initializer for an object may cause templates to be
4702      instantiated, etc., etc.  */
4703 
4704   emit_support_tinfos ();
4705 
4706   do
4707     {
4708       tree t;
4709       tree decl;
4710 
4711       reconsider = false;
4712 
4713       /* If there are templates that we've put off instantiating, do
4714 	 them now.  */
4715       instantiate_pending_templates (retries);
4716       ggc_collect ();
4717 
4718       /* Write out virtual tables as required.  Writing out the
4719 	 virtual table for a template class may cause the
4720 	 instantiation of members of that class.  If we write out
4721 	 vtables then we remove the class from our list so we don't
4722 	 have to look at it again.  */
4723       for (i = keyed_classes->length ();
4724 	   keyed_classes->iterate (--i, &t);)
4725 	if (maybe_emit_vtables (t))
4726 	  {
4727 	    reconsider = true;
4728 	    keyed_classes->unordered_remove (i);
4729 	  }
4730       /* The input_location may have been changed during marking of
4731 	 vtable entries.  */
4732       input_location = locus_at_end_of_parsing;
4733 
4734       /* Write out needed type info variables.  We have to be careful
4735 	 looping through unemitted decls, because emit_tinfo_decl may
4736 	 cause other variables to be needed. New elements will be
4737 	 appended, and we remove from the vector those that actually
4738 	 get emitted.  */
4739       for (i = unemitted_tinfo_decls->length ();
4740 	   unemitted_tinfo_decls->iterate (--i, &t);)
4741 	if (emit_tinfo_decl (t))
4742 	  {
4743 	    reconsider = true;
4744 	    unemitted_tinfo_decls->unordered_remove (i);
4745 	  }
4746 
4747       /* The list of objects with static storage duration is built up
4748 	 in reverse order.  We clear STATIC_AGGREGATES so that any new
4749 	 aggregates added during the initialization of these will be
4750 	 initialized in the correct order when we next come around the
4751 	 loop.  */
4752       vars = prune_vars_needing_no_initialization (&static_aggregates);
4753 
4754       if (vars)
4755 	{
4756 	  /* We need to start a new initialization function each time
4757 	     through the loop.  That's because we need to know which
4758 	     vtables have been referenced, and TREE_SYMBOL_REFERENCED
4759 	     isn't computed until a function is finished, and written
4760 	     out.  That's a deficiency in the back end.  When this is
4761 	     fixed, these initialization functions could all become
4762 	     inline, with resulting performance improvements.  */
4763 	  tree ssdf_body;
4764 
4765 	  /* Set the line and file, so that it is obviously not from
4766 	     the source file.  */
4767 	  input_location = locus_at_end_of_parsing;
4768 	  ssdf_body = start_static_storage_duration_function (ssdf_count);
4769 
4770 	  /* Make sure the back end knows about all the variables.  */
4771 	  write_out_vars (vars);
4772 
4773 	  /* First generate code to do all the initializations.  */
4774 	  if (vars)
4775 	    do_static_initialization_or_destruction (vars, /*initp=*/true);
4776 
4777 	  /* Then, generate code to do all the destructions.  Do these
4778 	     in reverse order so that the most recently constructed
4779 	     variable is the first destroyed.  If we're using
4780 	     __cxa_atexit, then we don't need to do this; functions
4781 	     were registered at initialization time to destroy the
4782 	     local statics.  */
4783 	  if (!flag_use_cxa_atexit && vars)
4784 	    {
4785 	      vars = nreverse (vars);
4786 	      do_static_initialization_or_destruction (vars, /*initp=*/false);
4787 	    }
4788 	  else
4789 	    vars = NULL_TREE;
4790 
4791 	  /* Finish up the static storage duration function for this
4792 	     round.  */
4793 	  input_location = locus_at_end_of_parsing;
4794 	  finish_static_storage_duration_function (ssdf_body);
4795 
4796 	  /* All those initializations and finalizations might cause
4797 	     us to need more inline functions, more template
4798 	     instantiations, etc.  */
4799 	  reconsider = true;
4800 	  ssdf_count++;
4801 	  /* ??? was:  locus_at_end_of_parsing.line++; */
4802 	}
4803 
4804       /* Now do the same for thread_local variables.  */
4805       handle_tls_init ();
4806 
4807       /* Go through the set of inline functions whose bodies have not
4808 	 been emitted yet.  If out-of-line copies of these functions
4809 	 are required, emit them.  */
4810       FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
4811 	{
4812 	  /* Does it need synthesizing?  */
4813 	  if (DECL_DEFAULTED_FN (decl) && ! DECL_INITIAL (decl)
4814 	      && (! DECL_REALLY_EXTERN (decl) || possibly_inlined_p (decl)))
4815 	    {
4816 	      /* Even though we're already at the top-level, we push
4817 		 there again.  That way, when we pop back a few lines
4818 		 hence, all of our state is restored.  Otherwise,
4819 		 finish_function doesn't clean things up, and we end
4820 		 up with CURRENT_FUNCTION_DECL set.  */
4821 	      push_to_top_level ();
4822 	      /* The decl's location will mark where it was first
4823 		 needed.  Save that so synthesize method can indicate
4824 		 where it was needed from, in case of error  */
4825 	      input_location = DECL_SOURCE_LOCATION (decl);
4826 	      synthesize_method (decl);
4827 	      pop_from_top_level ();
4828 	      reconsider = true;
4829 	    }
4830 
4831 	  if (!DECL_INITIAL (decl) && decl_tls_wrapper_p (decl))
4832 	    generate_tls_wrapper (decl);
4833 
4834 	  if (!DECL_SAVED_TREE (decl))
4835 	    continue;
4836 
4837 	  cgraph_node *node = cgraph_node::get_create (decl);
4838 
4839 	  /* We lie to the back end, pretending that some functions
4840 	     are not defined when they really are.  This keeps these
4841 	     functions from being put out unnecessarily.  But, we must
4842 	     stop lying when the functions are referenced, or if they
4843 	     are not comdat since they need to be put out now.  If
4844 	     DECL_INTERFACE_KNOWN, then we have already set
4845 	     DECL_EXTERNAL appropriately, so there's no need to check
4846 	     again, and we do not want to clear DECL_EXTERNAL if a
4847 	     previous call to import_export_decl set it.
4848 
4849 	     This is done in a separate for cycle, because if some
4850 	     deferred function is contained in another deferred
4851 	     function later in deferred_fns varray,
4852 	     rest_of_compilation would skip this function and we
4853 	     really cannot expand the same function twice.  */
4854 	  import_export_decl (decl);
4855 	  if (DECL_NOT_REALLY_EXTERN (decl)
4856 	      && DECL_INITIAL (decl)
4857 	      && decl_needed_p (decl))
4858 	    {
4859 	      if (node->cpp_implicit_alias)
4860 		node = node->get_alias_target ();
4861 
4862 	      node->call_for_symbol_thunks_and_aliases (clear_decl_external,
4863 						      NULL, true);
4864 	      /* If we mark !DECL_EXTERNAL one of the symbols in some comdat
4865 		 group, we need to mark all symbols in the same comdat group
4866 		 that way.  */
4867 	      if (node->same_comdat_group)
4868 		for (cgraph_node *next
4869 		       = dyn_cast<cgraph_node *> (node->same_comdat_group);
4870 		     next != node;
4871 		     next = dyn_cast<cgraph_node *> (next->same_comdat_group))
4872 		  next->call_for_symbol_thunks_and_aliases (clear_decl_external,
4873 							  NULL, true);
4874 	    }
4875 
4876 	  /* If we're going to need to write this function out, and
4877 	     there's already a body for it, create RTL for it now.
4878 	     (There might be no body if this is a method we haven't
4879 	     gotten around to synthesizing yet.)  */
4880 	  if (!DECL_EXTERNAL (decl)
4881 	      && decl_needed_p (decl)
4882 	      && !TREE_ASM_WRITTEN (decl)
4883 	      && !node->definition)
4884 	    {
4885 	      /* We will output the function; no longer consider it in this
4886 		 loop.  */
4887 	      DECL_DEFER_OUTPUT (decl) = 0;
4888 	      /* Generate RTL for this function now that we know we
4889 		 need it.  */
4890 	      expand_or_defer_fn (decl);
4891 	      /* If we're compiling -fsyntax-only pretend that this
4892 		 function has been written out so that we don't try to
4893 		 expand it again.  */
4894 	      if (flag_syntax_only)
4895 		TREE_ASM_WRITTEN (decl) = 1;
4896 	      reconsider = true;
4897 	    }
4898 	}
4899 
4900       if (wrapup_namespace_globals ())
4901 	reconsider = true;
4902 
4903       /* Static data members are just like namespace-scope globals.  */
4904       FOR_EACH_VEC_SAFE_ELT (pending_statics, i, decl)
4905 	{
4906 	  if (var_finalized_p (decl) || DECL_REALLY_EXTERN (decl)
4907 	      /* Don't write it out if we haven't seen a definition.  */
4908 	      || (DECL_IN_AGGR_P (decl) && !DECL_INLINE_VAR_P (decl))
4909 	      /* Or haven't instantiated it.  */
4910 	      || (DECL_TEMPLATE_INSTANTIATION (decl)
4911 		  && !DECL_TEMPLATE_INSTANTIATED (decl)))
4912 	    continue;
4913 	  import_export_decl (decl);
4914 	  /* If this static data member is needed, provide it to the
4915 	     back end.  */
4916 	  if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
4917 	    DECL_EXTERNAL (decl) = 0;
4918 	}
4919       if (vec_safe_length (pending_statics) != 0
4920 	  && wrapup_global_declarations (pending_statics->address (),
4921 					 pending_statics->length ()))
4922 	reconsider = true;
4923 
4924       retries++;
4925     }
4926   while (reconsider);
4927 
4928   lower_var_init ();
4929 
4930   generate_mangling_aliases ();
4931 
4932   /* All used inline functions must have a definition at this point.  */
4933   FOR_EACH_VEC_SAFE_ELT (deferred_fns, i, decl)
4934     {
4935       if (/* Check online inline functions that were actually used.  */
4936 	  DECL_ODR_USED (decl) && DECL_DECLARED_INLINE_P (decl)
4937 	  /* If the definition actually was available here, then the
4938 	     fact that the function was not defined merely represents
4939 	     that for some reason (use of a template repository,
4940 	     #pragma interface, etc.) we decided not to emit the
4941 	     definition here.  */
4942 	  && !DECL_INITIAL (decl)
4943 	  /* Don't complain if the template was defined.  */
4944 	  && !(DECL_TEMPLATE_INSTANTIATION (decl)
4945 	       && DECL_INITIAL (DECL_TEMPLATE_RESULT
4946 				(template_for_substitution (decl)))))
4947 	{
4948 	  warning_at (DECL_SOURCE_LOCATION (decl), 0,
4949 		      "inline function %qD used but never defined", decl);
4950 	  /* Avoid a duplicate warning from check_global_declaration.  */
4951 	  TREE_NO_WARNING (decl) = 1;
4952 	}
4953     }
4954 
4955   /* So must decls that use a type with no linkage.  */
4956   FOR_EACH_VEC_SAFE_ELT (no_linkage_decls, i, decl)
4957     no_linkage_error (decl);
4958 
4959   maybe_warn_sized_delete ();
4960 
4961   /* Then, do the Objective-C stuff.  This is where all the
4962      Objective-C module stuff gets generated (symtab,
4963      class/protocol/selector lists etc).  This must be done after C++
4964      templates, destructors etc. so that selectors used in C++
4965      templates are properly allocated.  */
4966   if (c_dialect_objc ())
4967     objc_write_global_declarations ();
4968 
4969   /* We give C linkage to static constructors and destructors.  */
4970   push_lang_context (lang_name_c);
4971 
4972   /* Generate initialization and destruction functions for all
4973      priorities for which they are required.  */
4974   if (priority_info_map)
4975     splay_tree_foreach (priority_info_map,
4976 			generate_ctor_and_dtor_functions_for_priority,
4977 			/*data=*/&locus_at_end_of_parsing);
4978   else if (c_dialect_objc () && objc_static_init_needed_p ())
4979     /* If this is obj-c++ and we need a static init, call
4980        generate_ctor_or_dtor_function.  */
4981     generate_ctor_or_dtor_function (/*constructor_p=*/true,
4982 				    DEFAULT_INIT_PRIORITY,
4983 				    &locus_at_end_of_parsing);
4984 
4985   /* We're done with the splay-tree now.  */
4986   if (priority_info_map)
4987     splay_tree_delete (priority_info_map);
4988 
4989   /* Generate any missing aliases.  */
4990   maybe_apply_pending_pragma_weaks ();
4991 
4992   /* We're done with static constructors, so we can go back to "C++"
4993      linkage now.  */
4994   pop_lang_context ();
4995 
4996   if (flag_vtable_verify)
4997     {
4998       vtv_recover_class_info ();
4999       vtv_compute_class_hierarchy_transitive_closure ();
5000       vtv_build_vtable_verify_fndecl ();
5001     }
5002 
5003   perform_deferred_noexcept_checks ();
5004 
5005   finish_repo ();
5006   fini_constexpr ();
5007 
5008   /* The entire file is now complete.  If requested, dump everything
5009      to a file.  */
5010   dump_tu ();
5011 
5012   if (flag_detailed_statistics)
5013     {
5014       dump_tree_statistics ();
5015       dump_time_statistics ();
5016     }
5017 
5018   timevar_stop (TV_PHASE_DEFERRED);
5019   timevar_start (TV_PHASE_PARSING);
5020 
5021   /* Indicate that we're done with front end processing.  */
5022   at_eof = 2;
5023 }
5024 
5025 /* Perform any post compilation-proper cleanups for the C++ front-end.
5026    This should really go away.  No front-end should need to do
5027    anything past the compilation process.  */
5028 
5029 void
5030 cxx_post_compilation_parsing_cleanups (void)
5031 {
5032   timevar_start (TV_PHASE_LATE_PARSING_CLEANUPS);
5033 
5034   if (flag_vtable_verify)
5035     {
5036       /* Generate the special constructor initialization function that
5037          calls __VLTRegisterPairs, and give it a very high
5038          initialization priority.  This must be done after
5039          finalize_compilation_unit so that we have accurate
5040          information about which vtable will actually be emitted.  */
5041       vtv_generate_init_routine ();
5042     }
5043 
5044   input_location = locus_at_end_of_parsing;
5045 
5046   if (flag_checking)
5047     validate_conversion_obstack ();
5048 
5049   timevar_stop (TV_PHASE_LATE_PARSING_CLEANUPS);
5050 }
5051 
5052 /* FN is an OFFSET_REF, DOTSTAR_EXPR or MEMBER_REF indicating the
5053    function to call in parse-tree form; it has not yet been
5054    semantically analyzed.  ARGS are the arguments to the function.
5055    They have already been semantically analyzed.  This may change
5056    ARGS.  */
5057 
5058 tree
5059 build_offset_ref_call_from_tree (tree fn, vec<tree, va_gc> **args,
5060 				 tsubst_flags_t complain)
5061 {
5062   tree orig_fn;
5063   vec<tree, va_gc> *orig_args = NULL;
5064   tree expr;
5065   tree object;
5066 
5067   orig_fn = fn;
5068   object = TREE_OPERAND (fn, 0);
5069 
5070   if (processing_template_decl)
5071     {
5072       gcc_assert (TREE_CODE (fn) == DOTSTAR_EXPR
5073 		  || TREE_CODE (fn) == MEMBER_REF);
5074       if (type_dependent_expression_p (fn)
5075 	  || any_type_dependent_arguments_p (*args))
5076 	return build_min_nt_call_vec (fn, *args);
5077 
5078       orig_args = make_tree_vector_copy (*args);
5079 
5080       /* Transform the arguments and add the implicit "this"
5081 	 parameter.  That must be done before the FN is transformed
5082 	 because we depend on the form of FN.  */
5083       make_args_non_dependent (*args);
5084       object = build_non_dependent_expr (object);
5085       if (TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
5086 	{
5087 	  if (TREE_CODE (fn) == DOTSTAR_EXPR)
5088 	    object = cp_build_addr_expr (object, complain);
5089 	  vec_safe_insert (*args, 0, object);
5090 	}
5091       /* Now that the arguments are done, transform FN.  */
5092       fn = build_non_dependent_expr (fn);
5093     }
5094 
5095   /* A qualified name corresponding to a bound pointer-to-member is
5096      represented as an OFFSET_REF:
5097 
5098 	struct B { void g(); };
5099 	void (B::*p)();
5100 	void B::g() { (this->*p)(); }  */
5101   if (TREE_CODE (fn) == OFFSET_REF)
5102     {
5103       tree object_addr = cp_build_addr_expr (object, complain);
5104       fn = TREE_OPERAND (fn, 1);
5105       fn = get_member_function_from_ptrfunc (&object_addr, fn,
5106 					     complain);
5107       vec_safe_insert (*args, 0, object_addr);
5108     }
5109 
5110   if (CLASS_TYPE_P (TREE_TYPE (fn)))
5111     expr = build_op_call (fn, args, complain);
5112   else
5113     expr = cp_build_function_call_vec (fn, args, complain);
5114   if (processing_template_decl && expr != error_mark_node)
5115     expr = build_min_non_dep_call_vec (expr, orig_fn, orig_args);
5116 
5117   if (orig_args != NULL)
5118     release_tree_vector (orig_args);
5119 
5120   return expr;
5121 }
5122 
5123 
5124 void
5125 check_default_args (tree x)
5126 {
5127   tree arg = TYPE_ARG_TYPES (TREE_TYPE (x));
5128   bool saw_def = false;
5129   int i = 0 - (TREE_CODE (TREE_TYPE (x)) == METHOD_TYPE);
5130   for (; arg && arg != void_list_node; arg = TREE_CHAIN (arg), ++i)
5131     {
5132       if (TREE_PURPOSE (arg))
5133 	saw_def = true;
5134       else if (saw_def && !PACK_EXPANSION_P (TREE_VALUE (arg)))
5135 	{
5136 	  error ("default argument missing for parameter %P of %q+#D", i, x);
5137 	  TREE_PURPOSE (arg) = error_mark_node;
5138 	}
5139     }
5140 }
5141 
5142 /* Return true if function DECL can be inlined.  This is used to force
5143    instantiation of methods that might be interesting for inlining.  */
5144 bool
5145 possibly_inlined_p (tree decl)
5146 {
5147   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
5148   if (DECL_UNINLINABLE (decl))
5149     return false;
5150   if (!optimize)
5151     return DECL_DECLARED_INLINE_P (decl);
5152   /* When optimizing, we might inline everything when flatten
5153      attribute or heuristics inlining for size or autoinlining
5154      is used.  */
5155   return true;
5156 }
5157 
5158 /* Normally, we can wait until instantiation-time to synthesize DECL.
5159    However, if DECL is a static data member initialized with a constant
5160    or a constexpr function, we need it right now because a reference to
5161    such a data member or a call to such function is not value-dependent.
5162    For a function that uses auto in the return type, we need to instantiate
5163    it to find out its type.  For OpenMP user defined reductions, we need
5164    them instantiated for reduction clauses which inline them by hand
5165    directly.  */
5166 
5167 static void
5168 maybe_instantiate_decl (tree decl)
5169 {
5170   if (DECL_LANG_SPECIFIC (decl)
5171       && DECL_TEMPLATE_INFO (decl)
5172       && (decl_maybe_constant_var_p (decl)
5173 	  || (TREE_CODE (decl) == FUNCTION_DECL
5174 	      && DECL_OMP_DECLARE_REDUCTION_P (decl))
5175 	  || undeduced_auto_decl (decl))
5176       && !DECL_DECLARED_CONCEPT_P (decl)
5177       && !uses_template_parms (DECL_TI_ARGS (decl)))
5178     {
5179       /* Instantiating a function will result in garbage collection.  We
5180 	 must treat this situation as if we were within the body of a
5181 	 function so as to avoid collecting live data only referenced from
5182 	 the stack (such as overload resolution candidates).  */
5183       ++function_depth;
5184       instantiate_decl (decl, /*defer_ok=*/false,
5185 			/*expl_inst_class_mem_p=*/false);
5186       --function_depth;
5187     }
5188 }
5189 
5190 /* Mark DECL (either a _DECL or a BASELINK) as "used" in the program.
5191    If DECL is a specialization or implicitly declared class member,
5192    generate the actual definition.  Return false if something goes
5193    wrong, true otherwise.  */
5194 
5195 bool
5196 mark_used (tree decl, tsubst_flags_t complain)
5197 {
5198   /* If we're just testing conversions or resolving overloads, we
5199      don't want any permanent effects like forcing functions to be
5200      output or instantiating templates.  */
5201   if ((complain & tf_conv))
5202     return true;
5203 
5204   /* If DECL is a BASELINK for a single function, then treat it just
5205      like the DECL for the function.  Otherwise, if the BASELINK is
5206      for an overloaded function, we don't know which function was
5207      actually used until after overload resolution.  */
5208   if (BASELINK_P (decl))
5209     {
5210       decl = BASELINK_FUNCTIONS (decl);
5211       if (really_overloaded_fn (decl))
5212 	return true;
5213       decl = OVL_FIRST (decl);
5214     }
5215 
5216   /* Set TREE_USED for the benefit of -Wunused.  */
5217   TREE_USED (decl) = 1;
5218   /* And for structured bindings also the underlying decl.  */
5219   if (DECL_DECOMPOSITION_P (decl) && DECL_DECOMP_BASE (decl))
5220     TREE_USED (DECL_DECOMP_BASE (decl)) = 1;
5221 
5222   if (TREE_CODE (decl) == TEMPLATE_DECL)
5223     return true;
5224 
5225   if (DECL_CLONED_FUNCTION_P (decl))
5226     TREE_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5227 
5228   /* Mark enumeration types as used.  */
5229   if (TREE_CODE (decl) == CONST_DECL)
5230     used_types_insert (DECL_CONTEXT (decl));
5231 
5232   if (TREE_CODE (decl) == FUNCTION_DECL
5233       && !maybe_instantiate_noexcept (decl, complain))
5234     return false;
5235 
5236   if (TREE_CODE (decl) == FUNCTION_DECL
5237       && DECL_DELETED_FN (decl))
5238     {
5239       if (DECL_ARTIFICIAL (decl)
5240 	  && DECL_CONV_FN_P (decl)
5241 	  && LAMBDA_TYPE_P (DECL_CONTEXT (decl)))
5242 	/* We mark a lambda conversion op as deleted if we can't
5243 	   generate it properly; see maybe_add_lambda_conv_op.  */
5244 	sorry ("converting lambda that uses %<...%> to function pointer");
5245       else if (complain & tf_error)
5246 	{
5247 	  error ("use of deleted function %qD", decl);
5248 	  if (!maybe_explain_implicit_delete (decl))
5249 	    inform (DECL_SOURCE_LOCATION (decl), "declared here");
5250 	}
5251       return false;
5252     }
5253 
5254   if (TREE_DEPRECATED (decl) && (complain & tf_warning)
5255       && deprecated_state != DEPRECATED_SUPPRESS)
5256     warn_deprecated_use (decl, NULL_TREE);
5257 
5258   /* We can only check DECL_ODR_USED on variables or functions with
5259      DECL_LANG_SPECIFIC set, and these are also the only decls that we
5260      might need special handling for.  */
5261   if (!VAR_OR_FUNCTION_DECL_P (decl)
5262       || DECL_LANG_SPECIFIC (decl) == NULL
5263       || DECL_THUNK_P (decl))
5264     {
5265       if (!processing_template_decl
5266 	  && !require_deduced_type (decl, complain))
5267 	return false;
5268       return true;
5269     }
5270 
5271   /* We only want to do this processing once.  We don't need to keep trying
5272      to instantiate inline templates, because unit-at-a-time will make sure
5273      we get them compiled before functions that want to inline them.  */
5274   if (DECL_ODR_USED (decl))
5275     return true;
5276 
5277   /* Normally, we can wait until instantiation-time to synthesize DECL.
5278      However, if DECL is a static data member initialized with a constant
5279      or a constexpr function, we need it right now because a reference to
5280      such a data member or a call to such function is not value-dependent.
5281      For a function that uses auto in the return type, we need to instantiate
5282      it to find out its type.  For OpenMP user defined reductions, we need
5283      them instantiated for reduction clauses which inline them by hand
5284      directly.  */
5285   maybe_instantiate_decl (decl);
5286 
5287   if (processing_template_decl || in_template_function ())
5288     return true;
5289 
5290   /* Check this too in case we're within instantiate_non_dependent_expr.  */
5291   if (DECL_TEMPLATE_INFO (decl)
5292       && uses_template_parms (DECL_TI_ARGS (decl)))
5293     return true;
5294 
5295   if (!require_deduced_type (decl, complain))
5296     return false;
5297 
5298   if (builtin_pack_fn_p (decl))
5299     {
5300       error ("use of built-in parameter pack %qD outside of a template",
5301 	     DECL_NAME (decl));
5302       return false;
5303     }
5304 
5305   /* If we don't need a value, then we don't need to synthesize DECL.  */
5306   if (cp_unevaluated_operand || in_discarded_stmt)
5307     return true;
5308 
5309   DECL_ODR_USED (decl) = 1;
5310   if (DECL_CLONED_FUNCTION_P (decl))
5311     DECL_ODR_USED (DECL_CLONED_FUNCTION (decl)) = 1;
5312 
5313   /* DR 757: A type without linkage shall not be used as the type of a
5314      variable or function with linkage, unless
5315    o the variable or function has extern "C" linkage (7.5 [dcl.link]), or
5316    o the variable or function is not used (3.2 [basic.def.odr]) or is
5317    defined in the same translation unit.  */
5318   if (cxx_dialect > cxx98
5319       && decl_linkage (decl) != lk_none
5320       && !DECL_EXTERN_C_P (decl)
5321       && !DECL_ARTIFICIAL (decl)
5322       && !decl_defined_p (decl)
5323       && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
5324     {
5325       if (is_local_extern (decl))
5326 	/* There's no way to define a local extern, and adding it to
5327 	   the vector interferes with GC, so give an error now.  */
5328 	no_linkage_error (decl);
5329       else
5330 	vec_safe_push (no_linkage_decls, decl);
5331     }
5332 
5333   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl)
5334       && !DECL_INITIAL (decl) && !DECL_ARTIFICIAL (decl))
5335     /* Remember it, so we can check it was defined.  */
5336     note_vague_linkage_fn (decl);
5337 
5338   /* Is it a synthesized method that needs to be synthesized?  */
5339   if (TREE_CODE (decl) == FUNCTION_DECL
5340       && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
5341       && DECL_DEFAULTED_FN (decl)
5342       /* A function defaulted outside the class is synthesized either by
5343 	 cp_finish_decl or instantiate_decl.  */
5344       && !DECL_DEFAULTED_OUTSIDE_CLASS_P (decl)
5345       && ! DECL_INITIAL (decl))
5346     {
5347       /* Defer virtual destructors so that thunks get the right
5348 	 linkage.  */
5349       if (DECL_VIRTUAL_P (decl) && !at_eof)
5350 	{
5351 	  note_vague_linkage_fn (decl);
5352 	  return true;
5353 	}
5354 
5355       /* Remember the current location for a function we will end up
5356 	 synthesizing.  Then we can inform the user where it was
5357 	 required in the case of error.  */
5358       DECL_SOURCE_LOCATION (decl) = input_location;
5359 
5360       /* Synthesizing an implicitly defined member function will result in
5361 	 garbage collection.  We must treat this situation as if we were
5362 	 within the body of a function so as to avoid collecting live data
5363 	 on the stack (such as overload resolution candidates).
5364 
5365          We could just let cp_write_global_declarations handle synthesizing
5366          this function by adding it to deferred_fns, but doing
5367          it at the use site produces better error messages.  */
5368       ++function_depth;
5369       synthesize_method (decl);
5370       --function_depth;
5371       /* If this is a synthesized method we don't need to
5372 	 do the instantiation test below.  */
5373     }
5374   else if (VAR_OR_FUNCTION_DECL_P (decl)
5375 	   && DECL_TEMPLATE_INFO (decl)
5376            && !DECL_DECLARED_CONCEPT_P (decl)
5377 	   && (!DECL_EXPLICIT_INSTANTIATION (decl)
5378 	       || always_instantiate_p (decl)))
5379     /* If this is a function or variable that is an instance of some
5380        template, we now know that we will need to actually do the
5381        instantiation. We check that DECL is not an explicit
5382        instantiation because that is not checked in instantiate_decl.
5383 
5384        We put off instantiating functions in order to improve compile
5385        times.  Maintaining a stack of active functions is expensive,
5386        and the inliner knows to instantiate any functions it might
5387        need.  Therefore, we always try to defer instantiation.  */
5388     {
5389       ++function_depth;
5390       instantiate_decl (decl, /*defer_ok=*/true,
5391 			/*expl_inst_class_mem_p=*/false);
5392       --function_depth;
5393     }
5394 
5395   return true;
5396 }
5397 
5398 bool
5399 mark_used (tree decl)
5400 {
5401   return mark_used (decl, tf_warning_or_error);
5402 }
5403 
5404 tree
5405 vtv_start_verification_constructor_init_function (void)
5406 {
5407   return start_objects ('I', MAX_RESERVED_INIT_PRIORITY - 1);
5408 }
5409 
5410 tree
5411 vtv_finish_verification_constructor_init_function (tree function_body)
5412 {
5413   tree fn;
5414 
5415   finish_compound_stmt (function_body);
5416   fn = finish_function (/*inline_p=*/false);
5417   DECL_STATIC_CONSTRUCTOR (fn) = 1;
5418   decl_init_priority_insert (fn, MAX_RESERVED_INIT_PRIORITY - 1);
5419 
5420   return fn;
5421 }
5422 
5423 #include "gt-cp-decl2.h"
5424