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