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