1 /* Functions related to building classes and their related objects.
2    Copyright (C) 1987-2018 Free Software Foundation, Inc.
3    Contributed 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 /* High-level class interface.  */
23 
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "target.h"
28 #include "cp-tree.h"
29 #include "stringpool.h"
30 #include "cgraph.h"
31 #include "stor-layout.h"
32 #include "attribs.h"
33 #include "flags.h"
34 #include "toplev.h"
35 #include "convert.h"
36 #include "dumpfile.h"
37 #include "gimplify.h"
38 #include "intl.h"
39 #include "asan.h"
40 
41 /* Id for dumping the class hierarchy.  */
42 int class_dump_id;
43 
44 /* The number of nested classes being processed.  If we are not in the
45    scope of any class, this is zero.  */
46 
47 int current_class_depth;
48 
49 /* In order to deal with nested classes, we keep a stack of classes.
50    The topmost entry is the innermost class, and is the entry at index
51    CURRENT_CLASS_DEPTH  */
52 
53 typedef struct class_stack_node {
54   /* The name of the class.  */
55   tree name;
56 
57   /* The _TYPE node for the class.  */
58   tree type;
59 
60   /* The access specifier pending for new declarations in the scope of
61      this class.  */
62   tree access;
63 
64   /* If were defining TYPE, the names used in this class.  */
65   splay_tree names_used;
66 
67   /* Nonzero if this class is no longer open, because of a call to
68      push_to_top_level.  */
69   size_t hidden;
70 }* class_stack_node_t;
71 
72 struct vtbl_init_data
73 {
74   /* The base for which we're building initializers.  */
75   tree binfo;
76   /* The type of the most-derived type.  */
77   tree derived;
78   /* The binfo for the dynamic type. This will be TYPE_BINFO (derived),
79      unless ctor_vtbl_p is true.  */
80   tree rtti_binfo;
81   /* The negative-index vtable initializers built up so far.  These
82      are in order from least negative index to most negative index.  */
83   vec<constructor_elt, va_gc> *inits;
84   /* The binfo for the virtual base for which we're building
85      vcall offset initializers.  */
86   tree vbase;
87   /* The functions in vbase for which we have already provided vcall
88      offsets.  */
89   vec<tree, va_gc> *fns;
90   /* The vtable index of the next vcall or vbase offset.  */
91   tree index;
92   /* Nonzero if we are building the initializer for the primary
93      vtable.  */
94   int primary_vtbl_p;
95   /* Nonzero if we are building the initializer for a construction
96      vtable.  */
97   int ctor_vtbl_p;
98   /* True when adding vcall offset entries to the vtable.  False when
99      merely computing the indices.  */
100   bool generate_vcall_entries;
101 };
102 
103 /* The type of a function passed to walk_subobject_offsets.  */
104 typedef int (*subobject_offset_fn) (tree, tree, splay_tree);
105 
106 /* The stack itself.  This is a dynamically resized array.  The
107    number of elements allocated is CURRENT_CLASS_STACK_SIZE.  */
108 static int current_class_stack_size;
109 static class_stack_node_t current_class_stack;
110 
111 /* The size of the largest empty class seen in this translation unit.  */
112 static GTY (()) tree sizeof_biggest_empty_class;
113 
114 /* An array of all local classes present in this translation unit, in
115    declaration order.  */
116 vec<tree, va_gc> *local_classes;
117 
118 static tree get_vfield_name (tree);
119 static void finish_struct_anon (tree);
120 static tree get_vtable_name (tree);
121 static void get_basefndecls (tree, tree, vec<tree> *);
122 static int build_primary_vtable (tree, tree);
123 static int build_secondary_vtable (tree);
124 static void finish_vtbls (tree);
125 static void modify_vtable_entry (tree, tree, tree, tree, tree *);
126 static void finish_struct_bits (tree);
127 static int alter_access (tree, tree, tree);
128 static void handle_using_decl (tree, tree);
129 static tree dfs_modify_vtables (tree, void *);
130 static tree modify_all_vtables (tree, tree);
131 static void determine_primary_bases (tree);
132 static void maybe_warn_about_overly_private_class (tree);
133 static void add_implicitly_declared_members (tree, tree*, int, int);
134 static tree fixed_type_or_null (tree, int *, int *);
135 static tree build_simple_base_path (tree expr, tree binfo);
136 static tree build_vtbl_ref_1 (tree, tree);
137 static void build_vtbl_initializer (tree, tree, tree, tree, int *,
138 				    vec<constructor_elt, va_gc> **);
139 static bool check_bitfield_decl (tree);
140 static bool check_field_decl (tree, tree, int *, int *);
141 static void check_field_decls (tree, tree *, int *, int *);
142 static tree *build_base_field (record_layout_info, tree, splay_tree, tree *);
143 static void build_base_fields (record_layout_info, splay_tree, tree *);
144 static void check_methods (tree);
145 static void remove_zero_width_bit_fields (tree);
146 static bool accessible_nvdtor_p (tree);
147 
148 /* Used by find_flexarrays and related functions.  */
149 struct flexmems_t;
150 static void diagnose_flexarrays (tree, const flexmems_t *);
151 static void find_flexarrays (tree, flexmems_t *, bool = false,
152 			     tree = NULL_TREE, tree = NULL_TREE);
153 static void check_flexarrays (tree, flexmems_t * = NULL, bool = false);
154 static void check_bases (tree, int *, int *);
155 static void check_bases_and_members (tree);
156 static tree create_vtable_ptr (tree, tree *);
157 static void include_empty_classes (record_layout_info);
158 static void layout_class_type (tree, tree *);
159 static void propagate_binfo_offsets (tree, tree);
160 static void layout_virtual_bases (record_layout_info, splay_tree);
161 static void build_vbase_offset_vtbl_entries (tree, vtbl_init_data *);
162 static void add_vcall_offset_vtbl_entries_r (tree, vtbl_init_data *);
163 static void add_vcall_offset_vtbl_entries_1 (tree, vtbl_init_data *);
164 static void build_vcall_offset_vtbl_entries (tree, vtbl_init_data *);
165 static void add_vcall_offset (tree, tree, vtbl_init_data *);
166 static void layout_vtable_decl (tree, int);
167 static tree dfs_find_final_overrider_pre (tree, void *);
168 static tree dfs_find_final_overrider_post (tree, void *);
169 static tree find_final_overrider (tree, tree, tree);
170 static int make_new_vtable (tree, tree);
171 static tree get_primary_binfo (tree);
172 static int maybe_indent_hierarchy (FILE *, int, int);
173 static tree dump_class_hierarchy_r (FILE *, dump_flags_t, tree, tree, int);
174 static void dump_class_hierarchy (tree);
175 static void dump_class_hierarchy_1 (FILE *, dump_flags_t, tree);
176 static void dump_array (FILE *, tree);
177 static void dump_vtable (tree, tree, tree);
178 static void dump_vtt (tree, tree);
179 static void dump_thunk (FILE *, int, tree);
180 static tree build_vtable (tree, tree, tree);
181 static void initialize_vtable (tree, vec<constructor_elt, va_gc> *);
182 static void layout_nonempty_base_or_field (record_layout_info,
183 					   tree, tree, splay_tree);
184 static tree end_of_class (tree, int);
185 static bool layout_empty_base (record_layout_info, tree, tree, splay_tree);
186 static void accumulate_vtbl_inits (tree, tree, tree, tree, tree,
187 				   vec<constructor_elt, va_gc> **);
188 static void dfs_accumulate_vtbl_inits (tree, tree, tree, tree, tree,
189 				       vec<constructor_elt, va_gc> **);
190 static void build_rtti_vtbl_entries (tree, vtbl_init_data *);
191 static void build_vcall_and_vbase_vtbl_entries (tree, vtbl_init_data *);
192 static void clone_constructors_and_destructors (tree);
193 static tree build_clone (tree, tree);
194 static void update_vtable_entry_for_fn (tree, tree, tree, tree *, unsigned);
195 static void build_ctor_vtbl_group (tree, tree);
196 static void build_vtt (tree);
197 static tree binfo_ctor_vtable (tree);
198 static void build_vtt_inits (tree, tree, vec<constructor_elt, va_gc> **,
199 			     tree *);
200 static tree dfs_build_secondary_vptr_vtt_inits (tree, void *);
201 static tree dfs_fixup_binfo_vtbls (tree, void *);
202 static int record_subobject_offset (tree, tree, splay_tree);
203 static int check_subobject_offset (tree, tree, splay_tree);
204 static int walk_subobject_offsets (tree, subobject_offset_fn,
205 				   tree, splay_tree, tree, int);
206 static void record_subobject_offsets (tree, tree, splay_tree, bool);
207 static int layout_conflict_p (tree, tree, splay_tree, int);
208 static int splay_tree_compare_integer_csts (splay_tree_key k1,
209 					    splay_tree_key k2);
210 static void warn_about_ambiguous_bases (tree);
211 static bool type_requires_array_cookie (tree);
212 static bool base_derived_from (tree, tree);
213 static int empty_base_at_nonzero_offset_p (tree, tree, splay_tree);
214 static tree end_of_base (tree);
215 static tree get_vcall_index (tree, tree);
216 static bool type_maybe_constexpr_default_constructor (tree);
217 
218 /* Return a COND_EXPR that executes TRUE_STMT if this execution of the
219    'structor is in charge of 'structing virtual bases, or FALSE_STMT
220    otherwise.  */
221 
222 tree
build_if_in_charge(tree true_stmt,tree false_stmt)223 build_if_in_charge (tree true_stmt, tree false_stmt)
224 {
225   gcc_assert (DECL_HAS_IN_CHARGE_PARM_P (current_function_decl));
226   tree cmp = build2 (NE_EXPR, boolean_type_node,
227 		     current_in_charge_parm, integer_zero_node);
228   tree type = unlowered_expr_type (true_stmt);
229   if (VOID_TYPE_P (type))
230     type = unlowered_expr_type (false_stmt);
231   tree cond = build3 (COND_EXPR, type,
232 		      cmp, true_stmt, false_stmt);
233   return cond;
234 }
235 
236 /* Convert to or from a base subobject.  EXPR is an expression of type
237    `A' or `A*', an expression of type `B' or `B*' is returned.  To
238    convert A to a base B, CODE is PLUS_EXPR and BINFO is the binfo for
239    the B base instance within A.  To convert base A to derived B, CODE
240    is MINUS_EXPR and BINFO is the binfo for the A instance within B.
241    In this latter case, A must not be a morally virtual base of B.
242    NONNULL is true if EXPR is known to be non-NULL (this is only
243    needed when EXPR is of pointer type).  CV qualifiers are preserved
244    from EXPR.  */
245 
246 tree
build_base_path(enum tree_code code,tree expr,tree binfo,int nonnull,tsubst_flags_t complain)247 build_base_path (enum tree_code code,
248 		 tree expr,
249 		 tree binfo,
250 		 int nonnull,
251 		 tsubst_flags_t complain)
252 {
253   tree v_binfo = NULL_TREE;
254   tree d_binfo = NULL_TREE;
255   tree probe;
256   tree offset;
257   tree target_type;
258   tree null_test = NULL;
259   tree ptr_target_type;
260   int fixed_type_p;
261   int want_pointer = TYPE_PTR_P (TREE_TYPE (expr));
262   bool has_empty = false;
263   bool virtual_access;
264   bool rvalue = false;
265 
266   if (expr == error_mark_node || binfo == error_mark_node || !binfo)
267     return error_mark_node;
268 
269   for (probe = binfo; probe; probe = BINFO_INHERITANCE_CHAIN (probe))
270     {
271       d_binfo = probe;
272       if (is_empty_class (BINFO_TYPE (probe)))
273 	has_empty = true;
274       if (!v_binfo && BINFO_VIRTUAL_P (probe))
275 	v_binfo = probe;
276     }
277 
278   probe = TYPE_MAIN_VARIANT (TREE_TYPE (expr));
279   if (want_pointer)
280     probe = TYPE_MAIN_VARIANT (TREE_TYPE (probe));
281   if (dependent_type_p (probe))
282     if (tree open = currently_open_class (probe))
283       probe = open;
284 
285   if (code == PLUS_EXPR
286       && !SAME_BINFO_TYPE_P (BINFO_TYPE (d_binfo), probe))
287     {
288       /* This can happen when adjust_result_of_qualified_name_lookup can't
289 	 find a unique base binfo in a call to a member function.  We
290 	 couldn't give the diagnostic then since we might have been calling
291 	 a static member function, so we do it now.  In other cases, eg.
292 	 during error recovery (c++/71979), we may not have a base at all.  */
293       if (complain & tf_error)
294 	{
295 	  tree base = lookup_base (probe, BINFO_TYPE (d_binfo),
296 				   ba_unique, NULL, complain);
297 	  gcc_assert (base == error_mark_node || !base);
298 	}
299       return error_mark_node;
300     }
301 
302   gcc_assert ((code == MINUS_EXPR
303 	       && SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), probe))
304 	      || code == PLUS_EXPR);
305 
306   if (binfo == d_binfo)
307     /* Nothing to do.  */
308     return expr;
309 
310   if (code == MINUS_EXPR && v_binfo)
311     {
312       if (complain & tf_error)
313 	{
314 	  if (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), BINFO_TYPE (v_binfo)))
315 	    {
316 	      if (want_pointer)
317 		error ("cannot convert from pointer to base class %qT to "
318 		       "pointer to derived class %qT because the base is "
319 		       "virtual", BINFO_TYPE (binfo), BINFO_TYPE (d_binfo));
320 	      else
321 		error ("cannot convert from base class %qT to derived "
322 		       "class %qT because the base is virtual",
323 		       BINFO_TYPE (binfo), BINFO_TYPE (d_binfo));
324 	    }
325 	  else
326 	    {
327 	      if (want_pointer)
328 		error ("cannot convert from pointer to base class %qT to "
329 		       "pointer to derived class %qT via virtual base %qT",
330 		       BINFO_TYPE (binfo), BINFO_TYPE (d_binfo),
331 		       BINFO_TYPE (v_binfo));
332 	      else
333 		error ("cannot convert from base class %qT to derived "
334 		       "class %qT via virtual base %qT", BINFO_TYPE (binfo),
335 		       BINFO_TYPE (d_binfo), BINFO_TYPE (v_binfo));
336 	    }
337 	}
338       return error_mark_node;
339     }
340 
341   if (!want_pointer)
342     {
343       rvalue = !lvalue_p (expr);
344       /* This must happen before the call to save_expr.  */
345       expr = cp_build_addr_expr (expr, complain);
346     }
347   else
348     expr = mark_rvalue_use (expr);
349 
350   offset = BINFO_OFFSET (binfo);
351   fixed_type_p = resolves_to_fixed_type_p (expr, &nonnull);
352   target_type = code == PLUS_EXPR ? BINFO_TYPE (binfo) : BINFO_TYPE (d_binfo);
353   /* TARGET_TYPE has been extracted from BINFO, and, is therefore always
354      cv-unqualified.  Extract the cv-qualifiers from EXPR so that the
355      expression returned matches the input.  */
356   target_type = cp_build_qualified_type
357     (target_type, cp_type_quals (TREE_TYPE (TREE_TYPE (expr))));
358   ptr_target_type = build_pointer_type (target_type);
359 
360   /* Do we need to look in the vtable for the real offset?  */
361   virtual_access = (v_binfo && fixed_type_p <= 0);
362 
363   /* Don't bother with the calculations inside sizeof; they'll ICE if the
364      source type is incomplete and the pointer value doesn't matter.  In a
365      template (even in instantiate_non_dependent_expr), we don't have vtables
366      set up properly yet, and the value doesn't matter there either; we're
367      just interested in the result of overload resolution.  */
368   if (cp_unevaluated_operand != 0
369       || processing_template_decl
370       || in_template_function ())
371     {
372       expr = build_nop (ptr_target_type, expr);
373       goto indout;
374     }
375 
376   /* If we're in an NSDMI, we don't have the full constructor context yet
377      that we need for converting to a virtual base, so just build a stub
378      CONVERT_EXPR and expand it later in bot_replace.  */
379   if (virtual_access && fixed_type_p < 0
380       && current_scope () != current_function_decl)
381     {
382       expr = build1 (CONVERT_EXPR, ptr_target_type, expr);
383       CONVERT_EXPR_VBASE_PATH (expr) = true;
384       goto indout;
385     }
386 
387   /* Do we need to check for a null pointer?  */
388   if (want_pointer && !nonnull)
389     {
390       /* If we know the conversion will not actually change the value
391 	 of EXPR, then we can avoid testing the expression for NULL.
392 	 We have to avoid generating a COMPONENT_REF for a base class
393 	 field, because other parts of the compiler know that such
394 	 expressions are always non-NULL.  */
395       if (!virtual_access && integer_zerop (offset))
396 	return build_nop (ptr_target_type, expr);
397       null_test = error_mark_node;
398     }
399 
400   /* Protect against multiple evaluation if necessary.  */
401   if (TREE_SIDE_EFFECTS (expr) && (null_test || virtual_access))
402     expr = save_expr (expr);
403 
404   /* Now that we've saved expr, build the real null test.  */
405   if (null_test)
406     {
407       tree zero = cp_convert (TREE_TYPE (expr), nullptr_node, complain);
408       null_test = build2_loc (input_location, NE_EXPR, boolean_type_node,
409 			      expr, zero);
410       /* This is a compiler generated comparison, don't emit
411 	 e.g. -Wnonnull-compare warning for it.  */
412       TREE_NO_WARNING (null_test) = 1;
413     }
414 
415   /* If this is a simple base reference, express it as a COMPONENT_REF.  */
416   if (code == PLUS_EXPR && !virtual_access
417       /* We don't build base fields for empty bases, and they aren't very
418 	 interesting to the optimizers anyway.  */
419       && !has_empty)
420     {
421       expr = cp_build_fold_indirect_ref (expr);
422       expr = build_simple_base_path (expr, binfo);
423       if (rvalue && lvalue_p (expr))
424 	expr = move (expr);
425       if (want_pointer)
426 	expr = build_address (expr);
427       target_type = TREE_TYPE (expr);
428       goto out;
429     }
430 
431   if (virtual_access)
432     {
433       /* Going via virtual base V_BINFO.  We need the static offset
434 	 from V_BINFO to BINFO, and the dynamic offset from D_BINFO to
435 	 V_BINFO.  That offset is an entry in D_BINFO's vtable.  */
436       tree v_offset;
437 
438       if (fixed_type_p < 0 && in_base_initializer)
439 	{
440 	  /* In a base member initializer, we cannot rely on the
441 	     vtable being set up.  We have to indirect via the
442 	     vtt_parm.  */
443 	  tree t;
444 
445 	  t = TREE_TYPE (TYPE_VFIELD (current_class_type));
446 	  t = build_pointer_type (t);
447 	  v_offset = fold_convert (t, current_vtt_parm);
448 	  v_offset = cp_build_fold_indirect_ref (v_offset);
449 	}
450       else
451 	{
452 	  tree t = expr;
453 	  if (sanitize_flags_p (SANITIZE_VPTR)
454 	      && fixed_type_p == 0)
455 	    {
456 	      t = cp_ubsan_maybe_instrument_cast_to_vbase (input_location,
457 							   probe, expr);
458 	      if (t == NULL_TREE)
459 		t = expr;
460 	    }
461 	  v_offset = build_vfield_ref (cp_build_fold_indirect_ref (t),
462 	  TREE_TYPE (TREE_TYPE (expr)));
463 	}
464 
465       if (v_offset == error_mark_node)
466 	return error_mark_node;
467 
468       v_offset = fold_build_pointer_plus (v_offset, BINFO_VPTR_FIELD (v_binfo));
469       v_offset = build1 (NOP_EXPR,
470 			 build_pointer_type (ptrdiff_type_node),
471 			 v_offset);
472       v_offset = cp_build_fold_indirect_ref (v_offset);
473       TREE_CONSTANT (v_offset) = 1;
474 
475       offset = convert_to_integer (ptrdiff_type_node,
476 				   size_diffop_loc (input_location, offset,
477 						BINFO_OFFSET (v_binfo)));
478 
479       if (!integer_zerop (offset))
480 	v_offset = build2 (code, ptrdiff_type_node, v_offset, offset);
481 
482       if (fixed_type_p < 0)
483 	/* Negative fixed_type_p means this is a constructor or destructor;
484 	   virtual base layout is fixed in in-charge [cd]tors, but not in
485 	   base [cd]tors.  */
486 	offset = build_if_in_charge
487 	  (convert_to_integer (ptrdiff_type_node, BINFO_OFFSET (binfo)),
488 	   v_offset);
489       else
490 	offset = v_offset;
491     }
492 
493   if (want_pointer)
494     target_type = ptr_target_type;
495 
496   expr = build1 (NOP_EXPR, ptr_target_type, expr);
497 
498   if (!integer_zerop (offset))
499     {
500       offset = fold_convert (sizetype, offset);
501       if (code == MINUS_EXPR)
502 	offset = fold_build1_loc (input_location, NEGATE_EXPR, sizetype, offset);
503       expr = fold_build_pointer_plus (expr, offset);
504     }
505   else
506     null_test = NULL;
507 
508  indout:
509   if (!want_pointer)
510     {
511       expr = cp_build_fold_indirect_ref (expr);
512       if (rvalue)
513 	expr = move (expr);
514     }
515 
516  out:
517   if (null_test)
518     expr = fold_build3_loc (input_location, COND_EXPR, target_type, null_test, expr,
519 			    build_zero_cst (target_type));
520 
521   return expr;
522 }
523 
524 /* Subroutine of build_base_path; EXPR and BINFO are as in that function.
525    Perform a derived-to-base conversion by recursively building up a
526    sequence of COMPONENT_REFs to the appropriate base fields.  */
527 
528 static tree
build_simple_base_path(tree expr,tree binfo)529 build_simple_base_path (tree expr, tree binfo)
530 {
531   tree type = BINFO_TYPE (binfo);
532   tree d_binfo = BINFO_INHERITANCE_CHAIN (binfo);
533   tree field;
534 
535   if (d_binfo == NULL_TREE)
536     {
537       tree temp;
538 
539       gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (expr)) == type);
540 
541       /* Transform `(a, b).x' into `(*(a, &b)).x', `(a ? b : c).x'
542 	 into `(*(a ?  &b : &c)).x', and so on.  A COND_EXPR is only
543 	 an lvalue in the front end; only _DECLs and _REFs are lvalues
544 	 in the back end.  */
545       temp = unary_complex_lvalue (ADDR_EXPR, expr);
546       if (temp)
547 	expr = cp_build_fold_indirect_ref (temp);
548 
549       return expr;
550     }
551 
552   /* Recurse.  */
553   expr = build_simple_base_path (expr, d_binfo);
554 
555   for (field = TYPE_FIELDS (BINFO_TYPE (d_binfo));
556        field; field = DECL_CHAIN (field))
557     /* Is this the base field created by build_base_field?  */
558     if (TREE_CODE (field) == FIELD_DECL
559 	&& DECL_FIELD_IS_BASE (field)
560 	&& TREE_TYPE (field) == type
561 	/* If we're looking for a field in the most-derived class,
562 	   also check the field offset; we can have two base fields
563 	   of the same type if one is an indirect virtual base and one
564 	   is a direct non-virtual base.  */
565 	&& (BINFO_INHERITANCE_CHAIN (d_binfo)
566 	    || tree_int_cst_equal (byte_position (field),
567 				   BINFO_OFFSET (binfo))))
568       {
569 	/* We don't use build_class_member_access_expr here, as that
570 	   has unnecessary checks, and more importantly results in
571 	   recursive calls to dfs_walk_once.  */
572 	int type_quals = cp_type_quals (TREE_TYPE (expr));
573 
574 	expr = build3 (COMPONENT_REF,
575 		       cp_build_qualified_type (type, type_quals),
576 		       expr, field, NULL_TREE);
577 	/* Mark the expression const or volatile, as appropriate.
578 	   Even though we've dealt with the type above, we still have
579 	   to mark the expression itself.  */
580 	if (type_quals & TYPE_QUAL_CONST)
581 	  TREE_READONLY (expr) = 1;
582 	if (type_quals & TYPE_QUAL_VOLATILE)
583 	  TREE_THIS_VOLATILE (expr) = 1;
584 
585 	return expr;
586       }
587 
588   /* Didn't find the base field?!?  */
589   gcc_unreachable ();
590 }
591 
592 /* Convert OBJECT to the base TYPE.  OBJECT is an expression whose
593    type is a class type or a pointer to a class type.  In the former
594    case, TYPE is also a class type; in the latter it is another
595    pointer type.  If CHECK_ACCESS is true, an error message is emitted
596    if TYPE is inaccessible.  If OBJECT has pointer type, the value is
597    assumed to be non-NULL.  */
598 
599 tree
convert_to_base(tree object,tree type,bool check_access,bool nonnull,tsubst_flags_t complain)600 convert_to_base (tree object, tree type, bool check_access, bool nonnull,
601 		 tsubst_flags_t complain)
602 {
603   tree binfo;
604   tree object_type;
605 
606   if (TYPE_PTR_P (TREE_TYPE (object)))
607     {
608       object_type = TREE_TYPE (TREE_TYPE (object));
609       type = TREE_TYPE (type);
610     }
611   else
612     object_type = TREE_TYPE (object);
613 
614   binfo = lookup_base (object_type, type, check_access ? ba_check : ba_unique,
615 		       NULL, complain);
616   if (!binfo || binfo == error_mark_node)
617     return error_mark_node;
618 
619   return build_base_path (PLUS_EXPR, object, binfo, nonnull, complain);
620 }
621 
622 /* EXPR is an expression with unqualified class type.  BASE is a base
623    binfo of that class type.  Returns EXPR, converted to the BASE
624    type.  This function assumes that EXPR is the most derived class;
625    therefore virtual bases can be found at their static offsets.  */
626 
627 tree
convert_to_base_statically(tree expr,tree base)628 convert_to_base_statically (tree expr, tree base)
629 {
630   tree expr_type;
631 
632   expr_type = TREE_TYPE (expr);
633   if (!SAME_BINFO_TYPE_P (BINFO_TYPE (base), expr_type))
634     {
635       /* If this is a non-empty base, use a COMPONENT_REF.  */
636       if (!is_empty_class (BINFO_TYPE (base)))
637 	return build_simple_base_path (expr, base);
638 
639       /* We use fold_build2 and fold_convert below to simplify the trees
640 	 provided to the optimizers.  It is not safe to call these functions
641 	 when processing a template because they do not handle C++-specific
642 	 trees.  */
643       gcc_assert (!processing_template_decl);
644       expr = cp_build_addr_expr (expr, tf_warning_or_error);
645       if (!integer_zerop (BINFO_OFFSET (base)))
646         expr = fold_build_pointer_plus_loc (input_location,
647 					    expr, BINFO_OFFSET (base));
648       expr = fold_convert (build_pointer_type (BINFO_TYPE (base)), expr);
649       expr = build_fold_indirect_ref_loc (input_location, expr);
650     }
651 
652   return expr;
653 }
654 
655 
656 tree
build_vfield_ref(tree datum,tree type)657 build_vfield_ref (tree datum, tree type)
658 {
659   tree vfield, vcontext;
660 
661   if (datum == error_mark_node
662       /* Can happen in case of duplicate base types (c++/59082).  */
663       || !TYPE_VFIELD (type))
664     return error_mark_node;
665 
666   /* First, convert to the requested type.  */
667   if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (datum), type))
668     datum = convert_to_base (datum, type, /*check_access=*/false,
669 			     /*nonnull=*/true, tf_warning_or_error);
670 
671   /* Second, the requested type may not be the owner of its own vptr.
672      If not, convert to the base class that owns it.  We cannot use
673      convert_to_base here, because VCONTEXT may appear more than once
674      in the inheritance hierarchy of TYPE, and thus direct conversion
675      between the types may be ambiguous.  Following the path back up
676      one step at a time via primary bases avoids the problem.  */
677   vfield = TYPE_VFIELD (type);
678   vcontext = DECL_CONTEXT (vfield);
679   while (!same_type_ignoring_top_level_qualifiers_p (vcontext, type))
680     {
681       datum = build_simple_base_path (datum, CLASSTYPE_PRIMARY_BINFO (type));
682       type = TREE_TYPE (datum);
683     }
684 
685   return build3 (COMPONENT_REF, TREE_TYPE (vfield), datum, vfield, NULL_TREE);
686 }
687 
688 /* Given an object INSTANCE, return an expression which yields the
689    vtable element corresponding to INDEX.  There are many special
690    cases for INSTANCE which we take care of here, mainly to avoid
691    creating extra tree nodes when we don't have to.  */
692 
693 static tree
build_vtbl_ref_1(tree instance,tree idx)694 build_vtbl_ref_1 (tree instance, tree idx)
695 {
696   tree aref;
697   tree vtbl = NULL_TREE;
698 
699   /* Try to figure out what a reference refers to, and
700      access its virtual function table directly.  */
701 
702   int cdtorp = 0;
703   tree fixed_type = fixed_type_or_null (instance, NULL, &cdtorp);
704 
705   tree basetype = non_reference (TREE_TYPE (instance));
706 
707   if (fixed_type && !cdtorp)
708     {
709       tree binfo = lookup_base (fixed_type, basetype,
710 				ba_unique, NULL, tf_none);
711       if (binfo && binfo != error_mark_node)
712 	vtbl = unshare_expr (BINFO_VTABLE (binfo));
713     }
714 
715   if (!vtbl)
716     vtbl = build_vfield_ref (instance, basetype);
717 
718   aref = build_array_ref (input_location, vtbl, idx);
719   TREE_CONSTANT (aref) |= TREE_CONSTANT (vtbl) && TREE_CONSTANT (idx);
720 
721   return aref;
722 }
723 
724 tree
build_vtbl_ref(tree instance,tree idx)725 build_vtbl_ref (tree instance, tree idx)
726 {
727   tree aref = build_vtbl_ref_1 (instance, idx);
728 
729   return aref;
730 }
731 
732 /* Given a stable object pointer INSTANCE_PTR, return an expression which
733    yields a function pointer corresponding to vtable element INDEX.  */
734 
735 tree
build_vfn_ref(tree instance_ptr,tree idx)736 build_vfn_ref (tree instance_ptr, tree idx)
737 {
738   tree aref;
739 
740   aref = build_vtbl_ref_1 (cp_build_fold_indirect_ref (instance_ptr),
741                            idx);
742 
743   /* When using function descriptors, the address of the
744      vtable entry is treated as a function pointer.  */
745   if (TARGET_VTABLE_USES_DESCRIPTORS)
746     aref = build1 (NOP_EXPR, TREE_TYPE (aref),
747 		   cp_build_addr_expr (aref, tf_warning_or_error));
748 
749   /* Remember this as a method reference, for later devirtualization.  */
750   aref = build3 (OBJ_TYPE_REF, TREE_TYPE (aref), aref, instance_ptr, idx);
751 
752   return aref;
753 }
754 
755 /* Return the name of the virtual function table (as an IDENTIFIER_NODE)
756    for the given TYPE.  */
757 
758 static tree
get_vtable_name(tree type)759 get_vtable_name (tree type)
760 {
761   return mangle_vtbl_for_type (type);
762 }
763 
764 /* DECL is an entity associated with TYPE, like a virtual table or an
765    implicitly generated constructor.  Determine whether or not DECL
766    should have external or internal linkage at the object file
767    level.  This routine does not deal with COMDAT linkage and other
768    similar complexities; it simply sets TREE_PUBLIC if it possible for
769    entities in other translation units to contain copies of DECL, in
770    the abstract.  */
771 
772 void
set_linkage_according_to_type(tree,tree decl)773 set_linkage_according_to_type (tree /*type*/, tree decl)
774 {
775   TREE_PUBLIC (decl) = 1;
776   determine_visibility (decl);
777 }
778 
779 /* Create a VAR_DECL for a primary or secondary vtable for CLASS_TYPE.
780    (For a secondary vtable for B-in-D, CLASS_TYPE should be D, not B.)
781    Use NAME for the name of the vtable, and VTABLE_TYPE for its type.  */
782 
783 static tree
build_vtable(tree class_type,tree name,tree vtable_type)784 build_vtable (tree class_type, tree name, tree vtable_type)
785 {
786   tree decl;
787 
788   decl = build_lang_decl (VAR_DECL, name, vtable_type);
789   /* vtable names are already mangled; give them their DECL_ASSEMBLER_NAME
790      now to avoid confusion in mangle_decl.  */
791   SET_DECL_ASSEMBLER_NAME (decl, name);
792   DECL_CONTEXT (decl) = class_type;
793   DECL_ARTIFICIAL (decl) = 1;
794   TREE_STATIC (decl) = 1;
795   TREE_READONLY (decl) = 1;
796   DECL_VIRTUAL_P (decl) = 1;
797   SET_DECL_ALIGN (decl, TARGET_VTABLE_ENTRY_ALIGN);
798   DECL_USER_ALIGN (decl) = true;
799   DECL_VTABLE_OR_VTT_P (decl) = 1;
800   set_linkage_according_to_type (class_type, decl);
801   /* The vtable has not been defined -- yet.  */
802   DECL_EXTERNAL (decl) = 1;
803   DECL_NOT_REALLY_EXTERN (decl) = 1;
804 
805   /* Mark the VAR_DECL node representing the vtable itself as a
806      "gratuitous" one, thereby forcing dwarfout.c to ignore it.  It
807      is rather important that such things be ignored because any
808      effort to actually generate DWARF for them will run into
809      trouble when/if we encounter code like:
810 
811      #pragma interface
812      struct S { virtual void member (); };
813 
814      because the artificial declaration of the vtable itself (as
815      manufactured by the g++ front end) will say that the vtable is
816      a static member of `S' but only *after* the debug output for
817      the definition of `S' has already been output.  This causes
818      grief because the DWARF entry for the definition of the vtable
819      will try to refer back to an earlier *declaration* of the
820      vtable as a static member of `S' and there won't be one.  We
821      might be able to arrange to have the "vtable static member"
822      attached to the member list for `S' before the debug info for
823      `S' get written (which would solve the problem) but that would
824      require more intrusive changes to the g++ front end.  */
825   DECL_IGNORED_P (decl) = 1;
826 
827   return decl;
828 }
829 
830 /* Get the VAR_DECL of the vtable for TYPE. TYPE need not be polymorphic,
831    or even complete.  If this does not exist, create it.  If COMPLETE is
832    nonzero, then complete the definition of it -- that will render it
833    impossible to actually build the vtable, but is useful to get at those
834    which are known to exist in the runtime.  */
835 
836 tree
get_vtable_decl(tree type,int complete)837 get_vtable_decl (tree type, int complete)
838 {
839   tree decl;
840 
841   if (CLASSTYPE_VTABLES (type))
842     return CLASSTYPE_VTABLES (type);
843 
844   decl = build_vtable (type, get_vtable_name (type), vtbl_type_node);
845   CLASSTYPE_VTABLES (type) = decl;
846 
847   if (complete)
848     {
849       DECL_EXTERNAL (decl) = 1;
850       cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
851     }
852 
853   return decl;
854 }
855 
856 /* Build the primary virtual function table for TYPE.  If BINFO is
857    non-NULL, build the vtable starting with the initial approximation
858    that it is the same as the one which is the head of the association
859    list.  Returns a nonzero value if a new vtable is actually
860    created.  */
861 
862 static int
build_primary_vtable(tree binfo,tree type)863 build_primary_vtable (tree binfo, tree type)
864 {
865   tree decl;
866   tree virtuals;
867 
868   decl = get_vtable_decl (type, /*complete=*/0);
869 
870   if (binfo)
871     {
872       if (BINFO_NEW_VTABLE_MARKED (binfo))
873 	/* We have already created a vtable for this base, so there's
874 	   no need to do it again.  */
875 	return 0;
876 
877       virtuals = copy_list (BINFO_VIRTUALS (binfo));
878       TREE_TYPE (decl) = TREE_TYPE (get_vtbl_decl_for_binfo (binfo));
879       DECL_SIZE (decl) = TYPE_SIZE (TREE_TYPE (decl));
880       DECL_SIZE_UNIT (decl) = TYPE_SIZE_UNIT (TREE_TYPE (decl));
881     }
882   else
883     {
884       gcc_assert (TREE_TYPE (decl) == vtbl_type_node);
885       virtuals = NULL_TREE;
886     }
887 
888   /* Initialize the association list for this type, based
889      on our first approximation.  */
890   BINFO_VTABLE (TYPE_BINFO (type)) = decl;
891   BINFO_VIRTUALS (TYPE_BINFO (type)) = virtuals;
892   SET_BINFO_NEW_VTABLE_MARKED (TYPE_BINFO (type));
893   return 1;
894 }
895 
896 /* Give BINFO a new virtual function table which is initialized
897    with a skeleton-copy of its original initialization.  The only
898    entry that changes is the `delta' entry, so we can really
899    share a lot of structure.
900 
901    FOR_TYPE is the most derived type which caused this table to
902    be needed.
903 
904    Returns nonzero if we haven't met BINFO before.
905 
906    The order in which vtables are built (by calling this function) for
907    an object must remain the same, otherwise a binary incompatibility
908    can result.  */
909 
910 static int
build_secondary_vtable(tree binfo)911 build_secondary_vtable (tree binfo)
912 {
913   if (BINFO_NEW_VTABLE_MARKED (binfo))
914     /* We already created a vtable for this base.  There's no need to
915        do it again.  */
916     return 0;
917 
918   /* Remember that we've created a vtable for this BINFO, so that we
919      don't try to do so again.  */
920   SET_BINFO_NEW_VTABLE_MARKED (binfo);
921 
922   /* Make fresh virtual list, so we can smash it later.  */
923   BINFO_VIRTUALS (binfo) = copy_list (BINFO_VIRTUALS (binfo));
924 
925   /* Secondary vtables are laid out as part of the same structure as
926      the primary vtable.  */
927   BINFO_VTABLE (binfo) = NULL_TREE;
928   return 1;
929 }
930 
931 /* Create a new vtable for BINFO which is the hierarchy dominated by
932    T. Return nonzero if we actually created a new vtable.  */
933 
934 static int
make_new_vtable(tree t,tree binfo)935 make_new_vtable (tree t, tree binfo)
936 {
937   if (binfo == TYPE_BINFO (t))
938     /* In this case, it is *type*'s vtable we are modifying.  We start
939        with the approximation that its vtable is that of the
940        immediate base class.  */
941     return build_primary_vtable (binfo, t);
942   else
943     /* This is our very own copy of `basetype' to play with.  Later,
944        we will fill in all the virtual functions that override the
945        virtual functions in these base classes which are not defined
946        by the current type.  */
947     return build_secondary_vtable (binfo);
948 }
949 
950 /* Make *VIRTUALS, an entry on the BINFO_VIRTUALS list for BINFO
951    (which is in the hierarchy dominated by T) list FNDECL as its
952    BV_FN.  DELTA is the required constant adjustment from the `this'
953    pointer where the vtable entry appears to the `this' required when
954    the function is actually called.  */
955 
956 static void
modify_vtable_entry(tree t,tree binfo,tree fndecl,tree delta,tree * virtuals)957 modify_vtable_entry (tree t,
958 		     tree binfo,
959 		     tree fndecl,
960 		     tree delta,
961 		     tree *virtuals)
962 {
963   tree v;
964 
965   v = *virtuals;
966 
967   if (fndecl != BV_FN (v)
968       || !tree_int_cst_equal (delta, BV_DELTA (v)))
969     {
970       /* We need a new vtable for BINFO.  */
971       if (make_new_vtable (t, binfo))
972 	{
973 	  /* If we really did make a new vtable, we also made a copy
974 	     of the BINFO_VIRTUALS list.  Now, we have to find the
975 	     corresponding entry in that list.  */
976 	  *virtuals = BINFO_VIRTUALS (binfo);
977 	  while (BV_FN (*virtuals) != BV_FN (v))
978 	    *virtuals = TREE_CHAIN (*virtuals);
979 	  v = *virtuals;
980 	}
981 
982       BV_DELTA (v) = delta;
983       BV_VCALL_INDEX (v) = NULL_TREE;
984       BV_FN (v) = fndecl;
985     }
986 }
987 
988 
989 /* Add method METHOD to class TYPE.  If VIA_USING indicates whether
990    METHOD is being injected via a using_decl.  Returns true if the
991    method could be added to the method vec.  */
992 
993 bool
add_method(tree type,tree method,bool via_using)994 add_method (tree type, tree method, bool via_using)
995 {
996   if (method == error_mark_node)
997     return false;
998 
999   gcc_assert (!DECL_EXTERN_C_P (method));
1000 
1001   tree *slot = find_member_slot (type, DECL_NAME (method));
1002   tree current_fns = slot ? *slot : NULL_TREE;
1003 
1004   /* Check to see if we've already got this method.  */
1005   for (ovl_iterator iter (current_fns); iter; ++iter)
1006     {
1007       tree fn = *iter;
1008       tree fn_type;
1009       tree method_type;
1010       tree parms1;
1011       tree parms2;
1012 
1013       if (TREE_CODE (fn) != TREE_CODE (method))
1014 	continue;
1015 
1016       /* Two using-declarations can coexist, we'll complain about ambiguity in
1017 	 overload resolution.  */
1018       if (via_using && iter.using_p ()
1019 	  /* Except handle inherited constructors specially.  */
1020 	  && ! DECL_CONSTRUCTOR_P (fn))
1021 	continue;
1022 
1023       /* [over.load] Member function declarations with the
1024 	 same name and the same parameter types cannot be
1025 	 overloaded if any of them is a static member
1026 	 function declaration.
1027 
1028 	 [over.load] Member function declarations with the same name and
1029 	 the same parameter-type-list as well as member function template
1030 	 declarations with the same name, the same parameter-type-list, and
1031 	 the same template parameter lists cannot be overloaded if any of
1032 	 them, but not all, have a ref-qualifier.
1033 
1034 	 [namespace.udecl] When a using-declaration brings names
1035 	 from a base class into a derived class scope, member
1036 	 functions in the derived class override and/or hide member
1037 	 functions with the same name and parameter types in a base
1038 	 class (rather than conflicting).  */
1039       fn_type = TREE_TYPE (fn);
1040       method_type = TREE_TYPE (method);
1041       parms1 = TYPE_ARG_TYPES (fn_type);
1042       parms2 = TYPE_ARG_TYPES (method_type);
1043 
1044       /* Compare the quals on the 'this' parm.  Don't compare
1045 	 the whole types, as used functions are treated as
1046 	 coming from the using class in overload resolution.  */
1047       if (! DECL_STATIC_FUNCTION_P (fn)
1048 	  && ! DECL_STATIC_FUNCTION_P (method)
1049 	  /* Either both or neither need to be ref-qualified for
1050 	     differing quals to allow overloading.  */
1051 	  && (FUNCTION_REF_QUALIFIED (fn_type)
1052 	      == FUNCTION_REF_QUALIFIED (method_type))
1053 	  && (type_memfn_quals (fn_type) != type_memfn_quals (method_type)
1054 	      || type_memfn_rqual (fn_type) != type_memfn_rqual (method_type)))
1055 	  continue;
1056 
1057       /* For templates, the return type and template parameters
1058 	 must be identical.  */
1059       if (TREE_CODE (fn) == TEMPLATE_DECL
1060 	  && (!same_type_p (TREE_TYPE (fn_type),
1061 			    TREE_TYPE (method_type))
1062 	      || !comp_template_parms (DECL_TEMPLATE_PARMS (fn),
1063 				       DECL_TEMPLATE_PARMS (method))))
1064 	continue;
1065 
1066       if (! DECL_STATIC_FUNCTION_P (fn))
1067 	parms1 = TREE_CHAIN (parms1);
1068       if (! DECL_STATIC_FUNCTION_P (method))
1069 	parms2 = TREE_CHAIN (parms2);
1070 
1071       /* Bring back parameters omitted from an inherited ctor.  */
1072       if (ctor_omit_inherited_parms (fn))
1073 	parms1 = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (fn));
1074       if (ctor_omit_inherited_parms (method))
1075 	parms2 = FUNCTION_FIRST_USER_PARMTYPE (DECL_ORIGIN (method));
1076 
1077       if (compparms (parms1, parms2)
1078 	  && (!DECL_CONV_FN_P (fn)
1079 	      || same_type_p (TREE_TYPE (fn_type),
1080 			      TREE_TYPE (method_type)))
1081           && equivalently_constrained (fn, method))
1082 	{
1083 	  /* If these are versions of the same function, process and
1084 	     move on.  */
1085 	  if (TREE_CODE (fn) == FUNCTION_DECL
1086 	      && maybe_version_functions (method, fn, true))
1087 	    continue;
1088 
1089 	  if (DECL_INHERITED_CTOR (method))
1090 	    {
1091 	      if (DECL_INHERITED_CTOR (fn))
1092 		{
1093 		  tree basem = DECL_INHERITED_CTOR_BASE (method);
1094 		  tree basef = DECL_INHERITED_CTOR_BASE (fn);
1095 		  if (flag_new_inheriting_ctors)
1096 		    {
1097 		      if (basem == basef)
1098 			{
1099 			  /* Inheriting the same constructor along different
1100 			     paths, combine them.  */
1101 			  SET_DECL_INHERITED_CTOR
1102 			    (fn, ovl_make (DECL_INHERITED_CTOR (method),
1103 					   DECL_INHERITED_CTOR (fn)));
1104 			  /* And discard the new one.  */
1105 			  return false;
1106 			}
1107 		      else
1108 			/* Inherited ctors can coexist until overload
1109 			   resolution.  */
1110 			continue;
1111 		    }
1112 		  error_at (DECL_SOURCE_LOCATION (method),
1113 			    "%q#D conflicts with version inherited from %qT",
1114 			    method, basef);
1115 		  inform (DECL_SOURCE_LOCATION (fn),
1116 			  "version inherited from %qT declared here",
1117 			  basef);
1118 		}
1119 	      /* Otherwise defer to the other function.  */
1120 	      return false;
1121 	    }
1122 
1123 	  if (via_using)
1124 	    /* Defer to the local function.  */
1125 	    return false;
1126 	  else if (flag_new_inheriting_ctors
1127 		   && DECL_INHERITED_CTOR (fn))
1128 	    {
1129 	      /* Remove the inherited constructor.  */
1130 	      current_fns = iter.remove_node (current_fns);
1131 	      continue;
1132 	    }
1133 	  else
1134 	    {
1135 	      error_at (DECL_SOURCE_LOCATION (method),
1136 			"%q#D cannot be overloaded with %q#D", method, fn);
1137 	      inform (DECL_SOURCE_LOCATION (fn),
1138 		      "previous declaration %q#D", fn);
1139 	      return false;
1140 	    }
1141 	}
1142     }
1143 
1144   current_fns = ovl_insert (method, current_fns, via_using);
1145 
1146   if (!COMPLETE_TYPE_P (type) && !DECL_CONV_FN_P (method)
1147       && !push_class_level_binding (DECL_NAME (method), current_fns))
1148     return false;
1149 
1150   if (!slot)
1151     slot = add_member_slot (type, DECL_NAME (method));
1152 
1153   /* Maintain TYPE_HAS_USER_CONSTRUCTOR, etc.  */
1154   grok_special_member_properties (method);
1155 
1156   *slot = current_fns;
1157 
1158   return true;
1159 }
1160 
1161 /* Subroutines of finish_struct.  */
1162 
1163 /* Change the access of FDECL to ACCESS in T.  Return 1 if change was
1164    legit, otherwise return 0.  */
1165 
1166 static int
alter_access(tree t,tree fdecl,tree access)1167 alter_access (tree t, tree fdecl, tree access)
1168 {
1169   tree elem;
1170 
1171   retrofit_lang_decl (fdecl);
1172 
1173   gcc_assert (!DECL_DISCRIMINATOR_P (fdecl));
1174 
1175   elem = purpose_member (t, DECL_ACCESS (fdecl));
1176   if (elem)
1177     {
1178       if (TREE_VALUE (elem) != access)
1179 	{
1180 	  if (TREE_CODE (TREE_TYPE (fdecl)) == FUNCTION_DECL)
1181 	    error ("conflicting access specifications for method"
1182 		   " %q+D, ignored", TREE_TYPE (fdecl));
1183 	  else
1184 	    error ("conflicting access specifications for field %qE, ignored",
1185 		   DECL_NAME (fdecl));
1186 	}
1187       else
1188 	{
1189 	  /* They're changing the access to the same thing they changed
1190 	     it to before.  That's OK.  */
1191 	  ;
1192 	}
1193     }
1194   else
1195     {
1196       perform_or_defer_access_check (TYPE_BINFO (t), fdecl, fdecl,
1197 				     tf_warning_or_error);
1198       DECL_ACCESS (fdecl) = tree_cons (t, access, DECL_ACCESS (fdecl));
1199       return 1;
1200     }
1201   return 0;
1202 }
1203 
1204 /* Return the access node for DECL's access in its enclosing class.  */
1205 
1206 tree
declared_access(tree decl)1207 declared_access (tree decl)
1208 {
1209   return (TREE_PRIVATE (decl) ? access_private_node
1210 	  : TREE_PROTECTED (decl) ? access_protected_node
1211 	  : access_public_node);
1212 }
1213 
1214 /* Process the USING_DECL, which is a member of T.  */
1215 
1216 static void
handle_using_decl(tree using_decl,tree t)1217 handle_using_decl (tree using_decl, tree t)
1218 {
1219   tree decl = USING_DECL_DECLS (using_decl);
1220   tree name = DECL_NAME (using_decl);
1221   tree access = declared_access (using_decl);
1222   tree flist = NULL_TREE;
1223   tree old_value;
1224 
1225   gcc_assert (!processing_template_decl && decl);
1226 
1227   old_value = lookup_member (t, name, /*protect=*/0, /*want_type=*/false,
1228 			     tf_warning_or_error);
1229   if (old_value)
1230     {
1231       old_value = OVL_FIRST (old_value);
1232 
1233       if (DECL_P (old_value) && DECL_CONTEXT (old_value) == t)
1234 	/* OK */;
1235       else
1236 	old_value = NULL_TREE;
1237     }
1238 
1239   cp_emit_debug_info_for_using (decl, t);
1240 
1241   if (is_overloaded_fn (decl))
1242     flist = decl;
1243 
1244   if (! old_value)
1245     ;
1246   else if (is_overloaded_fn (old_value))
1247     {
1248       if (flist)
1249 	/* It's OK to use functions from a base when there are functions with
1250 	   the same name already present in the current class.  */;
1251       else
1252 	{
1253 	  error_at (DECL_SOURCE_LOCATION (using_decl), "%qD invalid in %q#T "
1254 		    "because of local method %q#D with same name",
1255 		    using_decl, t, old_value);
1256 	  inform (DECL_SOURCE_LOCATION (old_value),
1257 		  "local method %q#D declared here", old_value);
1258 	  return;
1259 	}
1260     }
1261   else if (!DECL_ARTIFICIAL (old_value))
1262     {
1263       error_at (DECL_SOURCE_LOCATION (using_decl), "%qD invalid in %q#T "
1264 		"because of local member %q#D with same name",
1265 		using_decl, t, old_value);
1266       inform (DECL_SOURCE_LOCATION (old_value),
1267 	      "local member %q#D declared here", old_value);
1268       return;
1269     }
1270 
1271   /* Make type T see field decl FDECL with access ACCESS.  */
1272   if (flist)
1273     for (ovl_iterator iter (flist); iter; ++iter)
1274       {
1275 	add_method (t, *iter, true);
1276 	alter_access (t, *iter, access);
1277       }
1278   else
1279     alter_access (t, decl, access);
1280 }
1281 
1282 /* Data structure for find_abi_tags_r, below.  */
1283 
1284 struct abi_tag_data
1285 {
1286   tree t;		// The type that we're checking for missing tags.
1287   tree subob;		// The subobject of T that we're getting tags from.
1288   tree tags; // error_mark_node for diagnostics, or a list of missing tags.
1289 };
1290 
1291 /* Subroutine of find_abi_tags_r. Handle a single TAG found on the class TP
1292    in the context of P.  TAG can be either an identifier (the DECL_NAME of
1293    a tag NAMESPACE_DECL) or a STRING_CST (a tag attribute).  */
1294 
1295 static void
check_tag(tree tag,tree id,tree * tp,abi_tag_data * p)1296 check_tag (tree tag, tree id, tree *tp, abi_tag_data *p)
1297 {
1298   if (!IDENTIFIER_MARKED (id))
1299     {
1300       if (p->tags != error_mark_node)
1301 	{
1302 	  /* We're collecting tags from template arguments or from
1303 	     the type of a variable or function return type.  */
1304 	  p->tags = tree_cons (NULL_TREE, tag, p->tags);
1305 
1306 	  /* Don't inherit this tag multiple times.  */
1307 	  IDENTIFIER_MARKED (id) = true;
1308 
1309 	  if (TYPE_P (p->t))
1310 	    {
1311 	      /* Tags inherited from type template arguments are only used
1312 		 to avoid warnings.  */
1313 	      ABI_TAG_IMPLICIT (p->tags) = true;
1314 	      return;
1315 	    }
1316 	  /* For functions and variables we want to warn, too.  */
1317 	}
1318 
1319       /* Otherwise we're diagnosing missing tags.  */
1320       if (TREE_CODE (p->t) == FUNCTION_DECL)
1321 	{
1322 	  if (warning (OPT_Wabi_tag, "%qD inherits the %E ABI tag "
1323 		       "that %qT (used in its return type) has",
1324 		       p->t, tag, *tp))
1325 	    inform (location_of (*tp), "%qT declared here", *tp);
1326 	}
1327       else if (VAR_P (p->t))
1328 	{
1329 	  if (warning (OPT_Wabi_tag, "%qD inherits the %E ABI tag "
1330 		       "that %qT (used in its type) has", p->t, tag, *tp))
1331 	    inform (location_of (*tp), "%qT declared here", *tp);
1332 	}
1333       else if (TYPE_P (p->subob))
1334 	{
1335 	  if (warning (OPT_Wabi_tag, "%qT does not have the %E ABI tag "
1336 		       "that base %qT has", p->t, tag, p->subob))
1337 	    inform (location_of (p->subob), "%qT declared here",
1338 		    p->subob);
1339 	}
1340       else
1341 	{
1342 	  if (warning (OPT_Wabi_tag, "%qT does not have the %E ABI tag "
1343 		       "that %qT (used in the type of %qD) has",
1344 		       p->t, tag, *tp, p->subob))
1345 	    {
1346 	      inform (location_of (p->subob), "%qD declared here",
1347 		      p->subob);
1348 	      inform (location_of (*tp), "%qT declared here", *tp);
1349 	    }
1350 	}
1351     }
1352 }
1353 
1354 /* Find all the ABI tags in the attribute list ATTR and either call
1355    check_tag (if TP is non-null) or set IDENTIFIER_MARKED to val.  */
1356 
1357 static void
mark_or_check_attr_tags(tree attr,tree * tp,abi_tag_data * p,bool val)1358 mark_or_check_attr_tags (tree attr, tree *tp, abi_tag_data *p, bool val)
1359 {
1360   if (!attr)
1361     return;
1362   for (; (attr = lookup_attribute ("abi_tag", attr));
1363        attr = TREE_CHAIN (attr))
1364     for (tree list = TREE_VALUE (attr); list;
1365 	 list = TREE_CHAIN (list))
1366       {
1367 	tree tag = TREE_VALUE (list);
1368 	tree id = get_identifier (TREE_STRING_POINTER (tag));
1369 	if (tp)
1370 	  check_tag (tag, id, tp, p);
1371 	else
1372 	  IDENTIFIER_MARKED (id) = val;
1373       }
1374 }
1375 
1376 /* Find all the ABI tags on T and its enclosing scopes and either call
1377    check_tag (if TP is non-null) or set IDENTIFIER_MARKED to val.  */
1378 
1379 static void
mark_or_check_tags(tree t,tree * tp,abi_tag_data * p,bool val)1380 mark_or_check_tags (tree t, tree *tp, abi_tag_data *p, bool val)
1381 {
1382   while (t != global_namespace)
1383     {
1384       tree attr;
1385       if (TYPE_P (t))
1386 	{
1387 	  attr = TYPE_ATTRIBUTES (t);
1388 	  t = CP_TYPE_CONTEXT (t);
1389 	}
1390       else
1391 	{
1392 	  attr = DECL_ATTRIBUTES (t);
1393 	  t = CP_DECL_CONTEXT (t);
1394 	}
1395       mark_or_check_attr_tags (attr, tp, p, val);
1396     }
1397 }
1398 
1399 /* walk_tree callback for check_abi_tags: if the type at *TP involves any
1400    types with ABI tags, add the corresponding identifiers to the VEC in
1401    *DATA and set IDENTIFIER_MARKED.  */
1402 
1403 static tree
find_abi_tags_r(tree * tp,int * walk_subtrees,void * data)1404 find_abi_tags_r (tree *tp, int *walk_subtrees, void *data)
1405 {
1406   if (!OVERLOAD_TYPE_P (*tp))
1407     return NULL_TREE;
1408 
1409   /* walk_tree shouldn't be walking into any subtrees of a RECORD_TYPE
1410      anyway, but let's make sure of it.  */
1411   *walk_subtrees = false;
1412 
1413   abi_tag_data *p = static_cast<struct abi_tag_data*>(data);
1414 
1415   mark_or_check_tags (*tp, tp, p, false);
1416 
1417   return NULL_TREE;
1418 }
1419 
1420 /* walk_tree callback for mark_abi_tags: if *TP is a class, set
1421    IDENTIFIER_MARKED on its ABI tags.  */
1422 
1423 static tree
mark_abi_tags_r(tree * tp,int * walk_subtrees,void * data)1424 mark_abi_tags_r (tree *tp, int *walk_subtrees, void *data)
1425 {
1426   if (!OVERLOAD_TYPE_P (*tp))
1427     return NULL_TREE;
1428 
1429   /* walk_tree shouldn't be walking into any subtrees of a RECORD_TYPE
1430      anyway, but let's make sure of it.  */
1431   *walk_subtrees = false;
1432 
1433   bool *valp = static_cast<bool*>(data);
1434 
1435   mark_or_check_tags (*tp, NULL, NULL, *valp);
1436 
1437   return NULL_TREE;
1438 }
1439 
1440 /* Set IDENTIFIER_MARKED on all the ABI tags on T and its enclosing
1441    scopes.  */
1442 
1443 static void
mark_abi_tags(tree t,bool val)1444 mark_abi_tags (tree t, bool val)
1445 {
1446   mark_or_check_tags (t, NULL, NULL, val);
1447   if (DECL_P (t))
1448     {
1449       if (DECL_LANG_SPECIFIC (t) && DECL_USE_TEMPLATE (t)
1450 	  && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)))
1451 	{
1452 	  /* Template arguments are part of the signature.  */
1453 	  tree level = INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (t));
1454 	  for (int j = 0; j < TREE_VEC_LENGTH (level); ++j)
1455 	    {
1456 	      tree arg = TREE_VEC_ELT (level, j);
1457 	      cp_walk_tree_without_duplicates (&arg, mark_abi_tags_r, &val);
1458 	    }
1459 	}
1460       if (TREE_CODE (t) == FUNCTION_DECL)
1461 	/* A function's parameter types are part of the signature, so
1462 	   we don't need to inherit any tags that are also in them.  */
1463 	for (tree arg = FUNCTION_FIRST_USER_PARMTYPE (t); arg;
1464 	     arg = TREE_CHAIN (arg))
1465 	  cp_walk_tree_without_duplicates (&TREE_VALUE (arg),
1466 					   mark_abi_tags_r, &val);
1467     }
1468 }
1469 
1470 /* Check that T has all the ABI tags that subobject SUBOB has, or
1471    warn if not.  If T is a (variable or function) declaration, also
1472    return any missing tags, and add them to T if JUST_CHECKING is false.  */
1473 
1474 static tree
1475 check_abi_tags (tree t, tree subob, bool just_checking = false)
1476 {
1477   bool inherit = DECL_P (t);
1478 
1479   if (!inherit && !warn_abi_tag)
1480     return NULL_TREE;
1481 
1482   tree decl = TYPE_P (t) ? TYPE_NAME (t) : t;
1483   if (!TREE_PUBLIC (decl))
1484     /* No need to worry about things local to this TU.  */
1485     return NULL_TREE;
1486 
1487   mark_abi_tags (t, true);
1488 
1489   tree subtype = TYPE_P (subob) ? subob : TREE_TYPE (subob);
1490   struct abi_tag_data data = { t, subob, error_mark_node };
1491   if (inherit)
1492     data.tags = NULL_TREE;
1493 
1494   cp_walk_tree_without_duplicates (&subtype, find_abi_tags_r, &data);
1495 
1496   if (!(inherit && data.tags))
1497     /* We don't need to do anything with data.tags.  */;
1498   else if (just_checking)
1499     for (tree t = data.tags; t; t = TREE_CHAIN (t))
1500       {
1501 	tree id = get_identifier (TREE_STRING_POINTER (TREE_VALUE (t)));
1502 	IDENTIFIER_MARKED (id) = false;
1503       }
1504   else
1505     {
1506       tree attr = lookup_attribute ("abi_tag", DECL_ATTRIBUTES (t));
1507       if (attr)
1508 	TREE_VALUE (attr) = chainon (data.tags, TREE_VALUE (attr));
1509       else
1510 	DECL_ATTRIBUTES (t)
1511 	  = tree_cons (get_identifier ("abi_tag"), data.tags,
1512 		       DECL_ATTRIBUTES (t));
1513     }
1514 
1515   mark_abi_tags (t, false);
1516 
1517   return data.tags;
1518 }
1519 
1520 /* Check that DECL has all the ABI tags that are used in parts of its type
1521    that are not reflected in its mangled name.  */
1522 
1523 void
check_abi_tags(tree decl)1524 check_abi_tags (tree decl)
1525 {
1526   if (VAR_P (decl))
1527     check_abi_tags (decl, TREE_TYPE (decl));
1528   else if (TREE_CODE (decl) == FUNCTION_DECL
1529 	   && !DECL_CONV_FN_P (decl)
1530 	   && !mangle_return_type_p (decl))
1531     check_abi_tags (decl, TREE_TYPE (TREE_TYPE (decl)));
1532 }
1533 
1534 /* Return any ABI tags that are used in parts of the type of DECL
1535    that are not reflected in its mangled name.  This function is only
1536    used in backward-compatible mangling for ABI <11.  */
1537 
1538 tree
missing_abi_tags(tree decl)1539 missing_abi_tags (tree decl)
1540 {
1541   if (VAR_P (decl))
1542     return check_abi_tags (decl, TREE_TYPE (decl), true);
1543   else if (TREE_CODE (decl) == FUNCTION_DECL
1544 	   /* Don't check DECL_CONV_FN_P here like we do in check_abi_tags, so
1545 	      that we can use this function for setting need_abi_warning
1546 	      regardless of the current flag_abi_version.  */
1547 	   && !mangle_return_type_p (decl))
1548     return check_abi_tags (decl, TREE_TYPE (TREE_TYPE (decl)), true);
1549   else
1550     return NULL_TREE;
1551 }
1552 
1553 void
inherit_targ_abi_tags(tree t)1554 inherit_targ_abi_tags (tree t)
1555 {
1556   if (!CLASS_TYPE_P (t)
1557       || CLASSTYPE_TEMPLATE_INFO (t) == NULL_TREE)
1558     return;
1559 
1560   mark_abi_tags (t, true);
1561 
1562   tree args = CLASSTYPE_TI_ARGS (t);
1563   struct abi_tag_data data = { t, NULL_TREE, NULL_TREE };
1564   for (int i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
1565     {
1566       tree level = TMPL_ARGS_LEVEL (args, i+1);
1567       for (int j = 0; j < TREE_VEC_LENGTH (level); ++j)
1568 	{
1569 	  tree arg = TREE_VEC_ELT (level, j);
1570 	  data.subob = arg;
1571 	  cp_walk_tree_without_duplicates (&arg, find_abi_tags_r, &data);
1572 	}
1573     }
1574 
1575   // If we found some tags on our template arguments, add them to our
1576   // abi_tag attribute.
1577   if (data.tags)
1578     {
1579       tree attr = lookup_attribute ("abi_tag", TYPE_ATTRIBUTES (t));
1580       if (attr)
1581 	TREE_VALUE (attr) = chainon (data.tags, TREE_VALUE (attr));
1582       else
1583 	TYPE_ATTRIBUTES (t)
1584 	  = tree_cons (get_identifier ("abi_tag"), data.tags,
1585 		       TYPE_ATTRIBUTES (t));
1586     }
1587 
1588   mark_abi_tags (t, false);
1589 }
1590 
1591 /* Return true, iff class T has a non-virtual destructor that is
1592    accessible from outside the class heirarchy (i.e. is public, or
1593    there's a suitable friend.  */
1594 
1595 static bool
accessible_nvdtor_p(tree t)1596 accessible_nvdtor_p (tree t)
1597 {
1598   tree dtor = CLASSTYPE_DESTRUCTOR (t);
1599 
1600   /* An implicitly declared destructor is always public.  And,
1601      if it were virtual, we would have created it by now.  */
1602   if (!dtor)
1603     return true;
1604 
1605   if (DECL_VINDEX (dtor))
1606     return false; /* Virtual */
1607 
1608   if (!TREE_PRIVATE (dtor) && !TREE_PROTECTED (dtor))
1609     return true;  /* Public */
1610 
1611   if (CLASSTYPE_FRIEND_CLASSES (t)
1612       || DECL_FRIENDLIST (TYPE_MAIN_DECL (t)))
1613     return true;   /* Has friends */
1614 
1615   return false;
1616 }
1617 
1618 /* Run through the base classes of T, updating CANT_HAVE_CONST_CTOR_P,
1619    and NO_CONST_ASN_REF_P.  Also set flag bits in T based on
1620    properties of the bases.  */
1621 
1622 static void
check_bases(tree t,int * cant_have_const_ctor_p,int * no_const_asn_ref_p)1623 check_bases (tree t,
1624 	     int* cant_have_const_ctor_p,
1625 	     int* no_const_asn_ref_p)
1626 {
1627   int i;
1628   bool seen_non_virtual_nearly_empty_base_p = 0;
1629   int seen_tm_mask = 0;
1630   tree base_binfo;
1631   tree binfo;
1632   tree field = NULL_TREE;
1633 
1634   if (!CLASSTYPE_NON_STD_LAYOUT (t))
1635     for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
1636       if (TREE_CODE (field) == FIELD_DECL)
1637 	break;
1638 
1639   for (binfo = TYPE_BINFO (t), i = 0;
1640        BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
1641     {
1642       tree basetype = TREE_TYPE (base_binfo);
1643 
1644       gcc_assert (COMPLETE_TYPE_P (basetype));
1645 
1646       if (CLASSTYPE_FINAL (basetype))
1647         error ("cannot derive from %<final%> base %qT in derived type %qT",
1648                basetype, t);
1649 
1650       /* If any base class is non-literal, so is the derived class.  */
1651       if (!CLASSTYPE_LITERAL_P (basetype))
1652         CLASSTYPE_LITERAL_P (t) = false;
1653 
1654       /* If the base class doesn't have copy constructors or
1655 	 assignment operators that take const references, then the
1656 	 derived class cannot have such a member automatically
1657 	 generated.  */
1658       if (TYPE_HAS_COPY_CTOR (basetype)
1659 	  && ! TYPE_HAS_CONST_COPY_CTOR (basetype))
1660 	*cant_have_const_ctor_p = 1;
1661       if (TYPE_HAS_COPY_ASSIGN (basetype)
1662 	  && !TYPE_HAS_CONST_COPY_ASSIGN (basetype))
1663 	*no_const_asn_ref_p = 1;
1664 
1665       if (BINFO_VIRTUAL_P (base_binfo))
1666 	/* A virtual base does not effect nearly emptiness.  */
1667 	;
1668       else if (CLASSTYPE_NEARLY_EMPTY_P (basetype))
1669 	{
1670 	  if (seen_non_virtual_nearly_empty_base_p)
1671 	    /* And if there is more than one nearly empty base, then the
1672 	       derived class is not nearly empty either.  */
1673 	    CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
1674 	  else
1675 	    /* Remember we've seen one.  */
1676 	    seen_non_virtual_nearly_empty_base_p = 1;
1677 	}
1678       else if (!is_empty_class (basetype))
1679 	/* If the base class is not empty or nearly empty, then this
1680 	   class cannot be nearly empty.  */
1681 	CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
1682 
1683       /* A lot of properties from the bases also apply to the derived
1684 	 class.  */
1685       TYPE_NEEDS_CONSTRUCTING (t) |= TYPE_NEEDS_CONSTRUCTING (basetype);
1686       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t)
1687 	|= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (basetype);
1688       TYPE_HAS_COMPLEX_COPY_ASSIGN (t)
1689 	|= (TYPE_HAS_COMPLEX_COPY_ASSIGN (basetype)
1690 	    || !TYPE_HAS_COPY_ASSIGN (basetype));
1691       TYPE_HAS_COMPLEX_COPY_CTOR (t) |= (TYPE_HAS_COMPLEX_COPY_CTOR (basetype)
1692 					 || !TYPE_HAS_COPY_CTOR (basetype));
1693       TYPE_HAS_COMPLEX_MOVE_ASSIGN (t)
1694 	|= TYPE_HAS_COMPLEX_MOVE_ASSIGN (basetype);
1695       TYPE_HAS_COMPLEX_MOVE_CTOR (t) |= TYPE_HAS_COMPLEX_MOVE_CTOR (basetype);
1696       TYPE_POLYMORPHIC_P (t) |= TYPE_POLYMORPHIC_P (basetype);
1697       CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t)
1698 	|= CLASSTYPE_CONTAINS_EMPTY_CLASS_P (basetype);
1699       TYPE_HAS_COMPLEX_DFLT (t) |= (!TYPE_HAS_DEFAULT_CONSTRUCTOR (basetype)
1700 				    || TYPE_HAS_COMPLEX_DFLT (basetype));
1701       SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT
1702 	(t, CLASSTYPE_READONLY_FIELDS_NEED_INIT (t)
1703 	 | CLASSTYPE_READONLY_FIELDS_NEED_INIT (basetype));
1704       SET_CLASSTYPE_REF_FIELDS_NEED_INIT
1705 	(t, CLASSTYPE_REF_FIELDS_NEED_INIT (t)
1706 	 | CLASSTYPE_REF_FIELDS_NEED_INIT (basetype));
1707       if (TYPE_HAS_MUTABLE_P (basetype))
1708 	CLASSTYPE_HAS_MUTABLE (t) = 1;
1709 
1710       /*  A standard-layout class is a class that:
1711 	  ...
1712 	  * has no non-standard-layout base classes,  */
1713       CLASSTYPE_NON_STD_LAYOUT (t) |= CLASSTYPE_NON_STD_LAYOUT (basetype);
1714       if (!CLASSTYPE_NON_STD_LAYOUT (t))
1715 	{
1716 	  tree basefield;
1717 	  /* ...has no base classes of the same type as the first non-static
1718 	     data member...  */
1719 	  if (field && DECL_CONTEXT (field) == t
1720 	      && (same_type_ignoring_top_level_qualifiers_p
1721 		  (TREE_TYPE (field), basetype)))
1722 	    CLASSTYPE_NON_STD_LAYOUT (t) = 1;
1723 	  else
1724 	    /* ...either has no non-static data members in the most-derived
1725 	       class and at most one base class with non-static data
1726 	       members, or has no base classes with non-static data
1727 	       members */
1728 	    for (basefield = TYPE_FIELDS (basetype); basefield;
1729 		 basefield = DECL_CHAIN (basefield))
1730 	      if (TREE_CODE (basefield) == FIELD_DECL
1731 		  && !(DECL_FIELD_IS_BASE (basefield)
1732 		       && integer_zerop (DECL_SIZE (basefield))))
1733 		{
1734 		  if (field)
1735 		    CLASSTYPE_NON_STD_LAYOUT (t) = 1;
1736 		  else
1737 		    field = basefield;
1738 		  break;
1739 		}
1740 	}
1741 
1742       /* Don't bother collecting tm attributes if transactional memory
1743 	 support is not enabled.  */
1744       if (flag_tm)
1745 	{
1746 	  tree tm_attr = find_tm_attribute (TYPE_ATTRIBUTES (basetype));
1747 	  if (tm_attr)
1748 	    seen_tm_mask |= tm_attr_to_mask (tm_attr);
1749 	}
1750 
1751       check_abi_tags (t, basetype);
1752     }
1753 
1754   /* If one of the base classes had TM attributes, and the current class
1755      doesn't define its own, then the current class inherits one.  */
1756   if (seen_tm_mask && !find_tm_attribute (TYPE_ATTRIBUTES (t)))
1757     {
1758       tree tm_attr = tm_mask_to_attr (least_bit_hwi (seen_tm_mask));
1759       TYPE_ATTRIBUTES (t) = tree_cons (tm_attr, NULL, TYPE_ATTRIBUTES (t));
1760     }
1761 }
1762 
1763 /* Determine all the primary bases within T.  Sets BINFO_PRIMARY_BASE_P for
1764    those that are primaries.  Sets BINFO_LOST_PRIMARY_P for those
1765    that have had a nearly-empty virtual primary base stolen by some
1766    other base in the hierarchy.  Determines CLASSTYPE_PRIMARY_BASE for
1767    T.  */
1768 
1769 static void
determine_primary_bases(tree t)1770 determine_primary_bases (tree t)
1771 {
1772   unsigned i;
1773   tree primary = NULL_TREE;
1774   tree type_binfo = TYPE_BINFO (t);
1775   tree base_binfo;
1776 
1777   /* Determine the primary bases of our bases.  */
1778   for (base_binfo = TREE_CHAIN (type_binfo); base_binfo;
1779        base_binfo = TREE_CHAIN (base_binfo))
1780     {
1781       tree primary = CLASSTYPE_PRIMARY_BINFO (BINFO_TYPE (base_binfo));
1782 
1783       /* See if we're the non-virtual primary of our inheritance
1784 	 chain.  */
1785       if (!BINFO_VIRTUAL_P (base_binfo))
1786 	{
1787 	  tree parent = BINFO_INHERITANCE_CHAIN (base_binfo);
1788 	  tree parent_primary = CLASSTYPE_PRIMARY_BINFO (BINFO_TYPE (parent));
1789 
1790 	  if (parent_primary
1791 	      && SAME_BINFO_TYPE_P (BINFO_TYPE (base_binfo),
1792 				    BINFO_TYPE (parent_primary)))
1793 	    /* We are the primary binfo.  */
1794 	    BINFO_PRIMARY_P (base_binfo) = 1;
1795 	}
1796       /* Determine if we have a virtual primary base, and mark it so.
1797        */
1798       if (primary && BINFO_VIRTUAL_P (primary))
1799 	{
1800 	  tree this_primary = copied_binfo (primary, base_binfo);
1801 
1802 	  if (BINFO_PRIMARY_P (this_primary))
1803 	    /* Someone already claimed this base.  */
1804 	    BINFO_LOST_PRIMARY_P (base_binfo) = 1;
1805 	  else
1806 	    {
1807 	      tree delta;
1808 
1809 	      BINFO_PRIMARY_P (this_primary) = 1;
1810 	      BINFO_INHERITANCE_CHAIN (this_primary) = base_binfo;
1811 
1812 	      /* A virtual binfo might have been copied from within
1813 		 another hierarchy. As we're about to use it as a
1814 		 primary base, make sure the offsets match.  */
1815 	      delta = size_diffop_loc (input_location,
1816 				   fold_convert (ssizetype,
1817 					    BINFO_OFFSET (base_binfo)),
1818 				   fold_convert (ssizetype,
1819 					    BINFO_OFFSET (this_primary)));
1820 
1821 	      propagate_binfo_offsets (this_primary, delta);
1822 	    }
1823 	}
1824     }
1825 
1826   /* First look for a dynamic direct non-virtual base.  */
1827   for (i = 0; BINFO_BASE_ITERATE (type_binfo, i, base_binfo); i++)
1828     {
1829       tree basetype = BINFO_TYPE (base_binfo);
1830 
1831       if (TYPE_CONTAINS_VPTR_P (basetype) && !BINFO_VIRTUAL_P (base_binfo))
1832 	{
1833 	  primary = base_binfo;
1834 	  goto found;
1835 	}
1836     }
1837 
1838   /* A "nearly-empty" virtual base class can be the primary base
1839      class, if no non-virtual polymorphic base can be found.  Look for
1840      a nearly-empty virtual dynamic base that is not already a primary
1841      base of something in the hierarchy.  If there is no such base,
1842      just pick the first nearly-empty virtual base.  */
1843 
1844   for (base_binfo = TREE_CHAIN (type_binfo); base_binfo;
1845        base_binfo = TREE_CHAIN (base_binfo))
1846     if (BINFO_VIRTUAL_P (base_binfo)
1847 	&& CLASSTYPE_NEARLY_EMPTY_P (BINFO_TYPE (base_binfo)))
1848       {
1849 	if (!BINFO_PRIMARY_P (base_binfo))
1850 	  {
1851 	    /* Found one that is not primary.  */
1852 	    primary = base_binfo;
1853 	    goto found;
1854 	  }
1855 	else if (!primary)
1856 	  /* Remember the first candidate.  */
1857 	  primary = base_binfo;
1858       }
1859 
1860  found:
1861   /* If we've got a primary base, use it.  */
1862   if (primary)
1863     {
1864       tree basetype = BINFO_TYPE (primary);
1865 
1866       CLASSTYPE_PRIMARY_BINFO (t) = primary;
1867       if (BINFO_PRIMARY_P (primary))
1868 	/* We are stealing a primary base.  */
1869 	BINFO_LOST_PRIMARY_P (BINFO_INHERITANCE_CHAIN (primary)) = 1;
1870       BINFO_PRIMARY_P (primary) = 1;
1871       if (BINFO_VIRTUAL_P (primary))
1872 	{
1873 	  tree delta;
1874 
1875 	  BINFO_INHERITANCE_CHAIN (primary) = type_binfo;
1876 	  /* A virtual binfo might have been copied from within
1877 	     another hierarchy. As we're about to use it as a primary
1878 	     base, make sure the offsets match.  */
1879 	  delta = size_diffop_loc (input_location, ssize_int (0),
1880 			       fold_convert (ssizetype, BINFO_OFFSET (primary)));
1881 
1882 	  propagate_binfo_offsets (primary, delta);
1883 	}
1884 
1885       primary = TYPE_BINFO (basetype);
1886 
1887       TYPE_VFIELD (t) = TYPE_VFIELD (basetype);
1888       BINFO_VTABLE (type_binfo) = BINFO_VTABLE (primary);
1889       BINFO_VIRTUALS (type_binfo) = BINFO_VIRTUALS (primary);
1890     }
1891 }
1892 
1893 /* Update the variant types of T.  */
1894 
1895 void
fixup_type_variants(tree t)1896 fixup_type_variants (tree t)
1897 {
1898   tree variants;
1899 
1900   if (!t)
1901     return;
1902 
1903   for (variants = TYPE_NEXT_VARIANT (t);
1904        variants;
1905        variants = TYPE_NEXT_VARIANT (variants))
1906     {
1907       /* These fields are in the _TYPE part of the node, not in
1908 	 the TYPE_LANG_SPECIFIC component, so they are not shared.  */
1909       TYPE_HAS_USER_CONSTRUCTOR (variants) = TYPE_HAS_USER_CONSTRUCTOR (t);
1910       TYPE_NEEDS_CONSTRUCTING (variants) = TYPE_NEEDS_CONSTRUCTING (t);
1911       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (variants)
1912 	= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t);
1913 
1914       TYPE_POLYMORPHIC_P (variants) = TYPE_POLYMORPHIC_P (t);
1915 
1916       TYPE_BINFO (variants) = TYPE_BINFO (t);
1917 
1918       /* Copy whatever these are holding today.  */
1919       TYPE_VFIELD (variants) = TYPE_VFIELD (t);
1920       TYPE_FIELDS (variants) = TYPE_FIELDS (t);
1921     }
1922 }
1923 
1924 /* KLASS is a class that we're applying may_alias to after the body is
1925    parsed.  Fixup any POINTER_TO and REFERENCE_TO types.  The
1926    canonical type(s) will be implicitly updated.  */
1927 
1928 static void
fixup_may_alias(tree klass)1929 fixup_may_alias (tree klass)
1930 {
1931   tree t, v;
1932 
1933   for (t = TYPE_POINTER_TO (klass); t; t = TYPE_NEXT_PTR_TO (t))
1934     for (v = TYPE_MAIN_VARIANT (t); v; v = TYPE_NEXT_VARIANT (v))
1935       TYPE_REF_CAN_ALIAS_ALL (v) = true;
1936   for (t = TYPE_REFERENCE_TO (klass); t; t = TYPE_NEXT_REF_TO (t))
1937     for (v = TYPE_MAIN_VARIANT (t); v; v = TYPE_NEXT_VARIANT (v))
1938       TYPE_REF_CAN_ALIAS_ALL (v) = true;
1939 }
1940 
1941 /* Early variant fixups: we apply attributes at the beginning of the class
1942    definition, and we need to fix up any variants that have already been
1943    made via elaborated-type-specifier so that check_qualified_type works.  */
1944 
1945 void
fixup_attribute_variants(tree t)1946 fixup_attribute_variants (tree t)
1947 {
1948   tree variants;
1949 
1950   if (!t)
1951     return;
1952 
1953   tree attrs = TYPE_ATTRIBUTES (t);
1954   unsigned align = TYPE_ALIGN (t);
1955   bool user_align = TYPE_USER_ALIGN (t);
1956   bool may_alias = lookup_attribute ("may_alias", attrs);
1957   bool packed = TYPE_PACKED (t);
1958 
1959   if (may_alias)
1960     fixup_may_alias (t);
1961 
1962   for (variants = TYPE_NEXT_VARIANT (t);
1963        variants;
1964        variants = TYPE_NEXT_VARIANT (variants))
1965     {
1966       /* These are the two fields that check_qualified_type looks at and
1967 	 are affected by attributes.  */
1968       TYPE_ATTRIBUTES (variants) = attrs;
1969       unsigned valign = align;
1970       if (TYPE_USER_ALIGN (variants))
1971 	valign = MAX (valign, TYPE_ALIGN (variants));
1972       else
1973 	TYPE_USER_ALIGN (variants) = user_align;
1974       SET_TYPE_ALIGN (variants, valign);
1975       TYPE_PACKED (variants) = packed;
1976       if (may_alias)
1977 	fixup_may_alias (variants);
1978     }
1979 }
1980 
1981 /* Set memoizing fields and bits of T (and its variants) for later
1982    use.  */
1983 
1984 static void
finish_struct_bits(tree t)1985 finish_struct_bits (tree t)
1986 {
1987   /* Fix up variants (if any).  */
1988   fixup_type_variants (t);
1989 
1990   if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)) && TYPE_POLYMORPHIC_P (t))
1991     /* For a class w/o baseclasses, 'finish_struct' has set
1992        CLASSTYPE_PURE_VIRTUALS correctly (by definition).
1993        Similarly for a class whose base classes do not have vtables.
1994        When neither of these is true, we might have removed abstract
1995        virtuals (by providing a definition), added some (by declaring
1996        new ones), or redeclared ones from a base class.  We need to
1997        recalculate what's really an abstract virtual at this point (by
1998        looking in the vtables).  */
1999     get_pure_virtuals (t);
2000 
2001   /* If this type has a copy constructor or a destructor, force its
2002      mode to be BLKmode, and force its TREE_ADDRESSABLE bit to be
2003      nonzero.  This will cause it to be passed by invisible reference
2004      and prevent it from being returned in a register.  */
2005   if (type_has_nontrivial_copy_init (t)
2006       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
2007     {
2008       tree variants;
2009       SET_DECL_MODE (TYPE_MAIN_DECL (t), BLKmode);
2010       for (variants = t; variants; variants = TYPE_NEXT_VARIANT (variants))
2011 	{
2012 	  SET_TYPE_MODE (variants, BLKmode);
2013 	  TREE_ADDRESSABLE (variants) = 1;
2014 	}
2015     }
2016 }
2017 
2018 /* Issue warnings about T having private constructors, but no friends,
2019    and so forth.
2020 
2021    HAS_NONPRIVATE_METHOD is nonzero if T has any non-private methods or
2022    static members.  HAS_NONPRIVATE_STATIC_FN is nonzero if T has any
2023    non-private static member functions.  */
2024 
2025 static void
maybe_warn_about_overly_private_class(tree t)2026 maybe_warn_about_overly_private_class (tree t)
2027 {
2028   int has_member_fn = 0;
2029   int has_nonprivate_method = 0;
2030   bool nonprivate_ctor = false;
2031 
2032   if (!warn_ctor_dtor_privacy
2033       /* If the class has friends, those entities might create and
2034 	 access instances, so we should not warn.  */
2035       || (CLASSTYPE_FRIEND_CLASSES (t)
2036 	  || DECL_FRIENDLIST (TYPE_MAIN_DECL (t)))
2037       /* We will have warned when the template was declared; there's
2038 	 no need to warn on every instantiation.  */
2039       || CLASSTYPE_TEMPLATE_INSTANTIATION (t))
2040     /* There's no reason to even consider warning about this
2041        class.  */
2042     return;
2043 
2044   /* We only issue one warning, if more than one applies, because
2045      otherwise, on code like:
2046 
2047      class A {
2048        // Oops - forgot `public:'
2049        A();
2050        A(const A&);
2051        ~A();
2052      };
2053 
2054      we warn several times about essentially the same problem.  */
2055 
2056   /* Check to see if all (non-constructor, non-destructor) member
2057      functions are private.  (Since there are no friends or
2058      non-private statics, we can't ever call any of the private member
2059      functions.)  */
2060   for (tree fn = TYPE_FIELDS (t); fn; fn = DECL_CHAIN (fn))
2061     if (TREE_CODE (fn) == USING_DECL
2062 	&& DECL_NAME (fn) == ctor_identifier
2063 	&& !TREE_PRIVATE (fn))
2064       nonprivate_ctor = true;
2065     else if (!DECL_DECLARES_FUNCTION_P (fn))
2066       /* Not a function.  */;
2067     else if (DECL_ARTIFICIAL (fn))
2068       /* We're not interested in compiler-generated methods; they don't
2069 	 provide any way to call private members.  */;
2070     else if (!TREE_PRIVATE (fn))
2071       {
2072 	if (DECL_STATIC_FUNCTION_P (fn))
2073 	  /* A non-private static member function is just like a
2074 	     friend; it can create and invoke private member
2075 	     functions, and be accessed without a class
2076 	     instance.  */
2077 	  return;
2078 
2079 	has_nonprivate_method = 1;
2080 	/* Keep searching for a static member function.  */
2081       }
2082     else if (!DECL_CONSTRUCTOR_P (fn) && !DECL_DESTRUCTOR_P (fn))
2083       has_member_fn = 1;
2084 
2085   if (!has_nonprivate_method && has_member_fn)
2086     {
2087       /* There are no non-private methods, and there's at least one
2088 	 private member function that isn't a constructor or
2089 	 destructor.  (If all the private members are
2090 	 constructors/destructors we want to use the code below that
2091 	 issues error messages specifically referring to
2092 	 constructors/destructors.)  */
2093       unsigned i;
2094       tree binfo = TYPE_BINFO (t);
2095 
2096       for (i = 0; i != BINFO_N_BASE_BINFOS (binfo); i++)
2097 	if (BINFO_BASE_ACCESS (binfo, i) != access_private_node)
2098 	  {
2099 	    has_nonprivate_method = 1;
2100 	    break;
2101 	  }
2102       if (!has_nonprivate_method)
2103 	{
2104 	  warning (OPT_Wctor_dtor_privacy,
2105 		   "all member functions in class %qT are private", t);
2106 	  return;
2107 	}
2108     }
2109 
2110   /* Even if some of the member functions are non-private, the class
2111      won't be useful for much if all the constructors or destructors
2112      are private: such an object can never be created or destroyed.  */
2113   if (tree dtor = CLASSTYPE_DESTRUCTOR (t))
2114     if (TREE_PRIVATE (dtor))
2115       {
2116 	warning (OPT_Wctor_dtor_privacy,
2117 		 "%q#T only defines a private destructor and has no friends",
2118 		 t);
2119 	return;
2120       }
2121 
2122   /* Warn about classes that have private constructors and no friends.  */
2123   if (TYPE_HAS_USER_CONSTRUCTOR (t)
2124       /* Implicitly generated constructors are always public.  */
2125       && !CLASSTYPE_LAZY_DEFAULT_CTOR (t))
2126     {
2127       tree copy_or_move = NULL_TREE;
2128 
2129       /* If a non-template class does not define a copy
2130 	 constructor, one is defined for it, enabling it to avoid
2131 	 this warning.  For a template class, this does not
2132 	 happen, and so we would normally get a warning on:
2133 
2134 	   template <class T> class C { private: C(); };
2135 
2136 	 To avoid this asymmetry, we check TYPE_HAS_COPY_CTOR.  All
2137 	 complete non-template or fully instantiated classes have this
2138 	 flag set.  */
2139       if (!TYPE_HAS_COPY_CTOR (t))
2140 	nonprivate_ctor = true;
2141       else
2142 	for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t));
2143 	     !nonprivate_ctor && iter; ++iter)
2144 	  if (TREE_PRIVATE (*iter))
2145 	    continue;
2146 	  else if (copy_fn_p (*iter) || move_fn_p (*iter))
2147 	    /* Ideally, we wouldn't count any constructor that takes
2148 	       an argument of the class type as a parameter, because
2149 	       such things cannot be used to construct an instance of
2150 	       the class unless you already have one.  */
2151 	    copy_or_move = *iter;
2152 	  else
2153 	    nonprivate_ctor = true;
2154 
2155       if (!nonprivate_ctor)
2156 	{
2157 	  warning (OPT_Wctor_dtor_privacy,
2158 		   "%q#T only defines private constructors and has no friends",
2159 		   t);
2160 	  if (copy_or_move)
2161 	    inform (DECL_SOURCE_LOCATION (copy_or_move),
2162 		    "%q#D is public, but requires an existing %q#T object",
2163 		    copy_or_move, t);
2164 	  return;
2165 	}
2166     }
2167 }
2168 
2169 /* Make BINFO's vtable have N entries, including RTTI entries,
2170    vbase and vcall offsets, etc.  Set its type and call the back end
2171    to lay it out.  */
2172 
2173 static void
layout_vtable_decl(tree binfo,int n)2174 layout_vtable_decl (tree binfo, int n)
2175 {
2176   tree atype;
2177   tree vtable;
2178 
2179   atype = build_array_of_n_type (vtable_entry_type, n);
2180   layout_type (atype);
2181 
2182   /* We may have to grow the vtable.  */
2183   vtable = get_vtbl_decl_for_binfo (binfo);
2184   if (!same_type_p (TREE_TYPE (vtable), atype))
2185     {
2186       TREE_TYPE (vtable) = atype;
2187       DECL_SIZE (vtable) = DECL_SIZE_UNIT (vtable) = NULL_TREE;
2188       layout_decl (vtable, 0);
2189     }
2190 }
2191 
2192 /* True iff FNDECL and BASE_FNDECL (both non-static member functions)
2193    have the same signature.  */
2194 
2195 int
same_signature_p(const_tree fndecl,const_tree base_fndecl)2196 same_signature_p (const_tree fndecl, const_tree base_fndecl)
2197 {
2198   /* One destructor overrides another if they are the same kind of
2199      destructor.  */
2200   if (DECL_DESTRUCTOR_P (base_fndecl) && DECL_DESTRUCTOR_P (fndecl)
2201       && special_function_p (base_fndecl) == special_function_p (fndecl))
2202     return 1;
2203   /* But a non-destructor never overrides a destructor, nor vice
2204      versa, nor do different kinds of destructors override
2205      one-another.  For example, a complete object destructor does not
2206      override a deleting destructor.  */
2207   if (DECL_DESTRUCTOR_P (base_fndecl) || DECL_DESTRUCTOR_P (fndecl))
2208     return 0;
2209 
2210   if (DECL_NAME (fndecl) == DECL_NAME (base_fndecl)
2211       || (DECL_CONV_FN_P (fndecl)
2212 	  && DECL_CONV_FN_P (base_fndecl)
2213 	  && same_type_p (DECL_CONV_FN_TYPE (fndecl),
2214 			  DECL_CONV_FN_TYPE (base_fndecl))))
2215     {
2216       tree fntype = TREE_TYPE (fndecl);
2217       tree base_fntype = TREE_TYPE (base_fndecl);
2218       if (type_memfn_quals (fntype) == type_memfn_quals (base_fntype)
2219 	  && type_memfn_rqual (fntype) == type_memfn_rqual (base_fntype)
2220 	  && compparms (FUNCTION_FIRST_USER_PARMTYPE (fndecl),
2221 			FUNCTION_FIRST_USER_PARMTYPE (base_fndecl)))
2222 	return 1;
2223     }
2224   return 0;
2225 }
2226 
2227 /* Returns TRUE if DERIVED is a binfo containing the binfo BASE as a
2228    subobject.  */
2229 
2230 static bool
base_derived_from(tree derived,tree base)2231 base_derived_from (tree derived, tree base)
2232 {
2233   tree probe;
2234 
2235   for (probe = base; probe; probe = BINFO_INHERITANCE_CHAIN (probe))
2236     {
2237       if (probe == derived)
2238 	return true;
2239       else if (BINFO_VIRTUAL_P (probe))
2240 	/* If we meet a virtual base, we can't follow the inheritance
2241 	   any more.  See if the complete type of DERIVED contains
2242 	   such a virtual base.  */
2243 	return (binfo_for_vbase (BINFO_TYPE (probe), BINFO_TYPE (derived))
2244 		!= NULL_TREE);
2245     }
2246   return false;
2247 }
2248 
2249 struct find_final_overrider_data {
2250   /* The function for which we are trying to find a final overrider.  */
2251   tree fn;
2252   /* The base class in which the function was declared.  */
2253   tree declaring_base;
2254   /* The candidate overriders.  */
2255   tree candidates;
2256   /* Path to most derived.  */
2257   vec<tree> path;
2258 };
2259 
2260 /* Add the overrider along the current path to FFOD->CANDIDATES.
2261    Returns true if an overrider was found; false otherwise.  */
2262 
2263 static bool
dfs_find_final_overrider_1(tree binfo,find_final_overrider_data * ffod,unsigned depth)2264 dfs_find_final_overrider_1 (tree binfo,
2265 			    find_final_overrider_data *ffod,
2266 			    unsigned depth)
2267 {
2268   tree method;
2269 
2270   /* If BINFO is not the most derived type, try a more derived class.
2271      A definition there will overrider a definition here.  */
2272   if (depth)
2273     {
2274       depth--;
2275       if (dfs_find_final_overrider_1
2276 	  (ffod->path[depth], ffod, depth))
2277 	return true;
2278     }
2279 
2280   method = look_for_overrides_here (BINFO_TYPE (binfo), ffod->fn);
2281   if (method)
2282     {
2283       tree *candidate = &ffod->candidates;
2284 
2285       /* Remove any candidates overridden by this new function.  */
2286       while (*candidate)
2287 	{
2288 	  /* If *CANDIDATE overrides METHOD, then METHOD
2289 	     cannot override anything else on the list.  */
2290 	  if (base_derived_from (TREE_VALUE (*candidate), binfo))
2291 	    return true;
2292 	  /* If METHOD overrides *CANDIDATE, remove *CANDIDATE.  */
2293 	  if (base_derived_from (binfo, TREE_VALUE (*candidate)))
2294 	    *candidate = TREE_CHAIN (*candidate);
2295 	  else
2296 	    candidate = &TREE_CHAIN (*candidate);
2297 	}
2298 
2299       /* Add the new function.  */
2300       ffod->candidates = tree_cons (method, binfo, ffod->candidates);
2301       return true;
2302     }
2303 
2304   return false;
2305 }
2306 
2307 /* Called from find_final_overrider via dfs_walk.  */
2308 
2309 static tree
dfs_find_final_overrider_pre(tree binfo,void * data)2310 dfs_find_final_overrider_pre (tree binfo, void *data)
2311 {
2312   find_final_overrider_data *ffod = (find_final_overrider_data *) data;
2313 
2314   if (binfo == ffod->declaring_base)
2315     dfs_find_final_overrider_1 (binfo, ffod, ffod->path.length ());
2316   ffod->path.safe_push (binfo);
2317 
2318   return NULL_TREE;
2319 }
2320 
2321 static tree
dfs_find_final_overrider_post(tree,void * data)2322 dfs_find_final_overrider_post (tree /*binfo*/, void *data)
2323 {
2324   find_final_overrider_data *ffod = (find_final_overrider_data *) data;
2325   ffod->path.pop ();
2326 
2327   return NULL_TREE;
2328 }
2329 
2330 /* Returns a TREE_LIST whose TREE_PURPOSE is the final overrider for
2331    FN and whose TREE_VALUE is the binfo for the base where the
2332    overriding occurs.  BINFO (in the hierarchy dominated by the binfo
2333    DERIVED) is the base object in which FN is declared.  */
2334 
2335 static tree
find_final_overrider(tree derived,tree binfo,tree fn)2336 find_final_overrider (tree derived, tree binfo, tree fn)
2337 {
2338   find_final_overrider_data ffod;
2339 
2340   /* Getting this right is a little tricky.  This is valid:
2341 
2342        struct S { virtual void f (); };
2343        struct T { virtual void f (); };
2344        struct U : public S, public T { };
2345 
2346      even though calling `f' in `U' is ambiguous.  But,
2347 
2348        struct R { virtual void f(); };
2349        struct S : virtual public R { virtual void f (); };
2350        struct T : virtual public R { virtual void f (); };
2351        struct U : public S, public T { };
2352 
2353      is not -- there's no way to decide whether to put `S::f' or
2354      `T::f' in the vtable for `R'.
2355 
2356      The solution is to look at all paths to BINFO.  If we find
2357      different overriders along any two, then there is a problem.  */
2358   if (DECL_THUNK_P (fn))
2359     fn = THUNK_TARGET (fn);
2360 
2361   /* Determine the depth of the hierarchy.  */
2362   ffod.fn = fn;
2363   ffod.declaring_base = binfo;
2364   ffod.candidates = NULL_TREE;
2365   ffod.path.create (30);
2366 
2367   dfs_walk_all (derived, dfs_find_final_overrider_pre,
2368 		dfs_find_final_overrider_post, &ffod);
2369 
2370   ffod.path.release ();
2371 
2372   /* If there was no winner, issue an error message.  */
2373   if (!ffod.candidates || TREE_CHAIN (ffod.candidates))
2374     return error_mark_node;
2375 
2376   return ffod.candidates;
2377 }
2378 
2379 /* Return the index of the vcall offset for FN when TYPE is used as a
2380    virtual base.  */
2381 
2382 static tree
get_vcall_index(tree fn,tree type)2383 get_vcall_index (tree fn, tree type)
2384 {
2385   vec<tree_pair_s, va_gc> *indices = CLASSTYPE_VCALL_INDICES (type);
2386   tree_pair_p p;
2387   unsigned ix;
2388 
2389   FOR_EACH_VEC_SAFE_ELT (indices, ix, p)
2390     if ((DECL_DESTRUCTOR_P (fn) && DECL_DESTRUCTOR_P (p->purpose))
2391 	|| same_signature_p (fn, p->purpose))
2392       return p->value;
2393 
2394   /* There should always be an appropriate index.  */
2395   gcc_unreachable ();
2396 }
2397 
2398 /* Given a DECL_VINDEX of a virtual function found in BINFO, return the final
2399    overrider at that index in the vtable.  This should only be used when we
2400    know that BINFO is correct for the dynamic type of the object.  */
2401 
2402 tree
lookup_vfn_in_binfo(tree idx,tree binfo)2403 lookup_vfn_in_binfo (tree idx, tree binfo)
2404 {
2405   int ix = tree_to_shwi (idx);
2406   if (TARGET_VTABLE_USES_DESCRIPTORS)
2407     ix /= MAX (TARGET_VTABLE_USES_DESCRIPTORS, 1);
2408   while (BINFO_PRIMARY_P (binfo))
2409     /* BINFO_VIRTUALS in a primary base isn't accurate, find the derived
2410        class that actually owns the vtable.  */
2411     binfo = BINFO_INHERITANCE_CHAIN (binfo);
2412   tree virtuals = BINFO_VIRTUALS (binfo);
2413   return TREE_VALUE (chain_index (ix, virtuals));
2414 }
2415 
2416 /* Update an entry in the vtable for BINFO, which is in the hierarchy
2417    dominated by T.  FN is the old function; VIRTUALS points to the
2418    corresponding position in the new BINFO_VIRTUALS list.  IX is the index
2419    of that entry in the list.  */
2420 
2421 static void
update_vtable_entry_for_fn(tree t,tree binfo,tree fn,tree * virtuals,unsigned ix)2422 update_vtable_entry_for_fn (tree t, tree binfo, tree fn, tree* virtuals,
2423 			    unsigned ix)
2424 {
2425   tree b;
2426   tree overrider;
2427   tree delta;
2428   tree virtual_base;
2429   tree first_defn;
2430   tree overrider_fn, overrider_target;
2431   tree target_fn = DECL_THUNK_P (fn) ? THUNK_TARGET (fn) : fn;
2432   tree over_return, base_return;
2433   bool lost = false;
2434 
2435   /* Find the nearest primary base (possibly binfo itself) which defines
2436      this function; this is the class the caller will convert to when
2437      calling FN through BINFO.  */
2438   for (b = binfo; ; b = get_primary_binfo (b))
2439     {
2440       gcc_assert (b);
2441       if (look_for_overrides_here (BINFO_TYPE (b), target_fn))
2442 	break;
2443 
2444       /* The nearest definition is from a lost primary.  */
2445       if (BINFO_LOST_PRIMARY_P (b))
2446 	lost = true;
2447     }
2448   first_defn = b;
2449 
2450   /* Find the final overrider.  */
2451   overrider = find_final_overrider (TYPE_BINFO (t), b, target_fn);
2452   if (overrider == error_mark_node)
2453     {
2454       error ("no unique final overrider for %qD in %qT", target_fn, t);
2455       return;
2456     }
2457   overrider_target = overrider_fn = TREE_PURPOSE (overrider);
2458 
2459   /* Check for adjusting covariant return types.  */
2460   over_return = TREE_TYPE (TREE_TYPE (overrider_target));
2461   base_return = TREE_TYPE (TREE_TYPE (target_fn));
2462 
2463   if (POINTER_TYPE_P (over_return)
2464       && TREE_CODE (over_return) == TREE_CODE (base_return)
2465       && CLASS_TYPE_P (TREE_TYPE (over_return))
2466       && CLASS_TYPE_P (TREE_TYPE (base_return))
2467       /* If the overrider is invalid, don't even try.  */
2468       && !DECL_INVALID_OVERRIDER_P (overrider_target))
2469     {
2470       /* If FN is a covariant thunk, we must figure out the adjustment
2471 	 to the final base FN was converting to. As OVERRIDER_TARGET might
2472 	 also be converting to the return type of FN, we have to
2473 	 combine the two conversions here.  */
2474       tree fixed_offset, virtual_offset;
2475 
2476       over_return = TREE_TYPE (over_return);
2477       base_return = TREE_TYPE (base_return);
2478 
2479       if (DECL_THUNK_P (fn))
2480 	{
2481 	  gcc_assert (DECL_RESULT_THUNK_P (fn));
2482 	  fixed_offset = ssize_int (THUNK_FIXED_OFFSET (fn));
2483 	  virtual_offset = THUNK_VIRTUAL_OFFSET (fn);
2484 	}
2485       else
2486 	fixed_offset = virtual_offset = NULL_TREE;
2487 
2488       if (virtual_offset)
2489 	/* Find the equivalent binfo within the return type of the
2490 	   overriding function. We will want the vbase offset from
2491 	   there.  */
2492 	virtual_offset = binfo_for_vbase (BINFO_TYPE (virtual_offset),
2493 					  over_return);
2494       else if (!same_type_ignoring_top_level_qualifiers_p
2495 	       (over_return, base_return))
2496 	{
2497 	  /* There was no existing virtual thunk (which takes
2498 	     precedence).  So find the binfo of the base function's
2499 	     return type within the overriding function's return type.
2500 	     Fortunately we know the covariancy is valid (it
2501 	     has already been checked), so we can just iterate along
2502 	     the binfos, which have been chained in inheritance graph
2503 	     order.  Of course it is lame that we have to repeat the
2504 	     search here anyway -- we should really be caching pieces
2505 	     of the vtable and avoiding this repeated work.  */
2506 	  tree thunk_binfo = NULL_TREE;
2507 	  tree base_binfo = TYPE_BINFO (base_return);
2508 
2509 	  /* Find the base binfo within the overriding function's
2510 	     return type.  We will always find a thunk_binfo, except
2511 	     when the covariancy is invalid (which we will have
2512 	     already diagnosed).  */
2513 	  if (base_binfo)
2514 	    for (thunk_binfo = TYPE_BINFO (over_return); thunk_binfo;
2515 		 thunk_binfo = TREE_CHAIN (thunk_binfo))
2516 	      if (SAME_BINFO_TYPE_P (BINFO_TYPE (thunk_binfo),
2517 				     BINFO_TYPE (base_binfo)))
2518 		break;
2519 	  gcc_assert (thunk_binfo || errorcount);
2520 
2521 	  /* See if virtual inheritance is involved.  */
2522 	  for (virtual_offset = thunk_binfo;
2523 	       virtual_offset;
2524 	       virtual_offset = BINFO_INHERITANCE_CHAIN (virtual_offset))
2525 	    if (BINFO_VIRTUAL_P (virtual_offset))
2526 	      break;
2527 
2528 	  if (virtual_offset
2529 	      || (thunk_binfo && !BINFO_OFFSET_ZEROP (thunk_binfo)))
2530 	    {
2531 	      tree offset = fold_convert (ssizetype, BINFO_OFFSET (thunk_binfo));
2532 
2533 	      if (virtual_offset)
2534 		{
2535 		  /* We convert via virtual base.  Adjust the fixed
2536 		     offset to be from there.  */
2537 		  offset =
2538 		    size_diffop (offset,
2539 				 fold_convert (ssizetype,
2540 					  BINFO_OFFSET (virtual_offset)));
2541 		}
2542 	      if (fixed_offset)
2543 		/* There was an existing fixed offset, this must be
2544 		   from the base just converted to, and the base the
2545 		   FN was thunking to.  */
2546 		fixed_offset = size_binop (PLUS_EXPR, fixed_offset, offset);
2547 	      else
2548 		fixed_offset = offset;
2549 	    }
2550 	}
2551 
2552       if (fixed_offset || virtual_offset)
2553 	/* Replace the overriding function with a covariant thunk.  We
2554 	   will emit the overriding function in its own slot as
2555 	   well.  */
2556 	overrider_fn = make_thunk (overrider_target, /*this_adjusting=*/0,
2557 				   fixed_offset, virtual_offset);
2558     }
2559   else
2560     gcc_assert (DECL_INVALID_OVERRIDER_P (overrider_target) ||
2561 		!DECL_THUNK_P (fn));
2562 
2563   /* If we need a covariant thunk, then we may need to adjust first_defn.
2564      The ABI specifies that the thunks emitted with a function are
2565      determined by which bases the function overrides, so we need to be
2566      sure that we're using a thunk for some overridden base; even if we
2567      know that the necessary this adjustment is zero, there may not be an
2568      appropriate zero-this-adjustment thunk for us to use since thunks for
2569      overriding virtual bases always use the vcall offset.
2570 
2571      Furthermore, just choosing any base that overrides this function isn't
2572      quite right, as this slot won't be used for calls through a type that
2573      puts a covariant thunk here.  Calling the function through such a type
2574      will use a different slot, and that slot is the one that determines
2575      the thunk emitted for that base.
2576 
2577      So, keep looking until we find the base that we're really overriding
2578      in this slot: the nearest primary base that doesn't use a covariant
2579      thunk in this slot.  */
2580   if (overrider_target != overrider_fn)
2581     {
2582       if (BINFO_TYPE (b) == DECL_CONTEXT (overrider_target))
2583 	/* We already know that the overrider needs a covariant thunk.  */
2584 	b = get_primary_binfo (b);
2585       for (; ; b = get_primary_binfo (b))
2586 	{
2587 	  tree main_binfo = TYPE_BINFO (BINFO_TYPE (b));
2588 	  tree bv = chain_index (ix, BINFO_VIRTUALS (main_binfo));
2589 	  if (!DECL_THUNK_P (TREE_VALUE (bv)))
2590 	    break;
2591 	  if (BINFO_LOST_PRIMARY_P (b))
2592 	    lost = true;
2593 	}
2594       first_defn = b;
2595     }
2596 
2597   /* Assume that we will produce a thunk that convert all the way to
2598      the final overrider, and not to an intermediate virtual base.  */
2599   virtual_base = NULL_TREE;
2600 
2601   /* See if we can convert to an intermediate virtual base first, and then
2602      use the vcall offset located there to finish the conversion.  */
2603   for (; b; b = BINFO_INHERITANCE_CHAIN (b))
2604     {
2605       /* If we find the final overrider, then we can stop
2606 	 walking.  */
2607       if (SAME_BINFO_TYPE_P (BINFO_TYPE (b),
2608 			     BINFO_TYPE (TREE_VALUE (overrider))))
2609 	break;
2610 
2611       /* If we find a virtual base, and we haven't yet found the
2612 	 overrider, then there is a virtual base between the
2613 	 declaring base (first_defn) and the final overrider.  */
2614       if (BINFO_VIRTUAL_P (b))
2615 	{
2616 	  virtual_base = b;
2617 	  break;
2618 	}
2619     }
2620 
2621   /* Compute the constant adjustment to the `this' pointer.  The
2622      `this' pointer, when this function is called, will point at BINFO
2623      (or one of its primary bases, which are at the same offset).  */
2624   if (virtual_base)
2625     /* The `this' pointer needs to be adjusted from the declaration to
2626        the nearest virtual base.  */
2627     delta = size_diffop_loc (input_location,
2628 			 fold_convert (ssizetype, BINFO_OFFSET (virtual_base)),
2629 			 fold_convert (ssizetype, BINFO_OFFSET (first_defn)));
2630   else if (lost)
2631     /* If the nearest definition is in a lost primary, we don't need an
2632        entry in our vtable.  Except possibly in a constructor vtable,
2633        if we happen to get our primary back.  In that case, the offset
2634        will be zero, as it will be a primary base.  */
2635     delta = size_zero_node;
2636   else
2637     /* The `this' pointer needs to be adjusted from pointing to
2638        BINFO to pointing at the base where the final overrider
2639        appears.  */
2640     delta = size_diffop_loc (input_location,
2641 			 fold_convert (ssizetype,
2642 				  BINFO_OFFSET (TREE_VALUE (overrider))),
2643 			 fold_convert (ssizetype, BINFO_OFFSET (binfo)));
2644 
2645   modify_vtable_entry (t, binfo, overrider_fn, delta, virtuals);
2646 
2647   if (virtual_base)
2648     BV_VCALL_INDEX (*virtuals)
2649       = get_vcall_index (overrider_target, BINFO_TYPE (virtual_base));
2650   else
2651     BV_VCALL_INDEX (*virtuals) = NULL_TREE;
2652 
2653   BV_LOST_PRIMARY (*virtuals) = lost;
2654 }
2655 
2656 /* Called from modify_all_vtables via dfs_walk.  */
2657 
2658 static tree
dfs_modify_vtables(tree binfo,void * data)2659 dfs_modify_vtables (tree binfo, void* data)
2660 {
2661   tree t = (tree) data;
2662   tree virtuals;
2663   tree old_virtuals;
2664   unsigned ix;
2665 
2666   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
2667     /* A base without a vtable needs no modification, and its bases
2668        are uninteresting.  */
2669     return dfs_skip_bases;
2670 
2671   if (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t)
2672       && !CLASSTYPE_HAS_PRIMARY_BASE_P (t))
2673     /* Don't do the primary vtable, if it's new.  */
2674     return NULL_TREE;
2675 
2676   if (BINFO_PRIMARY_P (binfo) && !BINFO_VIRTUAL_P (binfo))
2677     /* There's no need to modify the vtable for a non-virtual primary
2678        base; we're not going to use that vtable anyhow.  We do still
2679        need to do this for virtual primary bases, as they could become
2680        non-primary in a construction vtable.  */
2681     return NULL_TREE;
2682 
2683   make_new_vtable (t, binfo);
2684 
2685   /* Now, go through each of the virtual functions in the virtual
2686      function table for BINFO.  Find the final overrider, and update
2687      the BINFO_VIRTUALS list appropriately.  */
2688   for (ix = 0, virtuals = BINFO_VIRTUALS (binfo),
2689 	 old_virtuals = BINFO_VIRTUALS (TYPE_BINFO (BINFO_TYPE (binfo)));
2690        virtuals;
2691        ix++, virtuals = TREE_CHAIN (virtuals),
2692 	 old_virtuals = TREE_CHAIN (old_virtuals))
2693     update_vtable_entry_for_fn (t,
2694 				binfo,
2695 				BV_FN (old_virtuals),
2696 				&virtuals, ix);
2697 
2698   return NULL_TREE;
2699 }
2700 
2701 /* Update all of the primary and secondary vtables for T.  Create new
2702    vtables as required, and initialize their RTTI information.  Each
2703    of the functions in VIRTUALS is declared in T and may override a
2704    virtual function from a base class; find and modify the appropriate
2705    entries to point to the overriding functions.  Returns a list, in
2706    declaration order, of the virtual functions that are declared in T,
2707    but do not appear in the primary base class vtable, and which
2708    should therefore be appended to the end of the vtable for T.  */
2709 
2710 static tree
modify_all_vtables(tree t,tree virtuals)2711 modify_all_vtables (tree t, tree virtuals)
2712 {
2713   tree binfo = TYPE_BINFO (t);
2714   tree *fnsp;
2715 
2716   /* Mangle the vtable name before entering dfs_walk (c++/51884).  */
2717   if (TYPE_CONTAINS_VPTR_P (t))
2718     get_vtable_decl (t, false);
2719 
2720   /* Update all of the vtables.  */
2721   dfs_walk_once (binfo, dfs_modify_vtables, NULL, t);
2722 
2723   /* Add virtual functions not already in our primary vtable. These
2724      will be both those introduced by this class, and those overridden
2725      from secondary bases.  It does not include virtuals merely
2726      inherited from secondary bases.  */
2727   for (fnsp = &virtuals; *fnsp; )
2728     {
2729       tree fn = TREE_VALUE (*fnsp);
2730 
2731       if (!value_member (fn, BINFO_VIRTUALS (binfo))
2732 	  || DECL_VINDEX (fn) == error_mark_node)
2733 	{
2734 	  /* We don't need to adjust the `this' pointer when
2735 	     calling this function.  */
2736 	  BV_DELTA (*fnsp) = integer_zero_node;
2737 	  BV_VCALL_INDEX (*fnsp) = NULL_TREE;
2738 
2739 	  /* This is a function not already in our vtable.  Keep it.  */
2740 	  fnsp = &TREE_CHAIN (*fnsp);
2741 	}
2742       else
2743 	/* We've already got an entry for this function.  Skip it.  */
2744 	*fnsp = TREE_CHAIN (*fnsp);
2745     }
2746 
2747   return virtuals;
2748 }
2749 
2750 /* Get the base virtual function declarations in T that have the
2751    indicated NAME.  */
2752 
2753 static void
get_basefndecls(tree name,tree t,vec<tree> * base_fndecls)2754 get_basefndecls (tree name, tree t, vec<tree> *base_fndecls)
2755 {
2756   bool found_decls = false;
2757 
2758   /* Find virtual functions in T with the indicated NAME.  */
2759   for (ovl_iterator iter (get_class_binding (t, name)); iter; ++iter)
2760     {
2761       tree method = *iter;
2762 
2763       if (TREE_CODE (method) == FUNCTION_DECL && DECL_VINDEX (method))
2764 	{
2765 	  base_fndecls->safe_push (method);
2766 	  found_decls = true;
2767 	}
2768     }
2769 
2770   if (found_decls)
2771     return;
2772 
2773   int n_baseclasses = BINFO_N_BASE_BINFOS (TYPE_BINFO (t));
2774   for (int i = 0; i < n_baseclasses; i++)
2775     {
2776       tree basetype = BINFO_TYPE (BINFO_BASE_BINFO (TYPE_BINFO (t), i));
2777       get_basefndecls (name, basetype, base_fndecls);
2778     }
2779 }
2780 
2781 /* If this declaration supersedes the declaration of
2782    a method declared virtual in the base class, then
2783    mark this field as being virtual as well.  */
2784 
2785 void
check_for_override(tree decl,tree ctype)2786 check_for_override (tree decl, tree ctype)
2787 {
2788   bool overrides_found = false;
2789   if (TREE_CODE (decl) == TEMPLATE_DECL)
2790     /* In [temp.mem] we have:
2791 
2792 	 A specialization of a member function template does not
2793 	 override a virtual function from a base class.  */
2794     return;
2795   if ((DECL_DESTRUCTOR_P (decl)
2796        || IDENTIFIER_VIRTUAL_P (DECL_NAME (decl))
2797        || DECL_CONV_FN_P (decl))
2798       && look_for_overrides (ctype, decl)
2799       && !DECL_STATIC_FUNCTION_P (decl))
2800     /* Set DECL_VINDEX to a value that is neither an INTEGER_CST nor
2801        the error_mark_node so that we know it is an overriding
2802        function.  */
2803     {
2804       DECL_VINDEX (decl) = decl;
2805       overrides_found = true;
2806       if (warn_override && !DECL_OVERRIDE_P (decl)
2807 	  && !DECL_DESTRUCTOR_P (decl))
2808 	warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wsuggest_override,
2809 		    "%qD can be marked override", decl);
2810     }
2811 
2812   if (DECL_VIRTUAL_P (decl))
2813     {
2814       if (!DECL_VINDEX (decl))
2815 	DECL_VINDEX (decl) = error_mark_node;
2816       IDENTIFIER_VIRTUAL_P (DECL_NAME (decl)) = 1;
2817       if (DECL_DESTRUCTOR_P (decl))
2818 	TYPE_HAS_NONTRIVIAL_DESTRUCTOR (ctype) = true;
2819     }
2820   else if (DECL_FINAL_P (decl))
2821     error ("%q+#D marked %<final%>, but is not virtual", decl);
2822   if (DECL_OVERRIDE_P (decl) && !overrides_found)
2823     error ("%q+#D marked %<override%>, but does not override", decl);
2824 }
2825 
2826 /* Warn about hidden virtual functions that are not overridden in t.
2827    We know that constructors and destructors don't apply.  */
2828 
2829 static void
warn_hidden(tree t)2830 warn_hidden (tree t)
2831 {
2832   if (vec<tree, va_gc> *member_vec = CLASSTYPE_MEMBER_VEC (t))
2833     for (unsigned ix = member_vec->length (); ix--;)
2834       {
2835 	tree fns = (*member_vec)[ix];
2836 
2837 	if (!OVL_P (fns))
2838 	  continue;
2839 
2840 	tree name = OVL_NAME (fns);
2841 	auto_vec<tree, 20> base_fndecls;
2842 	tree base_binfo;
2843 	tree binfo;
2844 	unsigned j;
2845 
2846 	/* Iterate through all of the base classes looking for possibly
2847 	   hidden functions.  */
2848 	for (binfo = TYPE_BINFO (t), j = 0;
2849 	     BINFO_BASE_ITERATE (binfo, j, base_binfo); j++)
2850 	  {
2851 	    tree basetype = BINFO_TYPE (base_binfo);
2852 	    get_basefndecls (name, basetype, &base_fndecls);
2853 	  }
2854 
2855 	/* If there are no functions to hide, continue.  */
2856 	if (base_fndecls.is_empty ())
2857 	  continue;
2858 
2859 	/* Remove any overridden functions.  */
2860 	for (ovl_iterator iter (fns); iter; ++iter)
2861 	  {
2862 	    tree fndecl = *iter;
2863 	    if (TREE_CODE (fndecl) == FUNCTION_DECL
2864 		&& DECL_VINDEX (fndecl))
2865 	      {
2866 		/* If the method from the base class has the same
2867 		   signature as the method from the derived class, it
2868 		   has been overridden.  */
2869 		for (size_t k = 0; k < base_fndecls.length (); k++)
2870 		  if (base_fndecls[k]
2871 		      && same_signature_p (fndecl, base_fndecls[k]))
2872 		    base_fndecls[k] = NULL_TREE;
2873 	      }
2874 	  }
2875 
2876 	/* Now give a warning for all base functions without overriders,
2877 	   as they are hidden.  */
2878 	tree base_fndecl;
2879 	FOR_EACH_VEC_ELT (base_fndecls, j, base_fndecl)
2880 	  if (base_fndecl)
2881 	    {
2882 	      /* Here we know it is a hider, and no overrider exists.  */
2883 	      warning_at (location_of (base_fndecl),
2884 			  OPT_Woverloaded_virtual,
2885 			  "%qD was hidden", base_fndecl);
2886 	      warning_at (location_of (fns),
2887 			  OPT_Woverloaded_virtual, "  by %qD", fns);
2888 	    }
2889       }
2890 }
2891 
2892 /* Recursive helper for finish_struct_anon.  */
2893 
2894 static void
finish_struct_anon_r(tree field,bool complain)2895 finish_struct_anon_r (tree field, bool complain)
2896 {
2897   for (tree elt = TYPE_FIELDS (TREE_TYPE (field)); elt; elt = DECL_CHAIN (elt))
2898     {
2899       /* We're generally only interested in entities the user
2900 	 declared, but we also find nested classes by noticing
2901 	 the TYPE_DECL that we create implicitly.  You're
2902 	 allowed to put one anonymous union inside another,
2903 	 though, so we explicitly tolerate that.  We use
2904 	 TYPE_UNNAMED_P rather than ANON_AGGR_TYPE_P so that
2905 	 we also allow unnamed types used for defining fields.  */
2906       if (DECL_ARTIFICIAL (elt)
2907 	  && (!DECL_IMPLICIT_TYPEDEF_P (elt)
2908 	      || TYPE_UNNAMED_P (TREE_TYPE (elt))))
2909 	continue;
2910 
2911       if (complain
2912 	  && (TREE_CODE (elt) != FIELD_DECL
2913 	      || (TREE_PRIVATE (elt) || TREE_PROTECTED (elt))))
2914 	{
2915 	  /* We already complained about static data members in
2916 	     finish_static_data_member_decl.  */
2917 	  if (!VAR_P (elt)
2918 	      && permerror (DECL_SOURCE_LOCATION (elt),
2919 			    TREE_CODE (TREE_TYPE (field)) == UNION_TYPE
2920 			    ? "%q#D invalid; an anonymous union may "
2921 			    "only have public non-static data members"
2922 			    : "%q#D invalid; an anonymous struct may "
2923 			    "only have public non-static data members", elt))
2924 	    {
2925 	      static bool hint;
2926 	      if (flag_permissive && !hint)
2927 		{
2928 		  hint = true;
2929 		  inform (DECL_SOURCE_LOCATION (elt),
2930 			  "this flexibility is deprecated and will be removed");
2931 		}
2932 	    }
2933 	}
2934 
2935       TREE_PRIVATE (elt) = TREE_PRIVATE (field);
2936       TREE_PROTECTED (elt) = TREE_PROTECTED (field);
2937 
2938       /* Recurse into the anonymous aggregates to correctly handle
2939 	 access control (c++/24926):
2940 
2941 	 class A {
2942 	   union {
2943 	     union {
2944 	       int i;
2945 	     };
2946 	   };
2947 	 };
2948 
2949 	 int j=A().i;  */
2950       if (DECL_NAME (elt) == NULL_TREE
2951 	  && ANON_AGGR_TYPE_P (TREE_TYPE (elt)))
2952 	finish_struct_anon_r (elt, /*complain=*/false);
2953     }
2954 }
2955 
2956 /* Check for things that are invalid.  There are probably plenty of other
2957    things we should check for also.  */
2958 
2959 static void
finish_struct_anon(tree t)2960 finish_struct_anon (tree t)
2961 {
2962   for (tree field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
2963     {
2964       if (TREE_STATIC (field))
2965 	continue;
2966       if (TREE_CODE (field) != FIELD_DECL)
2967 	continue;
2968 
2969       if (DECL_NAME (field) == NULL_TREE
2970 	  && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2971 	finish_struct_anon_r (field, /*complain=*/true);
2972     }
2973 }
2974 
2975 /* Add T to CLASSTYPE_DECL_LIST of current_class_type which
2976    will be used later during class template instantiation.
2977    When FRIEND_P is zero, T can be a static member data (VAR_DECL),
2978    a non-static member data (FIELD_DECL), a member function
2979    (FUNCTION_DECL), a nested type (RECORD_TYPE, ENUM_TYPE),
2980    a typedef (TYPE_DECL) or a member class template (TEMPLATE_DECL)
2981    When FRIEND_P is nonzero, T is either a friend class
2982    (RECORD_TYPE, TEMPLATE_DECL) or a friend function
2983    (FUNCTION_DECL, TEMPLATE_DECL).  */
2984 
2985 void
maybe_add_class_template_decl_list(tree type,tree t,int friend_p)2986 maybe_add_class_template_decl_list (tree type, tree t, int friend_p)
2987 {
2988   /* Save some memory by not creating TREE_LIST if TYPE is not template.  */
2989   if (CLASSTYPE_TEMPLATE_INFO (type))
2990     CLASSTYPE_DECL_LIST (type)
2991       = tree_cons (friend_p ? NULL_TREE : type,
2992 		   t, CLASSTYPE_DECL_LIST (type));
2993 }
2994 
2995 /* This function is called from declare_virt_assop_and_dtor via
2996    dfs_walk_all.
2997 
2998    DATA is a type that direcly or indirectly inherits the base
2999    represented by BINFO.  If BINFO contains a virtual assignment [copy
3000    assignment or move assigment] operator or a virtual constructor,
3001    declare that function in DATA if it hasn't been already declared.  */
3002 
3003 static tree
dfs_declare_virt_assop_and_dtor(tree binfo,void * data)3004 dfs_declare_virt_assop_and_dtor (tree binfo, void *data)
3005 {
3006   tree bv, fn, t = (tree)data;
3007   tree opname = assign_op_identifier;
3008 
3009   gcc_assert (t && CLASS_TYPE_P (t));
3010   gcc_assert (binfo && TREE_CODE (binfo) == TREE_BINFO);
3011 
3012   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
3013     /* A base without a vtable needs no modification, and its bases
3014        are uninteresting.  */
3015     return dfs_skip_bases;
3016 
3017   if (BINFO_PRIMARY_P (binfo))
3018     /* If this is a primary base, then we have already looked at the
3019        virtual functions of its vtable.  */
3020     return NULL_TREE;
3021 
3022   for (bv = BINFO_VIRTUALS (binfo); bv; bv = TREE_CHAIN (bv))
3023     {
3024       fn = BV_FN (bv);
3025 
3026       if (DECL_NAME (fn) == opname)
3027 	{
3028 	  if (CLASSTYPE_LAZY_COPY_ASSIGN (t))
3029 	    lazily_declare_fn (sfk_copy_assignment, t);
3030 	  if (CLASSTYPE_LAZY_MOVE_ASSIGN (t))
3031 	    lazily_declare_fn (sfk_move_assignment, t);
3032 	}
3033       else if (DECL_DESTRUCTOR_P (fn)
3034 	       && CLASSTYPE_LAZY_DESTRUCTOR (t))
3035 	lazily_declare_fn (sfk_destructor, t);
3036     }
3037 
3038   return NULL_TREE;
3039 }
3040 
3041 /* If the class type T has a direct or indirect base that contains a
3042    virtual assignment operator or a virtual destructor, declare that
3043    function in T if it hasn't been already declared.  */
3044 
3045 static void
declare_virt_assop_and_dtor(tree t)3046 declare_virt_assop_and_dtor (tree t)
3047 {
3048   if (!(TYPE_POLYMORPHIC_P (t)
3049 	&& (CLASSTYPE_LAZY_COPY_ASSIGN (t)
3050 	    || CLASSTYPE_LAZY_MOVE_ASSIGN (t)
3051 	    || CLASSTYPE_LAZY_DESTRUCTOR (t))))
3052     return;
3053 
3054   dfs_walk_all (TYPE_BINFO (t),
3055 		dfs_declare_virt_assop_and_dtor,
3056 		NULL, t);
3057 }
3058 
3059 /* Declare the inheriting constructor for class T inherited from base
3060    constructor CTOR with the parameter array PARMS of size NPARMS.  */
3061 
3062 static void
one_inheriting_sig(tree t,tree ctor,tree * parms,int nparms)3063 one_inheriting_sig (tree t, tree ctor, tree *parms, int nparms)
3064 {
3065   gcc_assert (TYPE_MAIN_VARIANT (t) == t);
3066 
3067   /* We don't declare an inheriting ctor that would be a default,
3068      copy or move ctor for derived or base.  */
3069   if (nparms == 0)
3070     return;
3071   if (nparms == 1
3072       && TREE_CODE (parms[0]) == REFERENCE_TYPE)
3073     {
3074       tree parm = TYPE_MAIN_VARIANT (TREE_TYPE (parms[0]));
3075       if (parm == t || parm == DECL_CONTEXT (ctor))
3076 	return;
3077     }
3078 
3079   tree parmlist = void_list_node;
3080   for (int i = nparms - 1; i >= 0; i--)
3081     parmlist = tree_cons (NULL_TREE, parms[i], parmlist);
3082   tree fn = implicitly_declare_fn (sfk_inheriting_constructor,
3083 				   t, false, ctor, parmlist);
3084 
3085   if (add_method (t, fn, false))
3086     {
3087       DECL_CHAIN (fn) = TYPE_FIELDS (t);
3088       TYPE_FIELDS (t) = fn;
3089     }
3090 }
3091 
3092 /* Declare all the inheriting constructors for class T inherited from base
3093    constructor CTOR.  */
3094 
3095 static void
one_inherited_ctor(tree ctor,tree t,tree using_decl)3096 one_inherited_ctor (tree ctor, tree t, tree using_decl)
3097 {
3098   tree parms = FUNCTION_FIRST_USER_PARMTYPE (ctor);
3099 
3100   if (flag_new_inheriting_ctors)
3101     {
3102       ctor = implicitly_declare_fn (sfk_inheriting_constructor,
3103 				    t, /*const*/false, ctor, parms);
3104       add_method (t, ctor, using_decl != NULL_TREE);
3105       TYPE_HAS_USER_CONSTRUCTOR (t) = true;
3106       return;
3107     }
3108 
3109   tree *new_parms = XALLOCAVEC (tree, list_length (parms));
3110   int i = 0;
3111   for (; parms && parms != void_list_node; parms = TREE_CHAIN (parms))
3112     {
3113       if (TREE_PURPOSE (parms))
3114 	one_inheriting_sig (t, ctor, new_parms, i);
3115       new_parms[i++] = TREE_VALUE (parms);
3116     }
3117   one_inheriting_sig (t, ctor, new_parms, i);
3118   if (parms == NULL_TREE)
3119     {
3120       if (warning (OPT_Winherited_variadic_ctor,
3121 		   "the ellipsis in %qD is not inherited", ctor))
3122 	inform (DECL_SOURCE_LOCATION (ctor), "%qD declared here", ctor);
3123     }
3124 }
3125 
3126 /* Create default constructors, assignment operators, and so forth for
3127    the type indicated by T, if they are needed.  CANT_HAVE_CONST_CTOR,
3128    and CANT_HAVE_CONST_ASSIGNMENT are nonzero if, for whatever reason,
3129    the class cannot have a default constructor, copy constructor
3130    taking a const reference argument, or an assignment operator taking
3131    a const reference, respectively.  */
3132 
3133 static void
add_implicitly_declared_members(tree t,tree * access_decls,int cant_have_const_cctor,int cant_have_const_assignment)3134 add_implicitly_declared_members (tree t, tree* access_decls,
3135 				 int cant_have_const_cctor,
3136 				 int cant_have_const_assignment)
3137 {
3138   /* Destructor.  */
3139   if (!CLASSTYPE_DESTRUCTOR (t))
3140     /* In general, we create destructors lazily.  */
3141     CLASSTYPE_LAZY_DESTRUCTOR (t) = 1;
3142 
3143   bool move_ok = false;
3144   if (cxx_dialect >= cxx11 && CLASSTYPE_LAZY_DESTRUCTOR (t)
3145       && !TYPE_HAS_COPY_CTOR (t) && !TYPE_HAS_COPY_ASSIGN (t)
3146       && !classtype_has_move_assign_or_move_ctor_p (t, false))
3147     move_ok = true;
3148 
3149   /* [class.ctor]
3150 
3151      If there is no user-declared constructor for a class, a default
3152      constructor is implicitly declared.  */
3153   if (! TYPE_HAS_USER_CONSTRUCTOR (t))
3154     {
3155       TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 1;
3156       CLASSTYPE_LAZY_DEFAULT_CTOR (t) = 1;
3157       if (cxx_dialect >= cxx11)
3158 	TYPE_HAS_CONSTEXPR_CTOR (t)
3159 	  /* Don't force the declaration to get a hard answer; if the
3160 	     definition would have made the class non-literal, it will still be
3161 	     non-literal because of the base or member in question, and that
3162 	     gives a better diagnostic.  */
3163 	  = type_maybe_constexpr_default_constructor (t);
3164     }
3165 
3166   /* [class.ctor]
3167 
3168      If a class definition does not explicitly declare a copy
3169      constructor, one is declared implicitly.  */
3170   if (! TYPE_HAS_COPY_CTOR (t))
3171     {
3172       TYPE_HAS_COPY_CTOR (t) = 1;
3173       TYPE_HAS_CONST_COPY_CTOR (t) = !cant_have_const_cctor;
3174       CLASSTYPE_LAZY_COPY_CTOR (t) = 1;
3175       if (move_ok)
3176 	CLASSTYPE_LAZY_MOVE_CTOR (t) = 1;
3177     }
3178 
3179   /* If there is no assignment operator, one will be created if and
3180      when it is needed.  For now, just record whether or not the type
3181      of the parameter to the assignment operator will be a const or
3182      non-const reference.  */
3183   if (!TYPE_HAS_COPY_ASSIGN (t))
3184     {
3185       TYPE_HAS_COPY_ASSIGN (t) = 1;
3186       TYPE_HAS_CONST_COPY_ASSIGN (t) = !cant_have_const_assignment;
3187       CLASSTYPE_LAZY_COPY_ASSIGN (t) = 1;
3188       if (move_ok && !LAMBDA_TYPE_P (t))
3189 	CLASSTYPE_LAZY_MOVE_ASSIGN (t) = 1;
3190     }
3191 
3192   /* We can't be lazy about declaring functions that might override
3193      a virtual function from a base class.  */
3194   declare_virt_assop_and_dtor (t);
3195 
3196   while (*access_decls)
3197     {
3198       tree using_decl = TREE_VALUE (*access_decls);
3199       tree decl = USING_DECL_DECLS (using_decl);
3200       if (DECL_NAME (using_decl) == ctor_identifier)
3201 	{
3202 	  /* declare, then remove the decl */
3203 	  tree ctor_list = decl;
3204 	  location_t loc = input_location;
3205 	  input_location = DECL_SOURCE_LOCATION (using_decl);
3206 	  for (ovl_iterator iter (ctor_list); iter; ++iter)
3207 	    one_inherited_ctor (*iter, t, using_decl);
3208 	  *access_decls = TREE_CHAIN (*access_decls);
3209 	  input_location = loc;
3210 	}
3211       else
3212 	access_decls = &TREE_CHAIN (*access_decls);
3213     }
3214 }
3215 
3216 /* Cache of enum_min_precision values.  */
3217 static GTY((deletable)) hash_map<tree, int> *enum_to_min_precision;
3218 
3219 /* Return the minimum precision of a bit-field needed to store all
3220    enumerators of ENUMERAL_TYPE TYPE.  */
3221 
3222 static int
enum_min_precision(tree type)3223 enum_min_precision (tree type)
3224 {
3225   type = TYPE_MAIN_VARIANT (type);
3226   /* For unscoped enums without fixed underlying type and without mode
3227      attribute we can just use precision of the underlying type.  */
3228   if (UNSCOPED_ENUM_P (type)
3229       && !ENUM_FIXED_UNDERLYING_TYPE_P (type)
3230       && !lookup_attribute ("mode", TYPE_ATTRIBUTES (type)))
3231     return TYPE_PRECISION (ENUM_UNDERLYING_TYPE (type));
3232 
3233   if (enum_to_min_precision == NULL)
3234     enum_to_min_precision = hash_map<tree, int>::create_ggc (37);
3235 
3236   bool existed;
3237   int &prec = enum_to_min_precision->get_or_insert (type, &existed);
3238   if (existed)
3239     return prec;
3240 
3241   tree minnode, maxnode;
3242   if (TYPE_VALUES (type))
3243     {
3244       minnode = maxnode = NULL_TREE;
3245       for (tree values = TYPE_VALUES (type);
3246 	   values; values = TREE_CHAIN (values))
3247 	{
3248 	  tree decl = TREE_VALUE (values);
3249 	  tree value = DECL_INITIAL (decl);
3250 	  if (value == error_mark_node)
3251 	    value = integer_zero_node;
3252 	  if (!minnode)
3253 	    minnode = maxnode = value;
3254 	  else if (tree_int_cst_lt (maxnode, value))
3255 	    maxnode = value;
3256 	  else if (tree_int_cst_lt (value, minnode))
3257 	    minnode = value;
3258 	}
3259     }
3260   else
3261     minnode = maxnode = integer_zero_node;
3262 
3263   signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
3264   int lowprec = tree_int_cst_min_precision (minnode, sgn);
3265   int highprec = tree_int_cst_min_precision (maxnode, sgn);
3266   prec = MAX (lowprec, highprec);
3267   return prec;
3268 }
3269 
3270 /* FIELD is a bit-field.  We are finishing the processing for its
3271    enclosing type.  Issue any appropriate messages and set appropriate
3272    flags.  Returns false if an error has been diagnosed.  */
3273 
3274 static bool
check_bitfield_decl(tree field)3275 check_bitfield_decl (tree field)
3276 {
3277   tree type = TREE_TYPE (field);
3278   tree w;
3279 
3280   /* Extract the declared width of the bitfield, which has been
3281      temporarily stashed in DECL_BIT_FIELD_REPRESENTATIVE by grokbitfield.  */
3282   w = DECL_BIT_FIELD_REPRESENTATIVE (field);
3283   gcc_assert (w != NULL_TREE);
3284   /* Remove the bit-field width indicator so that the rest of the
3285      compiler does not treat that value as a qualifier.  */
3286   DECL_BIT_FIELD_REPRESENTATIVE (field) = NULL_TREE;
3287 
3288   /* Detect invalid bit-field type.  */
3289   if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
3290     {
3291       error ("bit-field %q+#D with non-integral type", field);
3292       w = error_mark_node;
3293     }
3294   else
3295     {
3296       location_t loc = input_location;
3297       /* Avoid the non_lvalue wrapper added by fold for PLUS_EXPRs.  */
3298       STRIP_NOPS (w);
3299 
3300       /* detect invalid field size.  */
3301       input_location = DECL_SOURCE_LOCATION (field);
3302       w = cxx_constant_value (w);
3303       input_location = loc;
3304 
3305       if (TREE_CODE (w) != INTEGER_CST)
3306 	{
3307 	  error ("bit-field %q+D width not an integer constant", field);
3308 	  w = error_mark_node;
3309 	}
3310       else if (tree_int_cst_sgn (w) < 0)
3311 	{
3312 	  error ("negative width in bit-field %q+D", field);
3313 	  w = error_mark_node;
3314 	}
3315       else if (integer_zerop (w) && DECL_NAME (field) != 0)
3316 	{
3317 	  error ("zero width for bit-field %q+D", field);
3318 	  w = error_mark_node;
3319 	}
3320       else if ((TREE_CODE (type) != ENUMERAL_TYPE
3321 		&& TREE_CODE (type) != BOOLEAN_TYPE
3322 		&& compare_tree_int (w, TYPE_PRECISION (type)) > 0)
3323 	       || ((TREE_CODE (type) == ENUMERAL_TYPE
3324 		    || TREE_CODE (type) == BOOLEAN_TYPE)
3325 		   && tree_int_cst_lt (TYPE_SIZE (type), w)))
3326 	warning_at (DECL_SOURCE_LOCATION (field), 0,
3327 		    "width of %qD exceeds its type", field);
3328       else if (TREE_CODE (type) == ENUMERAL_TYPE)
3329 	{
3330 	  int prec = enum_min_precision (type);
3331 	  if (compare_tree_int (w, prec) < 0)
3332 	    warning_at (DECL_SOURCE_LOCATION (field), 0,
3333 			"%qD is too small to hold all values of %q#T",
3334 			field, type);
3335 	}
3336     }
3337 
3338   if (w != error_mark_node)
3339     {
3340       DECL_SIZE (field) = fold_convert (bitsizetype, w);
3341       DECL_BIT_FIELD (field) = 1;
3342       return true;
3343     }
3344   else
3345     {
3346       /* Non-bit-fields are aligned for their type.  */
3347       DECL_BIT_FIELD (field) = 0;
3348       CLEAR_DECL_C_BIT_FIELD (field);
3349       return false;
3350     }
3351 }
3352 
3353 /* FIELD is a non bit-field.  We are finishing the processing for its
3354    enclosing type T.  Issue any appropriate messages and set appropriate
3355    flags.  */
3356 
3357 static bool
check_field_decl(tree field,tree t,int * cant_have_const_ctor,int * no_const_asn_ref)3358 check_field_decl (tree field,
3359 		  tree t,
3360 		  int* cant_have_const_ctor,
3361 		  int* no_const_asn_ref)
3362 {
3363   tree type = strip_array_types (TREE_TYPE (field));
3364   bool any_default_members = false;
3365 
3366   /* In C++98 an anonymous union cannot contain any fields which would change
3367      the settings of CANT_HAVE_CONST_CTOR and friends.  */
3368   if (ANON_UNION_TYPE_P (type) && cxx_dialect < cxx11)
3369     ;
3370   /* And, we don't set TYPE_HAS_CONST_COPY_CTOR, etc., for anonymous
3371      structs.  So, we recurse through their fields here.  */
3372   else if (ANON_AGGR_TYPE_P (type))
3373     {
3374       for (tree fields = TYPE_FIELDS (type); fields;
3375 	   fields = DECL_CHAIN (fields))
3376 	if (TREE_CODE (fields) == FIELD_DECL)
3377 	  any_default_members |= check_field_decl (fields, t,
3378 						   cant_have_const_ctor,
3379 						   no_const_asn_ref);
3380     }
3381   /* Check members with class type for constructors, destructors,
3382      etc.  */
3383   else if (CLASS_TYPE_P (type))
3384     {
3385       /* Never let anything with uninheritable virtuals
3386 	 make it through without complaint.  */
3387       abstract_virtuals_error (field, type);
3388 
3389       if (TREE_CODE (t) == UNION_TYPE && cxx_dialect < cxx11)
3390 	{
3391 	  static bool warned;
3392 	  int oldcount = errorcount;
3393 	  if (TYPE_NEEDS_CONSTRUCTING (type))
3394 	    error ("member %q+#D with constructor not allowed in union",
3395 		   field);
3396 	  if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3397 	    error ("member %q+#D with destructor not allowed in union", field);
3398 	  if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
3399 	    error ("member %q+#D with copy assignment operator not allowed in union",
3400 		   field);
3401 	  if (!warned && errorcount > oldcount)
3402 	    {
3403 	      inform (DECL_SOURCE_LOCATION (field), "unrestricted unions "
3404 		      "only available with -std=c++11 or -std=gnu++11");
3405 	      warned = true;
3406 	    }
3407 	}
3408       else
3409 	{
3410 	  TYPE_NEEDS_CONSTRUCTING (t) |= TYPE_NEEDS_CONSTRUCTING (type);
3411 	  TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t)
3412 	    |= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type);
3413 	  TYPE_HAS_COMPLEX_COPY_ASSIGN (t)
3414 	    |= (TYPE_HAS_COMPLEX_COPY_ASSIGN (type)
3415 		|| !TYPE_HAS_COPY_ASSIGN (type));
3416 	  TYPE_HAS_COMPLEX_COPY_CTOR (t) |= (TYPE_HAS_COMPLEX_COPY_CTOR (type)
3417 					     || !TYPE_HAS_COPY_CTOR (type));
3418 	  TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) |= TYPE_HAS_COMPLEX_MOVE_ASSIGN (type);
3419 	  TYPE_HAS_COMPLEX_MOVE_CTOR (t) |= TYPE_HAS_COMPLEX_MOVE_CTOR (type);
3420 	  TYPE_HAS_COMPLEX_DFLT (t) |= (!TYPE_HAS_DEFAULT_CONSTRUCTOR (type)
3421 					|| TYPE_HAS_COMPLEX_DFLT (type));
3422 	}
3423 
3424       if (TYPE_HAS_COPY_CTOR (type)
3425 	  && !TYPE_HAS_CONST_COPY_CTOR (type))
3426 	*cant_have_const_ctor = 1;
3427 
3428       if (TYPE_HAS_COPY_ASSIGN (type)
3429 	  && !TYPE_HAS_CONST_COPY_ASSIGN (type))
3430 	*no_const_asn_ref = 1;
3431     }
3432 
3433   check_abi_tags (t, field);
3434 
3435   if (DECL_INITIAL (field) != NULL_TREE)
3436     /* `build_class_init_list' does not recognize
3437        non-FIELD_DECLs.  */
3438     any_default_members = true;
3439 
3440   return any_default_members;
3441 }
3442 
3443 /* Check the data members (both static and non-static), class-scoped
3444    typedefs, etc., appearing in the declaration of T.  Issue
3445    appropriate diagnostics.  Sets ACCESS_DECLS to a list (in
3446    declaration order) of access declarations; each TREE_VALUE in this
3447    list is a USING_DECL.
3448 
3449    In addition, set the following flags:
3450 
3451      EMPTY_P
3452        The class is empty, i.e., contains no non-static data members.
3453 
3454      CANT_HAVE_CONST_CTOR_P
3455        This class cannot have an implicitly generated copy constructor
3456        taking a const reference.
3457 
3458      CANT_HAVE_CONST_ASN_REF
3459        This class cannot have an implicitly generated assignment
3460        operator taking a const reference.
3461 
3462    All of these flags should be initialized before calling this
3463    function.
3464 
3465    Returns a pointer to the end of the TYPE_FIELDs chain; additional
3466    fields can be added by adding to this chain.  */
3467 
3468 static void
check_field_decls(tree t,tree * access_decls,int * cant_have_const_ctor_p,int * no_const_asn_ref_p)3469 check_field_decls (tree t, tree *access_decls,
3470 		   int *cant_have_const_ctor_p,
3471 		   int *no_const_asn_ref_p)
3472 {
3473   tree *field;
3474   tree *next;
3475   bool has_pointers;
3476   bool any_default_members;
3477   int cant_pack = 0;
3478   int field_access = -1;
3479 
3480   /* Assume there are no access declarations.  */
3481   *access_decls = NULL_TREE;
3482   /* Assume this class has no pointer members.  */
3483   has_pointers = false;
3484   /* Assume none of the members of this class have default
3485      initializations.  */
3486   any_default_members = false;
3487 
3488   for (field = &TYPE_FIELDS (t); *field; field = next)
3489     {
3490       tree x = *field;
3491       tree type = TREE_TYPE (x);
3492       int this_field_access;
3493 
3494       next = &DECL_CHAIN (x);
3495 
3496       if (TREE_CODE (x) == USING_DECL)
3497 	{
3498 	  /* Save the access declarations for our caller.  */
3499 	  *access_decls = tree_cons (NULL_TREE, x, *access_decls);
3500 	  continue;
3501 	}
3502 
3503       if (TREE_CODE (x) == TYPE_DECL
3504 	  || TREE_CODE (x) == TEMPLATE_DECL)
3505 	continue;
3506 
3507       if (TREE_CODE (x) == FUNCTION_DECL)
3508 	/* FIXME: We should fold in the checking from check_methods.  */
3509 	continue;
3510 
3511       /* If we've gotten this far, it's a data member, possibly static,
3512 	 or an enumerator.  */
3513       if (TREE_CODE (x) != CONST_DECL)
3514 	DECL_CONTEXT (x) = t;
3515 
3516       /* When this goes into scope, it will be a non-local reference.  */
3517       DECL_NONLOCAL (x) = 1;
3518 
3519       if (TREE_CODE (t) == UNION_TYPE)
3520 	{
3521 	  /* [class.union] (C++98)
3522 
3523 	     If a union contains a static data member, or a member of
3524 	     reference type, the program is ill-formed.
3525 
3526 	     In C++11 [class.union] says:
3527 	     If a union contains a non-static data member of reference type
3528 	     the program is ill-formed.  */
3529 	  if (VAR_P (x) && cxx_dialect < cxx11)
3530 	    {
3531 	      error ("in C++98 %q+D may not be static because it is "
3532 		     "a member of a union", x);
3533 	      continue;
3534 	    }
3535 	  if (TREE_CODE (type) == REFERENCE_TYPE
3536 	      && TREE_CODE (x) == FIELD_DECL)
3537 	    {
3538 	      error ("non-static data member %q+D in a union may not "
3539 		     "have reference type %qT", x, type);
3540 	      continue;
3541 	    }
3542 	}
3543 
3544       /* Perform error checking that did not get done in
3545 	 grokdeclarator.  */
3546       if (TREE_CODE (type) == FUNCTION_TYPE)
3547 	{
3548 	  error ("field %q+D invalidly declared function type", x);
3549 	  type = build_pointer_type (type);
3550 	  TREE_TYPE (x) = type;
3551 	}
3552       else if (TREE_CODE (type) == METHOD_TYPE)
3553 	{
3554 	  error ("field %q+D invalidly declared method type", x);
3555 	  type = build_pointer_type (type);
3556 	  TREE_TYPE (x) = type;
3557 	}
3558 
3559       if (type == error_mark_node)
3560 	continue;
3561 
3562       if (TREE_CODE (x) == CONST_DECL || VAR_P (x))
3563 	continue;
3564 
3565       /* Now it can only be a FIELD_DECL.  */
3566 
3567       if (TREE_PRIVATE (x) || TREE_PROTECTED (x))
3568 	CLASSTYPE_NON_AGGREGATE (t) = 1;
3569 
3570       /* If at least one non-static data member is non-literal, the whole
3571          class becomes non-literal.  Per Core/1453, volatile non-static
3572 	 data members and base classes are also not allowed.
3573 	 Note: if the type is incomplete we will complain later on.  */
3574       if (COMPLETE_TYPE_P (type)
3575 	  && (!literal_type_p (type) || CP_TYPE_VOLATILE_P (type)))
3576         CLASSTYPE_LITERAL_P (t) = false;
3577 
3578       /* A standard-layout class is a class that:
3579 	 ...
3580 	 has the same access control (Clause 11) for all non-static data members,
3581          ...  */
3582       this_field_access = TREE_PROTECTED (x) ? 1 : TREE_PRIVATE (x) ? 2 : 0;
3583       if (field_access == -1)
3584 	field_access = this_field_access;
3585       else if (this_field_access != field_access)
3586 	CLASSTYPE_NON_STD_LAYOUT (t) = 1;
3587 
3588       /* If this is of reference type, check if it needs an init.  */
3589       if (TREE_CODE (type) == REFERENCE_TYPE)
3590 	{
3591 	  CLASSTYPE_NON_LAYOUT_POD_P (t) = 1;
3592 	  CLASSTYPE_NON_STD_LAYOUT (t) = 1;
3593 	  if (DECL_INITIAL (x) == NULL_TREE)
3594 	    SET_CLASSTYPE_REF_FIELDS_NEED_INIT (t, 1);
3595 	  if (cxx_dialect < cxx11)
3596 	    {
3597 	      /* ARM $12.6.2: [A member initializer list] (or, for an
3598 		 aggregate, initialization by a brace-enclosed list) is the
3599 		 only way to initialize nonstatic const and reference
3600 		 members.  */
3601 	      TYPE_HAS_COMPLEX_COPY_ASSIGN (t) = 1;
3602 	      TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) = 1;
3603 	    }
3604 	}
3605 
3606       type = strip_array_types (type);
3607 
3608       if (TYPE_PACKED (t))
3609 	{
3610 	  if (!layout_pod_type_p (type) && !TYPE_PACKED (type))
3611 	    {
3612 	      warning_at
3613 		(DECL_SOURCE_LOCATION (x), 0,
3614 		 "ignoring packed attribute because of unpacked non-POD field %q#D",
3615 		 x);
3616 	      cant_pack = 1;
3617 	    }
3618 	  else if (DECL_C_BIT_FIELD (x)
3619 		   || TYPE_ALIGN (TREE_TYPE (x)) > BITS_PER_UNIT)
3620 	    DECL_PACKED (x) = 1;
3621 	}
3622 
3623       if (DECL_C_BIT_FIELD (x)
3624 	  && integer_zerop (DECL_BIT_FIELD_REPRESENTATIVE (x)))
3625 	/* We don't treat zero-width bitfields as making a class
3626 	   non-empty.  */
3627 	;
3628       else
3629 	{
3630 	  /* The class is non-empty.  */
3631 	  CLASSTYPE_EMPTY_P (t) = 0;
3632 	  /* The class is not even nearly empty.  */
3633 	  CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
3634 	  /* If one of the data members contains an empty class,
3635 	     so does T.  */
3636 	  if (CLASS_TYPE_P (type)
3637 	      && CLASSTYPE_CONTAINS_EMPTY_CLASS_P (type))
3638 	    CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t) = 1;
3639 	}
3640 
3641       /* This is used by -Weffc++ (see below). Warn only for pointers
3642 	 to members which might hold dynamic memory. So do not warn
3643 	 for pointers to functions or pointers to members.  */
3644       if (TYPE_PTR_P (type)
3645 	  && !TYPE_PTRFN_P (type))
3646 	has_pointers = true;
3647 
3648       if (CLASS_TYPE_P (type))
3649 	{
3650 	  if (CLASSTYPE_REF_FIELDS_NEED_INIT (type))
3651 	    SET_CLASSTYPE_REF_FIELDS_NEED_INIT (t, 1);
3652 	  if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (type))
3653 	    SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT (t, 1);
3654 	}
3655 
3656       if (DECL_MUTABLE_P (x) || TYPE_HAS_MUTABLE_P (type))
3657 	CLASSTYPE_HAS_MUTABLE (t) = 1;
3658 
3659       if (DECL_MUTABLE_P (x))
3660 	{
3661 	  if (CP_TYPE_CONST_P (type))
3662 	    {
3663 	      error ("member %q+D cannot be declared both %<const%> "
3664 		     "and %<mutable%>", x);
3665 	      continue;
3666 	    }
3667 	  if (TREE_CODE (type) == REFERENCE_TYPE)
3668 	    {
3669 	      error ("member %q+D cannot be declared as a %<mutable%> "
3670 		     "reference", x);
3671 	      continue;
3672 	    }
3673 	}
3674 
3675       if (! layout_pod_type_p (type))
3676 	/* DR 148 now allows pointers to members (which are POD themselves),
3677 	   to be allowed in POD structs.  */
3678 	CLASSTYPE_NON_LAYOUT_POD_P (t) = 1;
3679 
3680       if (!std_layout_type_p (type))
3681 	CLASSTYPE_NON_STD_LAYOUT (t) = 1;
3682 
3683       if (! zero_init_p (type))
3684 	CLASSTYPE_NON_ZERO_INIT_P (t) = 1;
3685 
3686       /* We set DECL_C_BIT_FIELD in grokbitfield.
3687 	 If the type and width are valid, we'll also set DECL_BIT_FIELD.  */
3688       if (DECL_C_BIT_FIELD (x))
3689 	check_bitfield_decl (x);
3690 
3691       if (check_field_decl (x, t, cant_have_const_ctor_p, no_const_asn_ref_p))
3692 	{
3693 	  if (any_default_members
3694 	      && TREE_CODE (t) == UNION_TYPE)
3695 	    error ("multiple fields in union %qT initialized", t);
3696 	  any_default_members = true;
3697 	}
3698 
3699       /* Now that we've removed bit-field widths from DECL_INITIAL,
3700 	 anything left in DECL_INITIAL is an NSDMI that makes the class
3701 	 non-aggregate in C++11.  */
3702       if (DECL_INITIAL (x) && cxx_dialect < cxx14)
3703 	CLASSTYPE_NON_AGGREGATE (t) = true;
3704 
3705       /* If any field is const, the structure type is pseudo-const.  */
3706       if (CP_TYPE_CONST_P (type))
3707 	{
3708 	  C_TYPE_FIELDS_READONLY (t) = 1;
3709 	  if (DECL_INITIAL (x) == NULL_TREE)
3710 	    SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT (t, 1);
3711 	  if (cxx_dialect < cxx11)
3712 	    {
3713 	      /* ARM $12.6.2: [A member initializer list] (or, for an
3714 		 aggregate, initialization by a brace-enclosed list) is the
3715 		 only way to initialize nonstatic const and reference
3716 		 members.  */
3717 	      TYPE_HAS_COMPLEX_COPY_ASSIGN (t) = 1;
3718 	      TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) = 1;
3719 	    }
3720 	}
3721       /* A field that is pseudo-const makes the structure likewise.  */
3722       else if (CLASS_TYPE_P (type))
3723 	{
3724 	  C_TYPE_FIELDS_READONLY (t) |= C_TYPE_FIELDS_READONLY (type);
3725 	  SET_CLASSTYPE_READONLY_FIELDS_NEED_INIT (t,
3726 	    CLASSTYPE_READONLY_FIELDS_NEED_INIT (t)
3727 	    | CLASSTYPE_READONLY_FIELDS_NEED_INIT (type));
3728 	}
3729 
3730       /* Core issue 80: A nonstatic data member is required to have a
3731 	 different name from the class iff the class has a
3732 	 user-declared constructor.  */
3733       if (constructor_name_p (DECL_NAME (x), t)
3734 	  && TYPE_HAS_USER_CONSTRUCTOR (t))
3735 	permerror (DECL_SOURCE_LOCATION (x),
3736 		   "field %q#D with same name as class", x);
3737     }
3738 
3739   /* Effective C++ rule 11: if a class has dynamic memory held by pointers,
3740      it should also define a copy constructor and an assignment operator to
3741      implement the correct copy semantic (deep vs shallow, etc.). As it is
3742      not feasible to check whether the constructors do allocate dynamic memory
3743      and store it within members, we approximate the warning like this:
3744 
3745      -- Warn only if there are members which are pointers
3746      -- Warn only if there is a non-trivial constructor (otherwise,
3747 	there cannot be memory allocated).
3748      -- Warn only if there is a non-trivial destructor. We assume that the
3749 	user at least implemented the cleanup correctly, and a destructor
3750 	is needed to free dynamic memory.
3751 
3752      This seems enough for practical purposes.  */
3753   if (warn_ecpp
3754       && has_pointers
3755       && TYPE_HAS_USER_CONSTRUCTOR (t)
3756       && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t)
3757       && !(TYPE_HAS_COPY_CTOR (t) && TYPE_HAS_COPY_ASSIGN (t)))
3758     {
3759       warning (OPT_Weffc__, "%q#T has pointer data members", t);
3760 
3761       if (! TYPE_HAS_COPY_CTOR (t))
3762 	{
3763 	  warning (OPT_Weffc__,
3764 		   "  but does not override %<%T(const %T&)%>", t, t);
3765 	  if (!TYPE_HAS_COPY_ASSIGN (t))
3766 	    warning (OPT_Weffc__, "  or %<operator=(const %T&)%>", t);
3767 	}
3768       else if (! TYPE_HAS_COPY_ASSIGN (t))
3769 	warning (OPT_Weffc__,
3770 		 "  but does not override %<operator=(const %T&)%>", t);
3771     }
3772 
3773   /* Non-static data member initializers make the default constructor
3774      non-trivial.  */
3775   if (any_default_members)
3776     {
3777       TYPE_NEEDS_CONSTRUCTING (t) = true;
3778       TYPE_HAS_COMPLEX_DFLT (t) = true;
3779     }
3780 
3781   /* If any of the fields couldn't be packed, unset TYPE_PACKED.  */
3782   if (cant_pack)
3783     TYPE_PACKED (t) = 0;
3784 
3785   /* Check anonymous struct/anonymous union fields.  */
3786   finish_struct_anon (t);
3787 
3788   /* We've built up the list of access declarations in reverse order.
3789      Fix that now.  */
3790   *access_decls = nreverse (*access_decls);
3791 }
3792 
3793 /* If TYPE is an empty class type, records its OFFSET in the table of
3794    OFFSETS.  */
3795 
3796 static int
record_subobject_offset(tree type,tree offset,splay_tree offsets)3797 record_subobject_offset (tree type, tree offset, splay_tree offsets)
3798 {
3799   splay_tree_node n;
3800 
3801   if (!is_empty_class (type))
3802     return 0;
3803 
3804   /* Record the location of this empty object in OFFSETS.  */
3805   n = splay_tree_lookup (offsets, (splay_tree_key) offset);
3806   if (!n)
3807     n = splay_tree_insert (offsets,
3808 			   (splay_tree_key) offset,
3809 			   (splay_tree_value) NULL_TREE);
3810   n->value = ((splay_tree_value)
3811 	      tree_cons (NULL_TREE,
3812 			 type,
3813 			 (tree) n->value));
3814 
3815   return 0;
3816 }
3817 
3818 /* Returns nonzero if TYPE is an empty class type and there is
3819    already an entry in OFFSETS for the same TYPE as the same OFFSET.  */
3820 
3821 static int
check_subobject_offset(tree type,tree offset,splay_tree offsets)3822 check_subobject_offset (tree type, tree offset, splay_tree offsets)
3823 {
3824   splay_tree_node n;
3825   tree t;
3826 
3827   if (!is_empty_class (type))
3828     return 0;
3829 
3830   /* Record the location of this empty object in OFFSETS.  */
3831   n = splay_tree_lookup (offsets, (splay_tree_key) offset);
3832   if (!n)
3833     return 0;
3834 
3835   for (t = (tree) n->value; t; t = TREE_CHAIN (t))
3836     if (same_type_p (TREE_VALUE (t), type))
3837       return 1;
3838 
3839   return 0;
3840 }
3841 
3842 /* Walk through all the subobjects of TYPE (located at OFFSET).  Call
3843    F for every subobject, passing it the type, offset, and table of
3844    OFFSETS.  If VBASES_P is one, then virtual non-primary bases should
3845    be traversed.
3846 
3847    If MAX_OFFSET is non-NULL, then subobjects with an offset greater
3848    than MAX_OFFSET will not be walked.
3849 
3850    If F returns a nonzero value, the traversal ceases, and that value
3851    is returned.  Otherwise, returns zero.  */
3852 
3853 static int
walk_subobject_offsets(tree type,subobject_offset_fn f,tree offset,splay_tree offsets,tree max_offset,int vbases_p)3854 walk_subobject_offsets (tree type,
3855 			subobject_offset_fn f,
3856 			tree offset,
3857 			splay_tree offsets,
3858 			tree max_offset,
3859 			int vbases_p)
3860 {
3861   int r = 0;
3862   tree type_binfo = NULL_TREE;
3863 
3864   /* If this OFFSET is bigger than the MAX_OFFSET, then we should
3865      stop.  */
3866   if (max_offset && tree_int_cst_lt (max_offset, offset))
3867     return 0;
3868 
3869   if (type == error_mark_node)
3870     return 0;
3871 
3872   if (!TYPE_P (type))
3873     {
3874       type_binfo = type;
3875       type = BINFO_TYPE (type);
3876     }
3877 
3878   if (CLASS_TYPE_P (type))
3879     {
3880       tree field;
3881       tree binfo;
3882       int i;
3883 
3884       /* Avoid recursing into objects that are not interesting.  */
3885       if (!CLASSTYPE_CONTAINS_EMPTY_CLASS_P (type))
3886 	return 0;
3887 
3888       /* Record the location of TYPE.  */
3889       r = (*f) (type, offset, offsets);
3890       if (r)
3891 	return r;
3892 
3893       /* Iterate through the direct base classes of TYPE.  */
3894       if (!type_binfo)
3895 	type_binfo = TYPE_BINFO (type);
3896       for (i = 0; BINFO_BASE_ITERATE (type_binfo, i, binfo); i++)
3897 	{
3898 	  tree binfo_offset;
3899 
3900 	  if (BINFO_VIRTUAL_P (binfo))
3901 	    continue;
3902 
3903 	  tree orig_binfo;
3904 	  /* We cannot rely on BINFO_OFFSET being set for the base
3905 	     class yet, but the offsets for direct non-virtual
3906 	     bases can be calculated by going back to the TYPE.  */
3907 	  orig_binfo = BINFO_BASE_BINFO (TYPE_BINFO (type), i);
3908 	  binfo_offset = size_binop (PLUS_EXPR,
3909 				     offset,
3910 				     BINFO_OFFSET (orig_binfo));
3911 
3912 	  r = walk_subobject_offsets (binfo,
3913 				      f,
3914 				      binfo_offset,
3915 				      offsets,
3916 				      max_offset,
3917 				      /*vbases_p=*/0);
3918 	  if (r)
3919 	    return r;
3920 	}
3921 
3922       if (CLASSTYPE_VBASECLASSES (type))
3923 	{
3924 	  unsigned ix;
3925 	  vec<tree, va_gc> *vbases;
3926 
3927 	  /* Iterate through the virtual base classes of TYPE.  In G++
3928 	     3.2, we included virtual bases in the direct base class
3929 	     loop above, which results in incorrect results; the
3930 	     correct offsets for virtual bases are only known when
3931 	     working with the most derived type.  */
3932 	  if (vbases_p)
3933 	    for (vbases = CLASSTYPE_VBASECLASSES (type), ix = 0;
3934 		 vec_safe_iterate (vbases, ix, &binfo); ix++)
3935 	      {
3936 		r = walk_subobject_offsets (binfo,
3937 					    f,
3938 					    size_binop (PLUS_EXPR,
3939 							offset,
3940 							BINFO_OFFSET (binfo)),
3941 					    offsets,
3942 					    max_offset,
3943 					    /*vbases_p=*/0);
3944 		if (r)
3945 		  return r;
3946 	      }
3947 	  else
3948 	    {
3949 	      /* We still have to walk the primary base, if it is
3950 		 virtual.  (If it is non-virtual, then it was walked
3951 		 above.)  */
3952 	      tree vbase = get_primary_binfo (type_binfo);
3953 
3954 	      if (vbase && BINFO_VIRTUAL_P (vbase)
3955 		  && BINFO_PRIMARY_P (vbase)
3956 		  && BINFO_INHERITANCE_CHAIN (vbase) == type_binfo)
3957 		{
3958 		  r = (walk_subobject_offsets
3959 		       (vbase, f, offset,
3960 			offsets, max_offset, /*vbases_p=*/0));
3961 		  if (r)
3962 		    return r;
3963 		}
3964 	    }
3965 	}
3966 
3967       /* Iterate through the fields of TYPE.  */
3968       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
3969 	if (TREE_CODE (field) == FIELD_DECL
3970 	    && TREE_TYPE (field) != error_mark_node
3971 	    && !DECL_ARTIFICIAL (field))
3972 	  {
3973 	    tree field_offset;
3974 
3975 	    field_offset = byte_position (field);
3976 
3977 	    r = walk_subobject_offsets (TREE_TYPE (field),
3978 					f,
3979 					size_binop (PLUS_EXPR,
3980 						    offset,
3981 						    field_offset),
3982 					offsets,
3983 					max_offset,
3984 					/*vbases_p=*/1);
3985 	    if (r)
3986 	      return r;
3987 	  }
3988     }
3989   else if (TREE_CODE (type) == ARRAY_TYPE)
3990     {
3991       tree element_type = strip_array_types (type);
3992       tree domain = TYPE_DOMAIN (type);
3993       tree index;
3994 
3995       /* Avoid recursing into objects that are not interesting.  */
3996       if (!CLASS_TYPE_P (element_type)
3997 	  || !CLASSTYPE_CONTAINS_EMPTY_CLASS_P (element_type)
3998 	  || !domain
3999 	  || integer_minus_onep (TYPE_MAX_VALUE (domain)))
4000 	return 0;
4001 
4002       /* Step through each of the elements in the array.  */
4003       for (index = size_zero_node;
4004 	   !tree_int_cst_lt (TYPE_MAX_VALUE (domain), index);
4005 	   index = size_binop (PLUS_EXPR, index, size_one_node))
4006 	{
4007 	  r = walk_subobject_offsets (TREE_TYPE (type),
4008 				      f,
4009 				      offset,
4010 				      offsets,
4011 				      max_offset,
4012 				      /*vbases_p=*/1);
4013 	  if (r)
4014 	    return r;
4015 	  offset = size_binop (PLUS_EXPR, offset,
4016 			       TYPE_SIZE_UNIT (TREE_TYPE (type)));
4017 	  /* If this new OFFSET is bigger than the MAX_OFFSET, then
4018 	     there's no point in iterating through the remaining
4019 	     elements of the array.  */
4020 	  if (max_offset && tree_int_cst_lt (max_offset, offset))
4021 	    break;
4022 	}
4023     }
4024 
4025   return 0;
4026 }
4027 
4028 /* Record all of the empty subobjects of TYPE (either a type or a
4029    binfo).  If IS_DATA_MEMBER is true, then a non-static data member
4030    is being placed at OFFSET; otherwise, it is a base class that is
4031    being placed at OFFSET.  */
4032 
4033 static void
record_subobject_offsets(tree type,tree offset,splay_tree offsets,bool is_data_member)4034 record_subobject_offsets (tree type,
4035 			  tree offset,
4036 			  splay_tree offsets,
4037 			  bool is_data_member)
4038 {
4039   tree max_offset;
4040   /* If recording subobjects for a non-static data member or a
4041      non-empty base class , we do not need to record offsets beyond
4042      the size of the biggest empty class.  Additional data members
4043      will go at the end of the class.  Additional base classes will go
4044      either at offset zero (if empty, in which case they cannot
4045      overlap with offsets past the size of the biggest empty class) or
4046      at the end of the class.
4047 
4048      However, if we are placing an empty base class, then we must record
4049      all offsets, as either the empty class is at offset zero (where
4050      other empty classes might later be placed) or at the end of the
4051      class (where other objects might then be placed, so other empty
4052      subobjects might later overlap).  */
4053   if (is_data_member
4054       || !is_empty_class (BINFO_TYPE (type)))
4055     max_offset = sizeof_biggest_empty_class;
4056   else
4057     max_offset = NULL_TREE;
4058   walk_subobject_offsets (type, record_subobject_offset, offset,
4059 			  offsets, max_offset, is_data_member);
4060 }
4061 
4062 /* Returns nonzero if any of the empty subobjects of TYPE (located at
4063    OFFSET) conflict with entries in OFFSETS.  If VBASES_P is nonzero,
4064    virtual bases of TYPE are examined.  */
4065 
4066 static int
layout_conflict_p(tree type,tree offset,splay_tree offsets,int vbases_p)4067 layout_conflict_p (tree type,
4068 		   tree offset,
4069 		   splay_tree offsets,
4070 		   int vbases_p)
4071 {
4072   splay_tree_node max_node;
4073 
4074   /* Get the node in OFFSETS that indicates the maximum offset where
4075      an empty subobject is located.  */
4076   max_node = splay_tree_max (offsets);
4077   /* If there aren't any empty subobjects, then there's no point in
4078      performing this check.  */
4079   if (!max_node)
4080     return 0;
4081 
4082   return walk_subobject_offsets (type, check_subobject_offset, offset,
4083 				 offsets, (tree) (max_node->key),
4084 				 vbases_p);
4085 }
4086 
4087 /* DECL is a FIELD_DECL corresponding either to a base subobject of a
4088    non-static data member of the type indicated by RLI.  BINFO is the
4089    binfo corresponding to the base subobject, OFFSETS maps offsets to
4090    types already located at those offsets.  This function determines
4091    the position of the DECL.  */
4092 
4093 static void
layout_nonempty_base_or_field(record_layout_info rli,tree decl,tree binfo,splay_tree offsets)4094 layout_nonempty_base_or_field (record_layout_info rli,
4095 			       tree decl,
4096 			       tree binfo,
4097 			       splay_tree offsets)
4098 {
4099   tree offset = NULL_TREE;
4100   bool field_p;
4101   tree type;
4102 
4103   if (binfo)
4104     {
4105       /* For the purposes of determining layout conflicts, we want to
4106 	 use the class type of BINFO; TREE_TYPE (DECL) will be the
4107 	 CLASSTYPE_AS_BASE version, which does not contain entries for
4108 	 zero-sized bases.  */
4109       type = TREE_TYPE (binfo);
4110       field_p = false;
4111     }
4112   else
4113     {
4114       type = TREE_TYPE (decl);
4115       field_p = true;
4116     }
4117 
4118   /* Try to place the field.  It may take more than one try if we have
4119      a hard time placing the field without putting two objects of the
4120      same type at the same address.  */
4121   while (1)
4122     {
4123       struct record_layout_info_s old_rli = *rli;
4124 
4125       /* Place this field.  */
4126       place_field (rli, decl);
4127       offset = byte_position (decl);
4128 
4129       /* We have to check to see whether or not there is already
4130 	 something of the same type at the offset we're about to use.
4131 	 For example, consider:
4132 
4133 	   struct S {};
4134 	   struct T : public S { int i; };
4135 	   struct U : public S, public T {};
4136 
4137 	 Here, we put S at offset zero in U.  Then, we can't put T at
4138 	 offset zero -- its S component would be at the same address
4139 	 as the S we already allocated.  So, we have to skip ahead.
4140 	 Since all data members, including those whose type is an
4141 	 empty class, have nonzero size, any overlap can happen only
4142 	 with a direct or indirect base-class -- it can't happen with
4143 	 a data member.  */
4144       /* In a union, overlap is permitted; all members are placed at
4145 	 offset zero.  */
4146       if (TREE_CODE (rli->t) == UNION_TYPE)
4147 	break;
4148       if (layout_conflict_p (field_p ? type : binfo, offset,
4149 			     offsets, field_p))
4150 	{
4151 	  /* Strip off the size allocated to this field.  That puts us
4152 	     at the first place we could have put the field with
4153 	     proper alignment.  */
4154 	  *rli = old_rli;
4155 
4156 	  /* Bump up by the alignment required for the type.  */
4157 	  rli->bitpos
4158 	    = size_binop (PLUS_EXPR, rli->bitpos,
4159 			  bitsize_int (binfo
4160 				       ? CLASSTYPE_ALIGN (type)
4161 				       : TYPE_ALIGN (type)));
4162 	  normalize_rli (rli);
4163 	}
4164       else if (TREE_CODE (type) == NULLPTR_TYPE
4165 	       && warn_abi && abi_version_crosses (9))
4166 	{
4167 	  /* Before ABI v9, we were giving nullptr_t alignment of 1; if
4168 	     the offset wasn't aligned like a pointer when we started to
4169 	     layout this field, that affects its position.  */
4170 	  tree pos = rli_size_unit_so_far (&old_rli);
4171 	  if (int_cst_value (pos) % TYPE_ALIGN_UNIT (ptr_type_node) != 0)
4172 	    {
4173 	      if (abi_version_at_least (9))
4174 		warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wabi,
4175 			    "alignment of %qD increased in -fabi-version=9 "
4176 			    "(GCC 5.2)", decl);
4177 	      else
4178 		warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wabi, "alignment "
4179 			    "of %qD will increase in -fabi-version=9", decl);
4180 	    }
4181 	  break;
4182 	}
4183       else
4184 	/* There was no conflict.  We're done laying out this field.  */
4185 	break;
4186     }
4187 
4188   /* Now that we know where it will be placed, update its
4189      BINFO_OFFSET.  */
4190   if (binfo && CLASS_TYPE_P (BINFO_TYPE (binfo)))
4191     /* Indirect virtual bases may have a nonzero BINFO_OFFSET at
4192        this point because their BINFO_OFFSET is copied from another
4193        hierarchy.  Therefore, we may not need to add the entire
4194        OFFSET.  */
4195     propagate_binfo_offsets (binfo,
4196 			     size_diffop_loc (input_location,
4197 					  fold_convert (ssizetype, offset),
4198 					  fold_convert (ssizetype,
4199 						   BINFO_OFFSET (binfo))));
4200 }
4201 
4202 /* Returns true if TYPE is empty and OFFSET is nonzero.  */
4203 
4204 static int
empty_base_at_nonzero_offset_p(tree type,tree offset,splay_tree)4205 empty_base_at_nonzero_offset_p (tree type,
4206 				tree offset,
4207 				splay_tree /*offsets*/)
4208 {
4209   return is_empty_class (type) && !integer_zerop (offset);
4210 }
4211 
4212 /* Layout the empty base BINFO.  EOC indicates the byte currently just
4213    past the end of the class, and should be correctly aligned for a
4214    class of the type indicated by BINFO; OFFSETS gives the offsets of
4215    the empty bases allocated so far. T is the most derived
4216    type.  Return nonzero iff we added it at the end.  */
4217 
4218 static bool
layout_empty_base(record_layout_info rli,tree binfo,tree eoc,splay_tree offsets)4219 layout_empty_base (record_layout_info rli, tree binfo,
4220 		   tree eoc, splay_tree offsets)
4221 {
4222   tree alignment;
4223   tree basetype = BINFO_TYPE (binfo);
4224   bool atend = false;
4225 
4226   /* This routine should only be used for empty classes.  */
4227   gcc_assert (is_empty_class (basetype));
4228   alignment = ssize_int (CLASSTYPE_ALIGN_UNIT (basetype));
4229 
4230   if (!integer_zerop (BINFO_OFFSET (binfo)))
4231     propagate_binfo_offsets
4232       (binfo, size_diffop_loc (input_location,
4233 			       size_zero_node, BINFO_OFFSET (binfo)));
4234 
4235   /* This is an empty base class.  We first try to put it at offset
4236      zero.  */
4237   if (layout_conflict_p (binfo,
4238 			 BINFO_OFFSET (binfo),
4239 			 offsets,
4240 			 /*vbases_p=*/0))
4241     {
4242       /* That didn't work.  Now, we move forward from the next
4243 	 available spot in the class.  */
4244       atend = true;
4245       propagate_binfo_offsets (binfo, fold_convert (ssizetype, eoc));
4246       while (1)
4247 	{
4248 	  if (!layout_conflict_p (binfo,
4249 				  BINFO_OFFSET (binfo),
4250 				  offsets,
4251 				  /*vbases_p=*/0))
4252 	    /* We finally found a spot where there's no overlap.  */
4253 	    break;
4254 
4255 	  /* There's overlap here, too.  Bump along to the next spot.  */
4256 	  propagate_binfo_offsets (binfo, alignment);
4257 	}
4258     }
4259 
4260   if (CLASSTYPE_USER_ALIGN (basetype))
4261     {
4262       rli->record_align = MAX (rli->record_align, CLASSTYPE_ALIGN (basetype));
4263       if (warn_packed)
4264 	rli->unpacked_align = MAX (rli->unpacked_align, CLASSTYPE_ALIGN (basetype));
4265       TYPE_USER_ALIGN (rli->t) = 1;
4266     }
4267 
4268   return atend;
4269 }
4270 
4271 /* Build the FIELD_DECL for BASETYPE as a base of T, add it to the chain of
4272    fields at NEXT_FIELD, and return it.  */
4273 
4274 static tree
build_base_field_1(tree t,tree basetype,tree * & next_field)4275 build_base_field_1 (tree t, tree basetype, tree *&next_field)
4276 {
4277   /* Create the FIELD_DECL.  */
4278   gcc_assert (CLASSTYPE_AS_BASE (basetype));
4279   tree decl = build_decl (input_location,
4280 			  FIELD_DECL, NULL_TREE, CLASSTYPE_AS_BASE (basetype));
4281   DECL_ARTIFICIAL (decl) = 1;
4282   DECL_IGNORED_P (decl) = 1;
4283   DECL_FIELD_CONTEXT (decl) = t;
4284   if (is_empty_class (basetype))
4285     /* CLASSTYPE_SIZE is one byte, but the field needs to have size zero.  */
4286     DECL_SIZE (decl) = DECL_SIZE_UNIT (decl) = size_zero_node;
4287   else
4288     {
4289       DECL_SIZE (decl) = CLASSTYPE_SIZE (basetype);
4290       DECL_SIZE_UNIT (decl) = CLASSTYPE_SIZE_UNIT (basetype);
4291     }
4292   SET_DECL_ALIGN (decl, CLASSTYPE_ALIGN (basetype));
4293   DECL_USER_ALIGN (decl) = CLASSTYPE_USER_ALIGN (basetype);
4294   SET_DECL_MODE (decl, TYPE_MODE (basetype));
4295   DECL_FIELD_IS_BASE (decl) = 1;
4296 
4297   /* Add the new FIELD_DECL to the list of fields for T.  */
4298   DECL_CHAIN (decl) = *next_field;
4299   *next_field = decl;
4300   next_field = &DECL_CHAIN (decl);
4301 
4302   return decl;
4303 }
4304 
4305 /* Layout the base given by BINFO in the class indicated by RLI.
4306    *BASE_ALIGN is a running maximum of the alignments of
4307    any base class.  OFFSETS gives the location of empty base
4308    subobjects.  T is the most derived type.  Return nonzero if the new
4309    object cannot be nearly-empty.  A new FIELD_DECL is inserted at
4310    *NEXT_FIELD, unless BINFO is for an empty base class.
4311 
4312    Returns the location at which the next field should be inserted.  */
4313 
4314 static tree *
build_base_field(record_layout_info rli,tree binfo,splay_tree offsets,tree * next_field)4315 build_base_field (record_layout_info rli, tree binfo,
4316 		  splay_tree offsets, tree *next_field)
4317 {
4318   tree t = rli->t;
4319   tree basetype = BINFO_TYPE (binfo);
4320 
4321   if (!COMPLETE_TYPE_P (basetype))
4322     /* This error is now reported in xref_tag, thus giving better
4323        location information.  */
4324     return next_field;
4325 
4326   /* Place the base class.  */
4327   if (!is_empty_class (basetype))
4328     {
4329       tree decl;
4330 
4331       /* The containing class is non-empty because it has a non-empty
4332 	 base class.  */
4333       CLASSTYPE_EMPTY_P (t) = 0;
4334 
4335       /* Create the FIELD_DECL.  */
4336       decl = build_base_field_1 (t, basetype, next_field);
4337 
4338       /* Try to place the field.  It may take more than one try if we
4339 	 have a hard time placing the field without putting two
4340 	 objects of the same type at the same address.  */
4341       layout_nonempty_base_or_field (rli, decl, binfo, offsets);
4342     }
4343   else
4344     {
4345       tree eoc;
4346       bool atend;
4347 
4348       /* On some platforms (ARM), even empty classes will not be
4349 	 byte-aligned.  */
4350       eoc = round_up_loc (input_location,
4351 		      rli_size_unit_so_far (rli),
4352 		      CLASSTYPE_ALIGN_UNIT (basetype));
4353       atend = layout_empty_base (rli, binfo, eoc, offsets);
4354       /* A nearly-empty class "has no proper base class that is empty,
4355 	 not morally virtual, and at an offset other than zero."  */
4356       if (!BINFO_VIRTUAL_P (binfo) && CLASSTYPE_NEARLY_EMPTY_P (t))
4357 	{
4358 	  if (atend)
4359 	    CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
4360 	  /* The check above (used in G++ 3.2) is insufficient because
4361 	     an empty class placed at offset zero might itself have an
4362 	     empty base at a nonzero offset.  */
4363 	  else if (walk_subobject_offsets (basetype,
4364 					   empty_base_at_nonzero_offset_p,
4365 					   size_zero_node,
4366 					   /*offsets=*/NULL,
4367 					   /*max_offset=*/NULL_TREE,
4368 					   /*vbases_p=*/true))
4369 	    CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
4370 	}
4371 
4372       /* We used to not create a FIELD_DECL for empty base classes because of
4373 	 back end issues with overlapping FIELD_DECLs, but that doesn't seem to
4374 	 be a problem anymore.  We need them to handle initialization of C++17
4375 	 aggregate bases.  */
4376       if (cxx_dialect >= cxx17 && !BINFO_VIRTUAL_P (binfo))
4377 	{
4378 	  tree decl = build_base_field_1 (t, basetype, next_field);
4379 	  DECL_FIELD_OFFSET (decl) = BINFO_OFFSET (binfo);
4380 	  DECL_FIELD_BIT_OFFSET (decl) = bitsize_zero_node;
4381 	  SET_DECL_OFFSET_ALIGN (decl, BITS_PER_UNIT);
4382 	}
4383 
4384       /* An empty virtual base causes a class to be non-empty
4385 	 -- but in that case we do not need to clear CLASSTYPE_EMPTY_P
4386 	 here because that was already done when the virtual table
4387 	 pointer was created.  */
4388     }
4389 
4390   /* Record the offsets of BINFO and its base subobjects.  */
4391   record_subobject_offsets (binfo,
4392 			    BINFO_OFFSET (binfo),
4393 			    offsets,
4394 			    /*is_data_member=*/false);
4395 
4396   return next_field;
4397 }
4398 
4399 /* Layout all of the non-virtual base classes.  Record empty
4400    subobjects in OFFSETS.  T is the most derived type.  Return nonzero
4401    if the type cannot be nearly empty.  The fields created
4402    corresponding to the base classes will be inserted at
4403    *NEXT_FIELD.  */
4404 
4405 static void
build_base_fields(record_layout_info rli,splay_tree offsets,tree * next_field)4406 build_base_fields (record_layout_info rli,
4407 		   splay_tree offsets, tree *next_field)
4408 {
4409   /* Chain to hold all the new FIELD_DECLs which stand in for base class
4410      subobjects.  */
4411   tree t = rli->t;
4412   int n_baseclasses = BINFO_N_BASE_BINFOS (TYPE_BINFO (t));
4413   int i;
4414 
4415   /* The primary base class is always allocated first.  */
4416   if (CLASSTYPE_HAS_PRIMARY_BASE_P (t))
4417     next_field = build_base_field (rli, CLASSTYPE_PRIMARY_BINFO (t),
4418 				   offsets, next_field);
4419 
4420   /* Now allocate the rest of the bases.  */
4421   for (i = 0; i < n_baseclasses; ++i)
4422     {
4423       tree base_binfo;
4424 
4425       base_binfo = BINFO_BASE_BINFO (TYPE_BINFO (t), i);
4426 
4427       /* The primary base was already allocated above, so we don't
4428 	 need to allocate it again here.  */
4429       if (base_binfo == CLASSTYPE_PRIMARY_BINFO (t))
4430 	continue;
4431 
4432       /* Virtual bases are added at the end (a primary virtual base
4433 	 will have already been added).  */
4434       if (BINFO_VIRTUAL_P (base_binfo))
4435 	continue;
4436 
4437       next_field = build_base_field (rli, base_binfo,
4438 				     offsets, next_field);
4439     }
4440 }
4441 
4442 /* Go through the TYPE_FIELDS of T issuing any appropriate
4443    diagnostics, figuring out which methods override which other
4444    methods, and so forth.  */
4445 
4446 static void
check_methods(tree t)4447 check_methods (tree t)
4448 {
4449   for (tree x = TYPE_FIELDS (t); x; x = DECL_CHAIN (x))
4450     if (DECL_DECLARES_FUNCTION_P (x))
4451       {
4452 	check_for_override (x, t);
4453 
4454 	if (DECL_PURE_VIRTUAL_P (x)
4455 	    && (TREE_CODE (x) != FUNCTION_DECL || ! DECL_VINDEX (x)))
4456 	  error ("initializer specified for non-virtual method %q+D", x);
4457 	/* The name of the field is the original field name
4458 	   Save this in auxiliary field for later overloading.  */
4459 	if (TREE_CODE (x) == FUNCTION_DECL && DECL_VINDEX (x))
4460 	  {
4461 	    TYPE_POLYMORPHIC_P (t) = 1;
4462 	    if (DECL_PURE_VIRTUAL_P (x))
4463 	      vec_safe_push (CLASSTYPE_PURE_VIRTUALS (t), x);
4464 	  }
4465 
4466 	/* All user-provided destructors are non-trivial.
4467 	   Constructors and assignment ops are handled in
4468 	   grok_special_member_properties.  */
4469 	if (DECL_DESTRUCTOR_P (x) && user_provided_p (x))
4470 	  TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) = 1;
4471 	if (!DECL_VIRTUAL_P (x)
4472 	    && lookup_attribute ("transaction_safe_dynamic",
4473 				 DECL_ATTRIBUTES (x)))
4474 	  error_at (DECL_SOURCE_LOCATION (x),
4475 		    "%<transaction_safe_dynamic%> may only be specified for "
4476 		    "a virtual function");
4477       }
4478 }
4479 
4480 /* FN is a constructor or destructor.  Clone the declaration to create
4481    a specialized in-charge or not-in-charge version, as indicated by
4482    NAME.  */
4483 
4484 static tree
build_clone(tree fn,tree name)4485 build_clone (tree fn, tree name)
4486 {
4487   tree parms;
4488   tree clone;
4489 
4490   /* Copy the function.  */
4491   clone = copy_decl (fn);
4492   /* Reset the function name.  */
4493   DECL_NAME (clone) = name;
4494   /* Remember where this function came from.  */
4495   DECL_ABSTRACT_ORIGIN (clone) = fn;
4496   /* Make it easy to find the CLONE given the FN.  */
4497   DECL_CHAIN (clone) = DECL_CHAIN (fn);
4498   DECL_CHAIN (fn) = clone;
4499 
4500   /* If this is a template, do the rest on the DECL_TEMPLATE_RESULT.  */
4501   if (TREE_CODE (clone) == TEMPLATE_DECL)
4502     {
4503       tree result = build_clone (DECL_TEMPLATE_RESULT (clone), name);
4504       DECL_TEMPLATE_RESULT (clone) = result;
4505       DECL_TEMPLATE_INFO (result) = copy_node (DECL_TEMPLATE_INFO (result));
4506       DECL_TI_TEMPLATE (result) = clone;
4507       TREE_TYPE (clone) = TREE_TYPE (result);
4508       return clone;
4509     }
4510   else
4511     {
4512       // Clone constraints.
4513       if (flag_concepts)
4514         if (tree ci = get_constraints (fn))
4515           set_constraints (clone, copy_node (ci));
4516     }
4517 
4518 
4519   SET_DECL_ASSEMBLER_NAME (clone, NULL_TREE);
4520   DECL_CLONED_FUNCTION (clone) = fn;
4521   /* There's no pending inline data for this function.  */
4522   DECL_PENDING_INLINE_INFO (clone) = NULL;
4523   DECL_PENDING_INLINE_P (clone) = 0;
4524 
4525   /* The base-class destructor is not virtual.  */
4526   if (name == base_dtor_identifier)
4527     {
4528       DECL_VIRTUAL_P (clone) = 0;
4529       if (TREE_CODE (clone) != TEMPLATE_DECL)
4530 	DECL_VINDEX (clone) = NULL_TREE;
4531     }
4532 
4533   bool ctor_omit_inherited_parms_p = ctor_omit_inherited_parms (clone);
4534   if (ctor_omit_inherited_parms_p)
4535     gcc_assert (DECL_HAS_IN_CHARGE_PARM_P (clone));
4536 
4537   /* If there was an in-charge parameter, drop it from the function
4538      type.  */
4539   if (DECL_HAS_IN_CHARGE_PARM_P (clone))
4540     {
4541       tree basetype;
4542       tree parmtypes;
4543       tree exceptions;
4544 
4545       exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (clone));
4546       basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (clone));
4547       parmtypes = TYPE_ARG_TYPES (TREE_TYPE (clone));
4548       /* Skip the `this' parameter.  */
4549       parmtypes = TREE_CHAIN (parmtypes);
4550       /* Skip the in-charge parameter.  */
4551       parmtypes = TREE_CHAIN (parmtypes);
4552       /* And the VTT parm, in a complete [cd]tor.  */
4553       if (DECL_HAS_VTT_PARM_P (fn)
4554 	  && ! DECL_NEEDS_VTT_PARM_P (clone))
4555 	parmtypes = TREE_CHAIN (parmtypes);
4556       if (ctor_omit_inherited_parms_p)
4557 	{
4558 	  /* If we're omitting inherited parms, that just leaves the VTT.  */
4559 	  gcc_assert (DECL_NEEDS_VTT_PARM_P (clone));
4560 	  parmtypes = tree_cons (NULL_TREE, vtt_parm_type, void_list_node);
4561 	}
4562       TREE_TYPE (clone)
4563 	= build_method_type_directly (basetype,
4564 				      TREE_TYPE (TREE_TYPE (clone)),
4565 				      parmtypes);
4566       if (exceptions)
4567 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone),
4568 						     exceptions);
4569       TREE_TYPE (clone)
4570 	= cp_build_type_attribute_variant (TREE_TYPE (clone),
4571 					   TYPE_ATTRIBUTES (TREE_TYPE (fn)));
4572     }
4573 
4574   /* Copy the function parameters.  */
4575   DECL_ARGUMENTS (clone) = copy_list (DECL_ARGUMENTS (clone));
4576   /* Remove the in-charge parameter.  */
4577   if (DECL_HAS_IN_CHARGE_PARM_P (clone))
4578     {
4579       DECL_CHAIN (DECL_ARGUMENTS (clone))
4580 	= DECL_CHAIN (DECL_CHAIN (DECL_ARGUMENTS (clone)));
4581       DECL_HAS_IN_CHARGE_PARM_P (clone) = 0;
4582     }
4583   /* And the VTT parm, in a complete [cd]tor.  */
4584   if (DECL_HAS_VTT_PARM_P (fn))
4585     {
4586       if (DECL_NEEDS_VTT_PARM_P (clone))
4587 	DECL_HAS_VTT_PARM_P (clone) = 1;
4588       else
4589 	{
4590 	  DECL_CHAIN (DECL_ARGUMENTS (clone))
4591 	    = DECL_CHAIN (DECL_CHAIN (DECL_ARGUMENTS (clone)));
4592 	  DECL_HAS_VTT_PARM_P (clone) = 0;
4593 	}
4594     }
4595 
4596   /* A base constructor inheriting from a virtual base doesn't get the
4597      arguments.  */
4598   if (ctor_omit_inherited_parms_p)
4599     DECL_CHAIN (DECL_CHAIN (DECL_ARGUMENTS (clone))) = NULL_TREE;
4600 
4601   for (parms = DECL_ARGUMENTS (clone); parms; parms = DECL_CHAIN (parms))
4602     {
4603       DECL_CONTEXT (parms) = clone;
4604       cxx_dup_lang_specific_decl (parms);
4605     }
4606 
4607   /* Create the RTL for this function.  */
4608   SET_DECL_RTL (clone, NULL);
4609   rest_of_decl_compilation (clone, /*top_level=*/1, at_eof);
4610 
4611   return clone;
4612 }
4613 
4614 /* Implementation of DECL_CLONED_FUNCTION and DECL_CLONED_FUNCTION_P, do
4615    not invoke this function directly.
4616 
4617    For a non-thunk function, returns the address of the slot for storing
4618    the function it is a clone of.  Otherwise returns NULL_TREE.
4619 
4620    If JUST_TESTING, looks through TEMPLATE_DECL and returns NULL if
4621    cloned_function is unset.  This is to support the separate
4622    DECL_CLONED_FUNCTION and DECL_CLONED_FUNCTION_P modes; using the latter
4623    on a template makes sense, but not the former.  */
4624 
4625 tree *
decl_cloned_function_p(const_tree decl,bool just_testing)4626 decl_cloned_function_p (const_tree decl, bool just_testing)
4627 {
4628   tree *ptr;
4629   if (just_testing)
4630     decl = STRIP_TEMPLATE (decl);
4631 
4632   if (TREE_CODE (decl) != FUNCTION_DECL
4633       || !DECL_LANG_SPECIFIC (decl)
4634       || DECL_LANG_SPECIFIC (decl)->u.fn.thunk_p)
4635     {
4636 #if defined ENABLE_TREE_CHECKING && (GCC_VERSION >= 2007)
4637       if (!just_testing)
4638 	lang_check_failed (__FILE__, __LINE__, __FUNCTION__);
4639       else
4640 #endif
4641 	return NULL;
4642     }
4643 
4644   ptr = &DECL_LANG_SPECIFIC (decl)->u.fn.u5.cloned_function;
4645   if (just_testing && *ptr == NULL_TREE)
4646     return NULL;
4647   else
4648     return ptr;
4649 }
4650 
4651 /* Produce declarations for all appropriate clones of FN.  If
4652    UPDATE_METHODS is true, the clones are added to the
4653    CLASSTYPE_MEMBER_VEC.  */
4654 
4655 void
clone_function_decl(tree fn,bool update_methods)4656 clone_function_decl (tree fn, bool update_methods)
4657 {
4658   tree clone;
4659 
4660   /* Avoid inappropriate cloning.  */
4661   if (DECL_CHAIN (fn)
4662       && DECL_CLONED_FUNCTION_P (DECL_CHAIN (fn)))
4663     return;
4664 
4665   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (fn))
4666     {
4667       /* For each constructor, we need two variants: an in-charge version
4668 	 and a not-in-charge version.  */
4669       clone = build_clone (fn, complete_ctor_identifier);
4670       if (update_methods)
4671 	add_method (DECL_CONTEXT (clone), clone, false);
4672       clone = build_clone (fn, base_ctor_identifier);
4673       if (update_methods)
4674 	add_method (DECL_CONTEXT (clone), clone, false);
4675     }
4676   else
4677     {
4678       gcc_assert (DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (fn));
4679 
4680       /* For each destructor, we need three variants: an in-charge
4681 	 version, a not-in-charge version, and an in-charge deleting
4682 	 version.  We clone the deleting version first because that
4683 	 means it will go second on the TYPE_FIELDS list -- and that
4684 	 corresponds to the correct layout order in the virtual
4685 	 function table.
4686 
4687 	 For a non-virtual destructor, we do not build a deleting
4688 	 destructor.  */
4689       if (DECL_VIRTUAL_P (fn))
4690 	{
4691 	  clone = build_clone (fn, deleting_dtor_identifier);
4692 	  if (update_methods)
4693 	    add_method (DECL_CONTEXT (clone), clone, false);
4694 	}
4695       clone = build_clone (fn, complete_dtor_identifier);
4696       if (update_methods)
4697 	add_method (DECL_CONTEXT (clone), clone, false);
4698       clone = build_clone (fn, base_dtor_identifier);
4699       if (update_methods)
4700 	add_method (DECL_CONTEXT (clone), clone, false);
4701     }
4702 
4703   /* Note that this is an abstract function that is never emitted.  */
4704   DECL_ABSTRACT_P (fn) = true;
4705 }
4706 
4707 /* DECL is an in charge constructor, which is being defined. This will
4708    have had an in class declaration, from whence clones were
4709    declared. An out-of-class definition can specify additional default
4710    arguments. As it is the clones that are involved in overload
4711    resolution, we must propagate the information from the DECL to its
4712    clones.  */
4713 
4714 void
adjust_clone_args(tree decl)4715 adjust_clone_args (tree decl)
4716 {
4717   tree clone;
4718 
4719   for (clone = DECL_CHAIN (decl); clone && DECL_CLONED_FUNCTION_P (clone);
4720        clone = DECL_CHAIN (clone))
4721     {
4722       tree orig_clone_parms = TYPE_ARG_TYPES (TREE_TYPE (clone));
4723       tree orig_decl_parms = TYPE_ARG_TYPES (TREE_TYPE (decl));
4724       tree decl_parms, clone_parms;
4725 
4726       clone_parms = orig_clone_parms;
4727 
4728       /* Skip the 'this' parameter.  */
4729       orig_clone_parms = TREE_CHAIN (orig_clone_parms);
4730       orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4731 
4732       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
4733 	orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4734       if (DECL_HAS_VTT_PARM_P (decl))
4735 	orig_decl_parms = TREE_CHAIN (orig_decl_parms);
4736 
4737       clone_parms = orig_clone_parms;
4738       if (DECL_HAS_VTT_PARM_P (clone))
4739 	clone_parms = TREE_CHAIN (clone_parms);
4740 
4741       for (decl_parms = orig_decl_parms; decl_parms;
4742 	   decl_parms = TREE_CHAIN (decl_parms),
4743 	     clone_parms = TREE_CHAIN (clone_parms))
4744 	{
4745 	  if (clone_parms == void_list_node)
4746 	    {
4747 	      gcc_assert (decl_parms == clone_parms
4748 			  || ctor_omit_inherited_parms (clone));
4749 	      break;
4750 	    }
4751 
4752 	  gcc_assert (same_type_p (TREE_TYPE (decl_parms),
4753 				   TREE_TYPE (clone_parms)));
4754 
4755 	  if (TREE_PURPOSE (decl_parms) && !TREE_PURPOSE (clone_parms))
4756 	    {
4757 	      /* A default parameter has been added. Adjust the
4758 		 clone's parameters.  */
4759 	      tree exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (clone));
4760 	      tree attrs = TYPE_ATTRIBUTES (TREE_TYPE (clone));
4761 	      tree basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (clone));
4762 	      tree type;
4763 
4764 	      clone_parms = orig_decl_parms;
4765 
4766 	      if (DECL_HAS_VTT_PARM_P (clone))
4767 		{
4768 		  clone_parms = tree_cons (TREE_PURPOSE (orig_clone_parms),
4769 					   TREE_VALUE (orig_clone_parms),
4770 					   clone_parms);
4771 		  TREE_TYPE (clone_parms) = TREE_TYPE (orig_clone_parms);
4772 		}
4773 	      type = build_method_type_directly (basetype,
4774 						 TREE_TYPE (TREE_TYPE (clone)),
4775 						 clone_parms);
4776 	      if (exceptions)
4777 		type = build_exception_variant (type, exceptions);
4778 	      if (attrs)
4779 		type = cp_build_type_attribute_variant (type, attrs);
4780 	      TREE_TYPE (clone) = type;
4781 
4782 	      clone_parms = NULL_TREE;
4783 	      break;
4784 	    }
4785 	}
4786       gcc_assert (!clone_parms || clone_parms == void_list_node);
4787     }
4788 }
4789 
4790 /* For each of the constructors and destructors in T, create an
4791    in-charge and not-in-charge variant.  */
4792 
4793 static void
clone_constructors_and_destructors(tree t)4794 clone_constructors_and_destructors (tree t)
4795 {
4796   /* While constructors can be via a using declaration, at this point
4797      we no longer need to know that.  */
4798   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
4799     clone_function_decl (*iter, /*update_methods=*/true);
4800 
4801   if (tree dtor = CLASSTYPE_DESTRUCTOR (t))
4802     clone_function_decl (dtor, /*update_methods=*/true);
4803 }
4804 
4805 /* Deduce noexcept for a destructor DTOR.  */
4806 
4807 void
deduce_noexcept_on_destructor(tree dtor)4808 deduce_noexcept_on_destructor (tree dtor)
4809 {
4810   if (!TYPE_RAISES_EXCEPTIONS (TREE_TYPE (dtor)))
4811     TREE_TYPE (dtor) = build_exception_variant (TREE_TYPE (dtor),
4812 						noexcept_deferred_spec);
4813 }
4814 
4815 /* Subroutine of set_one_vmethod_tm_attributes.  Search base classes
4816    of TYPE for virtual functions which FNDECL overrides.  Return a
4817    mask of the tm attributes found therein.  */
4818 
4819 static int
look_for_tm_attr_overrides(tree type,tree fndecl)4820 look_for_tm_attr_overrides (tree type, tree fndecl)
4821 {
4822   tree binfo = TYPE_BINFO (type);
4823   tree base_binfo;
4824   int ix, found = 0;
4825 
4826   for (ix = 0; BINFO_BASE_ITERATE (binfo, ix, base_binfo); ++ix)
4827     {
4828       tree o, basetype = BINFO_TYPE (base_binfo);
4829 
4830       if (!TYPE_POLYMORPHIC_P (basetype))
4831 	continue;
4832 
4833       o = look_for_overrides_here (basetype, fndecl);
4834       if (o)
4835 	{
4836 	  if (lookup_attribute ("transaction_safe_dynamic",
4837 				DECL_ATTRIBUTES (o)))
4838 	    /* transaction_safe_dynamic is not inherited.  */;
4839 	  else
4840 	    found |= tm_attr_to_mask (find_tm_attribute
4841 				      (TYPE_ATTRIBUTES (TREE_TYPE (o))));
4842 	}
4843       else
4844 	found |= look_for_tm_attr_overrides (basetype, fndecl);
4845     }
4846 
4847   return found;
4848 }
4849 
4850 /* Subroutine of set_method_tm_attributes.  Handle the checks and
4851    inheritance for one virtual method FNDECL.  */
4852 
4853 static void
set_one_vmethod_tm_attributes(tree type,tree fndecl)4854 set_one_vmethod_tm_attributes (tree type, tree fndecl)
4855 {
4856   tree tm_attr;
4857   int found, have;
4858 
4859   found = look_for_tm_attr_overrides (type, fndecl);
4860 
4861   /* If FNDECL doesn't actually override anything (i.e. T is the
4862      class that first declares FNDECL virtual), then we're done.  */
4863   if (found == 0)
4864     return;
4865 
4866   tm_attr = find_tm_attribute (TYPE_ATTRIBUTES (TREE_TYPE (fndecl)));
4867   have = tm_attr_to_mask (tm_attr);
4868 
4869   /* Intel STM Language Extension 3.0, Section 4.2 table 4:
4870      tm_pure must match exactly, otherwise no weakening of
4871      tm_safe > tm_callable > nothing.  */
4872   /* ??? The tm_pure attribute didn't make the transition to the
4873      multivendor language spec.  */
4874   if (have == TM_ATTR_PURE)
4875     {
4876       if (found != TM_ATTR_PURE)
4877 	{
4878 	  found &= -found;
4879 	  goto err_override;
4880 	}
4881     }
4882   /* If the overridden function is tm_pure, then FNDECL must be.  */
4883   else if (found == TM_ATTR_PURE && tm_attr)
4884     goto err_override;
4885   /* Look for base class combinations that cannot be satisfied.  */
4886   else if (found != TM_ATTR_PURE && (found & TM_ATTR_PURE))
4887     {
4888       found &= ~TM_ATTR_PURE;
4889       found &= -found;
4890       error_at (DECL_SOURCE_LOCATION (fndecl),
4891 		"method overrides both %<transaction_pure%> and %qE methods",
4892 		tm_mask_to_attr (found));
4893     }
4894   /* If FNDECL did not declare an attribute, then inherit the most
4895      restrictive one.  */
4896   else if (tm_attr == NULL)
4897     {
4898       apply_tm_attr (fndecl, tm_mask_to_attr (least_bit_hwi (found)));
4899     }
4900   /* Otherwise validate that we're not weaker than a function
4901      that is being overridden.  */
4902   else
4903     {
4904       found &= -found;
4905       if (found <= TM_ATTR_CALLABLE && have > found)
4906 	goto err_override;
4907     }
4908   return;
4909 
4910  err_override:
4911   error_at (DECL_SOURCE_LOCATION (fndecl),
4912 	    "method declared %qE overriding %qE method",
4913 	    tm_attr, tm_mask_to_attr (found));
4914 }
4915 
4916 /* For each of the methods in T, propagate a class-level tm attribute.  */
4917 
4918 static void
set_method_tm_attributes(tree t)4919 set_method_tm_attributes (tree t)
4920 {
4921   tree class_tm_attr, fndecl;
4922 
4923   /* Don't bother collecting tm attributes if transactional memory
4924      support is not enabled.  */
4925   if (!flag_tm)
4926     return;
4927 
4928   /* Process virtual methods first, as they inherit directly from the
4929      base virtual function and also require validation of new attributes.  */
4930   if (TYPE_CONTAINS_VPTR_P (t))
4931     {
4932       tree vchain;
4933       for (vchain = BINFO_VIRTUALS (TYPE_BINFO (t)); vchain;
4934 	   vchain = TREE_CHAIN (vchain))
4935 	{
4936 	  fndecl = BV_FN (vchain);
4937 	  if (DECL_THUNK_P (fndecl))
4938 	    fndecl = THUNK_TARGET (fndecl);
4939 	  set_one_vmethod_tm_attributes (t, fndecl);
4940 	}
4941     }
4942 
4943   /* If the class doesn't have an attribute, nothing more to do.  */
4944   class_tm_attr = find_tm_attribute (TYPE_ATTRIBUTES (t));
4945   if (class_tm_attr == NULL)
4946     return;
4947 
4948   /* Any method that does not yet have a tm attribute inherits
4949      the one from the class.  */
4950   for (fndecl = TYPE_FIELDS (t); fndecl; fndecl = DECL_CHAIN (fndecl))
4951     if (DECL_DECLARES_FUNCTION_P (fndecl)
4952 	&& !find_tm_attribute (TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
4953       apply_tm_attr (fndecl, class_tm_attr);
4954 }
4955 
4956 /* Returns true if FN is a default constructor.  */
4957 
4958 bool
default_ctor_p(tree fn)4959 default_ctor_p (tree fn)
4960 {
4961   return (DECL_CONSTRUCTOR_P (fn)
4962 	  && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
4963 }
4964 
4965 /* Returns true iff class T has a user-defined constructor that can be called
4966    with more than zero arguments.  */
4967 
4968 bool
type_has_user_nondefault_constructor(tree t)4969 type_has_user_nondefault_constructor (tree t)
4970 {
4971   if (!TYPE_HAS_USER_CONSTRUCTOR (t))
4972     return false;
4973 
4974   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
4975     {
4976       tree fn = *iter;
4977       if (!DECL_ARTIFICIAL (fn)
4978 	  && (TREE_CODE (fn) == TEMPLATE_DECL
4979 	      || (skip_artificial_parms_for (fn, DECL_ARGUMENTS (fn))
4980 		  != NULL_TREE)))
4981 	return true;
4982     }
4983 
4984   return false;
4985 }
4986 
4987 /* Returns the defaulted constructor if T has one. Otherwise, returns
4988    NULL_TREE.  */
4989 
4990 tree
in_class_defaulted_default_constructor(tree t)4991 in_class_defaulted_default_constructor (tree t)
4992 {
4993   if (!TYPE_HAS_USER_CONSTRUCTOR (t))
4994     return NULL_TREE;
4995 
4996   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
4997     {
4998       tree fn = *iter;
4999 
5000       if (DECL_DEFAULTED_IN_CLASS_P (fn)
5001 	  && default_ctor_p (fn))
5002 	return fn;
5003     }
5004 
5005   return NULL_TREE;
5006 }
5007 
5008 /* Returns true iff FN is a user-provided function, i.e. user-declared
5009    and not defaulted at its first declaration.  */
5010 
5011 bool
user_provided_p(tree fn)5012 user_provided_p (tree fn)
5013 {
5014   if (TREE_CODE (fn) == TEMPLATE_DECL)
5015     return true;
5016   else
5017     return (!DECL_ARTIFICIAL (fn)
5018 	    && !(DECL_INITIALIZED_IN_CLASS_P (fn)
5019 		 && (DECL_DEFAULTED_FN (fn) || DECL_DELETED_FN (fn))));
5020 }
5021 
5022 /* Returns true iff class T has a user-provided constructor.  */
5023 
5024 bool
type_has_user_provided_constructor(tree t)5025 type_has_user_provided_constructor (tree t)
5026 {
5027   if (!CLASS_TYPE_P (t))
5028     return false;
5029 
5030   if (!TYPE_HAS_USER_CONSTRUCTOR (t))
5031     return false;
5032 
5033   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
5034     if (user_provided_p (*iter))
5035       return true;
5036 
5037   return false;
5038 }
5039 
5040 /* Returns true iff class T has a user-provided or explicit constructor.  */
5041 
5042 bool
type_has_user_provided_or_explicit_constructor(tree t)5043 type_has_user_provided_or_explicit_constructor (tree t)
5044 {
5045   if (!CLASS_TYPE_P (t))
5046     return false;
5047 
5048   if (!TYPE_HAS_USER_CONSTRUCTOR (t))
5049     return false;
5050 
5051   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
5052     {
5053       tree fn = *iter;
5054       if (user_provided_p (fn) || DECL_NONCONVERTING_P (fn))
5055 	return true;
5056     }
5057 
5058   return false;
5059 }
5060 
5061 /* Returns true iff class T has a non-user-provided (i.e. implicitly
5062    declared or explicitly defaulted in the class body) default
5063    constructor.  */
5064 
5065 bool
type_has_non_user_provided_default_constructor(tree t)5066 type_has_non_user_provided_default_constructor (tree t)
5067 {
5068   if (!TYPE_HAS_DEFAULT_CONSTRUCTOR (t))
5069     return false;
5070   if (CLASSTYPE_LAZY_DEFAULT_CTOR (t))
5071     return true;
5072 
5073   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
5074     {
5075       tree fn = *iter;
5076       if (TREE_CODE (fn) == FUNCTION_DECL
5077 	  && default_ctor_p (fn)
5078 	  && !user_provided_p (fn))
5079 	return true;
5080     }
5081 
5082   return false;
5083 }
5084 
5085 /* TYPE is being used as a virtual base, and has a non-trivial move
5086    assignment.  Return true if this is due to there being a user-provided
5087    move assignment in TYPE or one of its subobjects; if there isn't, then
5088    multiple move assignment can't cause any harm.  */
5089 
5090 bool
vbase_has_user_provided_move_assign(tree type)5091 vbase_has_user_provided_move_assign (tree type)
5092 {
5093   /* Does the type itself have a user-provided move assignment operator?  */
5094   if (!CLASSTYPE_LAZY_MOVE_ASSIGN (type))
5095     for (ovl_iterator iter (get_class_binding_direct
5096 			    (type, assign_op_identifier));
5097 	 iter; ++iter)
5098       if (!DECL_ARTIFICIAL (*iter) && move_fn_p (*iter))
5099 	return true;
5100 
5101   /* Do any of its bases?  */
5102   tree binfo = TYPE_BINFO (type);
5103   tree base_binfo;
5104   for (int i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
5105     if (vbase_has_user_provided_move_assign (BINFO_TYPE (base_binfo)))
5106       return true;
5107 
5108   /* Or non-static data members?  */
5109   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5110     {
5111       if (TREE_CODE (field) == FIELD_DECL
5112 	  && CLASS_TYPE_P (TREE_TYPE (field))
5113 	  && vbase_has_user_provided_move_assign (TREE_TYPE (field)))
5114 	return true;
5115     }
5116 
5117   /* Seems not.  */
5118   return false;
5119 }
5120 
5121 /* If default-initialization leaves part of TYPE uninitialized, returns
5122    a DECL for the field or TYPE itself (DR 253).  */
5123 
5124 tree
default_init_uninitialized_part(tree type)5125 default_init_uninitialized_part (tree type)
5126 {
5127   tree t, r, binfo;
5128   int i;
5129 
5130   type = strip_array_types (type);
5131   if (!CLASS_TYPE_P (type))
5132     return type;
5133   if (!type_has_non_user_provided_default_constructor (type))
5134     return NULL_TREE;
5135   for (binfo = TYPE_BINFO (type), i = 0;
5136        BINFO_BASE_ITERATE (binfo, i, t); ++i)
5137     {
5138       r = default_init_uninitialized_part (BINFO_TYPE (t));
5139       if (r)
5140 	return r;
5141     }
5142   for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
5143     if (TREE_CODE (t) == FIELD_DECL
5144 	&& !DECL_ARTIFICIAL (t)
5145 	&& !DECL_INITIAL (t))
5146       {
5147 	r = default_init_uninitialized_part (TREE_TYPE (t));
5148 	if (r)
5149 	  return DECL_P (r) ? r : t;
5150       }
5151 
5152   return NULL_TREE;
5153 }
5154 
5155 /* Returns true iff for class T, a trivial synthesized default constructor
5156    would be constexpr.  */
5157 
5158 bool
trivial_default_constructor_is_constexpr(tree t)5159 trivial_default_constructor_is_constexpr (tree t)
5160 {
5161   /* A defaulted trivial default constructor is constexpr
5162      if there is nothing to initialize.  */
5163   gcc_assert (!TYPE_HAS_COMPLEX_DFLT (t));
5164   return is_really_empty_class (t);
5165 }
5166 
5167 /* Returns true iff class T has a constexpr default constructor.  */
5168 
5169 bool
type_has_constexpr_default_constructor(tree t)5170 type_has_constexpr_default_constructor (tree t)
5171 {
5172   tree fns;
5173 
5174   if (!CLASS_TYPE_P (t))
5175     {
5176       /* The caller should have stripped an enclosing array.  */
5177       gcc_assert (TREE_CODE (t) != ARRAY_TYPE);
5178       return false;
5179     }
5180   if (CLASSTYPE_LAZY_DEFAULT_CTOR (t))
5181     {
5182       if (!TYPE_HAS_COMPLEX_DFLT (t))
5183 	return trivial_default_constructor_is_constexpr (t);
5184       /* Non-trivial, we need to check subobject constructors.  */
5185       lazily_declare_fn (sfk_constructor, t);
5186     }
5187   fns = locate_ctor (t);
5188   return (fns && DECL_DECLARED_CONSTEXPR_P (fns));
5189 }
5190 
5191 /* Returns true iff class T has a constexpr default constructor or has an
5192    implicitly declared default constructor that we can't tell if it's constexpr
5193    without forcing a lazy declaration (which might cause undesired
5194    instantiations).  */
5195 
5196 bool
type_maybe_constexpr_default_constructor(tree t)5197 type_maybe_constexpr_default_constructor (tree t)
5198 {
5199   if (CLASS_TYPE_P (t) && CLASSTYPE_LAZY_DEFAULT_CTOR (t)
5200       && TYPE_HAS_COMPLEX_DFLT (t))
5201     /* Assume it's constexpr.  */
5202     return true;
5203   return type_has_constexpr_default_constructor (t);
5204 }
5205 
5206 /* Returns true iff class TYPE has a virtual destructor.  */
5207 
5208 bool
type_has_virtual_destructor(tree type)5209 type_has_virtual_destructor (tree type)
5210 {
5211   tree dtor;
5212 
5213   if (!CLASS_TYPE_P (type))
5214     return false;
5215 
5216   gcc_assert (COMPLETE_TYPE_P (type));
5217   dtor = CLASSTYPE_DESTRUCTOR (type);
5218   return (dtor && DECL_VIRTUAL_P (dtor));
5219 }
5220 
5221 /* Returns true iff T, a class, has a move-assignment or
5222    move-constructor.  Does not lazily declare either.
5223    If USER_P is false, any move function will do.  If it is true, the
5224    move function must be user-declared.
5225 
5226    Note that user-declared here is different from "user-provided",
5227    which doesn't include functions that are defaulted in the
5228    class.  */
5229 
5230 bool
classtype_has_move_assign_or_move_ctor_p(tree t,bool user_p)5231 classtype_has_move_assign_or_move_ctor_p (tree t, bool user_p)
5232 {
5233   gcc_assert (user_p
5234 	      || (!CLASSTYPE_LAZY_MOVE_CTOR (t)
5235 		  && !CLASSTYPE_LAZY_MOVE_ASSIGN (t)));
5236 
5237   if (!CLASSTYPE_LAZY_MOVE_CTOR (t))
5238     for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
5239       if ((!user_p || !DECL_ARTIFICIAL (*iter)) && move_fn_p (*iter))
5240 	return true;
5241 
5242   if (!CLASSTYPE_LAZY_MOVE_ASSIGN (t))
5243     for (ovl_iterator iter (get_class_binding_direct
5244 			    (t, assign_op_identifier));
5245 	 iter; ++iter)
5246       if ((!user_p || !DECL_ARTIFICIAL (*iter))
5247 	  && DECL_CONTEXT (*iter) == t
5248 	  && move_fn_p (*iter))
5249 	return true;
5250 
5251   return false;
5252 }
5253 
5254 /* True iff T has a move constructor that is not deleted.  */
5255 
5256 bool
classtype_has_non_deleted_move_ctor(tree t)5257 classtype_has_non_deleted_move_ctor (tree t)
5258 {
5259   if (CLASSTYPE_LAZY_MOVE_CTOR (t))
5260     lazily_declare_fn (sfk_move_constructor, t);
5261   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
5262     if (move_fn_p (*iter) && !DECL_DELETED_FN (*iter))
5263       return true;
5264   return false;
5265 }
5266 
5267 /* Nonzero if we need to build up a constructor call when initializing an
5268    object of this class, either because it has a user-declared constructor
5269    or because it doesn't have a default constructor (so we need to give an
5270    error if no initializer is provided).  Use TYPE_NEEDS_CONSTRUCTING when
5271    what you care about is whether or not an object can be produced by a
5272    constructor (e.g. so we don't set TREE_READONLY on const variables of
5273    such type); use this function when what you care about is whether or not
5274    to try to call a constructor to create an object.  The latter case is
5275    the former plus some cases of constructors that cannot be called.  */
5276 
5277 bool
type_build_ctor_call(tree t)5278 type_build_ctor_call (tree t)
5279 {
5280   tree inner;
5281   if (TYPE_NEEDS_CONSTRUCTING (t))
5282     return true;
5283   inner = strip_array_types (t);
5284   if (!CLASS_TYPE_P (inner) || ANON_AGGR_TYPE_P (inner))
5285     return false;
5286   if (!TYPE_HAS_DEFAULT_CONSTRUCTOR (inner))
5287     return true;
5288   if (cxx_dialect < cxx11)
5289     return false;
5290   /* A user-declared constructor might be private, and a constructor might
5291      be trivial but deleted.  */
5292   for (ovl_iterator iter (get_class_binding (inner, complete_ctor_identifier));
5293        iter; ++iter)
5294     {
5295       tree fn = *iter;
5296       if (!DECL_ARTIFICIAL (fn)
5297 	  || DECL_DELETED_FN (fn))
5298 	return true;
5299     }
5300   return false;
5301 }
5302 
5303 /* Like type_build_ctor_call, but for destructors.  */
5304 
5305 bool
type_build_dtor_call(tree t)5306 type_build_dtor_call (tree t)
5307 {
5308   tree inner;
5309   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
5310     return true;
5311   inner = strip_array_types (t);
5312   if (!CLASS_TYPE_P (inner) || ANON_AGGR_TYPE_P (inner)
5313       || !COMPLETE_TYPE_P (inner))
5314     return false;
5315   if (cxx_dialect < cxx11)
5316     return false;
5317   /* A user-declared destructor might be private, and a destructor might
5318      be trivial but deleted.  */
5319   for (ovl_iterator iter (get_class_binding (inner, complete_dtor_identifier));
5320        iter; ++iter)
5321     {
5322       tree fn = *iter;
5323       if (!DECL_ARTIFICIAL (fn)
5324 	  || DECL_DELETED_FN (fn))
5325 	return true;
5326     }
5327   return false;
5328 }
5329 
5330 /* Remove all zero-width bit-fields from T.  */
5331 
5332 static void
remove_zero_width_bit_fields(tree t)5333 remove_zero_width_bit_fields (tree t)
5334 {
5335   tree *fieldsp;
5336 
5337   fieldsp = &TYPE_FIELDS (t);
5338   while (*fieldsp)
5339     {
5340       if (TREE_CODE (*fieldsp) == FIELD_DECL
5341 	  && DECL_C_BIT_FIELD (*fieldsp)
5342 	  /* We should not be confused by the fact that grokbitfield
5343 	     temporarily sets the width of the bit field into
5344 	     DECL_BIT_FIELD_REPRESENTATIVE (*fieldsp).
5345 	     check_bitfield_decl eventually sets DECL_SIZE (*fieldsp)
5346 	     to that width.  */
5347 	  && (DECL_SIZE (*fieldsp) == NULL_TREE
5348 	      || integer_zerop (DECL_SIZE (*fieldsp))))
5349 	*fieldsp = DECL_CHAIN (*fieldsp);
5350       else
5351 	fieldsp = &DECL_CHAIN (*fieldsp);
5352     }
5353 }
5354 
5355 /* Returns TRUE iff we need a cookie when dynamically allocating an
5356    array whose elements have the indicated class TYPE.  */
5357 
5358 static bool
type_requires_array_cookie(tree type)5359 type_requires_array_cookie (tree type)
5360 {
5361   tree fns;
5362   bool has_two_argument_delete_p = false;
5363 
5364   gcc_assert (CLASS_TYPE_P (type));
5365 
5366   /* If there's a non-trivial destructor, we need a cookie.  In order
5367      to iterate through the array calling the destructor for each
5368      element, we'll have to know how many elements there are.  */
5369   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5370     return true;
5371 
5372   /* If the usual deallocation function is a two-argument whose second
5373      argument is of type `size_t', then we have to pass the size of
5374      the array to the deallocation function, so we will need to store
5375      a cookie.  */
5376   fns = lookup_fnfields (TYPE_BINFO (type),
5377 			 ovl_op_identifier (false, VEC_DELETE_EXPR),
5378 			 /*protect=*/0);
5379   /* If there are no `operator []' members, or the lookup is
5380      ambiguous, then we don't need a cookie.  */
5381   if (!fns || fns == error_mark_node)
5382     return false;
5383   /* Loop through all of the functions.  */
5384   for (lkp_iterator iter (BASELINK_FUNCTIONS (fns)); iter; ++iter)
5385     {
5386       tree fn = *iter;
5387 
5388       /* See if this function is a one-argument delete function.  If
5389 	 it is, then it will be the usual deallocation function.  */
5390       tree second_parm = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fn)));
5391       if (second_parm == void_list_node)
5392 	return false;
5393       /* Do not consider this function if its second argument is an
5394 	 ellipsis.  */
5395       if (!second_parm)
5396 	continue;
5397       /* Otherwise, if we have a two-argument function and the second
5398 	 argument is `size_t', it will be the usual deallocation
5399 	 function -- unless there is one-argument function, too.  */
5400       if (TREE_CHAIN (second_parm) == void_list_node
5401 	  && same_type_p (TREE_VALUE (second_parm), size_type_node))
5402 	has_two_argument_delete_p = true;
5403     }
5404 
5405   return has_two_argument_delete_p;
5406 }
5407 
5408 /* Finish computing the `literal type' property of class type T.
5409 
5410    At this point, we have already processed base classes and
5411    non-static data members.  We need to check whether the copy
5412    constructor is trivial, the destructor is trivial, and there
5413    is a trivial default constructor or at least one constexpr
5414    constructor other than the copy constructor.  */
5415 
5416 static void
finalize_literal_type_property(tree t)5417 finalize_literal_type_property (tree t)
5418 {
5419   tree fn;
5420 
5421   if (cxx_dialect < cxx11
5422       || TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
5423     CLASSTYPE_LITERAL_P (t) = false;
5424   else if (CLASSTYPE_LITERAL_P (t) && LAMBDA_TYPE_P (t))
5425     CLASSTYPE_LITERAL_P (t) = (cxx_dialect >= cxx17);
5426   else if (CLASSTYPE_LITERAL_P (t) && !TYPE_HAS_TRIVIAL_DFLT (t)
5427 	   && CLASSTYPE_NON_AGGREGATE (t)
5428 	   && !TYPE_HAS_CONSTEXPR_CTOR (t))
5429     CLASSTYPE_LITERAL_P (t) = false;
5430 
5431   /* C++14 DR 1684 removed this restriction.  */
5432   if (cxx_dialect < cxx14
5433       && !CLASSTYPE_LITERAL_P (t) && !LAMBDA_TYPE_P (t))
5434     for (fn = TYPE_FIELDS (t); fn; fn = DECL_CHAIN (fn))
5435       if (TREE_CODE (fn) == FUNCTION_DECL
5436 	  && DECL_DECLARED_CONSTEXPR_P (fn)
5437 	  && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
5438 	  && !DECL_CONSTRUCTOR_P (fn))
5439 	{
5440 	  DECL_DECLARED_CONSTEXPR_P (fn) = false;
5441 	  if (!DECL_GENERATED_P (fn)
5442 	      && pedwarn (DECL_SOURCE_LOCATION (fn), OPT_Wpedantic,
5443 			  "enclosing class of %<constexpr%> non-static member "
5444 			  "function %q+#D is not a literal type", fn))
5445 	    explain_non_literal_class (t);
5446 	}
5447 }
5448 
5449 /* T is a non-literal type used in a context which requires a constant
5450    expression.  Explain why it isn't literal.  */
5451 
5452 void
explain_non_literal_class(tree t)5453 explain_non_literal_class (tree t)
5454 {
5455   static hash_set<tree> *diagnosed;
5456 
5457   if (!CLASS_TYPE_P (t))
5458     return;
5459   t = TYPE_MAIN_VARIANT (t);
5460 
5461   if (diagnosed == NULL)
5462     diagnosed = new hash_set<tree>;
5463   if (diagnosed->add (t))
5464     /* Already explained.  */
5465     return;
5466 
5467   inform (UNKNOWN_LOCATION, "%q+T is not literal because:", t);
5468   if (cxx_dialect < cxx17 && LAMBDA_TYPE_P (t))
5469     inform (UNKNOWN_LOCATION,
5470 	    "  %qT is a closure type, which is only literal in "
5471 	    "C++17 and later", t);
5472   else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t))
5473     inform (UNKNOWN_LOCATION, "  %q+T has a non-trivial destructor", t);
5474   else if (CLASSTYPE_NON_AGGREGATE (t)
5475 	   && !TYPE_HAS_TRIVIAL_DFLT (t)
5476 	   && !LAMBDA_TYPE_P (t)
5477 	   && !TYPE_HAS_CONSTEXPR_CTOR (t))
5478     {
5479       inform (UNKNOWN_LOCATION,
5480 	      "  %q+T is not an aggregate, does not have a trivial "
5481 	      "default constructor, and has no %<constexpr%> constructor that "
5482 	      "is not a copy or move constructor", t);
5483       if (type_has_non_user_provided_default_constructor (t))
5484 	/* Note that we can't simply call locate_ctor because when the
5485 	   constructor is deleted it just returns NULL_TREE.  */
5486 	for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (t)); iter; ++iter)
5487 	  {
5488 	    tree fn = *iter;
5489 	    tree parms = TYPE_ARG_TYPES (TREE_TYPE (fn));
5490 
5491 	    parms = skip_artificial_parms_for (fn, parms);
5492 
5493 	    if (sufficient_parms_p (parms))
5494 	      {
5495 		if (DECL_DELETED_FN (fn))
5496 		  maybe_explain_implicit_delete (fn);
5497 		else
5498 		  explain_invalid_constexpr_fn (fn);
5499 		break;
5500 	      }
5501 	}
5502     }
5503   else
5504     {
5505       tree binfo, base_binfo, field; int i;
5506       for (binfo = TYPE_BINFO (t), i = 0;
5507 	   BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5508 	{
5509 	  tree basetype = TREE_TYPE (base_binfo);
5510 	  if (!CLASSTYPE_LITERAL_P (basetype))
5511 	    {
5512 	      inform (UNKNOWN_LOCATION,
5513 		      "  base class %qT of %q+T is non-literal",
5514 		      basetype, t);
5515 	      explain_non_literal_class (basetype);
5516 	      return;
5517 	    }
5518 	}
5519       for (field = TYPE_FIELDS (t); field; field = TREE_CHAIN (field))
5520 	{
5521 	  tree ftype;
5522 	  if (TREE_CODE (field) != FIELD_DECL)
5523 	    continue;
5524 	  ftype = TREE_TYPE (field);
5525 	  if (!literal_type_p (ftype))
5526 	    {
5527 	      inform (DECL_SOURCE_LOCATION (field),
5528 		      "  non-static data member %qD has non-literal type",
5529 		      field);
5530 	      if (CLASS_TYPE_P (ftype))
5531 		explain_non_literal_class (ftype);
5532 	    }
5533 	  if (CP_TYPE_VOLATILE_P (ftype))
5534 	    inform (DECL_SOURCE_LOCATION (field),
5535 		    "  non-static data member %qD has volatile type", field);
5536 	}
5537     }
5538 }
5539 
5540 /* Check the validity of the bases and members declared in T.  Add any
5541    implicitly-generated functions (like copy-constructors and
5542    assignment operators).  Compute various flag bits (like
5543    CLASSTYPE_NON_LAYOUT_POD_T) for T.  This routine works purely at the C++
5544    level: i.e., independently of the ABI in use.  */
5545 
5546 static void
check_bases_and_members(tree t)5547 check_bases_and_members (tree t)
5548 {
5549   /* Nonzero if the implicitly generated copy constructor should take
5550      a non-const reference argument.  */
5551   int cant_have_const_ctor;
5552   /* Nonzero if the implicitly generated assignment operator
5553      should take a non-const reference argument.  */
5554   int no_const_asn_ref;
5555   tree access_decls;
5556   bool saved_complex_asn_ref;
5557   bool saved_nontrivial_dtor;
5558   tree fn;
5559 
5560   /* By default, we use const reference arguments and generate default
5561      constructors.  */
5562   cant_have_const_ctor = 0;
5563   no_const_asn_ref = 0;
5564 
5565   /* Check all the base-classes and set FMEM members to point to arrays
5566      of potential interest.  */
5567   check_bases (t, &cant_have_const_ctor, &no_const_asn_ref);
5568 
5569   /* Deduce noexcept on destructor.  This needs to happen after we've set
5570      triviality flags appropriately for our bases.  */
5571   if (cxx_dialect >= cxx11)
5572     if (tree dtor = CLASSTYPE_DESTRUCTOR (t))
5573       deduce_noexcept_on_destructor (dtor);
5574 
5575   /* Check all the method declarations.  */
5576   check_methods (t);
5577 
5578   /* Save the initial values of these flags which only indicate whether
5579      or not the class has user-provided functions.  As we analyze the
5580      bases and members we can set these flags for other reasons.  */
5581   saved_complex_asn_ref = TYPE_HAS_COMPLEX_COPY_ASSIGN (t);
5582   saved_nontrivial_dtor = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t);
5583 
5584   /* Check all the data member declarations.  We cannot call
5585      check_field_decls until we have called check_bases check_methods,
5586      as check_field_decls depends on TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5587      being set appropriately.  */
5588   check_field_decls (t, &access_decls,
5589 		     &cant_have_const_ctor,
5590 		     &no_const_asn_ref);
5591 
5592   /* A nearly-empty class has to be vptr-containing; a nearly empty
5593      class contains just a vptr.  */
5594   if (!TYPE_CONTAINS_VPTR_P (t))
5595     CLASSTYPE_NEARLY_EMPTY_P (t) = 0;
5596 
5597   /* Do some bookkeeping that will guide the generation of implicitly
5598      declared member functions.  */
5599   TYPE_HAS_COMPLEX_COPY_CTOR (t) |= TYPE_CONTAINS_VPTR_P (t);
5600   TYPE_HAS_COMPLEX_MOVE_CTOR (t) |= TYPE_CONTAINS_VPTR_P (t);
5601   /* We need to call a constructor for this class if it has a
5602      user-provided constructor, or if the default constructor is going
5603      to initialize the vptr.  (This is not an if-and-only-if;
5604      TYPE_NEEDS_CONSTRUCTING is set elsewhere if bases or members
5605      themselves need constructing.)  */
5606   TYPE_NEEDS_CONSTRUCTING (t)
5607     |= (type_has_user_provided_constructor (t) || TYPE_CONTAINS_VPTR_P (t));
5608   /* [dcl.init.aggr]
5609 
5610      An aggregate is an array or a class with no user-provided
5611      constructors ... and no virtual functions.
5612 
5613      Again, other conditions for being an aggregate are checked
5614      elsewhere.  */
5615   CLASSTYPE_NON_AGGREGATE (t)
5616     |= (type_has_user_provided_or_explicit_constructor (t)
5617 	|| TYPE_POLYMORPHIC_P (t));
5618   /* This is the C++98/03 definition of POD; it changed in C++0x, but we
5619      retain the old definition internally for ABI reasons.  */
5620   CLASSTYPE_NON_LAYOUT_POD_P (t)
5621     |= (CLASSTYPE_NON_AGGREGATE (t)
5622 	|| saved_nontrivial_dtor || saved_complex_asn_ref);
5623   CLASSTYPE_NON_STD_LAYOUT (t) |= TYPE_CONTAINS_VPTR_P (t);
5624   TYPE_HAS_COMPLEX_COPY_ASSIGN (t) |= TYPE_CONTAINS_VPTR_P (t);
5625   TYPE_HAS_COMPLEX_MOVE_ASSIGN (t) |= TYPE_CONTAINS_VPTR_P (t);
5626   TYPE_HAS_COMPLEX_DFLT (t) |= TYPE_CONTAINS_VPTR_P (t);
5627 
5628   /* If the only explicitly declared default constructor is user-provided,
5629      set TYPE_HAS_COMPLEX_DFLT.  */
5630   if (!TYPE_HAS_COMPLEX_DFLT (t)
5631       && TYPE_HAS_DEFAULT_CONSTRUCTOR (t)
5632       && !type_has_non_user_provided_default_constructor (t))
5633     TYPE_HAS_COMPLEX_DFLT (t) = true;
5634 
5635   /* Warn if a public base of a polymorphic type has an accessible
5636      non-virtual destructor.  It is only now that we know the class is
5637      polymorphic.  Although a polymorphic base will have a already
5638      been diagnosed during its definition, we warn on use too.  */
5639   if (TYPE_POLYMORPHIC_P (t) && warn_nonvdtor)
5640     {
5641       tree binfo = TYPE_BINFO (t);
5642       vec<tree, va_gc> *accesses = BINFO_BASE_ACCESSES (binfo);
5643       tree base_binfo;
5644       unsigned i;
5645 
5646       for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5647 	{
5648 	  tree basetype = TREE_TYPE (base_binfo);
5649 
5650 	  if ((*accesses)[i] == access_public_node
5651 	      && (TYPE_POLYMORPHIC_P (basetype) || warn_ecpp)
5652 	      && accessible_nvdtor_p (basetype))
5653 	    warning (OPT_Wnon_virtual_dtor,
5654 		     "base class %q#T has accessible non-virtual destructor",
5655 		     basetype);
5656 	}
5657     }
5658 
5659   /* If the class has no user-declared constructor, but does have
5660      non-static const or reference data members that can never be
5661      initialized, issue a warning.  */
5662   if (warn_uninitialized
5663       /* Classes with user-declared constructors are presumed to
5664 	 initialize these members.  */
5665       && !TYPE_HAS_USER_CONSTRUCTOR (t)
5666       /* Aggregates can be initialized with brace-enclosed
5667 	 initializers.  */
5668       && CLASSTYPE_NON_AGGREGATE (t))
5669     {
5670       tree field;
5671 
5672       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5673 	{
5674 	  tree type;
5675 
5676 	  if (TREE_CODE (field) != FIELD_DECL
5677 	      || DECL_INITIAL (field) != NULL_TREE)
5678 	    continue;
5679 
5680 	  type = TREE_TYPE (field);
5681 	  if (TREE_CODE (type) == REFERENCE_TYPE)
5682 	    warning_at (DECL_SOURCE_LOCATION (field),
5683 			OPT_Wuninitialized, "non-static reference %q#D "
5684 			"in class without a constructor", field);
5685 	  else if (CP_TYPE_CONST_P (type)
5686 		   && (!CLASS_TYPE_P (type)
5687 		       || !TYPE_HAS_DEFAULT_CONSTRUCTOR (type)))
5688 	    warning_at (DECL_SOURCE_LOCATION (field),
5689 			OPT_Wuninitialized, "non-static const member %q#D "
5690 			"in class without a constructor", field);
5691 	}
5692     }
5693 
5694   /* Synthesize any needed methods.  */
5695   add_implicitly_declared_members (t, &access_decls,
5696 				   cant_have_const_ctor,
5697 				   no_const_asn_ref);
5698 
5699   /* Check defaulted declarations here so we have cant_have_const_ctor
5700      and don't need to worry about clones.  */
5701   for (fn = TYPE_FIELDS (t); fn; fn = DECL_CHAIN (fn))
5702     if (DECL_DECLARES_FUNCTION_P (fn)
5703 	&& !DECL_ARTIFICIAL (fn)
5704 	&& DECL_DEFAULTED_IN_CLASS_P (fn))
5705       {
5706 	int copy = copy_fn_p (fn);
5707 	if (copy > 0)
5708 	  {
5709 	    bool imp_const_p
5710 	      = (DECL_CONSTRUCTOR_P (fn) ? !cant_have_const_ctor
5711 		 : !no_const_asn_ref);
5712 	    bool fn_const_p = (copy == 2);
5713 
5714 	    if (fn_const_p && !imp_const_p)
5715 	      /* If the function is defaulted outside the class, we just
5716 		 give the synthesis error.  */
5717 	      error ("%q+D declared to take const reference, but implicit "
5718 		     "declaration would take non-const", fn);
5719 	  }
5720 	defaulted_late_check (fn);
5721       }
5722 
5723   if (LAMBDA_TYPE_P (t))
5724     {
5725       /* "This class type is not an aggregate."  */
5726       CLASSTYPE_NON_AGGREGATE (t) = 1;
5727     }
5728 
5729   /* Compute the 'literal type' property before we
5730      do anything with non-static member functions.  */
5731   finalize_literal_type_property (t);
5732 
5733   /* Create the in-charge and not-in-charge variants of constructors
5734      and destructors.  */
5735   clone_constructors_and_destructors (t);
5736 
5737   /* Process the using-declarations.  */
5738   for (; access_decls; access_decls = TREE_CHAIN (access_decls))
5739     handle_using_decl (TREE_VALUE (access_decls), t);
5740 
5741   /* Figure out whether or not we will need a cookie when dynamically
5742      allocating an array of this type.  */
5743   LANG_TYPE_CLASS_CHECK (t)->vec_new_uses_cookie
5744     = type_requires_array_cookie (t);
5745 }
5746 
5747 /* If T needs a pointer to its virtual function table, set TYPE_VFIELD
5748    accordingly.  If a new vfield was created (because T doesn't have a
5749    primary base class), then the newly created field is returned.  It
5750    is not added to the TYPE_FIELDS list; it is the caller's
5751    responsibility to do that.  Accumulate declared virtual functions
5752    on VIRTUALS_P.  */
5753 
5754 static tree
create_vtable_ptr(tree t,tree * virtuals_p)5755 create_vtable_ptr (tree t, tree* virtuals_p)
5756 {
5757   tree fn;
5758 
5759   /* Collect the virtual functions declared in T.  */
5760   for (fn = TYPE_FIELDS (t); fn; fn = DECL_CHAIN (fn))
5761     if (TREE_CODE (fn) == FUNCTION_DECL
5762 	&& DECL_VINDEX (fn) && !DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (fn)
5763 	&& TREE_CODE (DECL_VINDEX (fn)) != INTEGER_CST)
5764       {
5765 	tree new_virtual = make_node (TREE_LIST);
5766 
5767 	BV_FN (new_virtual) = fn;
5768 	BV_DELTA (new_virtual) = integer_zero_node;
5769 	BV_VCALL_INDEX (new_virtual) = NULL_TREE;
5770 
5771 	TREE_CHAIN (new_virtual) = *virtuals_p;
5772 	*virtuals_p = new_virtual;
5773       }
5774 
5775   /* If we couldn't find an appropriate base class, create a new field
5776      here.  Even if there weren't any new virtual functions, we might need a
5777      new virtual function table if we're supposed to include vptrs in
5778      all classes that need them.  */
5779   if (!TYPE_VFIELD (t) && (*virtuals_p || TYPE_CONTAINS_VPTR_P (t)))
5780     {
5781       /* We build this decl with vtbl_ptr_type_node, which is a
5782 	 `vtable_entry_type*'.  It might seem more precise to use
5783 	 `vtable_entry_type (*)[N]' where N is the number of virtual
5784 	 functions.  However, that would require the vtable pointer in
5785 	 base classes to have a different type than the vtable pointer
5786 	 in derived classes.  We could make that happen, but that
5787 	 still wouldn't solve all the problems.  In particular, the
5788 	 type-based alias analysis code would decide that assignments
5789 	 to the base class vtable pointer can't alias assignments to
5790 	 the derived class vtable pointer, since they have different
5791 	 types.  Thus, in a derived class destructor, where the base
5792 	 class constructor was inlined, we could generate bad code for
5793 	 setting up the vtable pointer.
5794 
5795 	 Therefore, we use one type for all vtable pointers.  We still
5796 	 use a type-correct type; it's just doesn't indicate the array
5797 	 bounds.  That's better than using `void*' or some such; it's
5798 	 cleaner, and it let's the alias analysis code know that these
5799 	 stores cannot alias stores to void*!  */
5800       tree field;
5801 
5802       field = build_decl (input_location,
5803 			  FIELD_DECL, get_vfield_name (t), vtbl_ptr_type_node);
5804       DECL_VIRTUAL_P (field) = 1;
5805       DECL_ARTIFICIAL (field) = 1;
5806       DECL_FIELD_CONTEXT (field) = t;
5807       DECL_FCONTEXT (field) = t;
5808       if (TYPE_PACKED (t))
5809 	DECL_PACKED (field) = 1;
5810 
5811       TYPE_VFIELD (t) = field;
5812 
5813       /* This class is non-empty.  */
5814       CLASSTYPE_EMPTY_P (t) = 0;
5815 
5816       return field;
5817     }
5818 
5819   return NULL_TREE;
5820 }
5821 
5822 /* Add OFFSET to all base types of BINFO which is a base in the
5823    hierarchy dominated by T.
5824 
5825    OFFSET, which is a type offset, is number of bytes.  */
5826 
5827 static void
propagate_binfo_offsets(tree binfo,tree offset)5828 propagate_binfo_offsets (tree binfo, tree offset)
5829 {
5830   int i;
5831   tree primary_binfo;
5832   tree base_binfo;
5833 
5834   /* Update BINFO's offset.  */
5835   BINFO_OFFSET (binfo)
5836     = fold_convert (sizetype,
5837 	       size_binop (PLUS_EXPR,
5838 			   fold_convert (ssizetype, BINFO_OFFSET (binfo)),
5839 			   offset));
5840 
5841   /* Find the primary base class.  */
5842   primary_binfo = get_primary_binfo (binfo);
5843 
5844   if (primary_binfo && BINFO_INHERITANCE_CHAIN (primary_binfo) == binfo)
5845     propagate_binfo_offsets (primary_binfo, offset);
5846 
5847   /* Scan all of the bases, pushing the BINFO_OFFSET adjust
5848      downwards.  */
5849   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
5850     {
5851       /* Don't do the primary base twice.  */
5852       if (base_binfo == primary_binfo)
5853 	continue;
5854 
5855       if (BINFO_VIRTUAL_P (base_binfo))
5856 	continue;
5857 
5858       propagate_binfo_offsets (base_binfo, offset);
5859     }
5860 }
5861 
5862 /* Set BINFO_OFFSET for all of the virtual bases for RLI->T.  Update
5863    TYPE_ALIGN and TYPE_SIZE for T.  OFFSETS gives the location of
5864    empty subobjects of T.  */
5865 
5866 static void
layout_virtual_bases(record_layout_info rli,splay_tree offsets)5867 layout_virtual_bases (record_layout_info rli, splay_tree offsets)
5868 {
5869   tree vbase;
5870   tree t = rli->t;
5871   tree *next_field;
5872 
5873   if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)) == 0)
5874     return;
5875 
5876   /* Find the last field.  The artificial fields created for virtual
5877      bases will go after the last extant field to date.  */
5878   next_field = &TYPE_FIELDS (t);
5879   while (*next_field)
5880     next_field = &DECL_CHAIN (*next_field);
5881 
5882   /* Go through the virtual bases, allocating space for each virtual
5883      base that is not already a primary base class.  These are
5884      allocated in inheritance graph order.  */
5885   for (vbase = TYPE_BINFO (t); vbase; vbase = TREE_CHAIN (vbase))
5886     {
5887       if (!BINFO_VIRTUAL_P (vbase))
5888 	continue;
5889 
5890       if (!BINFO_PRIMARY_P (vbase))
5891 	{
5892 	  /* This virtual base is not a primary base of any class in the
5893 	     hierarchy, so we have to add space for it.  */
5894 	  next_field = build_base_field (rli, vbase,
5895 					 offsets, next_field);
5896 	}
5897     }
5898 }
5899 
5900 /* Returns the offset of the byte just past the end of the base class
5901    BINFO.  */
5902 
5903 static tree
end_of_base(tree binfo)5904 end_of_base (tree binfo)
5905 {
5906   tree size;
5907 
5908   if (!CLASSTYPE_AS_BASE (BINFO_TYPE (binfo)))
5909     size = TYPE_SIZE_UNIT (char_type_node);
5910   else if (is_empty_class (BINFO_TYPE (binfo)))
5911     /* An empty class has zero CLASSTYPE_SIZE_UNIT, but we need to
5912        allocate some space for it. It cannot have virtual bases, so
5913        TYPE_SIZE_UNIT is fine.  */
5914     size = TYPE_SIZE_UNIT (BINFO_TYPE (binfo));
5915   else
5916     size = CLASSTYPE_SIZE_UNIT (BINFO_TYPE (binfo));
5917 
5918   return size_binop (PLUS_EXPR, BINFO_OFFSET (binfo), size);
5919 }
5920 
5921 /* Returns the offset of the byte just past the end of the base class
5922    with the highest offset in T.  If INCLUDE_VIRTUALS_P is zero, then
5923    only non-virtual bases are included.  */
5924 
5925 static tree
end_of_class(tree t,int include_virtuals_p)5926 end_of_class (tree t, int include_virtuals_p)
5927 {
5928   tree result = size_zero_node;
5929   vec<tree, va_gc> *vbases;
5930   tree binfo;
5931   tree base_binfo;
5932   tree offset;
5933   int i;
5934 
5935   for (binfo = TYPE_BINFO (t), i = 0;
5936        BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
5937     {
5938       if (!include_virtuals_p
5939 	  && BINFO_VIRTUAL_P (base_binfo)
5940 	  && (!BINFO_PRIMARY_P (base_binfo)
5941 	      || BINFO_INHERITANCE_CHAIN (base_binfo) != TYPE_BINFO (t)))
5942 	continue;
5943 
5944       offset = end_of_base (base_binfo);
5945       if (tree_int_cst_lt (result, offset))
5946 	result = offset;
5947     }
5948 
5949   if (include_virtuals_p)
5950     for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
5951 	 vec_safe_iterate (vbases, i, &base_binfo); i++)
5952       {
5953 	offset = end_of_base (base_binfo);
5954 	if (tree_int_cst_lt (result, offset))
5955 	  result = offset;
5956       }
5957 
5958   return result;
5959 }
5960 
5961 /* Warn about bases of T that are inaccessible because they are
5962    ambiguous.  For example:
5963 
5964      struct S {};
5965      struct T : public S {};
5966      struct U : public S, public T {};
5967 
5968    Here, `(S*) new U' is not allowed because there are two `S'
5969    subobjects of U.  */
5970 
5971 static void
warn_about_ambiguous_bases(tree t)5972 warn_about_ambiguous_bases (tree t)
5973 {
5974   int i;
5975   vec<tree, va_gc> *vbases;
5976   tree basetype;
5977   tree binfo;
5978   tree base_binfo;
5979 
5980   /* If there are no repeated bases, nothing can be ambiguous.  */
5981   if (!CLASSTYPE_REPEATED_BASE_P (t))
5982     return;
5983 
5984   /* Check direct bases.  */
5985   for (binfo = TYPE_BINFO (t), i = 0;
5986        BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
5987     {
5988       basetype = BINFO_TYPE (base_binfo);
5989 
5990       if (!uniquely_derived_from_p (basetype, t))
5991 	warning (0, "direct base %qT inaccessible in %qT due to ambiguity",
5992 		 basetype, t);
5993     }
5994 
5995   /* Check for ambiguous virtual bases.  */
5996   if (extra_warnings)
5997     for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
5998 	 vec_safe_iterate (vbases, i, &binfo); i++)
5999       {
6000 	basetype = BINFO_TYPE (binfo);
6001 
6002 	if (!uniquely_derived_from_p (basetype, t))
6003 	  warning (OPT_Wextra, "virtual base %qT inaccessible in %qT due "
6004 		   "to ambiguity", basetype, t);
6005       }
6006 }
6007 
6008 /* Compare two INTEGER_CSTs K1 and K2.  */
6009 
6010 static int
splay_tree_compare_integer_csts(splay_tree_key k1,splay_tree_key k2)6011 splay_tree_compare_integer_csts (splay_tree_key k1, splay_tree_key k2)
6012 {
6013   return tree_int_cst_compare ((tree) k1, (tree) k2);
6014 }
6015 
6016 /* Increase the size indicated in RLI to account for empty classes
6017    that are "off the end" of the class.  */
6018 
6019 static void
include_empty_classes(record_layout_info rli)6020 include_empty_classes (record_layout_info rli)
6021 {
6022   tree eoc;
6023   tree rli_size;
6024 
6025   /* It might be the case that we grew the class to allocate a
6026      zero-sized base class.  That won't be reflected in RLI, yet,
6027      because we are willing to overlay multiple bases at the same
6028      offset.  However, now we need to make sure that RLI is big enough
6029      to reflect the entire class.  */
6030   eoc = end_of_class (rli->t, CLASSTYPE_AS_BASE (rli->t) != NULL_TREE);
6031   rli_size = rli_size_unit_so_far (rli);
6032   if (TREE_CODE (rli_size) == INTEGER_CST
6033       && tree_int_cst_lt (rli_size, eoc))
6034     {
6035       /* The size should have been rounded to a whole byte.  */
6036       gcc_assert (tree_int_cst_equal
6037 		  (rli->bitpos, round_down (rli->bitpos, BITS_PER_UNIT)));
6038       rli->bitpos
6039 	= size_binop (PLUS_EXPR,
6040 		      rli->bitpos,
6041 		      size_binop (MULT_EXPR,
6042 				  fold_convert (bitsizetype,
6043 					   size_binop (MINUS_EXPR,
6044 						       eoc, rli_size)),
6045 				  bitsize_int (BITS_PER_UNIT)));
6046       normalize_rli (rli);
6047     }
6048 }
6049 
6050 /* Calculate the TYPE_SIZE, TYPE_ALIGN, etc for T.  Calculate
6051    BINFO_OFFSETs for all of the base-classes.  Position the vtable
6052    pointer.  Accumulate declared virtual functions on VIRTUALS_P.  */
6053 
6054 static void
layout_class_type(tree t,tree * virtuals_p)6055 layout_class_type (tree t, tree *virtuals_p)
6056 {
6057   tree non_static_data_members;
6058   tree field;
6059   tree vptr;
6060   record_layout_info rli;
6061   /* Maps offsets (represented as INTEGER_CSTs) to a TREE_LIST of
6062      types that appear at that offset.  */
6063   splay_tree empty_base_offsets;
6064   /* True if the last field laid out was a bit-field.  */
6065   bool last_field_was_bitfield = false;
6066   /* The location at which the next field should be inserted.  */
6067   tree *next_field;
6068 
6069   /* Keep track of the first non-static data member.  */
6070   non_static_data_members = TYPE_FIELDS (t);
6071 
6072   /* Start laying out the record.  */
6073   rli = start_record_layout (t);
6074 
6075   /* Mark all the primary bases in the hierarchy.  */
6076   determine_primary_bases (t);
6077 
6078   /* Create a pointer to our virtual function table.  */
6079   vptr = create_vtable_ptr (t, virtuals_p);
6080 
6081   /* The vptr is always the first thing in the class.  */
6082   if (vptr)
6083     {
6084       DECL_CHAIN (vptr) = TYPE_FIELDS (t);
6085       TYPE_FIELDS (t) = vptr;
6086       next_field = &DECL_CHAIN (vptr);
6087       place_field (rli, vptr);
6088     }
6089   else
6090     next_field = &TYPE_FIELDS (t);
6091 
6092   /* Build FIELD_DECLs for all of the non-virtual base-types.  */
6093   empty_base_offsets = splay_tree_new (splay_tree_compare_integer_csts,
6094 				       NULL, NULL);
6095   build_base_fields (rli, empty_base_offsets, next_field);
6096 
6097   /* Layout the non-static data members.  */
6098   for (field = non_static_data_members; field; field = DECL_CHAIN (field))
6099     {
6100       tree type;
6101       tree padding;
6102 
6103       /* We still pass things that aren't non-static data members to
6104 	 the back end, in case it wants to do something with them.  */
6105       if (TREE_CODE (field) != FIELD_DECL)
6106 	{
6107 	  place_field (rli, field);
6108 	  /* If the static data member has incomplete type, keep track
6109 	     of it so that it can be completed later.  (The handling
6110 	     of pending statics in finish_record_layout is
6111 	     insufficient; consider:
6112 
6113 	       struct S1;
6114 	       struct S2 { static S1 s1; };
6115 
6116 	     At this point, finish_record_layout will be called, but
6117 	     S1 is still incomplete.)  */
6118 	  if (VAR_P (field))
6119 	    {
6120 	      maybe_register_incomplete_var (field);
6121 	      /* The visibility of static data members is determined
6122 		 at their point of declaration, not their point of
6123 		 definition.  */
6124 	      determine_visibility (field);
6125 	    }
6126 	  continue;
6127 	}
6128 
6129       type = TREE_TYPE (field);
6130       if (type == error_mark_node)
6131 	continue;
6132 
6133       padding = NULL_TREE;
6134 
6135       /* If this field is a bit-field whose width is greater than its
6136 	 type, then there are some special rules for allocating
6137 	 it.  */
6138       if (DECL_C_BIT_FIELD (field)
6139 	  && tree_int_cst_lt (TYPE_SIZE (type), DECL_SIZE (field)))
6140 	{
6141 	  bool was_unnamed_p = false;
6142 	  /* We must allocate the bits as if suitably aligned for the
6143 	     longest integer type that fits in this many bits.  Then,
6144 	     we are supposed to use the left over bits as additional
6145 	     padding.  */
6146 
6147 	  /* Do not pick a type bigger than MAX_FIXED_MODE_SIZE.  */
6148 	  tree limit = size_int (MAX_FIXED_MODE_SIZE);
6149 	  if (tree_int_cst_lt (DECL_SIZE (field), limit))
6150 	    limit = DECL_SIZE (field);
6151 
6152 	  tree integer_type = integer_types[itk_char];
6153 	  for (unsigned itk = itk_char; itk != itk_none; itk++)
6154 	    if (tree next = integer_types[itk])
6155 	      {
6156 		if (tree_int_cst_lt (limit, TYPE_SIZE (next)))
6157 		  /* Too big, so our current guess is what we want.  */
6158 		  break;
6159 		/* Not bigger than limit, ok  */
6160 		integer_type = next;
6161 	      }
6162 
6163 	  /* Figure out how much additional padding is required.  */
6164 	  if (TREE_CODE (t) == UNION_TYPE)
6165 	    /* In a union, the padding field must have the full width
6166 	       of the bit-field; all fields start at offset zero.  */
6167 	    padding = DECL_SIZE (field);
6168 	  else
6169 	    padding = size_binop (MINUS_EXPR, DECL_SIZE (field),
6170 				  TYPE_SIZE (integer_type));
6171 
6172  	  if (integer_zerop (padding))
6173 	    padding = NULL_TREE;
6174 
6175 	  /* An unnamed bitfield does not normally affect the
6176 	     alignment of the containing class on a target where
6177 	     PCC_BITFIELD_TYPE_MATTERS.  But, the C++ ABI does not
6178 	     make any exceptions for unnamed bitfields when the
6179 	     bitfields are longer than their types.  Therefore, we
6180 	     temporarily give the field a name.  */
6181 	  if (PCC_BITFIELD_TYPE_MATTERS && !DECL_NAME (field))
6182 	    {
6183 	      was_unnamed_p = true;
6184 	      DECL_NAME (field) = make_anon_name ();
6185 	    }
6186 
6187 	  DECL_SIZE (field) = TYPE_SIZE (integer_type);
6188 	  SET_DECL_ALIGN (field, TYPE_ALIGN (integer_type));
6189 	  DECL_USER_ALIGN (field) = TYPE_USER_ALIGN (integer_type);
6190 	  layout_nonempty_base_or_field (rli, field, NULL_TREE,
6191 					 empty_base_offsets);
6192 	  if (was_unnamed_p)
6193 	    DECL_NAME (field) = NULL_TREE;
6194 	  /* Now that layout has been performed, set the size of the
6195 	     field to the size of its declared type; the rest of the
6196 	     field is effectively invisible.  */
6197 	  DECL_SIZE (field) = TYPE_SIZE (type);
6198 	  /* We must also reset the DECL_MODE of the field.  */
6199 	  SET_DECL_MODE (field, TYPE_MODE (type));
6200 	}
6201       else
6202 	layout_nonempty_base_or_field (rli, field, NULL_TREE,
6203 				       empty_base_offsets);
6204 
6205       /* Remember the location of any empty classes in FIELD.  */
6206       record_subobject_offsets (TREE_TYPE (field),
6207 				byte_position(field),
6208 				empty_base_offsets,
6209 				/*is_data_member=*/true);
6210 
6211       /* If a bit-field does not immediately follow another bit-field,
6212 	 and yet it starts in the middle of a byte, we have failed to
6213 	 comply with the ABI.  */
6214       if (warn_abi
6215 	  && DECL_C_BIT_FIELD (field)
6216 	  /* The TREE_NO_WARNING flag gets set by Objective-C when
6217 	     laying out an Objective-C class.  The ObjC ABI differs
6218 	     from the C++ ABI, and so we do not want a warning
6219 	     here.  */
6220 	  && !TREE_NO_WARNING (field)
6221 	  && !last_field_was_bitfield
6222 	  && !integer_zerop (size_binop (TRUNC_MOD_EXPR,
6223 					 DECL_FIELD_BIT_OFFSET (field),
6224 					 bitsize_unit_node)))
6225 	warning_at (DECL_SOURCE_LOCATION (field), OPT_Wabi,
6226 		    "offset of %qD is not ABI-compliant and may "
6227 		    "change in a future version of GCC", field);
6228 
6229       /* The middle end uses the type of expressions to determine the
6230 	 possible range of expression values.  In order to optimize
6231 	 "x.i > 7" to "false" for a 2-bit bitfield "i", the middle end
6232 	 must be made aware of the width of "i", via its type.
6233 
6234 	 Because C++ does not have integer types of arbitrary width,
6235 	 we must (for the purposes of the front end) convert from the
6236 	 type assigned here to the declared type of the bitfield
6237 	 whenever a bitfield expression is used as an rvalue.
6238 	 Similarly, when assigning a value to a bitfield, the value
6239 	 must be converted to the type given the bitfield here.  */
6240       if (DECL_C_BIT_FIELD (field))
6241 	{
6242 	  unsigned HOST_WIDE_INT width;
6243 	  tree ftype = TREE_TYPE (field);
6244 	  width = tree_to_uhwi (DECL_SIZE (field));
6245 	  if (width != TYPE_PRECISION (ftype))
6246 	    {
6247 	      TREE_TYPE (field)
6248 		= c_build_bitfield_integer_type (width,
6249 						 TYPE_UNSIGNED (ftype));
6250 	      TREE_TYPE (field)
6251 		= cp_build_qualified_type (TREE_TYPE (field),
6252 					   cp_type_quals (ftype));
6253 	    }
6254 	}
6255 
6256       /* If we needed additional padding after this field, add it
6257 	 now.  */
6258       if (padding)
6259 	{
6260 	  tree padding_field;
6261 
6262 	  padding_field = build_decl (input_location,
6263 				      FIELD_DECL,
6264 				      NULL_TREE,
6265 				      char_type_node);
6266 	  DECL_BIT_FIELD (padding_field) = 1;
6267 	  DECL_SIZE (padding_field) = padding;
6268 	  DECL_CONTEXT (padding_field) = t;
6269 	  DECL_ARTIFICIAL (padding_field) = 1;
6270 	  DECL_IGNORED_P (padding_field) = 1;
6271 	  DECL_PADDING_P (padding_field) = 1;
6272 	  layout_nonempty_base_or_field (rli, padding_field,
6273 					 NULL_TREE,
6274 					 empty_base_offsets);
6275 	}
6276 
6277       last_field_was_bitfield = DECL_C_BIT_FIELD (field);
6278     }
6279 
6280   if (!integer_zerop (rli->bitpos))
6281     {
6282       /* Make sure that we are on a byte boundary so that the size of
6283 	 the class without virtual bases will always be a round number
6284 	 of bytes.  */
6285       rli->bitpos = round_up_loc (input_location, rli->bitpos, BITS_PER_UNIT);
6286       normalize_rli (rli);
6287     }
6288 
6289   /* Delete all zero-width bit-fields from the list of fields.  Now
6290      that the type is laid out they are no longer important.  */
6291   remove_zero_width_bit_fields (t);
6292 
6293   if (CLASSTYPE_NON_LAYOUT_POD_P (t) || CLASSTYPE_EMPTY_P (t))
6294     {
6295       /* T needs a different layout as a base (eliding virtual bases
6296 	 or whatever).  Create that version.  */
6297       tree base_t = make_node (TREE_CODE (t));
6298 
6299       /* If the ABI version is not at least two, and the last
6300 	 field was a bit-field, RLI may not be on a byte
6301 	 boundary.  In particular, rli_size_unit_so_far might
6302 	 indicate the last complete byte, while rli_size_so_far
6303 	 indicates the total number of bits used.  Therefore,
6304 	 rli_size_so_far, rather than rli_size_unit_so_far, is
6305 	 used to compute TYPE_SIZE_UNIT.  */
6306       tree eoc = end_of_class (t, /*include_virtuals_p=*/0);
6307       TYPE_SIZE_UNIT (base_t)
6308 	= size_binop (MAX_EXPR,
6309 		      fold_convert (sizetype,
6310 			       size_binop (CEIL_DIV_EXPR,
6311 					   rli_size_so_far (rli),
6312 					   bitsize_int (BITS_PER_UNIT))),
6313 		      eoc);
6314       TYPE_SIZE (base_t)
6315 	= size_binop (MAX_EXPR,
6316 		      rli_size_so_far (rli),
6317 		      size_binop (MULT_EXPR,
6318 				  fold_convert (bitsizetype, eoc),
6319 				  bitsize_int (BITS_PER_UNIT)));
6320       SET_TYPE_ALIGN (base_t, rli->record_align);
6321       TYPE_USER_ALIGN (base_t) = TYPE_USER_ALIGN (t);
6322       TYPE_TYPELESS_STORAGE (base_t) = TYPE_TYPELESS_STORAGE (t);
6323 
6324       /* Copy the non-static data members of T. This will include its
6325 	 direct non-virtual bases & vtable.  */
6326       next_field = &TYPE_FIELDS (base_t);
6327       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
6328 	if (TREE_CODE (field) == FIELD_DECL)
6329 	  {
6330 	    *next_field = copy_node (field);
6331 	    DECL_CONTEXT (*next_field) = base_t;
6332 	    next_field = &DECL_CHAIN (*next_field);
6333 	  }
6334       *next_field = NULL_TREE;
6335 
6336       /* We use the base type for trivial assignments, and hence it
6337 	 needs a mode.  */
6338       compute_record_mode (base_t);
6339 
6340       TYPE_CONTEXT (base_t) = t;
6341 
6342       /* Record the base version of the type.  */
6343       CLASSTYPE_AS_BASE (t) = base_t;
6344     }
6345   else
6346     CLASSTYPE_AS_BASE (t) = t;
6347 
6348   /* Every empty class contains an empty class.  */
6349   if (CLASSTYPE_EMPTY_P (t))
6350     CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t) = 1;
6351 
6352   /* Set the TYPE_DECL for this type to contain the right
6353      value for DECL_OFFSET, so that we can use it as part
6354      of a COMPONENT_REF for multiple inheritance.  */
6355   layout_decl (TYPE_MAIN_DECL (t), 0);
6356 
6357   /* Now fix up any virtual base class types that we left lying
6358      around.  We must get these done before we try to lay out the
6359      virtual function table.  As a side-effect, this will remove the
6360      base subobject fields.  */
6361   layout_virtual_bases (rli, empty_base_offsets);
6362 
6363   /* Make sure that empty classes are reflected in RLI at this
6364      point.  */
6365   include_empty_classes (rli);
6366 
6367   /* Make sure not to create any structures with zero size.  */
6368   if (integer_zerop (rli_size_unit_so_far (rli)) && CLASSTYPE_EMPTY_P (t))
6369     place_field (rli,
6370 		 build_decl (input_location,
6371 			     FIELD_DECL, NULL_TREE, char_type_node));
6372 
6373   /* If this is a non-POD, declaring it packed makes a difference to how it
6374      can be used as a field; don't let finalize_record_size undo it.  */
6375   if (TYPE_PACKED (t) && !layout_pod_type_p (t))
6376     rli->packed_maybe_necessary = true;
6377 
6378   /* Let the back end lay out the type.  */
6379   finish_record_layout (rli, /*free_p=*/true);
6380 
6381   if (TYPE_SIZE_UNIT (t)
6382       && TREE_CODE (TYPE_SIZE_UNIT (t)) == INTEGER_CST
6383       && !TREE_OVERFLOW (TYPE_SIZE_UNIT (t))
6384       && !valid_constant_size_p (TYPE_SIZE_UNIT (t)))
6385     error ("size of type %qT is too large (%qE bytes)", t, TYPE_SIZE_UNIT (t));
6386 
6387   /* Warn about bases that can't be talked about due to ambiguity.  */
6388   warn_about_ambiguous_bases (t);
6389 
6390   /* Now that we're done with layout, give the base fields the real types.  */
6391   for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
6392     if (DECL_ARTIFICIAL (field) && IS_FAKE_BASE_TYPE (TREE_TYPE (field)))
6393       TREE_TYPE (field) = TYPE_CONTEXT (TREE_TYPE (field));
6394 
6395   /* Clean up.  */
6396   splay_tree_delete (empty_base_offsets);
6397 
6398   if (CLASSTYPE_EMPTY_P (t)
6399       && tree_int_cst_lt (sizeof_biggest_empty_class,
6400 			  TYPE_SIZE_UNIT (t)))
6401     sizeof_biggest_empty_class = TYPE_SIZE_UNIT (t);
6402 }
6403 
6404 /* Determine the "key method" for the class type indicated by TYPE,
6405    and set CLASSTYPE_KEY_METHOD accordingly.  */
6406 
6407 void
determine_key_method(tree type)6408 determine_key_method (tree type)
6409 {
6410   tree method;
6411 
6412   if (processing_template_decl
6413       || CLASSTYPE_TEMPLATE_INSTANTIATION (type)
6414       || CLASSTYPE_INTERFACE_KNOWN (type))
6415     return;
6416 
6417   /* The key method is the first non-pure virtual function that is not
6418      inline at the point of class definition.  On some targets the
6419      key function may not be inline; those targets should not call
6420      this function until the end of the translation unit.  */
6421   for (method = TYPE_FIELDS (type); method; method = DECL_CHAIN (method))
6422     if (TREE_CODE (method) == FUNCTION_DECL
6423 	&& DECL_VINDEX (method) != NULL_TREE
6424 	&& ! DECL_DECLARED_INLINE_P (method)
6425 	&& ! DECL_PURE_VIRTUAL_P (method))
6426       {
6427 	CLASSTYPE_KEY_METHOD (type) = method;
6428 	break;
6429       }
6430 
6431   return;
6432 }
6433 
6434 /* Helper of find_flexarrays.  Return true when FLD refers to a non-static
6435    class data member of non-zero size, otherwise false.  */
6436 
6437 static inline bool
field_nonempty_p(const_tree fld)6438 field_nonempty_p (const_tree fld)
6439 {
6440   if (TREE_CODE (fld) == ERROR_MARK)
6441     return false;
6442 
6443   tree type = TREE_TYPE (fld);
6444   if (TREE_CODE (fld) == FIELD_DECL
6445       && TREE_CODE (type) != ERROR_MARK
6446       && (DECL_NAME (fld) || RECORD_OR_UNION_TYPE_P (type)))
6447     {
6448       return TYPE_SIZE (type)
6449 	&& (TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
6450 	    || !tree_int_cst_equal (size_zero_node, TYPE_SIZE (type)));
6451     }
6452 
6453   return false;
6454 }
6455 
6456 /* Used by find_flexarrays and related functions.  */
6457 
6458 struct flexmems_t
6459 {
6460   /* The first flexible array member or non-zero array member found
6461      in the order of layout.  */
6462   tree array;
6463   /* First non-static non-empty data member in the class or its bases.  */
6464   tree first;
6465   /* The first non-static non-empty data member following either
6466      the flexible array member, if found, or the zero-length array member
6467      otherwise.  AFTER[1] refers to the first such data member of a union
6468      of which the struct containing the flexible array member or zero-length
6469      array is a member, or NULL when no such union exists.  This element is
6470      only used during searching, not for diagnosing problems.  AFTER[0]
6471      refers to the first such data member that is not a member of such
6472      a union.  */
6473   tree after[2];
6474 
6475   /* Refers to a struct (not union) in which the struct of which the flexible
6476      array is member is defined.  Used to diagnose strictly (according to C)
6477      invalid uses of the latter structs.  */
6478   tree enclosing;
6479 };
6480 
6481 /* Find either the first flexible array member or the first zero-length
6482    array, in that order of preference, among members of class T (but not
6483    its base classes), and set members of FMEM accordingly.
6484    BASE_P is true if T is a base class of another class.
6485    PUN is set to the outermost union in which the flexible array member
6486    (or zero-length array) is defined if one such union exists, otherwise
6487    to NULL.
6488    Similarly, PSTR is set to a data member of the outermost struct of
6489    which the flexible array is a member if one such struct exists,
6490    otherwise to NULL.  */
6491 
6492 static void
find_flexarrays(tree t,flexmems_t * fmem,bool base_p,tree pun,tree pstr)6493 find_flexarrays (tree t, flexmems_t *fmem, bool base_p,
6494 		 tree pun /* = NULL_TREE */,
6495 		 tree pstr /* = NULL_TREE */)
6496 {
6497   /* Set the "pointer" to the outermost enclosing union if not set
6498      yet and maintain it for the remainder of the recursion.   */
6499   if (!pun && TREE_CODE (t) == UNION_TYPE)
6500     pun = t;
6501 
6502   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
6503     {
6504       if (fld == error_mark_node)
6505 	return;
6506 
6507       /* Is FLD a typedef for an anonymous struct?  */
6508 
6509       /* FIXME: Note that typedefs (as well as arrays) need to be fully
6510 	 handled elsewhere so that errors like the following are detected
6511 	 as well:
6512 	   typedef struct { int i, a[], j; } S;   // bug c++/72753
6513 	   S s [2];                               // bug c++/68489
6514       */
6515       if (TREE_CODE (fld) == TYPE_DECL
6516 	  && DECL_IMPLICIT_TYPEDEF_P (fld)
6517 	  && CLASS_TYPE_P (TREE_TYPE (fld))
6518 	  && anon_aggrname_p (DECL_NAME (fld)))
6519 	{
6520 	  /* Check the nested unnamed type referenced via a typedef
6521 	     independently of FMEM (since it's not a data member of
6522 	     the enclosing class).  */
6523 	  check_flexarrays (TREE_TYPE (fld));
6524 	  continue;
6525 	}
6526 
6527       /* Skip anything that's GCC-generated or not a (non-static) data
6528 	 member.  */
6529       if (DECL_ARTIFICIAL (fld) || TREE_CODE (fld) != FIELD_DECL)
6530 	continue;
6531 
6532       /* Type of the member.  */
6533       tree fldtype = TREE_TYPE (fld);
6534       if (fldtype == error_mark_node)
6535 	return;
6536 
6537       /* Determine the type of the array element or object referenced
6538 	 by the member so that it can be checked for flexible array
6539 	 members if it hasn't been yet.  */
6540       tree eltype = fldtype;
6541       while (TREE_CODE (eltype) == ARRAY_TYPE
6542 	     || TREE_CODE (eltype) == POINTER_TYPE
6543 	     || TREE_CODE (eltype) == REFERENCE_TYPE)
6544 	eltype = TREE_TYPE (eltype);
6545 
6546       if (RECORD_OR_UNION_TYPE_P (eltype))
6547 	{
6548 	  if (fmem->array && !fmem->after[bool (pun)])
6549 	    {
6550 	      /* Once the member after the flexible array has been found
6551 		 we're done.  */
6552 	      fmem->after[bool (pun)] = fld;
6553 	      break;
6554 	    }
6555 
6556 	  if (eltype == fldtype || TYPE_UNNAMED_P (eltype))
6557 	    {
6558 	      /* Descend into the non-static member struct or union and try
6559 		 to find a flexible array member or zero-length array among
6560 		 its members.  This is only necessary for anonymous types
6561 		 and types in whose context the current type T has not been
6562 		 defined (the latter must not be checked again because they
6563 		 are already in the process of being checked by one of the
6564 		 recursive calls).  */
6565 
6566 	      tree first = fmem->first;
6567 	      tree array = fmem->array;
6568 
6569 	      /* If this member isn't anonymous and a prior non-flexible array
6570 		 member has been seen in one of the enclosing structs, clear
6571 		 the FIRST member since it doesn't contribute to the flexible
6572 		 array struct's members.  */
6573 	      if (first && !array && !ANON_AGGR_TYPE_P (eltype))
6574 		fmem->first = NULL_TREE;
6575 
6576 	      find_flexarrays (eltype, fmem, false, pun,
6577 			       !pstr && TREE_CODE (t) == RECORD_TYPE ? fld : pstr);
6578 
6579 	      if (fmem->array != array)
6580 		continue;
6581 
6582 	      if (first && !array && !ANON_AGGR_TYPE_P (eltype))
6583 		{
6584 		  /* Restore the FIRST member reset above if no flexible
6585 		     array member has been found in this member's struct.  */
6586 		  fmem->first = first;
6587 		}
6588 
6589 	      /* If the member struct contains the first flexible array
6590 		 member, or if this member is a base class, continue to
6591 		 the next member and avoid setting the FMEM->NEXT pointer
6592 		 to point to it.  */
6593 	      if (base_p)
6594 		continue;
6595 	    }
6596 	}
6597 
6598       if (field_nonempty_p (fld))
6599 	{
6600 	  /* Remember the first non-static data member.  */
6601 	  if (!fmem->first)
6602 	    fmem->first = fld;
6603 
6604 	  /* Remember the first non-static data member after the flexible
6605 	     array member, if one has been found, or the zero-length array
6606 	     if it has been found.  */
6607 	  if (fmem->array && !fmem->after[bool (pun)])
6608 	    fmem->after[bool (pun)] = fld;
6609 	}
6610 
6611       /* Skip non-arrays.  */
6612       if (TREE_CODE (fldtype) != ARRAY_TYPE)
6613 	continue;
6614 
6615       /* Determine the upper bound of the array if it has one.  */
6616       if (TYPE_DOMAIN (fldtype))
6617 	{
6618 	  if (fmem->array)
6619 	    {
6620 	      /* Make a record of the zero-length array if either one
6621 		 such field or a flexible array member has been seen to
6622 		 handle the pathological and unlikely case of multiple
6623 		 such members.  */
6624 	      if (!fmem->after[bool (pun)])
6625 		fmem->after[bool (pun)] = fld;
6626 	    }
6627 	  else if (integer_all_onesp (TYPE_MAX_VALUE (TYPE_DOMAIN (fldtype))))
6628 	    {
6629 	      /* Remember the first zero-length array unless a flexible array
6630 		 member has already been seen.  */
6631 	      fmem->array = fld;
6632 	      fmem->enclosing = pstr;
6633 	    }
6634 	}
6635       else
6636 	{
6637 	  /* Flexible array members have no upper bound.  */
6638 	  if (fmem->array)
6639 	    {
6640 	      if (TYPE_DOMAIN (TREE_TYPE (fmem->array)))
6641 		{
6642 		  /* Replace the zero-length array if it's been stored and
6643 		     reset the after pointer.  */
6644 		  fmem->after[bool (pun)] = NULL_TREE;
6645 		  fmem->array = fld;
6646 		  fmem->enclosing = pstr;
6647 		}
6648 	      else if (!fmem->after[bool (pun)])
6649 		/* Make a record of another flexible array member.  */
6650 		fmem->after[bool (pun)] = fld;
6651 	    }
6652 	  else
6653 	    {
6654 	      fmem->array = fld;
6655 	      fmem->enclosing = pstr;
6656 	    }
6657 	}
6658     }
6659 }
6660 
6661 /* Diagnose a strictly (by the C standard) invalid use of a struct with
6662    a flexible array member (or the zero-length array extension).  */
6663 
6664 static void
diagnose_invalid_flexarray(const flexmems_t * fmem)6665 diagnose_invalid_flexarray (const flexmems_t *fmem)
6666 {
6667   if (fmem->array && fmem->enclosing
6668       && pedwarn (location_of (fmem->enclosing), OPT_Wpedantic,
6669 		  TYPE_DOMAIN (TREE_TYPE (fmem->array))
6670 		  ? G_("invalid use of %q#T with a zero-size array "
6671 		       "in %q#D")
6672 		  : G_("invalid use of %q#T with a flexible array member "
6673 		       "in %q#T"),
6674 		  DECL_CONTEXT (fmem->array),
6675 		  DECL_CONTEXT (fmem->enclosing)))
6676     inform (DECL_SOURCE_LOCATION (fmem->array),
6677 	    "array member %q#D declared here", fmem->array);
6678 }
6679 
6680 /* Issue diagnostics for invalid flexible array members or zero-length
6681    arrays that are not the last elements of the containing class or its
6682    base classes or that are its sole members.  */
6683 
6684 static void
diagnose_flexarrays(tree t,const flexmems_t * fmem)6685 diagnose_flexarrays (tree t, const flexmems_t *fmem)
6686 {
6687   if (!fmem->array)
6688     return;
6689 
6690   if (fmem->first && !fmem->after[0])
6691     {
6692       diagnose_invalid_flexarray (fmem);
6693       return;
6694     }
6695 
6696   /* Has a diagnostic been issued?  */
6697   bool diagd = false;
6698 
6699   const char *msg = 0;
6700 
6701   if (TYPE_DOMAIN (TREE_TYPE (fmem->array)))
6702     {
6703       if (fmem->after[0])
6704 	msg = G_("zero-size array member %qD not at end of %q#T");
6705       else if (!fmem->first)
6706 	msg = G_("zero-size array member %qD in an otherwise empty %q#T");
6707 
6708       if (msg)
6709 	{
6710 	  location_t loc = DECL_SOURCE_LOCATION (fmem->array);
6711 
6712 	  if (pedwarn (loc, OPT_Wpedantic, msg, fmem->array, t))
6713 	    {
6714 	      inform (location_of (t), "in the definition of %q#T", t);
6715 	      diagd = true;
6716 	    }
6717 	}
6718     }
6719   else
6720     {
6721       if (fmem->after[0])
6722 	msg = G_("flexible array member %qD not at end of %q#T");
6723       else if (!fmem->first)
6724 	msg = G_("flexible array member %qD in an otherwise empty %q#T");
6725 
6726       if (msg)
6727 	{
6728 	  location_t loc = DECL_SOURCE_LOCATION (fmem->array);
6729 	  diagd = true;
6730 
6731 	  error_at (loc, msg, fmem->array, t);
6732 
6733 	  /* In the unlikely event that the member following the flexible
6734 	     array member is declared in a different class, or the member
6735 	     overlaps another member of a common union, point to it.
6736 	     Otherwise it should be obvious.  */
6737 	  if (fmem->after[0]
6738 	      && ((DECL_CONTEXT (fmem->after[0])
6739 		   != DECL_CONTEXT (fmem->array))))
6740 	    {
6741 	      inform (DECL_SOURCE_LOCATION (fmem->after[0]),
6742 		      "next member %q#D declared here",
6743 		      fmem->after[0]);
6744 	      inform (location_of (t), "in the definition of %q#T", t);
6745 	    }
6746 	}
6747     }
6748 
6749   if (!diagd && fmem->array && fmem->enclosing)
6750     diagnose_invalid_flexarray (fmem);
6751 }
6752 
6753 
6754 /* Recursively check to make sure that any flexible array or zero-length
6755    array members of class T or its bases are valid (i.e., not the sole
6756    non-static data member of T and, if one exists, that it is the last
6757    non-static data member of T and its base classes.  FMEM is expected
6758    to be initially null and is used internally by recursive calls to
6759    the function.  Issue the appropriate diagnostics for the array member
6760    that fails the checks.  */
6761 
6762 static void
check_flexarrays(tree t,flexmems_t * fmem,bool base_p)6763 check_flexarrays (tree t, flexmems_t *fmem /* = NULL */,
6764 		  bool base_p /* = false */)
6765 {
6766   /* Initialize the result of a search for flexible array and zero-length
6767      array members.  Avoid doing any work if the most interesting FMEM data
6768      have already been populated.  */
6769   flexmems_t flexmems = flexmems_t ();
6770   if (!fmem)
6771     fmem = &flexmems;
6772   else if (fmem->array && fmem->first && fmem->after[0])
6773     return;
6774 
6775   tree fam = fmem->array;
6776 
6777   /* Recursively check the primary base class first.  */
6778   if (CLASSTYPE_HAS_PRIMARY_BASE_P (t))
6779     {
6780       tree basetype = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (t));
6781       check_flexarrays (basetype, fmem, true);
6782     }
6783 
6784   /* Recursively check the base classes.  */
6785   int nbases = TYPE_BINFO (t) ? BINFO_N_BASE_BINFOS (TYPE_BINFO (t)) : 0;
6786   for (int i = 0; i < nbases; ++i)
6787     {
6788       tree base_binfo = BINFO_BASE_BINFO (TYPE_BINFO (t), i);
6789 
6790       /* The primary base class was already checked above.  */
6791       if (base_binfo == CLASSTYPE_PRIMARY_BINFO (t))
6792 	continue;
6793 
6794       /* Virtual base classes are at the end.  */
6795       if (BINFO_VIRTUAL_P (base_binfo))
6796 	continue;
6797 
6798       /* Check the base class.  */
6799       check_flexarrays (BINFO_TYPE (base_binfo), fmem, /*base_p=*/true);
6800     }
6801 
6802   if (fmem == &flexmems)
6803     {
6804       /* Check virtual base classes only once per derived class.
6805 	 I.e., this check is not performed recursively for base
6806 	 classes.  */
6807       int i;
6808       tree base_binfo;
6809       vec<tree, va_gc> *vbases;
6810       for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
6811 	   vec_safe_iterate (vbases, i, &base_binfo); i++)
6812 	{
6813 	  /* Check the virtual base class.  */
6814 	  tree basetype = TREE_TYPE (base_binfo);
6815 
6816 	  check_flexarrays (basetype, fmem, /*base_p=*/true);
6817 	}
6818     }
6819 
6820   /* Is the type unnamed (and therefore a member of it potentially
6821      an anonymous struct or union)?  */
6822   bool maybe_anon_p = TYPE_UNNAMED_P (t);
6823 
6824   /* Search the members of the current (possibly derived) class, skipping
6825      unnamed structs and unions since those could be anonymous.  */
6826   if (fmem != &flexmems || !maybe_anon_p)
6827     find_flexarrays (t, fmem, base_p || fam != fmem->array);
6828 
6829   if (fmem == &flexmems && !maybe_anon_p)
6830     {
6831       /* Issue diagnostics for invalid flexible and zero-length array
6832 	 members found in base classes or among the members of the current
6833 	 class.  Ignore anonymous structs and unions whose members are
6834 	 considered to be members of the enclosing class and thus will
6835 	 be diagnosed when checking it.  */
6836       diagnose_flexarrays (t, fmem);
6837     }
6838 }
6839 
6840 /* Perform processing required when the definition of T (a class type)
6841    is complete.  Diagnose invalid definitions of flexible array members
6842    and zero-size arrays.  */
6843 
6844 void
finish_struct_1(tree t)6845 finish_struct_1 (tree t)
6846 {
6847   tree x;
6848   /* A TREE_LIST.  The TREE_VALUE of each node is a FUNCTION_DECL.  */
6849   tree virtuals = NULL_TREE;
6850 
6851   if (COMPLETE_TYPE_P (t))
6852     {
6853       gcc_assert (MAYBE_CLASS_TYPE_P (t));
6854       error ("redefinition of %q#T", t);
6855       popclass ();
6856       return;
6857     }
6858 
6859   /* If this type was previously laid out as a forward reference,
6860      make sure we lay it out again.  */
6861   TYPE_SIZE (t) = NULL_TREE;
6862   CLASSTYPE_PRIMARY_BINFO (t) = NULL_TREE;
6863 
6864   /* Make assumptions about the class; we'll reset the flags if
6865      necessary.  */
6866   CLASSTYPE_EMPTY_P (t) = 1;
6867   CLASSTYPE_NEARLY_EMPTY_P (t) = 1;
6868   CLASSTYPE_CONTAINS_EMPTY_CLASS_P (t) = 0;
6869   CLASSTYPE_LITERAL_P (t) = true;
6870 
6871   /* Do end-of-class semantic processing: checking the validity of the
6872      bases and members and add implicitly generated methods.  */
6873   check_bases_and_members (t);
6874 
6875   /* Find the key method.  */
6876   if (TYPE_CONTAINS_VPTR_P (t))
6877     {
6878       /* The Itanium C++ ABI permits the key method to be chosen when
6879 	 the class is defined -- even though the key method so
6880 	 selected may later turn out to be an inline function.  On
6881 	 some systems (such as ARM Symbian OS) the key method cannot
6882 	 be determined until the end of the translation unit.  On such
6883 	 systems, we leave CLASSTYPE_KEY_METHOD set to NULL, which
6884 	 will cause the class to be added to KEYED_CLASSES.  Then, in
6885 	 finish_file we will determine the key method.  */
6886       if (targetm.cxx.key_method_may_be_inline ())
6887 	determine_key_method (t);
6888 
6889       /* If a polymorphic class has no key method, we may emit the vtable
6890 	 in every translation unit where the class definition appears.  If
6891 	 we're devirtualizing, we can look into the vtable even if we
6892 	 aren't emitting it.  */
6893       if (!CLASSTYPE_KEY_METHOD (t))
6894 	vec_safe_push (keyed_classes, t);
6895     }
6896 
6897   /* Layout the class itself.  */
6898   layout_class_type (t, &virtuals);
6899   /* COMPLETE_TYPE_P is now true.  */
6900 
6901   set_class_bindings (t);
6902 
6903   /* With the layout complete, check for flexible array members and
6904      zero-length arrays that might overlap other members in the final
6905      layout.  */
6906   check_flexarrays (t);
6907 
6908   virtuals = modify_all_vtables (t, nreverse (virtuals));
6909 
6910   /* If necessary, create the primary vtable for this class.  */
6911   if (virtuals || TYPE_CONTAINS_VPTR_P (t))
6912     {
6913       /* We must enter these virtuals into the table.  */
6914       if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
6915 	build_primary_vtable (NULL_TREE, t);
6916       else if (! BINFO_NEW_VTABLE_MARKED (TYPE_BINFO (t)))
6917 	/* Here we know enough to change the type of our virtual
6918 	   function table, but we will wait until later this function.  */
6919 	build_primary_vtable (CLASSTYPE_PRIMARY_BINFO (t), t);
6920 
6921       /* If we're warning about ABI tags, check the types of the new
6922 	 virtual functions.  */
6923       if (warn_abi_tag)
6924 	for (tree v = virtuals; v; v = TREE_CHAIN (v))
6925 	  check_abi_tags (t, TREE_VALUE (v));
6926     }
6927 
6928   if (TYPE_CONTAINS_VPTR_P (t))
6929     {
6930       int vindex;
6931       tree fn;
6932 
6933       if (BINFO_VTABLE (TYPE_BINFO (t)))
6934 	gcc_assert (DECL_VIRTUAL_P (BINFO_VTABLE (TYPE_BINFO (t))));
6935       if (!CLASSTYPE_HAS_PRIMARY_BASE_P (t))
6936 	gcc_assert (BINFO_VIRTUALS (TYPE_BINFO (t)) == NULL_TREE);
6937 
6938       /* Add entries for virtual functions introduced by this class.  */
6939       BINFO_VIRTUALS (TYPE_BINFO (t))
6940 	= chainon (BINFO_VIRTUALS (TYPE_BINFO (t)), virtuals);
6941 
6942       /* Set DECL_VINDEX for all functions declared in this class.  */
6943       for (vindex = 0, fn = BINFO_VIRTUALS (TYPE_BINFO (t));
6944 	   fn;
6945 	   fn = TREE_CHAIN (fn),
6946 	     vindex += (TARGET_VTABLE_USES_DESCRIPTORS
6947 			? TARGET_VTABLE_USES_DESCRIPTORS : 1))
6948 	{
6949 	  tree fndecl = BV_FN (fn);
6950 
6951 	  if (DECL_THUNK_P (fndecl))
6952 	    /* A thunk. We should never be calling this entry directly
6953 	       from this vtable -- we'd use the entry for the non
6954 	       thunk base function.  */
6955 	    DECL_VINDEX (fndecl) = NULL_TREE;
6956 	  else if (TREE_CODE (DECL_VINDEX (fndecl)) != INTEGER_CST)
6957 	    DECL_VINDEX (fndecl) = build_int_cst (NULL_TREE, vindex);
6958 	}
6959     }
6960 
6961   finish_struct_bits (t);
6962 
6963   set_method_tm_attributes (t);
6964   if (flag_openmp || flag_openmp_simd)
6965     finish_omp_declare_simd_methods (t);
6966 
6967   /* Clear DECL_IN_AGGR_P for all member functions.  Complete the rtl
6968      for any static member objects of the type we're working on.  */
6969   for (x = TYPE_FIELDS (t); x; x = DECL_CHAIN (x))
6970     if (DECL_DECLARES_FUNCTION_P (x))
6971       DECL_IN_AGGR_P (x) = false;
6972     else if (VAR_P (x) && TREE_STATIC (x)
6973 	     && TREE_TYPE (x) != error_mark_node
6974 	     && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (x)), t))
6975       SET_DECL_MODE (x, TYPE_MODE (t));
6976 
6977   /* Complain if one of the field types requires lower visibility.  */
6978   constrain_class_visibility (t);
6979 
6980   /* Make the rtl for any new vtables we have created, and unmark
6981      the base types we marked.  */
6982   finish_vtbls (t);
6983 
6984   /* Build the VTT for T.  */
6985   build_vtt (t);
6986 
6987   if (warn_nonvdtor
6988       && TYPE_POLYMORPHIC_P (t) && accessible_nvdtor_p (t)
6989       && !CLASSTYPE_FINAL (t))
6990     warning (OPT_Wnon_virtual_dtor,
6991 	     "%q#T has virtual functions and accessible"
6992 	     " non-virtual destructor", t);
6993 
6994   complete_vars (t);
6995 
6996   if (warn_overloaded_virtual)
6997     warn_hidden (t);
6998 
6999   /* Class layout, assignment of virtual table slots, etc., is now
7000      complete.  Give the back end a chance to tweak the visibility of
7001      the class or perform any other required target modifications.  */
7002   targetm.cxx.adjust_class_at_definition (t);
7003 
7004   maybe_suppress_debug_info (t);
7005 
7006   if (flag_vtable_verify)
7007     vtv_save_class_info (t);
7008 
7009   dump_class_hierarchy (t);
7010 
7011   /* Finish debugging output for this type.  */
7012   rest_of_type_compilation (t, ! LOCAL_CLASS_P (t));
7013 
7014   if (TYPE_TRANSPARENT_AGGR (t))
7015     {
7016       tree field = first_field (t);
7017       if (field == NULL_TREE || error_operand_p (field))
7018 	{
7019 	  error ("type transparent %q#T does not have any fields", t);
7020 	  TYPE_TRANSPARENT_AGGR (t) = 0;
7021 	}
7022       else if (DECL_ARTIFICIAL (field))
7023 	{
7024 	  if (DECL_FIELD_IS_BASE (field))
7025 	    error ("type transparent class %qT has base classes", t);
7026 	  else
7027 	    {
7028 	      gcc_checking_assert (DECL_VIRTUAL_P (field));
7029 	      error ("type transparent class %qT has virtual functions", t);
7030 	    }
7031 	  TYPE_TRANSPARENT_AGGR (t) = 0;
7032 	}
7033       else if (TYPE_MODE (t) != DECL_MODE (field))
7034 	{
7035 	  error ("type transparent %q#T cannot be made transparent because "
7036 		 "the type of the first field has a different ABI from the "
7037 		 "class overall", t);
7038 	  TYPE_TRANSPARENT_AGGR (t) = 0;
7039 	}
7040     }
7041 }
7042 
7043 /* When T was built up, the member declarations were added in reverse
7044    order.  Rearrange them to declaration order.  */
7045 
7046 void
unreverse_member_declarations(tree t)7047 unreverse_member_declarations (tree t)
7048 {
7049   tree next;
7050   tree prev;
7051   tree x;
7052 
7053   /* The following lists are all in reverse order.  Put them in
7054      declaration order now.  */
7055   CLASSTYPE_DECL_LIST (t) = nreverse (CLASSTYPE_DECL_LIST (t));
7056 
7057   /* For the TYPE_FIELDS, only the non TYPE_DECLs are in reverse
7058      order, so we can't just use nreverse.  Due to stat_hack
7059      chicanery in finish_member_declaration.  */
7060   prev = NULL_TREE;
7061   for (x = TYPE_FIELDS (t);
7062        x && TREE_CODE (x) != TYPE_DECL;
7063        x = next)
7064     {
7065       next = DECL_CHAIN (x);
7066       DECL_CHAIN (x) = prev;
7067       prev = x;
7068     }
7069 
7070   if (prev)
7071     {
7072       DECL_CHAIN (TYPE_FIELDS (t)) = x;
7073       TYPE_FIELDS (t) = prev;
7074     }
7075 }
7076 
7077 tree
finish_struct(tree t,tree attributes)7078 finish_struct (tree t, tree attributes)
7079 {
7080   location_t saved_loc = input_location;
7081 
7082   /* Now that we've got all the field declarations, reverse everything
7083      as necessary.  */
7084   unreverse_member_declarations (t);
7085 
7086   cplus_decl_attributes (&t, attributes, (int) ATTR_FLAG_TYPE_IN_PLACE);
7087   fixup_attribute_variants (t);
7088 
7089   /* Nadger the current location so that diagnostics point to the start of
7090      the struct, not the end.  */
7091   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (t));
7092 
7093   if (processing_template_decl)
7094     {
7095       tree x;
7096 
7097       /* We need to add the target functions of USING_DECLS, so that
7098 	 they can be found when the using declaration is not
7099 	 instantiated yet.  */
7100       for (x = TYPE_FIELDS (t); x; x = DECL_CHAIN (x))
7101 	if (TREE_CODE (x) == USING_DECL)
7102 	  {
7103 	    tree fn = strip_using_decl (x);
7104   	    if (OVL_P (fn))
7105 	      for (lkp_iterator iter (fn); iter; ++iter)
7106 		add_method (t, *iter, true);
7107 	  }
7108 	else if (DECL_DECLARES_FUNCTION_P (x))
7109 	  DECL_IN_AGGR_P (x) = false;
7110 
7111       /* Also add a USING_DECL for operator=.  We know there'll be (at
7112 	 least) one, but we don't know the signature(s).  We want name
7113 	 lookup not to fail or recurse into bases.  This isn't added
7114 	 to the template decl list so we drop this at instantiation
7115 	 time.  */
7116       tree ass_op = build_lang_decl (USING_DECL, assign_op_identifier,
7117 				     NULL_TREE);
7118       DECL_CONTEXT (ass_op) = t;
7119       USING_DECL_SCOPE (ass_op) = t;
7120       DECL_DEPENDENT_P (ass_op) = true;
7121       DECL_ARTIFICIAL (ass_op) = true;
7122       DECL_CHAIN (ass_op) = TYPE_FIELDS (t);
7123       TYPE_FIELDS (t) = ass_op;
7124 
7125       TYPE_SIZE (t) = bitsize_zero_node;
7126       TYPE_SIZE_UNIT (t) = size_zero_node;
7127       /* COMPLETE_TYPE_P is now true.  */
7128 
7129       set_class_bindings (t);
7130 
7131       /* We need to emit an error message if this type was used as a parameter
7132 	 and it is an abstract type, even if it is a template. We construct
7133 	 a simple CLASSTYPE_PURE_VIRTUALS list without taking bases into
7134 	 account and we call complete_vars with this type, which will check
7135 	 the PARM_DECLS. Note that while the type is being defined,
7136 	 CLASSTYPE_PURE_VIRTUALS contains the list of the inline friends
7137 	 (see CLASSTYPE_INLINE_FRIENDS) so we need to clear it.  */
7138       CLASSTYPE_PURE_VIRTUALS (t) = NULL;
7139       for (x = TYPE_FIELDS (t); x; x = DECL_CHAIN (x))
7140 	if (TREE_CODE (x) == FUNCTION_DECL && DECL_PURE_VIRTUAL_P (x))
7141 	  vec_safe_push (CLASSTYPE_PURE_VIRTUALS (t), x);
7142       complete_vars (t);
7143 
7144       /* Remember current #pragma pack value.  */
7145       TYPE_PRECISION (t) = maximum_field_alignment;
7146 
7147       /* Fix up any variants we've already built.  */
7148       for (x = TYPE_NEXT_VARIANT (t); x; x = TYPE_NEXT_VARIANT (x))
7149 	{
7150 	  TYPE_SIZE (x) = TYPE_SIZE (t);
7151 	  TYPE_SIZE_UNIT (x) = TYPE_SIZE_UNIT (t);
7152 	  TYPE_FIELDS (x) = TYPE_FIELDS (t);
7153 	}
7154     }
7155   else
7156     finish_struct_1 (t);
7157   /* COMPLETE_TYPE_P is now true.  */
7158 
7159   maybe_warn_about_overly_private_class (t);
7160 
7161   if (is_std_init_list (t))
7162     {
7163       /* People keep complaining that the compiler crashes on an invalid
7164 	 definition of initializer_list, so I guess we should explicitly
7165 	 reject it.  What the compiler internals care about is that it's a
7166 	 template and has a pointer field followed by size_type field.  */
7167       bool ok = false;
7168       if (processing_template_decl)
7169 	{
7170 	  tree f = next_initializable_field (TYPE_FIELDS (t));
7171 	  if (f && TREE_CODE (TREE_TYPE (f)) == POINTER_TYPE)
7172 	    {
7173 	      f = next_initializable_field (DECL_CHAIN (f));
7174 	      if (f && same_type_p (TREE_TYPE (f), size_type_node))
7175 		ok = true;
7176 	    }
7177 	}
7178       if (!ok)
7179 	fatal_error (input_location, "definition of %qD does not match "
7180 		     "%<#include <initializer_list>%>", TYPE_NAME (t));
7181     }
7182 
7183   input_location = saved_loc;
7184 
7185   TYPE_BEING_DEFINED (t) = 0;
7186 
7187   if (current_class_type)
7188     popclass ();
7189   else
7190     error ("trying to finish struct, but kicked out due to previous parse errors");
7191 
7192   if (processing_template_decl && at_function_scope_p ()
7193       /* Lambdas are defined by the LAMBDA_EXPR.  */
7194       && !LAMBDA_TYPE_P (t))
7195     add_stmt (build_min (TAG_DEFN, t));
7196 
7197   return t;
7198 }
7199 
7200 /* Hash table to avoid endless recursion when handling references.  */
7201 static hash_table<nofree_ptr_hash<tree_node> > *fixed_type_or_null_ref_ht;
7202 
7203 /* Return the dynamic type of INSTANCE, if known.
7204    Used to determine whether the virtual function table is needed
7205    or not.
7206 
7207    *NONNULL is set iff INSTANCE can be known to be nonnull, regardless
7208    of our knowledge of its type.  *NONNULL should be initialized
7209    before this function is called.  */
7210 
7211 static tree
fixed_type_or_null(tree instance,int * nonnull,int * cdtorp)7212 fixed_type_or_null (tree instance, int *nonnull, int *cdtorp)
7213 {
7214 #define RECUR(T) fixed_type_or_null((T), nonnull, cdtorp)
7215 
7216   switch (TREE_CODE (instance))
7217     {
7218     case INDIRECT_REF:
7219       if (POINTER_TYPE_P (TREE_TYPE (instance)))
7220 	return NULL_TREE;
7221       else
7222 	return RECUR (TREE_OPERAND (instance, 0));
7223 
7224     case CALL_EXPR:
7225       /* This is a call to a constructor, hence it's never zero.  */
7226       if (CALL_EXPR_FN (instance)
7227 	  && TREE_HAS_CONSTRUCTOR (instance))
7228 	{
7229 	  if (nonnull)
7230 	    *nonnull = 1;
7231 	  return TREE_TYPE (instance);
7232 	}
7233       return NULL_TREE;
7234 
7235     case SAVE_EXPR:
7236       /* This is a call to a constructor, hence it's never zero.  */
7237       if (TREE_HAS_CONSTRUCTOR (instance))
7238 	{
7239 	  if (nonnull)
7240 	    *nonnull = 1;
7241 	  return TREE_TYPE (instance);
7242 	}
7243       return RECUR (TREE_OPERAND (instance, 0));
7244 
7245     case POINTER_PLUS_EXPR:
7246     case PLUS_EXPR:
7247     case MINUS_EXPR:
7248       if (TREE_CODE (TREE_OPERAND (instance, 0)) == ADDR_EXPR)
7249 	return RECUR (TREE_OPERAND (instance, 0));
7250       if (TREE_CODE (TREE_OPERAND (instance, 1)) == INTEGER_CST)
7251 	/* Propagate nonnull.  */
7252 	return RECUR (TREE_OPERAND (instance, 0));
7253 
7254       return NULL_TREE;
7255 
7256     CASE_CONVERT:
7257       return RECUR (TREE_OPERAND (instance, 0));
7258 
7259     case ADDR_EXPR:
7260       instance = TREE_OPERAND (instance, 0);
7261       if (nonnull)
7262 	{
7263 	  /* Just because we see an ADDR_EXPR doesn't mean we're dealing
7264 	     with a real object -- given &p->f, p can still be null.  */
7265 	  tree t = get_base_address (instance);
7266 	  /* ??? Probably should check DECL_WEAK here.  */
7267 	  if (t && DECL_P (t))
7268 	    *nonnull = 1;
7269 	}
7270       return RECUR (instance);
7271 
7272     case COMPONENT_REF:
7273       /* If this component is really a base class reference, then the field
7274 	 itself isn't definitive.  */
7275       if (DECL_FIELD_IS_BASE (TREE_OPERAND (instance, 1)))
7276 	return RECUR (TREE_OPERAND (instance, 0));
7277       return RECUR (TREE_OPERAND (instance, 1));
7278 
7279     case VAR_DECL:
7280     case FIELD_DECL:
7281       if (TREE_CODE (TREE_TYPE (instance)) == ARRAY_TYPE
7282 	  && MAYBE_CLASS_TYPE_P (TREE_TYPE (TREE_TYPE (instance))))
7283 	{
7284 	  if (nonnull)
7285 	    *nonnull = 1;
7286 	  return TREE_TYPE (TREE_TYPE (instance));
7287 	}
7288       /* fall through.  */
7289     case TARGET_EXPR:
7290     case PARM_DECL:
7291     case RESULT_DECL:
7292       if (MAYBE_CLASS_TYPE_P (TREE_TYPE (instance)))
7293 	{
7294 	  if (nonnull)
7295 	    *nonnull = 1;
7296 	  return TREE_TYPE (instance);
7297 	}
7298       else if (instance == current_class_ptr)
7299 	{
7300 	  if (nonnull)
7301 	    *nonnull = 1;
7302 
7303 	  /* if we're in a ctor or dtor, we know our type.  If
7304 	     current_class_ptr is set but we aren't in a function, we're in
7305 	     an NSDMI (and therefore a constructor).  */
7306 	  if (current_scope () != current_function_decl
7307 	      || (DECL_LANG_SPECIFIC (current_function_decl)
7308 		  && (DECL_CONSTRUCTOR_P (current_function_decl)
7309 		      || DECL_DESTRUCTOR_P (current_function_decl))))
7310 	    {
7311 	      if (cdtorp)
7312 		*cdtorp = 1;
7313 	      return TREE_TYPE (TREE_TYPE (instance));
7314 	    }
7315 	}
7316       else if (TREE_CODE (TREE_TYPE (instance)) == REFERENCE_TYPE)
7317 	{
7318 	  /* We only need one hash table because it is always left empty.  */
7319 	  if (!fixed_type_or_null_ref_ht)
7320 	    fixed_type_or_null_ref_ht
7321 	      = new hash_table<nofree_ptr_hash<tree_node> > (37);
7322 
7323 	  /* Reference variables should be references to objects.  */
7324 	  if (nonnull)
7325 	    *nonnull = 1;
7326 
7327 	  /* Enter the INSTANCE in a table to prevent recursion; a
7328 	     variable's initializer may refer to the variable
7329 	     itself.  */
7330 	  if (VAR_P (instance)
7331 	      && DECL_INITIAL (instance)
7332 	      && !type_dependent_expression_p_push (DECL_INITIAL (instance))
7333 	      && !fixed_type_or_null_ref_ht->find (instance))
7334 	    {
7335 	      tree type;
7336 	      tree_node **slot;
7337 
7338 	      slot = fixed_type_or_null_ref_ht->find_slot (instance, INSERT);
7339 	      *slot = instance;
7340 	      type = RECUR (DECL_INITIAL (instance));
7341 	      fixed_type_or_null_ref_ht->remove_elt (instance);
7342 
7343 	      return type;
7344 	    }
7345 	}
7346       return NULL_TREE;
7347 
7348     default:
7349       return NULL_TREE;
7350     }
7351 #undef RECUR
7352 }
7353 
7354 /* Return nonzero if the dynamic type of INSTANCE is known, and
7355    equivalent to the static type.  We also handle the case where
7356    INSTANCE is really a pointer. Return negative if this is a
7357    ctor/dtor. There the dynamic type is known, but this might not be
7358    the most derived base of the original object, and hence virtual
7359    bases may not be laid out according to this type.
7360 
7361    Used to determine whether the virtual function table is needed
7362    or not.
7363 
7364    *NONNULL is set iff INSTANCE can be known to be nonnull, regardless
7365    of our knowledge of its type.  *NONNULL should be initialized
7366    before this function is called.  */
7367 
7368 int
resolves_to_fixed_type_p(tree instance,int * nonnull)7369 resolves_to_fixed_type_p (tree instance, int* nonnull)
7370 {
7371   tree t = TREE_TYPE (instance);
7372   int cdtorp = 0;
7373   tree fixed;
7374 
7375   /* processing_template_decl can be false in a template if we're in
7376      instantiate_non_dependent_expr, but we still want to suppress
7377      this check.  */
7378   if (in_template_function ())
7379     {
7380       /* In a template we only care about the type of the result.  */
7381       if (nonnull)
7382 	*nonnull = true;
7383       return true;
7384     }
7385 
7386   fixed = fixed_type_or_null (instance, nonnull, &cdtorp);
7387   if (fixed == NULL_TREE)
7388     return 0;
7389   if (POINTER_TYPE_P (t))
7390     t = TREE_TYPE (t);
7391   if (!same_type_ignoring_top_level_qualifiers_p (t, fixed))
7392     return 0;
7393   return cdtorp ? -1 : 1;
7394 }
7395 
7396 
7397 void
init_class_processing(void)7398 init_class_processing (void)
7399 {
7400   current_class_depth = 0;
7401   current_class_stack_size = 10;
7402   current_class_stack
7403     = XNEWVEC (struct class_stack_node, current_class_stack_size);
7404   vec_alloc (local_classes, 8);
7405   sizeof_biggest_empty_class = size_zero_node;
7406 
7407   ridpointers[(int) RID_PUBLIC] = access_public_node;
7408   ridpointers[(int) RID_PRIVATE] = access_private_node;
7409   ridpointers[(int) RID_PROTECTED] = access_protected_node;
7410 }
7411 
7412 /* Restore the cached PREVIOUS_CLASS_LEVEL.  */
7413 
7414 static void
restore_class_cache(void)7415 restore_class_cache (void)
7416 {
7417   tree type;
7418 
7419   /* We are re-entering the same class we just left, so we don't
7420      have to search the whole inheritance matrix to find all the
7421      decls to bind again.  Instead, we install the cached
7422      class_shadowed list and walk through it binding names.  */
7423   push_binding_level (previous_class_level);
7424   class_binding_level = previous_class_level;
7425   /* Restore IDENTIFIER_TYPE_VALUE.  */
7426   for (type = class_binding_level->type_shadowed;
7427        type;
7428        type = TREE_CHAIN (type))
7429     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (type), TREE_TYPE (type));
7430 }
7431 
7432 /* Set global variables CURRENT_CLASS_NAME and CURRENT_CLASS_TYPE as
7433    appropriate for TYPE.
7434 
7435    So that we may avoid calls to lookup_name, we cache the _TYPE
7436    nodes of local TYPE_DECLs in the TREE_TYPE field of the name.
7437 
7438    For multiple inheritance, we perform a two-pass depth-first search
7439    of the type lattice.  */
7440 
7441 void
pushclass(tree type)7442 pushclass (tree type)
7443 {
7444   class_stack_node_t csn;
7445 
7446   type = TYPE_MAIN_VARIANT (type);
7447 
7448   /* Make sure there is enough room for the new entry on the stack.  */
7449   if (current_class_depth + 1 >= current_class_stack_size)
7450     {
7451       current_class_stack_size *= 2;
7452       current_class_stack
7453 	= XRESIZEVEC (struct class_stack_node, current_class_stack,
7454 		      current_class_stack_size);
7455     }
7456 
7457   /* Insert a new entry on the class stack.  */
7458   csn = current_class_stack + current_class_depth;
7459   csn->name = current_class_name;
7460   csn->type = current_class_type;
7461   csn->access = current_access_specifier;
7462   csn->names_used = 0;
7463   csn->hidden = 0;
7464   current_class_depth++;
7465 
7466   /* Now set up the new type.  */
7467   current_class_name = TYPE_NAME (type);
7468   if (TREE_CODE (current_class_name) == TYPE_DECL)
7469     current_class_name = DECL_NAME (current_class_name);
7470   current_class_type = type;
7471 
7472   /* By default, things in classes are private, while things in
7473      structures or unions are public.  */
7474   current_access_specifier = (CLASSTYPE_DECLARED_CLASS (type)
7475 			      ? access_private_node
7476 			      : access_public_node);
7477 
7478   if (previous_class_level
7479       && type != previous_class_level->this_entity
7480       && current_class_depth == 1)
7481     {
7482       /* Forcibly remove any old class remnants.  */
7483       invalidate_class_lookup_cache ();
7484     }
7485 
7486   if (!previous_class_level
7487       || type != previous_class_level->this_entity
7488       || current_class_depth > 1)
7489     pushlevel_class ();
7490   else
7491     restore_class_cache ();
7492 }
7493 
7494 /* When we exit a toplevel class scope, we save its binding level so
7495    that we can restore it quickly.  Here, we've entered some other
7496    class, so we must invalidate our cache.  */
7497 
7498 void
invalidate_class_lookup_cache(void)7499 invalidate_class_lookup_cache (void)
7500 {
7501   previous_class_level = NULL;
7502 }
7503 
7504 /* Get out of the current class scope. If we were in a class scope
7505    previously, that is the one popped to.  */
7506 
7507 void
popclass(void)7508 popclass (void)
7509 {
7510   poplevel_class ();
7511 
7512   current_class_depth--;
7513   current_class_name = current_class_stack[current_class_depth].name;
7514   current_class_type = current_class_stack[current_class_depth].type;
7515   current_access_specifier = current_class_stack[current_class_depth].access;
7516   if (current_class_stack[current_class_depth].names_used)
7517     splay_tree_delete (current_class_stack[current_class_depth].names_used);
7518 }
7519 
7520 /* Mark the top of the class stack as hidden.  */
7521 
7522 void
push_class_stack(void)7523 push_class_stack (void)
7524 {
7525   if (current_class_depth)
7526     ++current_class_stack[current_class_depth - 1].hidden;
7527 }
7528 
7529 /* Mark the top of the class stack as un-hidden.  */
7530 
7531 void
pop_class_stack(void)7532 pop_class_stack (void)
7533 {
7534   if (current_class_depth)
7535     --current_class_stack[current_class_depth - 1].hidden;
7536 }
7537 
7538 /* If the class type currently being defined is either T or
7539    a nested type of T, returns the type from the current_class_stack,
7540    which might be equivalent to but not equal to T in case of
7541    constrained partial specializations.  */
7542 
7543 tree
currently_open_class(tree t)7544 currently_open_class (tree t)
7545 {
7546   int i;
7547 
7548   if (!CLASS_TYPE_P (t))
7549     return NULL_TREE;
7550 
7551   t = TYPE_MAIN_VARIANT (t);
7552 
7553   /* We start looking from 1 because entry 0 is from global scope,
7554      and has no type.  */
7555   for (i = current_class_depth; i > 0; --i)
7556     {
7557       tree c;
7558       if (i == current_class_depth)
7559 	c = current_class_type;
7560       else
7561 	{
7562 	  if (current_class_stack[i].hidden)
7563 	    break;
7564 	  c = current_class_stack[i].type;
7565 	}
7566       if (!c)
7567 	continue;
7568       if (same_type_p (c, t))
7569 	return c;
7570     }
7571   return NULL_TREE;
7572 }
7573 
7574 /* If either current_class_type or one of its enclosing classes are derived
7575    from T, return the appropriate type.  Used to determine how we found
7576    something via unqualified lookup.  */
7577 
7578 tree
currently_open_derived_class(tree t)7579 currently_open_derived_class (tree t)
7580 {
7581   int i;
7582 
7583   /* The bases of a dependent type are unknown.  */
7584   if (dependent_type_p (t))
7585     return NULL_TREE;
7586 
7587   if (!current_class_type)
7588     return NULL_TREE;
7589 
7590   if (DERIVED_FROM_P (t, current_class_type))
7591     return current_class_type;
7592 
7593   for (i = current_class_depth - 1; i > 0; --i)
7594     {
7595       if (current_class_stack[i].hidden)
7596 	break;
7597       if (DERIVED_FROM_P (t, current_class_stack[i].type))
7598 	return current_class_stack[i].type;
7599     }
7600 
7601   return NULL_TREE;
7602 }
7603 
7604 /* Return the outermost enclosing class type that is still open, or
7605    NULL_TREE.  */
7606 
7607 tree
outermost_open_class(void)7608 outermost_open_class (void)
7609 {
7610   if (!current_class_type)
7611     return NULL_TREE;
7612   tree r = NULL_TREE;
7613   if (TYPE_BEING_DEFINED (current_class_type))
7614     r = current_class_type;
7615   for (int i = current_class_depth - 1; i > 0; --i)
7616     {
7617       if (current_class_stack[i].hidden)
7618 	break;
7619       tree t = current_class_stack[i].type;
7620       if (!TYPE_BEING_DEFINED (t))
7621 	break;
7622       r = t;
7623     }
7624   return r;
7625 }
7626 
7627 /* Returns the innermost class type which is not a lambda closure type.  */
7628 
7629 tree
current_nonlambda_class_type(void)7630 current_nonlambda_class_type (void)
7631 {
7632   tree type = current_class_type;
7633   while (type && LAMBDA_TYPE_P (type))
7634     type = decl_type_context (TYPE_NAME (type));
7635   return type;
7636 }
7637 
7638 /* When entering a class scope, all enclosing class scopes' names with
7639    static meaning (static variables, static functions, types and
7640    enumerators) have to be visible.  This recursive function calls
7641    pushclass for all enclosing class contexts until global or a local
7642    scope is reached.  TYPE is the enclosed class.  */
7643 
7644 void
push_nested_class(tree type)7645 push_nested_class (tree type)
7646 {
7647   /* A namespace might be passed in error cases, like A::B:C.  */
7648   if (type == NULL_TREE
7649       || !CLASS_TYPE_P (type))
7650     return;
7651 
7652   push_nested_class (DECL_CONTEXT (TYPE_MAIN_DECL (type)));
7653 
7654   pushclass (type);
7655 }
7656 
7657 /* Undoes a push_nested_class call.  */
7658 
7659 void
pop_nested_class(void)7660 pop_nested_class (void)
7661 {
7662   tree context = DECL_CONTEXT (TYPE_MAIN_DECL (current_class_type));
7663 
7664   popclass ();
7665   if (context && CLASS_TYPE_P (context))
7666     pop_nested_class ();
7667 }
7668 
7669 /* Returns the number of extern "LANG" blocks we are nested within.  */
7670 
7671 int
current_lang_depth(void)7672 current_lang_depth (void)
7673 {
7674   return vec_safe_length (current_lang_base);
7675 }
7676 
7677 /* Set global variables CURRENT_LANG_NAME to appropriate value
7678    so that behavior of name-mangling machinery is correct.  */
7679 
7680 void
push_lang_context(tree name)7681 push_lang_context (tree name)
7682 {
7683   vec_safe_push (current_lang_base, current_lang_name);
7684 
7685   if (name == lang_name_cplusplus)
7686     current_lang_name = name;
7687   else if (name == lang_name_c)
7688     current_lang_name = name;
7689   else
7690     error ("language string %<\"%E\"%> not recognized", name);
7691 }
7692 
7693 /* Get out of the current language scope.  */
7694 
7695 void
pop_lang_context(void)7696 pop_lang_context (void)
7697 {
7698   current_lang_name = current_lang_base->pop ();
7699 }
7700 
7701 /* Type instantiation routines.  */
7702 
7703 /* Given an OVERLOAD and a TARGET_TYPE, return the function that
7704    matches the TARGET_TYPE.  If there is no satisfactory match, return
7705    error_mark_node, and issue an error & warning messages under
7706    control of FLAGS.  Permit pointers to member function if FLAGS
7707    permits.  If TEMPLATE_ONLY, the name of the overloaded function was
7708    a template-id, and EXPLICIT_TARGS are the explicitly provided
7709    template arguments.
7710 
7711    If OVERLOAD is for one or more member functions, then ACCESS_PATH
7712    is the base path used to reference those member functions.  If
7713    the address is resolved to a member function, access checks will be
7714    performed and errors issued if appropriate.  */
7715 
7716 static tree
resolve_address_of_overloaded_function(tree target_type,tree overload,tsubst_flags_t complain,bool template_only,tree explicit_targs,tree access_path)7717 resolve_address_of_overloaded_function (tree target_type,
7718 					tree overload,
7719 					tsubst_flags_t complain,
7720 					bool template_only,
7721 					tree explicit_targs,
7722 					tree access_path)
7723 {
7724   /* Here's what the standard says:
7725 
7726        [over.over]
7727 
7728        If the name is a function template, template argument deduction
7729        is done, and if the argument deduction succeeds, the deduced
7730        arguments are used to generate a single template function, which
7731        is added to the set of overloaded functions considered.
7732 
7733        Non-member functions and static member functions match targets of
7734        type "pointer-to-function" or "reference-to-function."  Nonstatic
7735        member functions match targets of type "pointer-to-member
7736        function;" the function type of the pointer to member is used to
7737        select the member function from the set of overloaded member
7738        functions.  If a nonstatic member function is selected, the
7739        reference to the overloaded function name is required to have the
7740        form of a pointer to member as described in 5.3.1.
7741 
7742        If more than one function is selected, any template functions in
7743        the set are eliminated if the set also contains a non-template
7744        function, and any given template function is eliminated if the
7745        set contains a second template function that is more specialized
7746        than the first according to the partial ordering rules 14.5.5.2.
7747        After such eliminations, if any, there shall remain exactly one
7748        selected function.  */
7749 
7750   int is_ptrmem = 0;
7751   /* We store the matches in a TREE_LIST rooted here.  The functions
7752      are the TREE_PURPOSE, not the TREE_VALUE, in this list, for easy
7753      interoperability with most_specialized_instantiation.  */
7754   tree matches = NULL_TREE;
7755   tree fn;
7756   tree target_fn_type;
7757 
7758   /* By the time we get here, we should be seeing only real
7759      pointer-to-member types, not the internal POINTER_TYPE to
7760      METHOD_TYPE representation.  */
7761   gcc_assert (!TYPE_PTR_P (target_type)
7762 	      || TREE_CODE (TREE_TYPE (target_type)) != METHOD_TYPE);
7763 
7764   gcc_assert (is_overloaded_fn (overload));
7765 
7766   /* Check that the TARGET_TYPE is reasonable.  */
7767   if (TYPE_PTRFN_P (target_type)
7768       || TYPE_REFFN_P (target_type))
7769     /* This is OK.  */;
7770   else if (TYPE_PTRMEMFUNC_P (target_type))
7771     /* This is OK, too.  */
7772     is_ptrmem = 1;
7773   else if (TREE_CODE (target_type) == FUNCTION_TYPE)
7774     /* This is OK, too.  This comes from a conversion to reference
7775        type.  */
7776     target_type = build_reference_type (target_type);
7777   else
7778     {
7779       if (complain & tf_error)
7780 	error ("cannot resolve overloaded function %qD based on"
7781 	       " conversion to type %qT",
7782 	       OVL_NAME (overload), target_type);
7783       return error_mark_node;
7784     }
7785 
7786   /* Non-member functions and static member functions match targets of type
7787      "pointer-to-function" or "reference-to-function."  Nonstatic member
7788      functions match targets of type "pointer-to-member-function;" the
7789      function type of the pointer to member is used to select the member
7790      function from the set of overloaded member functions.
7791 
7792      So figure out the FUNCTION_TYPE that we want to match against.  */
7793   target_fn_type = static_fn_type (target_type);
7794 
7795   /* If we can find a non-template function that matches, we can just
7796      use it.  There's no point in generating template instantiations
7797      if we're just going to throw them out anyhow.  But, of course, we
7798      can only do this when we don't *need* a template function.  */
7799   if (!template_only)
7800     for (lkp_iterator iter (overload); iter; ++iter)
7801       {
7802 	tree fn = *iter;
7803 
7804 	if (TREE_CODE (fn) == TEMPLATE_DECL)
7805 	  /* We're not looking for templates just yet.  */
7806 	  continue;
7807 
7808 	if ((TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE) != is_ptrmem)
7809 	  /* We're looking for a non-static member, and this isn't
7810 	     one, or vice versa.  */
7811 	  continue;
7812 
7813 	/* In C++17 we need the noexcept-qualifier to compare types.  */
7814 	if (flag_noexcept_type
7815 	    && !maybe_instantiate_noexcept (fn, complain))
7816 	  continue;
7817 
7818 	/* See if there's a match.  */
7819 	tree fntype = static_fn_type (fn);
7820 	if (same_type_p (target_fn_type, fntype)
7821 	    || fnptr_conv_p (target_fn_type, fntype))
7822 	  matches = tree_cons (fn, NULL_TREE, matches);
7823       }
7824 
7825   /* Now, if we've already got a match (or matches), there's no need
7826      to proceed to the template functions.  But, if we don't have a
7827      match we need to look at them, too.  */
7828   if (!matches)
7829     {
7830       tree target_arg_types;
7831       tree target_ret_type;
7832       tree *args;
7833       unsigned int nargs, ia;
7834       tree arg;
7835 
7836       target_arg_types = TYPE_ARG_TYPES (target_fn_type);
7837       target_ret_type = TREE_TYPE (target_fn_type);
7838 
7839       nargs = list_length (target_arg_types);
7840       args = XALLOCAVEC (tree, nargs);
7841       for (arg = target_arg_types, ia = 0;
7842 	   arg != NULL_TREE && arg != void_list_node;
7843 	   arg = TREE_CHAIN (arg), ++ia)
7844 	args[ia] = TREE_VALUE (arg);
7845       nargs = ia;
7846 
7847       for (lkp_iterator iter (overload); iter; ++iter)
7848 	{
7849 	  tree fn = *iter;
7850 	  tree instantiation;
7851 	  tree targs;
7852 
7853 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
7854 	    /* We're only looking for templates.  */
7855 	    continue;
7856 
7857 	  if ((TREE_CODE (TREE_TYPE (fn)) == METHOD_TYPE)
7858 	      != is_ptrmem)
7859 	    /* We're not looking for a non-static member, and this is
7860 	       one, or vice versa.  */
7861 	    continue;
7862 
7863 	  tree ret = target_ret_type;
7864 
7865 	  /* If the template has a deduced return type, don't expose it to
7866 	     template argument deduction.  */
7867 	  if (undeduced_auto_decl (fn))
7868 	    ret = NULL_TREE;
7869 
7870 	  /* Try to do argument deduction.  */
7871 	  targs = make_tree_vec (DECL_NTPARMS (fn));
7872 	  instantiation = fn_type_unification (fn, explicit_targs, targs, args,
7873 					       nargs, ret,
7874 					      DEDUCE_EXACT, LOOKUP_NORMAL,
7875 					       false, false);
7876 	  if (instantiation == error_mark_node)
7877 	    /* Instantiation failed.  */
7878 	    continue;
7879 
7880 	  /* Constraints must be satisfied. This is done before
7881 	     return type deduction since that instantiates the
7882 	     function. */
7883 	  if (flag_concepts && !constraints_satisfied_p (instantiation))
7884 	    continue;
7885 
7886 	  /* And now force instantiation to do return type deduction.  */
7887 	  if (undeduced_auto_decl (instantiation))
7888 	    {
7889 	      ++function_depth;
7890 	      instantiate_decl (instantiation, /*defer*/false, /*class*/false);
7891 	      --function_depth;
7892 
7893 	      require_deduced_type (instantiation);
7894 	    }
7895 
7896 	  /* In C++17 we need the noexcept-qualifier to compare types.  */
7897 	  if (flag_noexcept_type)
7898 	    maybe_instantiate_noexcept (instantiation, complain);
7899 
7900 	  /* See if there's a match.  */
7901 	  tree fntype = static_fn_type (instantiation);
7902 	  if (same_type_p (target_fn_type, fntype)
7903 	      || fnptr_conv_p (target_fn_type, fntype))
7904 	    matches = tree_cons (instantiation, fn, matches);
7905 	}
7906 
7907       /* Now, remove all but the most specialized of the matches.  */
7908       if (matches)
7909 	{
7910 	  tree match = most_specialized_instantiation (matches);
7911 
7912 	  if (match != error_mark_node)
7913 	    matches = tree_cons (TREE_PURPOSE (match),
7914 				 NULL_TREE,
7915 				 NULL_TREE);
7916 	}
7917     }
7918 
7919   /* Now we should have exactly one function in MATCHES.  */
7920   if (matches == NULL_TREE)
7921     {
7922       /* There were *no* matches.  */
7923       if (complain & tf_error)
7924 	{
7925 	  error ("no matches converting function %qD to type %q#T",
7926 		 OVL_NAME (overload), target_type);
7927 
7928 	  print_candidates (overload);
7929 	}
7930       return error_mark_node;
7931     }
7932   else if (TREE_CHAIN (matches))
7933     {
7934       /* There were too many matches.  First check if they're all
7935 	 the same function.  */
7936       tree match = NULL_TREE;
7937 
7938       fn = TREE_PURPOSE (matches);
7939 
7940       /* For multi-versioned functions, more than one match is just fine and
7941 	 decls_match will return false as they are different.  */
7942       for (match = TREE_CHAIN (matches); match; match = TREE_CHAIN (match))
7943 	if (!decls_match (fn, TREE_PURPOSE (match))
7944 	    && !targetm.target_option.function_versions
7945 	       (fn, TREE_PURPOSE (match)))
7946           break;
7947 
7948       if (match)
7949 	{
7950 	  if (complain & tf_error)
7951 	    {
7952 	      error ("converting overloaded function %qD to type %q#T is ambiguous",
7953 		     OVL_NAME (overload), target_type);
7954 
7955 	      /* Since print_candidates expects the functions in the
7956 		 TREE_VALUE slot, we flip them here.  */
7957 	      for (match = matches; match; match = TREE_CHAIN (match))
7958 		TREE_VALUE (match) = TREE_PURPOSE (match);
7959 
7960 	      print_candidates (matches);
7961 	    }
7962 
7963 	  return error_mark_node;
7964 	}
7965     }
7966 
7967   /* Good, exactly one match.  Now, convert it to the correct type.  */
7968   fn = TREE_PURPOSE (matches);
7969 
7970   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
7971       && !(complain & tf_ptrmem_ok) && !flag_ms_extensions)
7972     {
7973       static int explained;
7974 
7975       if (!(complain & tf_error))
7976 	return error_mark_node;
7977 
7978       permerror (input_location, "assuming pointer to member %qD", fn);
7979       if (!explained)
7980 	{
7981 	  inform (input_location, "(a pointer to member can only be formed with %<&%E%>)", fn);
7982 	  explained = 1;
7983 	}
7984     }
7985 
7986   /* If a pointer to a function that is multi-versioned is requested, the
7987      pointer to the dispatcher function is returned instead.  This works
7988      well because indirectly calling the function will dispatch the right
7989      function version at run-time.  */
7990   if (DECL_FUNCTION_VERSIONED (fn))
7991     {
7992       fn = get_function_version_dispatcher (fn);
7993       if (fn == NULL)
7994 	return error_mark_node;
7995       /* Mark all the versions corresponding to the dispatcher as used.  */
7996       if (!(complain & tf_conv))
7997 	mark_versions_used (fn);
7998     }
7999 
8000   /* If we're doing overload resolution purely for the purpose of
8001      determining conversion sequences, we should not consider the
8002      function used.  If this conversion sequence is selected, the
8003      function will be marked as used at this point.  */
8004   if (!(complain & tf_conv))
8005     {
8006       /* Make =delete work with SFINAE.  */
8007       if (DECL_DELETED_FN (fn) && !(complain & tf_error))
8008 	return error_mark_node;
8009       if (!mark_used (fn, complain) && !(complain & tf_error))
8010 	return error_mark_node;
8011     }
8012 
8013   /* We could not check access to member functions when this
8014      expression was originally created since we did not know at that
8015      time to which function the expression referred.  */
8016   if (DECL_FUNCTION_MEMBER_P (fn))
8017     {
8018       gcc_assert (access_path);
8019       perform_or_defer_access_check (access_path, fn, fn, complain);
8020     }
8021 
8022   if (TYPE_PTRFN_P (target_type) || TYPE_PTRMEMFUNC_P (target_type))
8023     return cp_build_addr_expr (fn, complain);
8024   else
8025     {
8026       /* The target must be a REFERENCE_TYPE.  Above, cp_build_unary_op
8027 	 will mark the function as addressed, but here we must do it
8028 	 explicitly.  */
8029       cxx_mark_addressable (fn);
8030 
8031       return fn;
8032     }
8033 }
8034 
8035 /* This function will instantiate the type of the expression given in
8036    RHS to match the type of LHSTYPE.  If errors exist, then return
8037    error_mark_node. COMPLAIN is a bit mask.  If TF_ERROR is set, then
8038    we complain on errors.  If we are not complaining, never modify rhs,
8039    as overload resolution wants to try many possible instantiations, in
8040    the hope that at least one will work.
8041 
8042    For non-recursive calls, LHSTYPE should be a function, pointer to
8043    function, or a pointer to member function.  */
8044 
8045 tree
instantiate_type(tree lhstype,tree rhs,tsubst_flags_t complain)8046 instantiate_type (tree lhstype, tree rhs, tsubst_flags_t complain)
8047 {
8048   tsubst_flags_t complain_in = complain;
8049   tree access_path = NULL_TREE;
8050 
8051   complain &= ~tf_ptrmem_ok;
8052 
8053   if (lhstype == unknown_type_node)
8054     {
8055       if (complain & tf_error)
8056 	error ("not enough type information");
8057       return error_mark_node;
8058     }
8059 
8060   if (TREE_TYPE (rhs) != NULL_TREE && ! (type_unknown_p (rhs)))
8061     {
8062       tree fntype = non_reference (lhstype);
8063       if (same_type_p (fntype, TREE_TYPE (rhs)))
8064 	return rhs;
8065       if (fnptr_conv_p (fntype, TREE_TYPE (rhs)))
8066 	return rhs;
8067       if (flag_ms_extensions
8068 	  && TYPE_PTRMEMFUNC_P (fntype)
8069 	  && !TYPE_PTRMEMFUNC_P (TREE_TYPE (rhs)))
8070 	/* Microsoft allows `A::f' to be resolved to a
8071 	   pointer-to-member.  */
8072 	;
8073       else
8074 	{
8075 	  if (complain & tf_error)
8076 	    error ("cannot convert %qE from type %qT to type %qT",
8077 		   rhs, TREE_TYPE (rhs), fntype);
8078 	  return error_mark_node;
8079 	}
8080     }
8081 
8082   /* If we instantiate a template, and it is a A ?: C expression
8083      with omitted B, look through the SAVE_EXPR.  */
8084   if (TREE_CODE (rhs) == SAVE_EXPR)
8085     rhs = TREE_OPERAND (rhs, 0);
8086 
8087   if (BASELINK_P (rhs))
8088     {
8089       access_path = BASELINK_ACCESS_BINFO (rhs);
8090       rhs = BASELINK_FUNCTIONS (rhs);
8091     }
8092 
8093   /* If we are in a template, and have a NON_DEPENDENT_EXPR, we cannot
8094      deduce any type information.  */
8095   if (TREE_CODE (rhs) == NON_DEPENDENT_EXPR)
8096     {
8097       if (complain & tf_error)
8098 	error ("not enough type information");
8099       return error_mark_node;
8100     }
8101 
8102   /* There are only a few kinds of expressions that may have a type
8103      dependent on overload resolution.  */
8104   gcc_assert (TREE_CODE (rhs) == ADDR_EXPR
8105 	      || TREE_CODE (rhs) == COMPONENT_REF
8106 	      || is_overloaded_fn (rhs)
8107 	      || (flag_ms_extensions && TREE_CODE (rhs) == FUNCTION_DECL));
8108 
8109   /* This should really only be used when attempting to distinguish
8110      what sort of a pointer to function we have.  For now, any
8111      arithmetic operation which is not supported on pointers
8112      is rejected as an error.  */
8113 
8114   switch (TREE_CODE (rhs))
8115     {
8116     case COMPONENT_REF:
8117       {
8118 	tree member = TREE_OPERAND (rhs, 1);
8119 
8120 	member = instantiate_type (lhstype, member, complain);
8121 	if (member != error_mark_node
8122 	    && TREE_SIDE_EFFECTS (TREE_OPERAND (rhs, 0)))
8123 	  /* Do not lose object's side effects.  */
8124 	  return build2 (COMPOUND_EXPR, TREE_TYPE (member),
8125 			 TREE_OPERAND (rhs, 0), member);
8126 	return member;
8127       }
8128 
8129     case OFFSET_REF:
8130       rhs = TREE_OPERAND (rhs, 1);
8131       if (BASELINK_P (rhs))
8132 	return instantiate_type (lhstype, rhs, complain_in);
8133 
8134       /* This can happen if we are forming a pointer-to-member for a
8135 	 member template.  */
8136       gcc_assert (TREE_CODE (rhs) == TEMPLATE_ID_EXPR);
8137 
8138       /* Fall through.  */
8139 
8140     case TEMPLATE_ID_EXPR:
8141       {
8142 	tree fns = TREE_OPERAND (rhs, 0);
8143 	tree args = TREE_OPERAND (rhs, 1);
8144 
8145 	return
8146 	  resolve_address_of_overloaded_function (lhstype, fns, complain_in,
8147 						  /*template_only=*/true,
8148 						  args, access_path);
8149       }
8150 
8151     case OVERLOAD:
8152     case FUNCTION_DECL:
8153       return
8154 	resolve_address_of_overloaded_function (lhstype, rhs, complain_in,
8155 						/*template_only=*/false,
8156 						/*explicit_targs=*/NULL_TREE,
8157 						access_path);
8158 
8159     case ADDR_EXPR:
8160     {
8161       if (PTRMEM_OK_P (rhs))
8162 	complain |= tf_ptrmem_ok;
8163 
8164       return instantiate_type (lhstype, TREE_OPERAND (rhs, 0), complain);
8165     }
8166 
8167     case ERROR_MARK:
8168       return error_mark_node;
8169 
8170     default:
8171       gcc_unreachable ();
8172     }
8173   return error_mark_node;
8174 }
8175 
8176 /* Return the name of the virtual function pointer field
8177    (as an IDENTIFIER_NODE) for the given TYPE.  Note that
8178    this may have to look back through base types to find the
8179    ultimate field name.  (For single inheritance, these could
8180    all be the same name.  Who knows for multiple inheritance).  */
8181 
8182 static tree
get_vfield_name(tree type)8183 get_vfield_name (tree type)
8184 {
8185   tree binfo, base_binfo;
8186 
8187   for (binfo = TYPE_BINFO (type);
8188        BINFO_N_BASE_BINFOS (binfo);
8189        binfo = base_binfo)
8190     {
8191       base_binfo = BINFO_BASE_BINFO (binfo, 0);
8192 
8193       if (BINFO_VIRTUAL_P (base_binfo)
8194 	  || !TYPE_CONTAINS_VPTR_P (BINFO_TYPE (base_binfo)))
8195 	break;
8196     }
8197 
8198   type = BINFO_TYPE (binfo);
8199   tree ctor_name = constructor_name (type);
8200   char *buf = (char *) alloca (sizeof (VFIELD_NAME_FORMAT)
8201 			       + IDENTIFIER_LENGTH (ctor_name) + 2);
8202   sprintf (buf, VFIELD_NAME_FORMAT, IDENTIFIER_POINTER (ctor_name));
8203   return get_identifier (buf);
8204 }
8205 
8206 /* Build a dummy reference to ourselves so Derived::Base (and A::A) works,
8207    according to [class]:
8208 					  The class-name is also inserted
8209    into  the scope of the class itself.  For purposes of access checking,
8210    the inserted class name is treated as if it were a public member name.  */
8211 
8212 void
build_self_reference(void)8213 build_self_reference (void)
8214 {
8215   tree name = DECL_NAME (TYPE_NAME (current_class_type));
8216   tree value = build_lang_decl (TYPE_DECL, name, current_class_type);
8217 
8218   DECL_NONLOCAL (value) = 1;
8219   DECL_CONTEXT (value) = current_class_type;
8220   DECL_ARTIFICIAL (value) = 1;
8221   SET_DECL_SELF_REFERENCE_P (value);
8222   set_underlying_type (value);
8223 
8224   if (processing_template_decl)
8225     value = push_template_decl (value);
8226 
8227   tree saved_cas = current_access_specifier;
8228   current_access_specifier = access_public_node;
8229   finish_member_declaration (value);
8230   current_access_specifier = saved_cas;
8231 }
8232 
8233 /* Returns 1 if TYPE contains only padding bytes.  */
8234 
8235 int
is_empty_class(tree type)8236 is_empty_class (tree type)
8237 {
8238   if (type == error_mark_node)
8239     return 0;
8240 
8241   if (! CLASS_TYPE_P (type))
8242     return 0;
8243 
8244   return CLASSTYPE_EMPTY_P (type);
8245 }
8246 
8247 /* Returns true if TYPE contains no actual data, just various
8248    possible combinations of empty classes and possibly a vptr.  */
8249 
8250 bool
is_really_empty_class(tree type)8251 is_really_empty_class (tree type)
8252 {
8253   if (CLASS_TYPE_P (type))
8254     {
8255       tree field;
8256       tree binfo;
8257       tree base_binfo;
8258       int i;
8259 
8260       /* CLASSTYPE_EMPTY_P isn't set properly until the class is actually laid
8261 	 out, but we'd like to be able to check this before then.  */
8262       if (COMPLETE_TYPE_P (type) && is_empty_class (type))
8263 	return true;
8264 
8265       for (binfo = TYPE_BINFO (type), i = 0;
8266 	   BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
8267 	if (!is_really_empty_class (BINFO_TYPE (base_binfo)))
8268 	  return false;
8269       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8270 	if (TREE_CODE (field) == FIELD_DECL
8271 	    && !DECL_ARTIFICIAL (field)
8272 	    /* An unnamed bit-field is not a data member.  */
8273 	    && !DECL_UNNAMED_BIT_FIELD (field)
8274 	    && !is_really_empty_class (TREE_TYPE (field)))
8275 	  return false;
8276       return true;
8277     }
8278   else if (TREE_CODE (type) == ARRAY_TYPE)
8279     return (integer_zerop (array_type_nelts_top (type))
8280 	    || is_really_empty_class (TREE_TYPE (type)));
8281   return false;
8282 }
8283 
8284 /* Note that NAME was looked up while the current class was being
8285    defined and that the result of that lookup was DECL.  */
8286 
8287 void
maybe_note_name_used_in_class(tree name,tree decl)8288 maybe_note_name_used_in_class (tree name, tree decl)
8289 {
8290   splay_tree names_used;
8291 
8292   /* If we're not defining a class, there's nothing to do.  */
8293   if (!(innermost_scope_kind() == sk_class
8294 	&& TYPE_BEING_DEFINED (current_class_type)
8295 	&& !LAMBDA_TYPE_P (current_class_type)))
8296     return;
8297 
8298   /* If there's already a binding for this NAME, then we don't have
8299      anything to worry about.  */
8300   if (lookup_member (current_class_type, name,
8301 		     /*protect=*/0, /*want_type=*/false, tf_warning_or_error))
8302     return;
8303 
8304   if (!current_class_stack[current_class_depth - 1].names_used)
8305     current_class_stack[current_class_depth - 1].names_used
8306       = splay_tree_new (splay_tree_compare_pointers, 0, 0);
8307   names_used = current_class_stack[current_class_depth - 1].names_used;
8308 
8309   splay_tree_insert (names_used,
8310 		     (splay_tree_key) name,
8311 		     (splay_tree_value) decl);
8312 }
8313 
8314 /* Note that NAME was declared (as DECL) in the current class.  Check
8315    to see that the declaration is valid.  */
8316 
8317 void
note_name_declared_in_class(tree name,tree decl)8318 note_name_declared_in_class (tree name, tree decl)
8319 {
8320   splay_tree names_used;
8321   splay_tree_node n;
8322 
8323   /* Look to see if we ever used this name.  */
8324   names_used
8325     = current_class_stack[current_class_depth - 1].names_used;
8326   if (!names_used)
8327     return;
8328   /* The C language allows members to be declared with a type of the same
8329      name, and the C++ standard says this diagnostic is not required.  So
8330      allow it in extern "C" blocks unless predantic is specified.
8331      Allow it in all cases if -ms-extensions is specified.  */
8332   if ((!pedantic && current_lang_name == lang_name_c)
8333       || flag_ms_extensions)
8334     return;
8335   n = splay_tree_lookup (names_used, (splay_tree_key) name);
8336   if (n)
8337     {
8338       /* [basic.scope.class]
8339 
8340 	 A name N used in a class S shall refer to the same declaration
8341 	 in its context and when re-evaluated in the completed scope of
8342 	 S.  */
8343       permerror (input_location, "declaration of %q#D", decl);
8344       permerror (location_of ((tree) n->value),
8345 		 "changes meaning of %qD from %q#D",
8346 		 OVL_NAME (decl), (tree) n->value);
8347     }
8348 }
8349 
8350 /* Returns the VAR_DECL for the complete vtable associated with BINFO.
8351    Secondary vtables are merged with primary vtables; this function
8352    will return the VAR_DECL for the primary vtable.  */
8353 
8354 tree
get_vtbl_decl_for_binfo(tree binfo)8355 get_vtbl_decl_for_binfo (tree binfo)
8356 {
8357   tree decl;
8358 
8359   decl = BINFO_VTABLE (binfo);
8360   if (decl && TREE_CODE (decl) == POINTER_PLUS_EXPR)
8361     {
8362       gcc_assert (TREE_CODE (TREE_OPERAND (decl, 0)) == ADDR_EXPR);
8363       decl = TREE_OPERAND (TREE_OPERAND (decl, 0), 0);
8364     }
8365   if (decl)
8366     gcc_assert (VAR_P (decl));
8367   return decl;
8368 }
8369 
8370 
8371 /* Returns the binfo for the primary base of BINFO.  If the resulting
8372    BINFO is a virtual base, and it is inherited elsewhere in the
8373    hierarchy, then the returned binfo might not be the primary base of
8374    BINFO in the complete object.  Check BINFO_PRIMARY_P or
8375    BINFO_LOST_PRIMARY_P to be sure.  */
8376 
8377 static tree
get_primary_binfo(tree binfo)8378 get_primary_binfo (tree binfo)
8379 {
8380   tree primary_base;
8381 
8382   primary_base = CLASSTYPE_PRIMARY_BINFO (BINFO_TYPE (binfo));
8383   if (!primary_base)
8384     return NULL_TREE;
8385 
8386   return copied_binfo (primary_base, binfo);
8387 }
8388 
8389 /* As above, but iterate until we reach the binfo that actually provides the
8390    vptr for BINFO.  */
8391 
8392 static tree
most_primary_binfo(tree binfo)8393 most_primary_binfo (tree binfo)
8394 {
8395   tree b = binfo;
8396   while (CLASSTYPE_HAS_PRIMARY_BASE_P (BINFO_TYPE (b))
8397 	 && !BINFO_LOST_PRIMARY_P (b))
8398     {
8399       tree primary_base = get_primary_binfo (b);
8400       gcc_assert (BINFO_PRIMARY_P (primary_base)
8401 		  && BINFO_INHERITANCE_CHAIN (primary_base) == b);
8402       b = primary_base;
8403     }
8404   return b;
8405 }
8406 
8407 /* Returns true if BINFO gets its vptr from a virtual base of the most derived
8408    type.  Note that the virtual inheritance might be above or below BINFO in
8409    the hierarchy.  */
8410 
8411 bool
vptr_via_virtual_p(tree binfo)8412 vptr_via_virtual_p (tree binfo)
8413 {
8414   if (TYPE_P (binfo))
8415     binfo = TYPE_BINFO (binfo);
8416   tree primary = most_primary_binfo (binfo);
8417   /* Don't limit binfo_via_virtual, we want to return true when BINFO itself is
8418      a morally virtual base.  */
8419   tree virt = binfo_via_virtual (primary, NULL_TREE);
8420   return virt != NULL_TREE;
8421 }
8422 
8423 /* If INDENTED_P is zero, indent to INDENT. Return nonzero.  */
8424 
8425 static int
maybe_indent_hierarchy(FILE * stream,int indent,int indented_p)8426 maybe_indent_hierarchy (FILE * stream, int indent, int indented_p)
8427 {
8428   if (!indented_p)
8429     fprintf (stream, "%*s", indent, "");
8430   return 1;
8431 }
8432 
8433 /* Dump the offsets of all the bases rooted at BINFO to STREAM.
8434    INDENT should be zero when called from the top level; it is
8435    incremented recursively.  IGO indicates the next expected BINFO in
8436    inheritance graph ordering.  */
8437 
8438 static tree
dump_class_hierarchy_r(FILE * stream,dump_flags_t flags,tree binfo,tree igo,int indent)8439 dump_class_hierarchy_r (FILE *stream,
8440 			dump_flags_t flags,
8441 			tree binfo,
8442 			tree igo,
8443 			int indent)
8444 {
8445   int indented = 0;
8446   tree base_binfo;
8447   int i;
8448 
8449   indented = maybe_indent_hierarchy (stream, indent, 0);
8450   fprintf (stream, "%s (0x" HOST_WIDE_INT_PRINT_HEX ") ",
8451 	   type_as_string (BINFO_TYPE (binfo), TFF_PLAIN_IDENTIFIER),
8452 	   (HOST_WIDE_INT) (uintptr_t) binfo);
8453   if (binfo != igo)
8454     {
8455       fprintf (stream, "alternative-path\n");
8456       return igo;
8457     }
8458   igo = TREE_CHAIN (binfo);
8459 
8460   fprintf (stream, HOST_WIDE_INT_PRINT_DEC,
8461 	   tree_to_shwi (BINFO_OFFSET (binfo)));
8462   if (is_empty_class (BINFO_TYPE (binfo)))
8463     fprintf (stream, " empty");
8464   else if (CLASSTYPE_NEARLY_EMPTY_P (BINFO_TYPE (binfo)))
8465     fprintf (stream, " nearly-empty");
8466   if (BINFO_VIRTUAL_P (binfo))
8467     fprintf (stream, " virtual");
8468   fprintf (stream, "\n");
8469 
8470   indented = 0;
8471   if (BINFO_PRIMARY_P (binfo))
8472     {
8473       indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8474       fprintf (stream, " primary-for %s (0x" HOST_WIDE_INT_PRINT_HEX ")",
8475 	       type_as_string (BINFO_TYPE (BINFO_INHERITANCE_CHAIN (binfo)),
8476 			       TFF_PLAIN_IDENTIFIER),
8477 	       (HOST_WIDE_INT) (uintptr_t) BINFO_INHERITANCE_CHAIN (binfo));
8478     }
8479   if (BINFO_LOST_PRIMARY_P (binfo))
8480     {
8481       indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8482       fprintf (stream, " lost-primary");
8483     }
8484   if (indented)
8485     fprintf (stream, "\n");
8486 
8487   if (!(flags & TDF_SLIM))
8488     {
8489       int indented = 0;
8490 
8491       if (BINFO_SUBVTT_INDEX (binfo))
8492 	{
8493 	  indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8494 	  fprintf (stream, " subvttidx=%s",
8495 		   expr_as_string (BINFO_SUBVTT_INDEX (binfo),
8496 				   TFF_PLAIN_IDENTIFIER));
8497 	}
8498       if (BINFO_VPTR_INDEX (binfo))
8499 	{
8500 	  indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8501 	  fprintf (stream, " vptridx=%s",
8502 		   expr_as_string (BINFO_VPTR_INDEX (binfo),
8503 				   TFF_PLAIN_IDENTIFIER));
8504 	}
8505       if (BINFO_VPTR_FIELD (binfo))
8506 	{
8507 	  indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8508 	  fprintf (stream, " vbaseoffset=%s",
8509 		   expr_as_string (BINFO_VPTR_FIELD (binfo),
8510 				   TFF_PLAIN_IDENTIFIER));
8511 	}
8512       if (BINFO_VTABLE (binfo))
8513 	{
8514 	  indented = maybe_indent_hierarchy (stream, indent + 3, indented);
8515 	  fprintf (stream, " vptr=%s",
8516 		   expr_as_string (BINFO_VTABLE (binfo),
8517 				   TFF_PLAIN_IDENTIFIER));
8518 	}
8519 
8520       if (indented)
8521 	fprintf (stream, "\n");
8522     }
8523 
8524   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8525     igo = dump_class_hierarchy_r (stream, flags, base_binfo, igo, indent + 2);
8526 
8527   return igo;
8528 }
8529 
8530 /* Dump the BINFO hierarchy for T.  */
8531 
8532 static void
dump_class_hierarchy_1(FILE * stream,dump_flags_t flags,tree t)8533 dump_class_hierarchy_1 (FILE *stream, dump_flags_t flags, tree t)
8534 {
8535   fprintf (stream, "Class %s\n", type_as_string (t, TFF_PLAIN_IDENTIFIER));
8536   fprintf (stream, "   size=%lu align=%lu\n",
8537 	   (unsigned long)(tree_to_shwi (TYPE_SIZE (t)) / BITS_PER_UNIT),
8538 	   (unsigned long)(TYPE_ALIGN (t) / BITS_PER_UNIT));
8539   fprintf (stream, "   base size=%lu base align=%lu\n",
8540 	   (unsigned long)(tree_to_shwi (TYPE_SIZE (CLASSTYPE_AS_BASE (t)))
8541 			   / BITS_PER_UNIT),
8542 	   (unsigned long)(TYPE_ALIGN (CLASSTYPE_AS_BASE (t))
8543 			   / BITS_PER_UNIT));
8544   dump_class_hierarchy_r (stream, flags, TYPE_BINFO (t), TYPE_BINFO (t), 0);
8545   fprintf (stream, "\n");
8546 }
8547 
8548 /* Debug interface to hierarchy dumping.  */
8549 
8550 void
debug_class(tree t)8551 debug_class (tree t)
8552 {
8553   dump_class_hierarchy_1 (stderr, TDF_SLIM, t);
8554 }
8555 
8556 static void
dump_class_hierarchy(tree t)8557 dump_class_hierarchy (tree t)
8558 {
8559   dump_flags_t flags;
8560   if (FILE *stream = dump_begin (class_dump_id, &flags))
8561     {
8562       dump_class_hierarchy_1 (stream, flags, t);
8563       dump_end (class_dump_id, stream);
8564     }
8565 }
8566 
8567 static void
dump_array(FILE * stream,tree decl)8568 dump_array (FILE * stream, tree decl)
8569 {
8570   tree value;
8571   unsigned HOST_WIDE_INT ix;
8572   HOST_WIDE_INT elt;
8573   tree size = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (decl)));
8574 
8575   elt = (tree_to_shwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (decl))))
8576 	 / BITS_PER_UNIT);
8577   fprintf (stream, "%s:", decl_as_string (decl, TFF_PLAIN_IDENTIFIER));
8578   fprintf (stream, " %s entries",
8579 	   expr_as_string (size_binop (PLUS_EXPR, size, size_one_node),
8580 			   TFF_PLAIN_IDENTIFIER));
8581   fprintf (stream, "\n");
8582 
8583   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)),
8584 			      ix, value)
8585     fprintf (stream, "%-4ld  %s\n", (long)(ix * elt),
8586 	     expr_as_string (value, TFF_PLAIN_IDENTIFIER));
8587 }
8588 
8589 static void
dump_vtable(tree t,tree binfo,tree vtable)8590 dump_vtable (tree t, tree binfo, tree vtable)
8591 {
8592   dump_flags_t flags;
8593   FILE *stream = dump_begin (class_dump_id, &flags);
8594 
8595   if (!stream)
8596     return;
8597 
8598   if (!(flags & TDF_SLIM))
8599     {
8600       int ctor_vtbl_p = TYPE_BINFO (t) != binfo;
8601 
8602       fprintf (stream, "%s for %s",
8603 	       ctor_vtbl_p ? "Construction vtable" : "Vtable",
8604 	       type_as_string (BINFO_TYPE (binfo), TFF_PLAIN_IDENTIFIER));
8605       if (ctor_vtbl_p)
8606 	{
8607 	  if (!BINFO_VIRTUAL_P (binfo))
8608 	    fprintf (stream, " (0x" HOST_WIDE_INT_PRINT_HEX " instance)",
8609 		     (HOST_WIDE_INT) (uintptr_t) binfo);
8610 	  fprintf (stream, " in %s", type_as_string (t, TFF_PLAIN_IDENTIFIER));
8611 	}
8612       fprintf (stream, "\n");
8613       dump_array (stream, vtable);
8614       fprintf (stream, "\n");
8615     }
8616 
8617   dump_end (class_dump_id, stream);
8618 }
8619 
8620 static void
dump_vtt(tree t,tree vtt)8621 dump_vtt (tree t, tree vtt)
8622 {
8623   dump_flags_t flags;
8624   FILE *stream = dump_begin (class_dump_id, &flags);
8625 
8626   if (!stream)
8627     return;
8628 
8629   if (!(flags & TDF_SLIM))
8630     {
8631       fprintf (stream, "VTT for %s\n",
8632 	       type_as_string (t, TFF_PLAIN_IDENTIFIER));
8633       dump_array (stream, vtt);
8634       fprintf (stream, "\n");
8635     }
8636 
8637   dump_end (class_dump_id, stream);
8638 }
8639 
8640 /* Dump a function or thunk and its thunkees.  */
8641 
8642 static void
dump_thunk(FILE * stream,int indent,tree thunk)8643 dump_thunk (FILE *stream, int indent, tree thunk)
8644 {
8645   static const char spaces[] = "        ";
8646   tree name = DECL_NAME (thunk);
8647   tree thunks;
8648 
8649   fprintf (stream, "%.*s%p %s %s", indent, spaces,
8650 	   (void *)thunk,
8651 	   !DECL_THUNK_P (thunk) ? "function"
8652 	   : DECL_THIS_THUNK_P (thunk) ? "this-thunk" : "covariant-thunk",
8653 	   name ? IDENTIFIER_POINTER (name) : "<unset>");
8654   if (DECL_THUNK_P (thunk))
8655     {
8656       HOST_WIDE_INT fixed_adjust = THUNK_FIXED_OFFSET (thunk);
8657       tree virtual_adjust = THUNK_VIRTUAL_OFFSET (thunk);
8658 
8659       fprintf (stream, " fixed=" HOST_WIDE_INT_PRINT_DEC, fixed_adjust);
8660       if (!virtual_adjust)
8661 	/*NOP*/;
8662       else if (DECL_THIS_THUNK_P (thunk))
8663 	fprintf (stream, " vcall="  HOST_WIDE_INT_PRINT_DEC,
8664 		 tree_to_shwi (virtual_adjust));
8665       else
8666 	fprintf (stream, " vbase=" HOST_WIDE_INT_PRINT_DEC "(%s)",
8667 		 tree_to_shwi (BINFO_VPTR_FIELD (virtual_adjust)),
8668 		 type_as_string (BINFO_TYPE (virtual_adjust), TFF_SCOPE));
8669       if (THUNK_ALIAS (thunk))
8670 	fprintf (stream, " alias to %p", (void *)THUNK_ALIAS (thunk));
8671     }
8672   fprintf (stream, "\n");
8673   for (thunks = DECL_THUNKS (thunk); thunks; thunks = TREE_CHAIN (thunks))
8674     dump_thunk (stream, indent + 2, thunks);
8675 }
8676 
8677 /* Dump the thunks for FN.  */
8678 
8679 void
debug_thunks(tree fn)8680 debug_thunks (tree fn)
8681 {
8682   dump_thunk (stderr, 0, fn);
8683 }
8684 
8685 /* Virtual function table initialization.  */
8686 
8687 /* Create all the necessary vtables for T and its base classes.  */
8688 
8689 static void
finish_vtbls(tree t)8690 finish_vtbls (tree t)
8691 {
8692   tree vbase;
8693   vec<constructor_elt, va_gc> *v = NULL;
8694   tree vtable = BINFO_VTABLE (TYPE_BINFO (t));
8695 
8696   /* We lay out the primary and secondary vtables in one contiguous
8697      vtable.  The primary vtable is first, followed by the non-virtual
8698      secondary vtables in inheritance graph order.  */
8699   accumulate_vtbl_inits (TYPE_BINFO (t), TYPE_BINFO (t), TYPE_BINFO (t),
8700 			 vtable, t, &v);
8701 
8702   /* Then come the virtual bases, also in inheritance graph order.  */
8703   for (vbase = TYPE_BINFO (t); vbase; vbase = TREE_CHAIN (vbase))
8704     {
8705       if (!BINFO_VIRTUAL_P (vbase))
8706 	continue;
8707       accumulate_vtbl_inits (vbase, vbase, TYPE_BINFO (t), vtable, t, &v);
8708     }
8709 
8710   if (BINFO_VTABLE (TYPE_BINFO (t)))
8711     initialize_vtable (TYPE_BINFO (t), v);
8712 }
8713 
8714 /* Initialize the vtable for BINFO with the INITS.  */
8715 
8716 static void
initialize_vtable(tree binfo,vec<constructor_elt,va_gc> * inits)8717 initialize_vtable (tree binfo, vec<constructor_elt, va_gc> *inits)
8718 {
8719   tree decl;
8720 
8721   layout_vtable_decl (binfo, vec_safe_length (inits));
8722   decl = get_vtbl_decl_for_binfo (binfo);
8723   initialize_artificial_var (decl, inits);
8724   dump_vtable (BINFO_TYPE (binfo), binfo, decl);
8725 }
8726 
8727 /* Build the VTT (virtual table table) for T.
8728    A class requires a VTT if it has virtual bases.
8729 
8730    This holds
8731    1 - primary virtual pointer for complete object T
8732    2 - secondary VTTs for each direct non-virtual base of T which requires a
8733        VTT
8734    3 - secondary virtual pointers for each direct or indirect base of T which
8735        has virtual bases or is reachable via a virtual path from T.
8736    4 - secondary VTTs for each direct or indirect virtual base of T.
8737 
8738    Secondary VTTs look like complete object VTTs without part 4.  */
8739 
8740 static void
build_vtt(tree t)8741 build_vtt (tree t)
8742 {
8743   tree type;
8744   tree vtt;
8745   tree index;
8746   vec<constructor_elt, va_gc> *inits;
8747 
8748   /* Build up the initializers for the VTT.  */
8749   inits = NULL;
8750   index = size_zero_node;
8751   build_vtt_inits (TYPE_BINFO (t), t, &inits, &index);
8752 
8753   /* If we didn't need a VTT, we're done.  */
8754   if (!inits)
8755     return;
8756 
8757   /* Figure out the type of the VTT.  */
8758   type = build_array_of_n_type (const_ptr_type_node,
8759                                 inits->length ());
8760 
8761   /* Now, build the VTT object itself.  */
8762   vtt = build_vtable (t, mangle_vtt_for_type (t), type);
8763   initialize_artificial_var (vtt, inits);
8764   /* Add the VTT to the vtables list.  */
8765   DECL_CHAIN (vtt) = DECL_CHAIN (CLASSTYPE_VTABLES (t));
8766   DECL_CHAIN (CLASSTYPE_VTABLES (t)) = vtt;
8767 
8768   dump_vtt (t, vtt);
8769 }
8770 
8771 /* When building a secondary VTT, BINFO_VTABLE is set to a TREE_LIST with
8772    PURPOSE the RTTI_BINFO, VALUE the real vtable pointer for this binfo,
8773    and CHAIN the vtable pointer for this binfo after construction is
8774    complete.  VALUE can also be another BINFO, in which case we recurse.  */
8775 
8776 static tree
binfo_ctor_vtable(tree binfo)8777 binfo_ctor_vtable (tree binfo)
8778 {
8779   tree vt;
8780 
8781   while (1)
8782     {
8783       vt = BINFO_VTABLE (binfo);
8784       if (TREE_CODE (vt) == TREE_LIST)
8785 	vt = TREE_VALUE (vt);
8786       if (TREE_CODE (vt) == TREE_BINFO)
8787 	binfo = vt;
8788       else
8789 	break;
8790     }
8791 
8792   return vt;
8793 }
8794 
8795 /* Data for secondary VTT initialization.  */
8796 struct secondary_vptr_vtt_init_data
8797 {
8798   /* Is this the primary VTT? */
8799   bool top_level_p;
8800 
8801   /* Current index into the VTT.  */
8802   tree index;
8803 
8804   /* Vector of initializers built up.  */
8805   vec<constructor_elt, va_gc> *inits;
8806 
8807   /* The type being constructed by this secondary VTT.  */
8808   tree type_being_constructed;
8809 };
8810 
8811 /* Recursively build the VTT-initializer for BINFO (which is in the
8812    hierarchy dominated by T).  INITS points to the end of the initializer
8813    list to date.  INDEX is the VTT index where the next element will be
8814    replaced.  Iff BINFO is the binfo for T, this is the top level VTT (i.e.
8815    not a subvtt for some base of T).  When that is so, we emit the sub-VTTs
8816    for virtual bases of T. When it is not so, we build the constructor
8817    vtables for the BINFO-in-T variant.  */
8818 
8819 static void
build_vtt_inits(tree binfo,tree t,vec<constructor_elt,va_gc> ** inits,tree * index)8820 build_vtt_inits (tree binfo, tree t, vec<constructor_elt, va_gc> **inits,
8821 		 tree *index)
8822 {
8823   int i;
8824   tree b;
8825   tree init;
8826   secondary_vptr_vtt_init_data data;
8827   int top_level_p = SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t);
8828 
8829   /* We only need VTTs for subobjects with virtual bases.  */
8830   if (!CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo)))
8831     return;
8832 
8833   /* We need to use a construction vtable if this is not the primary
8834      VTT.  */
8835   if (!top_level_p)
8836     {
8837       build_ctor_vtbl_group (binfo, t);
8838 
8839       /* Record the offset in the VTT where this sub-VTT can be found.  */
8840       BINFO_SUBVTT_INDEX (binfo) = *index;
8841     }
8842 
8843   /* Add the address of the primary vtable for the complete object.  */
8844   init = binfo_ctor_vtable (binfo);
8845   CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, init);
8846   if (top_level_p)
8847     {
8848       gcc_assert (!BINFO_VPTR_INDEX (binfo));
8849       BINFO_VPTR_INDEX (binfo) = *index;
8850     }
8851   *index = size_binop (PLUS_EXPR, *index, TYPE_SIZE_UNIT (ptr_type_node));
8852 
8853   /* Recursively add the secondary VTTs for non-virtual bases.  */
8854   for (i = 0; BINFO_BASE_ITERATE (binfo, i, b); ++i)
8855     if (!BINFO_VIRTUAL_P (b))
8856       build_vtt_inits (b, t, inits, index);
8857 
8858   /* Add secondary virtual pointers for all subobjects of BINFO with
8859      either virtual bases or reachable along a virtual path, except
8860      subobjects that are non-virtual primary bases.  */
8861   data.top_level_p = top_level_p;
8862   data.index = *index;
8863   data.inits = *inits;
8864   data.type_being_constructed = BINFO_TYPE (binfo);
8865 
8866   dfs_walk_once (binfo, dfs_build_secondary_vptr_vtt_inits, NULL, &data);
8867 
8868   *index = data.index;
8869 
8870   /* data.inits might have grown as we added secondary virtual pointers.
8871      Make sure our caller knows about the new vector.  */
8872   *inits = data.inits;
8873 
8874   if (top_level_p)
8875     /* Add the secondary VTTs for virtual bases in inheritance graph
8876        order.  */
8877     for (b = TYPE_BINFO (BINFO_TYPE (binfo)); b; b = TREE_CHAIN (b))
8878       {
8879 	if (!BINFO_VIRTUAL_P (b))
8880 	  continue;
8881 
8882 	build_vtt_inits (b, t, inits, index);
8883       }
8884   else
8885     /* Remove the ctor vtables we created.  */
8886     dfs_walk_all (binfo, dfs_fixup_binfo_vtbls, NULL, binfo);
8887 }
8888 
8889 /* Called from build_vtt_inits via dfs_walk.  BINFO is the binfo for the base
8890    in most derived. DATA is a SECONDARY_VPTR_VTT_INIT_DATA structure.  */
8891 
8892 static tree
dfs_build_secondary_vptr_vtt_inits(tree binfo,void * data_)8893 dfs_build_secondary_vptr_vtt_inits (tree binfo, void *data_)
8894 {
8895   secondary_vptr_vtt_init_data *data = (secondary_vptr_vtt_init_data *)data_;
8896 
8897   /* We don't care about bases that don't have vtables.  */
8898   if (!TYPE_VFIELD (BINFO_TYPE (binfo)))
8899     return dfs_skip_bases;
8900 
8901   /* We're only interested in proper subobjects of the type being
8902      constructed.  */
8903   if (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), data->type_being_constructed))
8904     return NULL_TREE;
8905 
8906   /* We're only interested in bases with virtual bases or reachable
8907      via a virtual path from the type being constructed.  */
8908   if (!(CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo))
8909 	|| binfo_via_virtual (binfo, data->type_being_constructed)))
8910     return dfs_skip_bases;
8911 
8912   /* We're not interested in non-virtual primary bases.  */
8913   if (!BINFO_VIRTUAL_P (binfo) && BINFO_PRIMARY_P (binfo))
8914     return NULL_TREE;
8915 
8916   /* Record the index where this secondary vptr can be found.  */
8917   if (data->top_level_p)
8918     {
8919       gcc_assert (!BINFO_VPTR_INDEX (binfo));
8920       BINFO_VPTR_INDEX (binfo) = data->index;
8921 
8922       if (BINFO_VIRTUAL_P (binfo))
8923 	{
8924 	  /* It's a primary virtual base, and this is not a
8925 	     construction vtable.  Find the base this is primary of in
8926 	     the inheritance graph, and use that base's vtable
8927 	     now.  */
8928 	  while (BINFO_PRIMARY_P (binfo))
8929 	    binfo = BINFO_INHERITANCE_CHAIN (binfo);
8930 	}
8931     }
8932 
8933   /* Add the initializer for the secondary vptr itself.  */
8934   CONSTRUCTOR_APPEND_ELT (data->inits, NULL_TREE, binfo_ctor_vtable (binfo));
8935 
8936   /* Advance the vtt index.  */
8937   data->index = size_binop (PLUS_EXPR, data->index,
8938 			    TYPE_SIZE_UNIT (ptr_type_node));
8939 
8940   return NULL_TREE;
8941 }
8942 
8943 /* Called from build_vtt_inits via dfs_walk. After building
8944    constructor vtables and generating the sub-vtt from them, we need
8945    to restore the BINFO_VTABLES that were scribbled on.  DATA is the
8946    binfo of the base whose sub vtt was generated.  */
8947 
8948 static tree
dfs_fixup_binfo_vtbls(tree binfo,void * data)8949 dfs_fixup_binfo_vtbls (tree binfo, void* data)
8950 {
8951   tree vtable = BINFO_VTABLE (binfo);
8952 
8953   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
8954     /* If this class has no vtable, none of its bases do.  */
8955     return dfs_skip_bases;
8956 
8957   if (!vtable)
8958     /* This might be a primary base, so have no vtable in this
8959        hierarchy.  */
8960     return NULL_TREE;
8961 
8962   /* If we scribbled the construction vtable vptr into BINFO, clear it
8963      out now.  */
8964   if (TREE_CODE (vtable) == TREE_LIST
8965       && (TREE_PURPOSE (vtable) == (tree) data))
8966     BINFO_VTABLE (binfo) = TREE_CHAIN (vtable);
8967 
8968   return NULL_TREE;
8969 }
8970 
8971 /* Build the construction vtable group for BINFO which is in the
8972    hierarchy dominated by T.  */
8973 
8974 static void
build_ctor_vtbl_group(tree binfo,tree t)8975 build_ctor_vtbl_group (tree binfo, tree t)
8976 {
8977   tree type;
8978   tree vtbl;
8979   tree id;
8980   tree vbase;
8981   vec<constructor_elt, va_gc> *v;
8982 
8983   /* See if we've already created this construction vtable group.  */
8984   id = mangle_ctor_vtbl_for_type (t, binfo);
8985   if (get_global_binding (id))
8986     return;
8987 
8988   gcc_assert (!SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t));
8989   /* Build a version of VTBL (with the wrong type) for use in
8990      constructing the addresses of secondary vtables in the
8991      construction vtable group.  */
8992   vtbl = build_vtable (t, id, ptr_type_node);
8993   DECL_CONSTRUCTION_VTABLE_P (vtbl) = 1;
8994   /* Don't export construction vtables from shared libraries.  Even on
8995      targets that don't support hidden visibility, this tells
8996      can_refer_decl_in_current_unit_p not to assume that it's safe to
8997      access from a different compilation unit (bz 54314).  */
8998   DECL_VISIBILITY (vtbl) = VISIBILITY_HIDDEN;
8999   DECL_VISIBILITY_SPECIFIED (vtbl) = true;
9000 
9001   v = NULL;
9002   accumulate_vtbl_inits (binfo, TYPE_BINFO (TREE_TYPE (binfo)),
9003 			 binfo, vtbl, t, &v);
9004 
9005   /* Add the vtables for each of our virtual bases using the vbase in T
9006      binfo.  */
9007   for (vbase = TYPE_BINFO (BINFO_TYPE (binfo));
9008        vbase;
9009        vbase = TREE_CHAIN (vbase))
9010     {
9011       tree b;
9012 
9013       if (!BINFO_VIRTUAL_P (vbase))
9014 	continue;
9015       b = copied_binfo (vbase, binfo);
9016 
9017       accumulate_vtbl_inits (b, vbase, binfo, vtbl, t, &v);
9018     }
9019 
9020   /* Figure out the type of the construction vtable.  */
9021   type = build_array_of_n_type (vtable_entry_type, v->length ());
9022   layout_type (type);
9023   TREE_TYPE (vtbl) = type;
9024   DECL_SIZE (vtbl) = DECL_SIZE_UNIT (vtbl) = NULL_TREE;
9025   layout_decl (vtbl, 0);
9026 
9027   /* Initialize the construction vtable.  */
9028   CLASSTYPE_VTABLES (t) = chainon (CLASSTYPE_VTABLES (t), vtbl);
9029   initialize_artificial_var (vtbl, v);
9030   dump_vtable (t, binfo, vtbl);
9031 }
9032 
9033 /* Add the vtbl initializers for BINFO (and its bases other than
9034    non-virtual primaries) to the list of INITS.  BINFO is in the
9035    hierarchy dominated by T.  RTTI_BINFO is the binfo within T of
9036    the constructor the vtbl inits should be accumulated for. (If this
9037    is the complete object vtbl then RTTI_BINFO will be TYPE_BINFO (T).)
9038    ORIG_BINFO is the binfo for this object within BINFO_TYPE (RTTI_BINFO).
9039    BINFO is the active base equivalent of ORIG_BINFO in the inheritance
9040    graph of T. Both BINFO and ORIG_BINFO will have the same BINFO_TYPE,
9041    but are not necessarily the same in terms of layout.  */
9042 
9043 static void
accumulate_vtbl_inits(tree binfo,tree orig_binfo,tree rtti_binfo,tree vtbl,tree t,vec<constructor_elt,va_gc> ** inits)9044 accumulate_vtbl_inits (tree binfo,
9045 		       tree orig_binfo,
9046 		       tree rtti_binfo,
9047 		       tree vtbl,
9048 		       tree t,
9049 		       vec<constructor_elt, va_gc> **inits)
9050 {
9051   int i;
9052   tree base_binfo;
9053   int ctor_vtbl_p = !SAME_BINFO_TYPE_P (BINFO_TYPE (rtti_binfo), t);
9054 
9055   gcc_assert (SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), BINFO_TYPE (orig_binfo)));
9056 
9057   /* If it doesn't have a vptr, we don't do anything.  */
9058   if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
9059     return;
9060 
9061   /* If we're building a construction vtable, we're not interested in
9062      subobjects that don't require construction vtables.  */
9063   if (ctor_vtbl_p
9064       && !CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo))
9065       && !binfo_via_virtual (orig_binfo, BINFO_TYPE (rtti_binfo)))
9066     return;
9067 
9068   /* Build the initializers for the BINFO-in-T vtable.  */
9069   dfs_accumulate_vtbl_inits (binfo, orig_binfo, rtti_binfo, vtbl, t, inits);
9070 
9071   /* Walk the BINFO and its bases.  We walk in preorder so that as we
9072      initialize each vtable we can figure out at what offset the
9073      secondary vtable lies from the primary vtable.  We can't use
9074      dfs_walk here because we need to iterate through bases of BINFO
9075      and RTTI_BINFO simultaneously.  */
9076   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
9077     {
9078       /* Skip virtual bases.  */
9079       if (BINFO_VIRTUAL_P (base_binfo))
9080 	continue;
9081       accumulate_vtbl_inits (base_binfo,
9082 			     BINFO_BASE_BINFO (orig_binfo, i),
9083 			     rtti_binfo, vtbl, t,
9084 			     inits);
9085     }
9086 }
9087 
9088 /* Called from accumulate_vtbl_inits.  Adds the initializers for the
9089    BINFO vtable to L.  */
9090 
9091 static void
dfs_accumulate_vtbl_inits(tree binfo,tree orig_binfo,tree rtti_binfo,tree orig_vtbl,tree t,vec<constructor_elt,va_gc> ** l)9092 dfs_accumulate_vtbl_inits (tree binfo,
9093 			   tree orig_binfo,
9094 			   tree rtti_binfo,
9095 			   tree orig_vtbl,
9096 			   tree t,
9097 			   vec<constructor_elt, va_gc> **l)
9098 {
9099   tree vtbl = NULL_TREE;
9100   int ctor_vtbl_p = !SAME_BINFO_TYPE_P (BINFO_TYPE (rtti_binfo), t);
9101   int n_inits;
9102 
9103   if (ctor_vtbl_p
9104       && BINFO_VIRTUAL_P (orig_binfo) && BINFO_PRIMARY_P (orig_binfo))
9105     {
9106       /* In the hierarchy of BINFO_TYPE (RTTI_BINFO), this is a
9107 	 primary virtual base.  If it is not the same primary in
9108 	 the hierarchy of T, we'll need to generate a ctor vtable
9109 	 for it, to place at its location in T.  If it is the same
9110 	 primary, we still need a VTT entry for the vtable, but it
9111 	 should point to the ctor vtable for the base it is a
9112 	 primary for within the sub-hierarchy of RTTI_BINFO.
9113 
9114 	 There are three possible cases:
9115 
9116 	 1) We are in the same place.
9117 	 2) We are a primary base within a lost primary virtual base of
9118 	 RTTI_BINFO.
9119 	 3) We are primary to something not a base of RTTI_BINFO.  */
9120 
9121       tree b;
9122       tree last = NULL_TREE;
9123 
9124       /* First, look through the bases we are primary to for RTTI_BINFO
9125 	 or a virtual base.  */
9126       b = binfo;
9127       while (BINFO_PRIMARY_P (b))
9128 	{
9129 	  b = BINFO_INHERITANCE_CHAIN (b);
9130 	  last = b;
9131 	  if (BINFO_VIRTUAL_P (b) || b == rtti_binfo)
9132 	    goto found;
9133 	}
9134       /* If we run out of primary links, keep looking down our
9135 	 inheritance chain; we might be an indirect primary.  */
9136       for (b = last; b; b = BINFO_INHERITANCE_CHAIN (b))
9137 	if (BINFO_VIRTUAL_P (b) || b == rtti_binfo)
9138 	  break;
9139     found:
9140 
9141       /* If we found RTTI_BINFO, this is case 1.  If we found a virtual
9142 	 base B and it is a base of RTTI_BINFO, this is case 2.  In
9143 	 either case, we share our vtable with LAST, i.e. the
9144 	 derived-most base within B of which we are a primary.  */
9145       if (b == rtti_binfo
9146 	  || (b && binfo_for_vbase (BINFO_TYPE (b), BINFO_TYPE (rtti_binfo))))
9147 	/* Just set our BINFO_VTABLE to point to LAST, as we may not have
9148 	   set LAST's BINFO_VTABLE yet.  We'll extract the actual vptr in
9149 	   binfo_ctor_vtable after everything's been set up.  */
9150 	vtbl = last;
9151 
9152       /* Otherwise, this is case 3 and we get our own.  */
9153     }
9154   else if (!BINFO_NEW_VTABLE_MARKED (orig_binfo))
9155     return;
9156 
9157   n_inits = vec_safe_length (*l);
9158 
9159   if (!vtbl)
9160     {
9161       tree index;
9162       int non_fn_entries;
9163 
9164       /* Add the initializer for this vtable.  */
9165       build_vtbl_initializer (binfo, orig_binfo, t, rtti_binfo,
9166                               &non_fn_entries, l);
9167 
9168       /* Figure out the position to which the VPTR should point.  */
9169       vtbl = build1 (ADDR_EXPR, vtbl_ptr_type_node, orig_vtbl);
9170       index = size_binop (MULT_EXPR,
9171 			  TYPE_SIZE_UNIT (vtable_entry_type),
9172 			  size_int (non_fn_entries + n_inits));
9173       vtbl = fold_build_pointer_plus (vtbl, index);
9174     }
9175 
9176   if (ctor_vtbl_p)
9177     /* For a construction vtable, we can't overwrite BINFO_VTABLE.
9178        So, we make a TREE_LIST.  Later, dfs_fixup_binfo_vtbls will
9179        straighten this out.  */
9180     BINFO_VTABLE (binfo) = tree_cons (rtti_binfo, vtbl, BINFO_VTABLE (binfo));
9181   else if (BINFO_PRIMARY_P (binfo) && BINFO_VIRTUAL_P (binfo))
9182     /* Throw away any unneeded intializers.  */
9183     (*l)->truncate (n_inits);
9184   else
9185      /* For an ordinary vtable, set BINFO_VTABLE.  */
9186     BINFO_VTABLE (binfo) = vtbl;
9187 }
9188 
9189 static GTY(()) tree abort_fndecl_addr;
9190 static GTY(()) tree dvirt_fn;
9191 
9192 /* Construct the initializer for BINFO's virtual function table.  BINFO
9193    is part of the hierarchy dominated by T.  If we're building a
9194    construction vtable, the ORIG_BINFO is the binfo we should use to
9195    find the actual function pointers to put in the vtable - but they
9196    can be overridden on the path to most-derived in the graph that
9197    ORIG_BINFO belongs.  Otherwise,
9198    ORIG_BINFO should be the same as BINFO.  The RTTI_BINFO is the
9199    BINFO that should be indicated by the RTTI information in the
9200    vtable; it will be a base class of T, rather than T itself, if we
9201    are building a construction vtable.
9202 
9203    The value returned is a TREE_LIST suitable for wrapping in a
9204    CONSTRUCTOR to use as the DECL_INITIAL for a vtable.  If
9205    NON_FN_ENTRIES_P is not NULL, *NON_FN_ENTRIES_P is set to the
9206    number of non-function entries in the vtable.
9207 
9208    It might seem that this function should never be called with a
9209    BINFO for which BINFO_PRIMARY_P holds, the vtable for such a
9210    base is always subsumed by a derived class vtable.  However, when
9211    we are building construction vtables, we do build vtables for
9212    primary bases; we need these while the primary base is being
9213    constructed.  */
9214 
9215 static void
build_vtbl_initializer(tree binfo,tree orig_binfo,tree t,tree rtti_binfo,int * non_fn_entries_p,vec<constructor_elt,va_gc> ** inits)9216 build_vtbl_initializer (tree binfo,
9217 			tree orig_binfo,
9218 			tree t,
9219 			tree rtti_binfo,
9220 			int* non_fn_entries_p,
9221 			vec<constructor_elt, va_gc> **inits)
9222 {
9223   tree v;
9224   vtbl_init_data vid;
9225   unsigned ix, jx;
9226   tree vbinfo;
9227   vec<tree, va_gc> *vbases;
9228   constructor_elt *e;
9229 
9230   /* Initialize VID.  */
9231   memset (&vid, 0, sizeof (vid));
9232   vid.binfo = binfo;
9233   vid.derived = t;
9234   vid.rtti_binfo = rtti_binfo;
9235   vid.primary_vtbl_p = SAME_BINFO_TYPE_P (BINFO_TYPE (binfo), t);
9236   vid.ctor_vtbl_p = !SAME_BINFO_TYPE_P (BINFO_TYPE (rtti_binfo), t);
9237   vid.generate_vcall_entries = true;
9238   /* The first vbase or vcall offset is at index -3 in the vtable.  */
9239   vid.index = ssize_int(-3 * TARGET_VTABLE_DATA_ENTRY_DISTANCE);
9240 
9241   /* Add entries to the vtable for RTTI.  */
9242   build_rtti_vtbl_entries (binfo, &vid);
9243 
9244   /* Create an array for keeping track of the functions we've
9245      processed.  When we see multiple functions with the same
9246      signature, we share the vcall offsets.  */
9247   vec_alloc (vid.fns, 32);
9248   /* Add the vcall and vbase offset entries.  */
9249   build_vcall_and_vbase_vtbl_entries (binfo, &vid);
9250 
9251   /* Clear BINFO_VTABLE_PATH_MARKED; it's set by
9252      build_vbase_offset_vtbl_entries.  */
9253   for (vbases = CLASSTYPE_VBASECLASSES (t), ix = 0;
9254        vec_safe_iterate (vbases, ix, &vbinfo); ix++)
9255     BINFO_VTABLE_PATH_MARKED (vbinfo) = 0;
9256 
9257   /* If the target requires padding between data entries, add that now.  */
9258   if (TARGET_VTABLE_DATA_ENTRY_DISTANCE > 1)
9259     {
9260       int n_entries = vec_safe_length (vid.inits);
9261 
9262       vec_safe_grow (vid.inits, TARGET_VTABLE_DATA_ENTRY_DISTANCE * n_entries);
9263 
9264       /* Move data entries into their new positions and add padding
9265 	 after the new positions.  Iterate backwards so we don't
9266 	 overwrite entries that we would need to process later.  */
9267       for (ix = n_entries - 1;
9268 	   vid.inits->iterate (ix, &e);
9269 	   ix--)
9270 	{
9271 	  int j;
9272 	  int new_position = (TARGET_VTABLE_DATA_ENTRY_DISTANCE * ix
9273 			      + (TARGET_VTABLE_DATA_ENTRY_DISTANCE - 1));
9274 
9275 	  (*vid.inits)[new_position] = *e;
9276 
9277 	  for (j = 1; j < TARGET_VTABLE_DATA_ENTRY_DISTANCE; ++j)
9278 	    {
9279 	      constructor_elt *f = &(*vid.inits)[new_position - j];
9280 	      f->index = NULL_TREE;
9281 	      f->value = build1 (NOP_EXPR, vtable_entry_type,
9282 				 null_pointer_node);
9283 	    }
9284 	}
9285     }
9286 
9287   if (non_fn_entries_p)
9288     *non_fn_entries_p = vec_safe_length (vid.inits);
9289 
9290   /* The initializers for virtual functions were built up in reverse
9291      order.  Straighten them out and add them to the running list in one
9292      step.  */
9293   jx = vec_safe_length (*inits);
9294   vec_safe_grow (*inits, jx + vid.inits->length ());
9295 
9296   for (ix = vid.inits->length () - 1;
9297        vid.inits->iterate (ix, &e);
9298        ix--, jx++)
9299     (**inits)[jx] = *e;
9300 
9301   /* Go through all the ordinary virtual functions, building up
9302      initializers.  */
9303   for (v = BINFO_VIRTUALS (orig_binfo); v; v = TREE_CHAIN (v))
9304     {
9305       tree delta;
9306       tree vcall_index;
9307       tree fn, fn_original;
9308       tree init = NULL_TREE;
9309 
9310       fn = BV_FN (v);
9311       fn_original = fn;
9312       if (DECL_THUNK_P (fn))
9313 	{
9314 	  if (!DECL_NAME (fn))
9315 	    finish_thunk (fn);
9316 	  if (THUNK_ALIAS (fn))
9317 	    {
9318 	      fn = THUNK_ALIAS (fn);
9319 	      BV_FN (v) = fn;
9320 	    }
9321 	  fn_original = THUNK_TARGET (fn);
9322 	}
9323 
9324       /* If the only definition of this function signature along our
9325 	 primary base chain is from a lost primary, this vtable slot will
9326 	 never be used, so just zero it out.  This is important to avoid
9327 	 requiring extra thunks which cannot be generated with the function.
9328 
9329 	 We first check this in update_vtable_entry_for_fn, so we handle
9330 	 restored primary bases properly; we also need to do it here so we
9331 	 zero out unused slots in ctor vtables, rather than filling them
9332 	 with erroneous values (though harmless, apart from relocation
9333 	 costs).  */
9334       if (BV_LOST_PRIMARY (v))
9335 	init = size_zero_node;
9336 
9337       if (! init)
9338 	{
9339 	  /* Pull the offset for `this', and the function to call, out of
9340 	     the list.  */
9341 	  delta = BV_DELTA (v);
9342 	  vcall_index = BV_VCALL_INDEX (v);
9343 
9344 	  gcc_assert (TREE_CODE (delta) == INTEGER_CST);
9345 	  gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
9346 
9347 	  /* You can't call an abstract virtual function; it's abstract.
9348 	     So, we replace these functions with __pure_virtual.  */
9349 	  if (DECL_PURE_VIRTUAL_P (fn_original))
9350 	    {
9351 	      fn = abort_fndecl;
9352 	      if (!TARGET_VTABLE_USES_DESCRIPTORS)
9353 		{
9354 		  if (abort_fndecl_addr == NULL)
9355 		    abort_fndecl_addr
9356 		      = fold_convert (vfunc_ptr_type_node,
9357 				      build_fold_addr_expr (fn));
9358 		  init = abort_fndecl_addr;
9359 		}
9360 	    }
9361 	  /* Likewise for deleted virtuals.  */
9362 	  else if (DECL_DELETED_FN (fn_original))
9363 	    {
9364 	      if (!dvirt_fn)
9365 		{
9366 		  tree name = get_identifier ("__cxa_deleted_virtual");
9367 		  dvirt_fn = get_global_binding (name);
9368 		  if (!dvirt_fn)
9369 		    dvirt_fn = push_library_fn
9370 		      (name,
9371 		       build_function_type_list (void_type_node, NULL_TREE),
9372 		       NULL_TREE, ECF_NORETURN | ECF_COLD);
9373 		}
9374 	      fn = dvirt_fn;
9375 	      if (!TARGET_VTABLE_USES_DESCRIPTORS)
9376 		init = fold_convert (vfunc_ptr_type_node,
9377 				     build_fold_addr_expr (fn));
9378 	    }
9379 	  else
9380 	    {
9381 	      if (!integer_zerop (delta) || vcall_index)
9382 		{
9383 		  fn = make_thunk (fn, /*this_adjusting=*/1,
9384 				   delta, vcall_index);
9385 		  if (!DECL_NAME (fn))
9386 		    finish_thunk (fn);
9387 		}
9388 	      /* Take the address of the function, considering it to be of an
9389 		 appropriate generic type.  */
9390 	      if (!TARGET_VTABLE_USES_DESCRIPTORS)
9391 		init = fold_convert (vfunc_ptr_type_node,
9392 				     build_fold_addr_expr (fn));
9393 	      /* Don't refer to a virtual destructor from a constructor
9394 		 vtable or a vtable for an abstract class, since destroying
9395 		 an object under construction is undefined behavior and we
9396 		 don't want it to be considered a candidate for speculative
9397 		 devirtualization.  But do create the thunk for ABI
9398 		 compliance.  */
9399 	      if (DECL_DESTRUCTOR_P (fn_original)
9400 		  && (CLASSTYPE_PURE_VIRTUALS (DECL_CONTEXT (fn_original))
9401 		      || orig_binfo != binfo))
9402 		init = size_zero_node;
9403 	    }
9404 	}
9405 
9406       /* And add it to the chain of initializers.  */
9407       if (TARGET_VTABLE_USES_DESCRIPTORS)
9408 	{
9409 	  int i;
9410 	  if (init == size_zero_node)
9411 	    for (i = 0; i < TARGET_VTABLE_USES_DESCRIPTORS; ++i)
9412 	      CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, init);
9413 	  else
9414 	    for (i = 0; i < TARGET_VTABLE_USES_DESCRIPTORS; ++i)
9415 	      {
9416 		tree fdesc = build2 (FDESC_EXPR, vfunc_ptr_type_node,
9417 				     fn, build_int_cst (NULL_TREE, i));
9418 		TREE_CONSTANT (fdesc) = 1;
9419 
9420 		CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, fdesc);
9421 	      }
9422 	}
9423       else
9424 	CONSTRUCTOR_APPEND_ELT (*inits, NULL_TREE, init);
9425     }
9426 }
9427 
9428 /* Adds to vid->inits the initializers for the vbase and vcall
9429    offsets in BINFO, which is in the hierarchy dominated by T.  */
9430 
9431 static void
build_vcall_and_vbase_vtbl_entries(tree binfo,vtbl_init_data * vid)9432 build_vcall_and_vbase_vtbl_entries (tree binfo, vtbl_init_data* vid)
9433 {
9434   tree b;
9435 
9436   /* If this is a derived class, we must first create entries
9437      corresponding to the primary base class.  */
9438   b = get_primary_binfo (binfo);
9439   if (b)
9440     build_vcall_and_vbase_vtbl_entries (b, vid);
9441 
9442   /* Add the vbase entries for this base.  */
9443   build_vbase_offset_vtbl_entries (binfo, vid);
9444   /* Add the vcall entries for this base.  */
9445   build_vcall_offset_vtbl_entries (binfo, vid);
9446 }
9447 
9448 /* Returns the initializers for the vbase offset entries in the vtable
9449    for BINFO (which is part of the class hierarchy dominated by T), in
9450    reverse order.  VBASE_OFFSET_INDEX gives the vtable index
9451    where the next vbase offset will go.  */
9452 
9453 static void
build_vbase_offset_vtbl_entries(tree binfo,vtbl_init_data * vid)9454 build_vbase_offset_vtbl_entries (tree binfo, vtbl_init_data* vid)
9455 {
9456   tree vbase;
9457   tree t;
9458   tree non_primary_binfo;
9459 
9460   /* If there are no virtual baseclasses, then there is nothing to
9461      do.  */
9462   if (!CLASSTYPE_VBASECLASSES (BINFO_TYPE (binfo)))
9463     return;
9464 
9465   t = vid->derived;
9466 
9467   /* We might be a primary base class.  Go up the inheritance hierarchy
9468      until we find the most derived class of which we are a primary base:
9469      it is the offset of that which we need to use.  */
9470   non_primary_binfo = binfo;
9471   while (BINFO_INHERITANCE_CHAIN (non_primary_binfo))
9472     {
9473       tree b;
9474 
9475       /* If we have reached a virtual base, then it must be a primary
9476 	 base (possibly multi-level) of vid->binfo, or we wouldn't
9477 	 have called build_vcall_and_vbase_vtbl_entries for it.  But it
9478 	 might be a lost primary, so just skip down to vid->binfo.  */
9479       if (BINFO_VIRTUAL_P (non_primary_binfo))
9480 	{
9481 	  non_primary_binfo = vid->binfo;
9482 	  break;
9483 	}
9484 
9485       b = BINFO_INHERITANCE_CHAIN (non_primary_binfo);
9486       if (get_primary_binfo (b) != non_primary_binfo)
9487 	break;
9488       non_primary_binfo = b;
9489     }
9490 
9491   /* Go through the virtual bases, adding the offsets.  */
9492   for (vbase = TYPE_BINFO (BINFO_TYPE (binfo));
9493        vbase;
9494        vbase = TREE_CHAIN (vbase))
9495     {
9496       tree b;
9497       tree delta;
9498 
9499       if (!BINFO_VIRTUAL_P (vbase))
9500 	continue;
9501 
9502       /* Find the instance of this virtual base in the complete
9503 	 object.  */
9504       b = copied_binfo (vbase, binfo);
9505 
9506       /* If we've already got an offset for this virtual base, we
9507 	 don't need another one.  */
9508       if (BINFO_VTABLE_PATH_MARKED (b))
9509 	continue;
9510       BINFO_VTABLE_PATH_MARKED (b) = 1;
9511 
9512       /* Figure out where we can find this vbase offset.  */
9513       delta = size_binop (MULT_EXPR,
9514 			  vid->index,
9515 			  fold_convert (ssizetype,
9516 				   TYPE_SIZE_UNIT (vtable_entry_type)));
9517       if (vid->primary_vtbl_p)
9518 	BINFO_VPTR_FIELD (b) = delta;
9519 
9520       if (binfo != TYPE_BINFO (t))
9521 	/* The vbase offset had better be the same.  */
9522 	gcc_assert (tree_int_cst_equal (delta, BINFO_VPTR_FIELD (vbase)));
9523 
9524       /* The next vbase will come at a more negative offset.  */
9525       vid->index = size_binop (MINUS_EXPR, vid->index,
9526 			       ssize_int (TARGET_VTABLE_DATA_ENTRY_DISTANCE));
9527 
9528       /* The initializer is the delta from BINFO to this virtual base.
9529 	 The vbase offsets go in reverse inheritance-graph order, and
9530 	 we are walking in inheritance graph order so these end up in
9531 	 the right order.  */
9532       delta = size_diffop_loc (input_location,
9533 			   BINFO_OFFSET (b), BINFO_OFFSET (non_primary_binfo));
9534 
9535       CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE,
9536 			      fold_build1_loc (input_location, NOP_EXPR,
9537 					       vtable_entry_type, delta));
9538     }
9539 }
9540 
9541 /* Adds the initializers for the vcall offset entries in the vtable
9542    for BINFO (which is part of the class hierarchy dominated by VID->DERIVED)
9543    to VID->INITS.  */
9544 
9545 static void
build_vcall_offset_vtbl_entries(tree binfo,vtbl_init_data * vid)9546 build_vcall_offset_vtbl_entries (tree binfo, vtbl_init_data* vid)
9547 {
9548   /* We only need these entries if this base is a virtual base.  We
9549      compute the indices -- but do not add to the vtable -- when
9550      building the main vtable for a class.  */
9551   if (binfo == TYPE_BINFO (vid->derived)
9552       || (BINFO_VIRTUAL_P (binfo)
9553 	  /* If BINFO is RTTI_BINFO, then (since BINFO does not
9554 	     correspond to VID->DERIVED), we are building a primary
9555 	     construction virtual table.  Since this is a primary
9556 	     virtual table, we do not need the vcall offsets for
9557 	     BINFO.  */
9558 	  && binfo != vid->rtti_binfo))
9559     {
9560       /* We need a vcall offset for each of the virtual functions in this
9561 	 vtable.  For example:
9562 
9563 	   class A { virtual void f (); };
9564 	   class B1 : virtual public A { virtual void f (); };
9565 	   class B2 : virtual public A { virtual void f (); };
9566 	   class C: public B1, public B2 { virtual void f (); };
9567 
9568 	 A C object has a primary base of B1, which has a primary base of A.  A
9569 	 C also has a secondary base of B2, which no longer has a primary base
9570 	 of A.  So the B2-in-C construction vtable needs a secondary vtable for
9571 	 A, which will adjust the A* to a B2* to call f.  We have no way of
9572 	 knowing what (or even whether) this offset will be when we define B2,
9573 	 so we store this "vcall offset" in the A sub-vtable and look it up in
9574 	 a "virtual thunk" for B2::f.
9575 
9576 	 We need entries for all the functions in our primary vtable and
9577 	 in our non-virtual bases' secondary vtables.  */
9578       vid->vbase = binfo;
9579       /* If we are just computing the vcall indices -- but do not need
9580 	 the actual entries -- not that.  */
9581       if (!BINFO_VIRTUAL_P (binfo))
9582 	vid->generate_vcall_entries = false;
9583       /* Now, walk through the non-virtual bases, adding vcall offsets.  */
9584       add_vcall_offset_vtbl_entries_r (binfo, vid);
9585     }
9586 }
9587 
9588 /* Build vcall offsets, starting with those for BINFO.  */
9589 
9590 static void
add_vcall_offset_vtbl_entries_r(tree binfo,vtbl_init_data * vid)9591 add_vcall_offset_vtbl_entries_r (tree binfo, vtbl_init_data* vid)
9592 {
9593   int i;
9594   tree primary_binfo;
9595   tree base_binfo;
9596 
9597   /* Don't walk into virtual bases -- except, of course, for the
9598      virtual base for which we are building vcall offsets.  Any
9599      primary virtual base will have already had its offsets generated
9600      through the recursion in build_vcall_and_vbase_vtbl_entries.  */
9601   if (BINFO_VIRTUAL_P (binfo) && vid->vbase != binfo)
9602     return;
9603 
9604   /* If BINFO has a primary base, process it first.  */
9605   primary_binfo = get_primary_binfo (binfo);
9606   if (primary_binfo)
9607     add_vcall_offset_vtbl_entries_r (primary_binfo, vid);
9608 
9609   /* Add BINFO itself to the list.  */
9610   add_vcall_offset_vtbl_entries_1 (binfo, vid);
9611 
9612   /* Scan the non-primary bases of BINFO.  */
9613   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
9614     if (base_binfo != primary_binfo)
9615       add_vcall_offset_vtbl_entries_r (base_binfo, vid);
9616 }
9617 
9618 /* Called from build_vcall_offset_vtbl_entries_r.  */
9619 
9620 static void
add_vcall_offset_vtbl_entries_1(tree binfo,vtbl_init_data * vid)9621 add_vcall_offset_vtbl_entries_1 (tree binfo, vtbl_init_data* vid)
9622 {
9623   /* Make entries for the rest of the virtuals.  */
9624   tree orig_fn;
9625 
9626   /* The ABI requires that the methods be processed in declaration
9627      order.  */
9628   for (orig_fn = TYPE_FIELDS (BINFO_TYPE (binfo));
9629        orig_fn;
9630        orig_fn = DECL_CHAIN (orig_fn))
9631     if (TREE_CODE (orig_fn) == FUNCTION_DECL && DECL_VINDEX (orig_fn))
9632       add_vcall_offset (orig_fn, binfo, vid);
9633 }
9634 
9635 /* Add a vcall offset entry for ORIG_FN to the vtable.  */
9636 
9637 static void
add_vcall_offset(tree orig_fn,tree binfo,vtbl_init_data * vid)9638 add_vcall_offset (tree orig_fn, tree binfo, vtbl_init_data *vid)
9639 {
9640   size_t i;
9641   tree vcall_offset;
9642   tree derived_entry;
9643 
9644   /* If there is already an entry for a function with the same
9645      signature as FN, then we do not need a second vcall offset.
9646      Check the list of functions already present in the derived
9647      class vtable.  */
9648   FOR_EACH_VEC_SAFE_ELT (vid->fns, i, derived_entry)
9649     {
9650       if (same_signature_p (derived_entry, orig_fn)
9651 	  /* We only use one vcall offset for virtual destructors,
9652 	     even though there are two virtual table entries.  */
9653 	  || (DECL_DESTRUCTOR_P (derived_entry)
9654 	      && DECL_DESTRUCTOR_P (orig_fn)))
9655 	return;
9656     }
9657 
9658   /* If we are building these vcall offsets as part of building
9659      the vtable for the most derived class, remember the vcall
9660      offset.  */
9661   if (vid->binfo == TYPE_BINFO (vid->derived))
9662     {
9663       tree_pair_s elt = {orig_fn, vid->index};
9664       vec_safe_push (CLASSTYPE_VCALL_INDICES (vid->derived), elt);
9665     }
9666 
9667   /* The next vcall offset will be found at a more negative
9668      offset.  */
9669   vid->index = size_binop (MINUS_EXPR, vid->index,
9670 			   ssize_int (TARGET_VTABLE_DATA_ENTRY_DISTANCE));
9671 
9672   /* Keep track of this function.  */
9673   vec_safe_push (vid->fns, orig_fn);
9674 
9675   if (vid->generate_vcall_entries)
9676     {
9677       tree base;
9678       tree fn;
9679 
9680       /* Find the overriding function.  */
9681       fn = find_final_overrider (vid->rtti_binfo, binfo, orig_fn);
9682       if (fn == error_mark_node)
9683 	vcall_offset = build_zero_cst (vtable_entry_type);
9684       else
9685 	{
9686 	  base = TREE_VALUE (fn);
9687 
9688 	  /* The vbase we're working on is a primary base of
9689 	     vid->binfo.  But it might be a lost primary, so its
9690 	     BINFO_OFFSET might be wrong, so we just use the
9691 	     BINFO_OFFSET from vid->binfo.  */
9692 	  vcall_offset = size_diffop_loc (input_location,
9693 				      BINFO_OFFSET (base),
9694 				      BINFO_OFFSET (vid->binfo));
9695 	  vcall_offset = fold_build1_loc (input_location,
9696 				      NOP_EXPR, vtable_entry_type,
9697 				      vcall_offset);
9698 	}
9699       /* Add the initializer to the vtable.  */
9700       CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE, vcall_offset);
9701     }
9702 }
9703 
9704 /* Return vtbl initializers for the RTTI entries corresponding to the
9705    BINFO's vtable.  The RTTI entries should indicate the object given
9706    by VID->rtti_binfo.  */
9707 
9708 static void
build_rtti_vtbl_entries(tree binfo,vtbl_init_data * vid)9709 build_rtti_vtbl_entries (tree binfo, vtbl_init_data* vid)
9710 {
9711   tree b;
9712   tree t;
9713   tree offset;
9714   tree decl;
9715   tree init;
9716 
9717   t = BINFO_TYPE (vid->rtti_binfo);
9718 
9719   /* To find the complete object, we will first convert to our most
9720      primary base, and then add the offset in the vtbl to that value.  */
9721   b = most_primary_binfo (binfo);
9722   offset = size_diffop_loc (input_location,
9723 			BINFO_OFFSET (vid->rtti_binfo), BINFO_OFFSET (b));
9724 
9725   /* The second entry is the address of the typeinfo object.  */
9726   if (flag_rtti)
9727     decl = build_address (get_tinfo_decl (t));
9728   else
9729     decl = integer_zero_node;
9730 
9731   /* Convert the declaration to a type that can be stored in the
9732      vtable.  */
9733   init = build_nop (vfunc_ptr_type_node, decl);
9734   CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE, init);
9735 
9736   /* Add the offset-to-top entry.  It comes earlier in the vtable than
9737      the typeinfo entry.  Convert the offset to look like a
9738      function pointer, so that we can put it in the vtable.  */
9739   init = build_nop (vfunc_ptr_type_node, offset);
9740   CONSTRUCTOR_APPEND_ELT (vid->inits, NULL_TREE, init);
9741 }
9742 
9743 /* TRUE iff TYPE is uniquely derived from PARENT.  Ignores
9744    accessibility.  */
9745 
9746 bool
uniquely_derived_from_p(tree parent,tree type)9747 uniquely_derived_from_p (tree parent, tree type)
9748 {
9749   tree base = lookup_base (type, parent, ba_unique, NULL, tf_none);
9750   return base && base != error_mark_node;
9751 }
9752 
9753 /* TRUE iff TYPE is publicly & uniquely derived from PARENT.  */
9754 
9755 bool
publicly_uniquely_derived_p(tree parent,tree type)9756 publicly_uniquely_derived_p (tree parent, tree type)
9757 {
9758   tree base = lookup_base (type, parent, ba_ignore_scope | ba_check,
9759 			   NULL, tf_none);
9760   return base && base != error_mark_node;
9761 }
9762 
9763 /* CTX1 and CTX2 are declaration contexts.  Return the innermost common
9764    class between them, if any.  */
9765 
9766 tree
common_enclosing_class(tree ctx1,tree ctx2)9767 common_enclosing_class (tree ctx1, tree ctx2)
9768 {
9769   if (!TYPE_P (ctx1) || !TYPE_P (ctx2))
9770     return NULL_TREE;
9771   gcc_assert (ctx1 == TYPE_MAIN_VARIANT (ctx1)
9772 	      && ctx2 == TYPE_MAIN_VARIANT (ctx2));
9773   if (ctx1 == ctx2)
9774     return ctx1;
9775   for (tree t = ctx1; TYPE_P (t); t = TYPE_CONTEXT (t))
9776     TYPE_MARKED_P (t) = true;
9777   tree found = NULL_TREE;
9778   for (tree t = ctx2; TYPE_P (t); t = TYPE_CONTEXT (t))
9779     if (TYPE_MARKED_P (t))
9780       {
9781 	found = t;
9782 	break;
9783       }
9784   for (tree t = ctx1; TYPE_P (t); t = TYPE_CONTEXT (t))
9785     TYPE_MARKED_P (t) = false;
9786   return found;
9787 }
9788 
9789 #include "gt-cp-class.h"
9790