ChangeLog fix
[official-gcc.git] / gcc / cp / init.c
blobacf9c9b7c32f3e79fa3b717066dbe4dd36793076
1 /* Handle initialization things in C++.
2 Copyright (C) 1987-2018 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com)
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* High-level class interface. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "target.h"
27 #include "cp-tree.h"
28 #include "stringpool.h"
29 #include "varasm.h"
30 #include "gimplify.h"
31 #include "c-family/c-ubsan.h"
32 #include "intl.h"
33 #include "stringpool.h"
34 #include "attribs.h"
35 #include "asan.h"
37 static bool begin_init_stmts (tree *, tree *);
38 static tree finish_init_stmts (bool, tree, tree);
39 static void construct_virtual_base (tree, tree);
40 static void expand_aggr_init_1 (tree, tree, tree, tree, int, tsubst_flags_t);
41 static void expand_default_init (tree, tree, tree, tree, int, tsubst_flags_t);
42 static void perform_member_init (tree, tree);
43 static int member_init_ok_or_else (tree, tree, tree);
44 static void expand_virtual_init (tree, tree);
45 static tree sort_mem_initializers (tree, tree);
46 static tree initializing_context (tree);
47 static void expand_cleanup_for_base (tree, tree);
48 static tree dfs_initialize_vtbl_ptrs (tree, void *);
49 static tree build_field_list (tree, tree, int *);
50 static int diagnose_uninitialized_cst_or_ref_member_1 (tree, tree, bool, bool);
52 static GTY(()) tree fn;
54 /* We are about to generate some complex initialization code.
55 Conceptually, it is all a single expression. However, we may want
56 to include conditionals, loops, and other such statement-level
57 constructs. Therefore, we build the initialization code inside a
58 statement-expression. This function starts such an expression.
59 STMT_EXPR_P and COMPOUND_STMT_P are filled in by this function;
60 pass them back to finish_init_stmts when the expression is
61 complete. */
63 static bool
64 begin_init_stmts (tree *stmt_expr_p, tree *compound_stmt_p)
66 bool is_global = !building_stmt_list_p ();
68 *stmt_expr_p = begin_stmt_expr ();
69 *compound_stmt_p = begin_compound_stmt (BCS_NO_SCOPE);
71 return is_global;
74 /* Finish out the statement-expression begun by the previous call to
75 begin_init_stmts. Returns the statement-expression itself. */
77 static tree
78 finish_init_stmts (bool is_global, tree stmt_expr, tree compound_stmt)
80 finish_compound_stmt (compound_stmt);
82 stmt_expr = finish_stmt_expr (stmt_expr, true);
84 gcc_assert (!building_stmt_list_p () == is_global);
86 return stmt_expr;
89 /* Constructors */
91 /* Called from initialize_vtbl_ptrs via dfs_walk. BINFO is the base
92 which we want to initialize the vtable pointer for, DATA is
93 TREE_LIST whose TREE_VALUE is the this ptr expression. */
95 static tree
96 dfs_initialize_vtbl_ptrs (tree binfo, void *data)
98 if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
99 return dfs_skip_bases;
101 if (!BINFO_PRIMARY_P (binfo) || BINFO_VIRTUAL_P (binfo))
103 tree base_ptr = TREE_VALUE ((tree) data);
105 base_ptr = build_base_path (PLUS_EXPR, base_ptr, binfo, /*nonnull=*/1,
106 tf_warning_or_error);
108 expand_virtual_init (binfo, base_ptr);
111 return NULL_TREE;
114 /* Initialize all the vtable pointers in the object pointed to by
115 ADDR. */
117 void
118 initialize_vtbl_ptrs (tree addr)
120 tree list;
121 tree type;
123 type = TREE_TYPE (TREE_TYPE (addr));
124 list = build_tree_list (type, addr);
126 /* Walk through the hierarchy, initializing the vptr in each base
127 class. We do these in pre-order because we can't find the virtual
128 bases for a class until we've initialized the vtbl for that
129 class. */
130 dfs_walk_once (TYPE_BINFO (type), dfs_initialize_vtbl_ptrs, NULL, list);
133 /* Return an expression for the zero-initialization of an object with
134 type T. This expression will either be a constant (in the case
135 that T is a scalar), or a CONSTRUCTOR (in the case that T is an
136 aggregate), or NULL (in the case that T does not require
137 initialization). In either case, the value can be used as
138 DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
139 initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
140 is the number of elements in the array. If STATIC_STORAGE_P is
141 TRUE, initializers are only generated for entities for which
142 zero-initialization does not simply mean filling the storage with
143 zero bytes. FIELD_SIZE, if non-NULL, is the bit size of the field,
144 subfields with bit positions at or above that bit size shouldn't
145 be added. Note that this only works when the result is assigned
146 to a base COMPONENT_REF; if we only have a pointer to the base subobject,
147 expand_assignment will end up clearing the full size of TYPE. */
149 static tree
150 build_zero_init_1 (tree type, tree nelts, bool static_storage_p,
151 tree field_size)
153 tree init = NULL_TREE;
155 /* [dcl.init]
157 To zero-initialize an object of type T means:
159 -- if T is a scalar type, the storage is set to the value of zero
160 converted to T.
162 -- if T is a non-union class type, the storage for each nonstatic
163 data member and each base-class subobject is zero-initialized.
165 -- if T is a union type, the storage for its first data member is
166 zero-initialized.
168 -- if T is an array type, the storage for each element is
169 zero-initialized.
171 -- if T is a reference type, no initialization is performed. */
173 gcc_assert (nelts == NULL_TREE || TREE_CODE (nelts) == INTEGER_CST);
175 if (type == error_mark_node)
177 else if (static_storage_p && zero_init_p (type))
178 /* In order to save space, we do not explicitly build initializers
179 for items that do not need them. GCC's semantics are that
180 items with static storage duration that are not otherwise
181 initialized are initialized to zero. */
183 else if (TYPE_PTR_OR_PTRMEM_P (type))
184 init = fold (convert (type, nullptr_node));
185 else if (NULLPTR_TYPE_P (type))
186 init = build_int_cst (type, 0);
187 else if (SCALAR_TYPE_P (type))
188 init = fold (convert (type, integer_zero_node));
189 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (type)))
191 tree field;
192 vec<constructor_elt, va_gc> *v = NULL;
194 /* Iterate over the fields, building initializations. */
195 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
197 if (TREE_CODE (field) != FIELD_DECL)
198 continue;
200 if (TREE_TYPE (field) == error_mark_node)
201 continue;
203 /* Don't add virtual bases for base classes if they are beyond
204 the size of the current field, that means it is present
205 somewhere else in the object. */
206 if (field_size)
208 tree bitpos = bit_position (field);
209 if (TREE_CODE (bitpos) == INTEGER_CST
210 && !tree_int_cst_lt (bitpos, field_size))
211 continue;
214 /* Note that for class types there will be FIELD_DECLs
215 corresponding to base classes as well. Thus, iterating
216 over TYPE_FIELDs will result in correct initialization of
217 all of the subobjects. */
218 if (!static_storage_p || !zero_init_p (TREE_TYPE (field)))
220 tree new_field_size
221 = (DECL_FIELD_IS_BASE (field)
222 && DECL_SIZE (field)
223 && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
224 ? DECL_SIZE (field) : NULL_TREE;
225 tree value = build_zero_init_1 (TREE_TYPE (field),
226 /*nelts=*/NULL_TREE,
227 static_storage_p,
228 new_field_size);
229 if (value)
230 CONSTRUCTOR_APPEND_ELT(v, field, value);
233 /* For unions, only the first field is initialized. */
234 if (TREE_CODE (type) == UNION_TYPE)
235 break;
238 /* Build a constructor to contain the initializations. */
239 init = build_constructor (type, v);
241 else if (TREE_CODE (type) == ARRAY_TYPE)
243 tree max_index;
244 vec<constructor_elt, va_gc> *v = NULL;
246 /* Iterate over the array elements, building initializations. */
247 if (nelts)
248 max_index = fold_build2_loc (input_location,
249 MINUS_EXPR, TREE_TYPE (nelts),
250 nelts, integer_one_node);
251 else
252 max_index = array_type_nelts (type);
254 /* If we have an error_mark here, we should just return error mark
255 as we don't know the size of the array yet. */
256 if (max_index == error_mark_node)
257 return error_mark_node;
258 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
260 /* A zero-sized array, which is accepted as an extension, will
261 have an upper bound of -1. */
262 if (!tree_int_cst_equal (max_index, integer_minus_one_node))
264 constructor_elt ce;
266 /* If this is a one element array, we just use a regular init. */
267 if (tree_int_cst_equal (size_zero_node, max_index))
268 ce.index = size_zero_node;
269 else
270 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node,
271 max_index);
273 ce.value = build_zero_init_1 (TREE_TYPE (type),
274 /*nelts=*/NULL_TREE,
275 static_storage_p, NULL_TREE);
276 if (ce.value)
278 vec_alloc (v, 1);
279 v->quick_push (ce);
283 /* Build a constructor to contain the initializations. */
284 init = build_constructor (type, v);
286 else if (VECTOR_TYPE_P (type))
287 init = build_zero_cst (type);
288 else
290 gcc_assert (TYPE_REF_P (type));
291 init = build_zero_cst (type);
294 /* In all cases, the initializer is a constant. */
295 if (init)
296 TREE_CONSTANT (init) = 1;
298 return init;
301 /* Return an expression for the zero-initialization of an object with
302 type T. This expression will either be a constant (in the case
303 that T is a scalar), or a CONSTRUCTOR (in the case that T is an
304 aggregate), or NULL (in the case that T does not require
305 initialization). In either case, the value can be used as
306 DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
307 initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
308 is the number of elements in the array. If STATIC_STORAGE_P is
309 TRUE, initializers are only generated for entities for which
310 zero-initialization does not simply mean filling the storage with
311 zero bytes. */
313 tree
314 build_zero_init (tree type, tree nelts, bool static_storage_p)
316 return build_zero_init_1 (type, nelts, static_storage_p, NULL_TREE);
319 /* Return a suitable initializer for value-initializing an object of type
320 TYPE, as described in [dcl.init]. */
322 tree
323 build_value_init (tree type, tsubst_flags_t complain)
325 /* [dcl.init]
327 To value-initialize an object of type T means:
329 - if T is a class type (clause 9) with either no default constructor
330 (12.1) or a default constructor that is user-provided or deleted,
331 then the object is default-initialized;
333 - if T is a (possibly cv-qualified) class type without a user-provided
334 or deleted default constructor, then the object is zero-initialized
335 and the semantic constraints for default-initialization are checked,
336 and if T has a non-trivial default constructor, the object is
337 default-initialized;
339 - if T is an array type, then each element is value-initialized;
341 - otherwise, the object is zero-initialized.
343 A program that calls for default-initialization or
344 value-initialization of an entity of reference type is ill-formed. */
346 /* The AGGR_INIT_EXPR tweaking below breaks in templates. */
347 gcc_assert (!processing_template_decl
348 || (SCALAR_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE));
350 if (CLASS_TYPE_P (type)
351 && type_build_ctor_call (type))
353 tree ctor =
354 build_special_member_call (NULL_TREE, complete_ctor_identifier,
355 NULL, type, LOOKUP_NORMAL,
356 complain);
357 if (ctor == error_mark_node)
358 return ctor;
359 tree fn = NULL_TREE;
360 if (TREE_CODE (ctor) == CALL_EXPR)
361 fn = get_callee_fndecl (ctor);
362 ctor = build_aggr_init_expr (type, ctor);
363 if (fn && user_provided_p (fn))
364 return ctor;
365 else if (TYPE_HAS_COMPLEX_DFLT (type))
367 /* This is a class that needs constructing, but doesn't have
368 a user-provided constructor. So we need to zero-initialize
369 the object and then call the implicitly defined ctor.
370 This will be handled in simplify_aggr_init_expr. */
371 AGGR_INIT_ZERO_FIRST (ctor) = 1;
372 return ctor;
376 /* Discard any access checking during subobject initialization;
377 the checks are implied by the call to the ctor which we have
378 verified is OK (cpp0x/defaulted46.C). */
379 push_deferring_access_checks (dk_deferred);
380 tree r = build_value_init_noctor (type, complain);
381 pop_deferring_access_checks ();
382 return r;
385 /* Like build_value_init, but don't call the constructor for TYPE. Used
386 for base initializers. */
388 tree
389 build_value_init_noctor (tree type, tsubst_flags_t complain)
391 if (!COMPLETE_TYPE_P (type))
393 if (complain & tf_error)
394 error ("value-initialization of incomplete type %qT", type);
395 return error_mark_node;
397 /* FIXME the class and array cases should just use digest_init once it is
398 SFINAE-enabled. */
399 if (CLASS_TYPE_P (type))
401 gcc_assert (!TYPE_HAS_COMPLEX_DFLT (type)
402 || errorcount != 0);
404 if (TREE_CODE (type) != UNION_TYPE)
406 tree field;
407 vec<constructor_elt, va_gc> *v = NULL;
409 /* Iterate over the fields, building initializations. */
410 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
412 tree ftype, value;
414 if (TREE_CODE (field) != FIELD_DECL)
415 continue;
417 ftype = TREE_TYPE (field);
419 if (ftype == error_mark_node)
420 continue;
422 /* We could skip vfields and fields of types with
423 user-defined constructors, but I think that won't improve
424 performance at all; it should be simpler in general just
425 to zero out the entire object than try to only zero the
426 bits that actually need it. */
428 /* Note that for class types there will be FIELD_DECLs
429 corresponding to base classes as well. Thus, iterating
430 over TYPE_FIELDs will result in correct initialization of
431 all of the subobjects. */
432 value = build_value_init (ftype, complain);
433 value = maybe_constant_init (value);
435 if (value == error_mark_node)
436 return error_mark_node;
438 CONSTRUCTOR_APPEND_ELT(v, field, value);
440 /* We shouldn't have gotten here for anything that would need
441 non-trivial initialization, and gimplify_init_ctor_preeval
442 would need to be fixed to allow it. */
443 gcc_assert (TREE_CODE (value) != TARGET_EXPR
444 && TREE_CODE (value) != AGGR_INIT_EXPR);
447 /* Build a constructor to contain the zero- initializations. */
448 return build_constructor (type, v);
451 else if (TREE_CODE (type) == ARRAY_TYPE)
453 vec<constructor_elt, va_gc> *v = NULL;
455 /* Iterate over the array elements, building initializations. */
456 tree max_index = array_type_nelts (type);
458 /* If we have an error_mark here, we should just return error mark
459 as we don't know the size of the array yet. */
460 if (max_index == error_mark_node)
462 if (complain & tf_error)
463 error ("cannot value-initialize array of unknown bound %qT",
464 type);
465 return error_mark_node;
467 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
469 /* A zero-sized array, which is accepted as an extension, will
470 have an upper bound of -1. */
471 if (!tree_int_cst_equal (max_index, integer_minus_one_node))
473 constructor_elt ce;
475 /* If this is a one element array, we just use a regular init. */
476 if (tree_int_cst_equal (size_zero_node, max_index))
477 ce.index = size_zero_node;
478 else
479 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node, max_index);
481 ce.value = build_value_init (TREE_TYPE (type), complain);
482 ce.value = maybe_constant_init (ce.value);
483 if (ce.value == error_mark_node)
484 return error_mark_node;
486 vec_alloc (v, 1);
487 v->quick_push (ce);
489 /* We shouldn't have gotten here for anything that would need
490 non-trivial initialization, and gimplify_init_ctor_preeval
491 would need to be fixed to allow it. */
492 gcc_assert (TREE_CODE (ce.value) != TARGET_EXPR
493 && TREE_CODE (ce.value) != AGGR_INIT_EXPR);
496 /* Build a constructor to contain the initializations. */
497 return build_constructor (type, v);
499 else if (TREE_CODE (type) == FUNCTION_TYPE)
501 if (complain & tf_error)
502 error ("value-initialization of function type %qT", type);
503 return error_mark_node;
505 else if (TYPE_REF_P (type))
507 if (complain & tf_error)
508 error ("value-initialization of reference type %qT", type);
509 return error_mark_node;
512 return build_zero_init (type, NULL_TREE, /*static_storage_p=*/false);
515 /* Initialize current class with INIT, a TREE_LIST of
516 arguments for a target constructor. If TREE_LIST is void_type_node,
517 an empty initializer list was given. */
519 static void
520 perform_target_ctor (tree init)
522 tree decl = current_class_ref;
523 tree type = current_class_type;
525 finish_expr_stmt (build_aggr_init (decl, init,
526 LOOKUP_NORMAL|LOOKUP_DELEGATING_CONS,
527 tf_warning_or_error));
528 if (type_build_dtor_call (type))
530 tree expr = build_delete (type, decl, sfk_complete_destructor,
531 LOOKUP_NORMAL
532 |LOOKUP_NONVIRTUAL
533 |LOOKUP_DESTRUCTOR,
534 0, tf_warning_or_error);
535 if (expr != error_mark_node
536 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
537 finish_eh_cleanup (expr);
541 /* Return the non-static data initializer for FIELD_DECL MEMBER. */
543 static GTY((cache)) tree_cache_map *nsdmi_inst;
545 tree
546 get_nsdmi (tree member, bool in_ctor, tsubst_flags_t complain)
548 tree init;
549 tree save_ccp = current_class_ptr;
550 tree save_ccr = current_class_ref;
552 if (DECL_LANG_SPECIFIC (member) && DECL_TEMPLATE_INFO (member))
554 init = DECL_INITIAL (DECL_TI_TEMPLATE (member));
555 location_t expr_loc
556 = EXPR_LOC_OR_LOC (init, DECL_SOURCE_LOCATION (member));
557 tree *slot;
558 if (TREE_CODE (init) == DEFAULT_ARG)
559 /* Unparsed. */;
560 else if (nsdmi_inst && (slot = nsdmi_inst->get (member)))
561 init = *slot;
562 /* Check recursive instantiation. */
563 else if (DECL_INSTANTIATING_NSDMI_P (member))
565 if (complain & tf_error)
566 error_at (expr_loc, "recursive instantiation of default member "
567 "initializer for %qD", member);
568 init = error_mark_node;
570 else
572 int un = cp_unevaluated_operand;
573 cp_unevaluated_operand = 0;
575 location_t sloc = input_location;
576 input_location = expr_loc;
578 DECL_INSTANTIATING_NSDMI_P (member) = 1;
580 bool pushed = false;
581 if (!currently_open_class (DECL_CONTEXT (member)))
583 push_to_top_level ();
584 push_nested_class (DECL_CONTEXT (member));
585 pushed = true;
588 gcc_checking_assert (!processing_template_decl);
590 inject_this_parameter (DECL_CONTEXT (member), TYPE_UNQUALIFIED);
592 start_lambda_scope (member);
594 /* Do deferred instantiation of the NSDMI. */
595 init = (tsubst_copy_and_build
596 (init, DECL_TI_ARGS (member),
597 complain, member, /*function_p=*/false,
598 /*integral_constant_expression_p=*/false));
599 init = digest_nsdmi_init (member, init, complain);
601 finish_lambda_scope ();
603 DECL_INSTANTIATING_NSDMI_P (member) = 0;
605 if (init != error_mark_node)
607 if (!nsdmi_inst)
608 nsdmi_inst = tree_cache_map::create_ggc (37);
609 nsdmi_inst->put (member, init);
612 if (pushed)
614 pop_nested_class ();
615 pop_from_top_level ();
618 input_location = sloc;
619 cp_unevaluated_operand = un;
622 else
623 init = DECL_INITIAL (member);
625 if (init && TREE_CODE (init) == DEFAULT_ARG)
627 if (complain & tf_error)
629 error ("default member initializer for %qD required before the end "
630 "of its enclosing class", member);
631 inform (location_of (init), "defined here");
632 DECL_INITIAL (member) = error_mark_node;
634 init = error_mark_node;
637 if (in_ctor)
639 current_class_ptr = save_ccp;
640 current_class_ref = save_ccr;
642 else
644 /* Use a PLACEHOLDER_EXPR when we don't have a 'this' parameter to
645 refer to; constexpr evaluation knows what to do with it. */
646 current_class_ref = build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (member));
647 current_class_ptr = build_address (current_class_ref);
650 /* Strip redundant TARGET_EXPR so we don't need to remap it, and
651 so the aggregate init code below will see a CONSTRUCTOR. */
652 bool simple_target = (init && SIMPLE_TARGET_EXPR_P (init));
653 if (simple_target)
654 init = TARGET_EXPR_INITIAL (init);
655 init = break_out_target_exprs (init, /*loc*/true);
656 if (simple_target && TREE_CODE (init) != CONSTRUCTOR)
657 /* Now put it back so C++17 copy elision works. */
658 init = get_target_expr (init);
660 current_class_ptr = save_ccp;
661 current_class_ref = save_ccr;
662 return init;
665 /* Diagnose the flexible array MEMBER if its INITializer is non-null
666 and return true if so. Otherwise return false. */
668 bool
669 maybe_reject_flexarray_init (tree member, tree init)
671 tree type = TREE_TYPE (member);
673 if (!init
674 || TREE_CODE (type) != ARRAY_TYPE
675 || TYPE_DOMAIN (type))
676 return false;
678 /* Point at the flexible array member declaration if it's initialized
679 in-class, and at the ctor if it's initialized in a ctor member
680 initializer list. */
681 location_t loc;
682 if (DECL_INITIAL (member) == init
683 || !current_function_decl
684 || DECL_DEFAULTED_FN (current_function_decl))
685 loc = DECL_SOURCE_LOCATION (member);
686 else
687 loc = DECL_SOURCE_LOCATION (current_function_decl);
689 error_at (loc, "initializer for flexible array member %q#D", member);
690 return true;
693 /* If INIT's value can come from a call to std::initializer_list<T>::begin,
694 return that function. Otherwise, NULL_TREE. */
696 static tree
697 find_list_begin (tree init)
699 STRIP_NOPS (init);
700 while (TREE_CODE (init) == COMPOUND_EXPR)
701 init = TREE_OPERAND (init, 1);
702 STRIP_NOPS (init);
703 if (TREE_CODE (init) == COND_EXPR)
705 tree left = TREE_OPERAND (init, 1);
706 if (!left)
707 left = TREE_OPERAND (init, 0);
708 left = find_list_begin (left);
709 if (left)
710 return left;
711 return find_list_begin (TREE_OPERAND (init, 2));
713 if (TREE_CODE (init) == CALL_EXPR)
714 if (tree fn = get_callee_fndecl (init))
715 if (id_equal (DECL_NAME (fn), "begin")
716 && is_std_init_list (DECL_CONTEXT (fn)))
717 return fn;
718 return NULL_TREE;
721 /* If INIT initializing MEMBER is copying the address of the underlying array
722 of an initializer_list, warn. */
724 static void
725 maybe_warn_list_ctor (tree member, tree init)
727 tree memtype = TREE_TYPE (member);
728 if (!init || !TYPE_PTR_P (memtype)
729 || !is_list_ctor (current_function_decl))
730 return;
732 tree parms = FUNCTION_FIRST_USER_PARMTYPE (current_function_decl);
733 tree initlist = non_reference (TREE_VALUE (parms));
734 tree targs = CLASSTYPE_TI_ARGS (initlist);
735 tree elttype = TREE_VEC_ELT (targs, 0);
737 if (!same_type_ignoring_top_level_qualifiers_p
738 (TREE_TYPE (memtype), elttype))
739 return;
741 tree begin = find_list_begin (init);
742 if (!begin)
743 return;
745 location_t loc = EXPR_LOC_OR_LOC (init, input_location);
746 warning_at (loc, OPT_Winit_list_lifetime,
747 "initializing %qD from %qE does not extend the lifetime "
748 "of the underlying array", member, begin);
751 /* Initialize MEMBER, a FIELD_DECL, with INIT, a TREE_LIST of
752 arguments. If TREE_LIST is void_type_node, an empty initializer
753 list was given; if NULL_TREE no initializer was given. */
755 static void
756 perform_member_init (tree member, tree init)
758 tree decl;
759 tree type = TREE_TYPE (member);
761 /* Use the non-static data member initializer if there was no
762 mem-initializer for this field. */
763 if (init == NULL_TREE)
764 init = get_nsdmi (member, /*ctor*/true, tf_warning_or_error);
766 if (init == error_mark_node)
767 return;
769 /* Effective C++ rule 12 requires that all data members be
770 initialized. */
771 if (warn_ecpp && init == NULL_TREE && TREE_CODE (type) != ARRAY_TYPE)
772 warning_at (DECL_SOURCE_LOCATION (current_function_decl), OPT_Weffc__,
773 "%qD should be initialized in the member initialization list",
774 member);
776 /* Get an lvalue for the data member. */
777 decl = build_class_member_access_expr (current_class_ref, member,
778 /*access_path=*/NULL_TREE,
779 /*preserve_reference=*/true,
780 tf_warning_or_error);
781 if (decl == error_mark_node)
782 return;
784 if (warn_init_self && init && TREE_CODE (init) == TREE_LIST
785 && TREE_CHAIN (init) == NULL_TREE)
787 tree val = TREE_VALUE (init);
788 /* Handle references. */
789 if (REFERENCE_REF_P (val))
790 val = TREE_OPERAND (val, 0);
791 if (TREE_CODE (val) == COMPONENT_REF && TREE_OPERAND (val, 1) == member
792 && TREE_OPERAND (val, 0) == current_class_ref)
793 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
794 OPT_Winit_self, "%qD is initialized with itself",
795 member);
798 if (init == void_type_node)
800 /* mem() means value-initialization. */
801 if (TREE_CODE (type) == ARRAY_TYPE)
803 init = build_vec_init_expr (type, init, tf_warning_or_error);
804 init = build2 (INIT_EXPR, type, decl, init);
805 finish_expr_stmt (init);
807 else
809 tree value = build_value_init (type, tf_warning_or_error);
810 if (value == error_mark_node)
811 return;
812 init = build2 (INIT_EXPR, type, decl, value);
813 finish_expr_stmt (init);
816 /* Deal with this here, as we will get confused if we try to call the
817 assignment op for an anonymous union. This can happen in a
818 synthesized copy constructor. */
819 else if (ANON_AGGR_TYPE_P (type))
821 if (init)
823 init = build2 (INIT_EXPR, type, decl, TREE_VALUE (init));
824 finish_expr_stmt (init);
827 else if (init
828 && (TYPE_REF_P (type)
829 /* Pre-digested NSDMI. */
830 || (((TREE_CODE (init) == CONSTRUCTOR
831 && TREE_TYPE (init) == type)
832 /* { } mem-initializer. */
833 || (TREE_CODE (init) == TREE_LIST
834 && DIRECT_LIST_INIT_P (TREE_VALUE (init))))
835 && (CP_AGGREGATE_TYPE_P (type)
836 || is_std_init_list (type)))))
838 /* With references and list-initialization, we need to deal with
839 extending temporary lifetimes. 12.2p5: "A temporary bound to a
840 reference member in a constructor’s ctor-initializer (12.6.2)
841 persists until the constructor exits." */
842 unsigned i; tree t;
843 vec<tree, va_gc> *cleanups = make_tree_vector ();
844 if (TREE_CODE (init) == TREE_LIST)
845 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
846 tf_warning_or_error);
847 if (TREE_TYPE (init) != type)
849 if (BRACE_ENCLOSED_INITIALIZER_P (init)
850 && CP_AGGREGATE_TYPE_P (type))
851 init = reshape_init (type, init, tf_warning_or_error);
852 init = digest_init (type, init, tf_warning_or_error);
854 if (init == error_mark_node)
855 return;
856 /* A FIELD_DECL doesn't really have a suitable lifetime, but
857 make_temporary_var_for_ref_to_temp will treat it as automatic and
858 set_up_extended_ref_temp wants to use the decl in a warning. */
859 init = extend_ref_init_temps (member, init, &cleanups);
860 if (TREE_CODE (type) == ARRAY_TYPE
861 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (type)))
862 init = build_vec_init_expr (type, init, tf_warning_or_error);
863 init = build2 (INIT_EXPR, type, decl, init);
864 finish_expr_stmt (init);
865 FOR_EACH_VEC_ELT (*cleanups, i, t)
866 push_cleanup (decl, t, false);
867 release_tree_vector (cleanups);
869 else if (type_build_ctor_call (type)
870 || (init && CLASS_TYPE_P (strip_array_types (type))))
872 if (TREE_CODE (type) == ARRAY_TYPE)
874 if (init)
876 /* Check to make sure the member initializer is valid and
877 something like a CONSTRUCTOR in: T a[] = { 1, 2 } and
878 if it isn't, return early to avoid triggering another
879 error below. */
880 if (maybe_reject_flexarray_init (member, init))
881 return;
883 if (TREE_CODE (init) != TREE_LIST || TREE_CHAIN (init))
884 init = error_mark_node;
885 else
886 init = TREE_VALUE (init);
888 if (BRACE_ENCLOSED_INITIALIZER_P (init))
889 init = digest_init (type, init, tf_warning_or_error);
891 if (init == NULL_TREE
892 || same_type_ignoring_top_level_qualifiers_p (type,
893 TREE_TYPE (init)))
895 if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
897 /* Initialize the array only if it's not a flexible
898 array member (i.e., if it has an upper bound). */
899 init = build_vec_init_expr (type, init, tf_warning_or_error);
900 init = build2 (INIT_EXPR, type, decl, init);
901 finish_expr_stmt (init);
904 else
905 error ("invalid initializer for array member %q#D", member);
907 else
909 int flags = LOOKUP_NORMAL;
910 if (DECL_DEFAULTED_FN (current_function_decl))
911 flags |= LOOKUP_DEFAULTED;
912 if (CP_TYPE_CONST_P (type)
913 && init == NULL_TREE
914 && default_init_uninitialized_part (type))
916 /* TYPE_NEEDS_CONSTRUCTING can be set just because we have a
917 vtable; still give this diagnostic. */
918 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
919 "uninitialized const member in %q#T", type))
920 inform (DECL_SOURCE_LOCATION (member),
921 "%q#D should be initialized", member );
923 finish_expr_stmt (build_aggr_init (decl, init, flags,
924 tf_warning_or_error));
927 else
929 if (init == NULL_TREE)
931 tree core_type;
932 /* member traversal: note it leaves init NULL */
933 if (TYPE_REF_P (type))
935 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
936 "uninitialized reference member in %q#T", type))
937 inform (DECL_SOURCE_LOCATION (member),
938 "%q#D should be initialized", member);
940 else if (CP_TYPE_CONST_P (type))
942 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
943 "uninitialized const member in %q#T", type))
944 inform (DECL_SOURCE_LOCATION (member),
945 "%q#D should be initialized", member );
948 core_type = strip_array_types (type);
950 if (CLASS_TYPE_P (core_type)
951 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
952 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
953 diagnose_uninitialized_cst_or_ref_member (core_type,
954 /*using_new=*/false,
955 /*complain=*/true);
957 else if (TREE_CODE (init) == TREE_LIST)
958 /* There was an explicit member initialization. Do some work
959 in that case. */
960 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
961 tf_warning_or_error);
963 maybe_warn_list_ctor (member, init);
965 /* Reject a member initializer for a flexible array member. */
966 if (init && !maybe_reject_flexarray_init (member, init))
967 finish_expr_stmt (cp_build_modify_expr (input_location, decl,
968 INIT_EXPR, init,
969 tf_warning_or_error));
972 if (type_build_dtor_call (type))
974 tree expr;
976 expr = build_class_member_access_expr (current_class_ref, member,
977 /*access_path=*/NULL_TREE,
978 /*preserve_reference=*/false,
979 tf_warning_or_error);
980 expr = build_delete (type, expr, sfk_complete_destructor,
981 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0,
982 tf_warning_or_error);
984 if (expr != error_mark_node
985 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
986 finish_eh_cleanup (expr);
990 /* Returns a TREE_LIST containing (as the TREE_PURPOSE of each node) all
991 the FIELD_DECLs on the TYPE_FIELDS list for T, in reverse order. */
993 static tree
994 build_field_list (tree t, tree list, int *uses_unions_or_anon_p)
996 tree fields;
998 /* Note whether or not T is a union. */
999 if (TREE_CODE (t) == UNION_TYPE)
1000 *uses_unions_or_anon_p = 1;
1002 for (fields = TYPE_FIELDS (t); fields; fields = DECL_CHAIN (fields))
1004 tree fieldtype;
1006 /* Skip CONST_DECLs for enumeration constants and so forth. */
1007 if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
1008 continue;
1010 fieldtype = TREE_TYPE (fields);
1012 /* For an anonymous struct or union, we must recursively
1013 consider the fields of the anonymous type. They can be
1014 directly initialized from the constructor. */
1015 if (ANON_AGGR_TYPE_P (fieldtype))
1017 /* Add this field itself. Synthesized copy constructors
1018 initialize the entire aggregate. */
1019 list = tree_cons (fields, NULL_TREE, list);
1020 /* And now add the fields in the anonymous aggregate. */
1021 list = build_field_list (fieldtype, list, uses_unions_or_anon_p);
1022 *uses_unions_or_anon_p = 1;
1024 /* Add this field. */
1025 else if (DECL_NAME (fields))
1026 list = tree_cons (fields, NULL_TREE, list);
1029 return list;
1032 /* Return the innermost aggregate scope for FIELD, whether that is
1033 the enclosing class or an anonymous aggregate within it. */
1035 static tree
1036 innermost_aggr_scope (tree field)
1038 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1039 return TREE_TYPE (field);
1040 else
1041 return DECL_CONTEXT (field);
1044 /* The MEM_INITS are a TREE_LIST. The TREE_PURPOSE of each list gives
1045 a FIELD_DECL or BINFO in T that needs initialization. The
1046 TREE_VALUE gives the initializer, or list of initializer arguments.
1048 Return a TREE_LIST containing all of the initializations required
1049 for T, in the order in which they should be performed. The output
1050 list has the same format as the input. */
1052 static tree
1053 sort_mem_initializers (tree t, tree mem_inits)
1055 tree init;
1056 tree base, binfo, base_binfo;
1057 tree sorted_inits;
1058 tree next_subobject;
1059 vec<tree, va_gc> *vbases;
1060 int i;
1061 int uses_unions_or_anon_p = 0;
1063 /* Build up a list of initializations. The TREE_PURPOSE of entry
1064 will be the subobject (a FIELD_DECL or BINFO) to initialize. The
1065 TREE_VALUE will be the constructor arguments, or NULL if no
1066 explicit initialization was provided. */
1067 sorted_inits = NULL_TREE;
1069 /* Process the virtual bases. */
1070 for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
1071 vec_safe_iterate (vbases, i, &base); i++)
1072 sorted_inits = tree_cons (base, NULL_TREE, sorted_inits);
1074 /* Process the direct bases. */
1075 for (binfo = TYPE_BINFO (t), i = 0;
1076 BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
1077 if (!BINFO_VIRTUAL_P (base_binfo))
1078 sorted_inits = tree_cons (base_binfo, NULL_TREE, sorted_inits);
1080 /* Process the non-static data members. */
1081 sorted_inits = build_field_list (t, sorted_inits, &uses_unions_or_anon_p);
1082 /* Reverse the entire list of initializations, so that they are in
1083 the order that they will actually be performed. */
1084 sorted_inits = nreverse (sorted_inits);
1086 /* If the user presented the initializers in an order different from
1087 that in which they will actually occur, we issue a warning. Keep
1088 track of the next subobject which can be explicitly initialized
1089 without issuing a warning. */
1090 next_subobject = sorted_inits;
1092 /* Go through the explicit initializers, filling in TREE_PURPOSE in
1093 the SORTED_INITS. */
1094 for (init = mem_inits; init; init = TREE_CHAIN (init))
1096 tree subobject;
1097 tree subobject_init;
1099 subobject = TREE_PURPOSE (init);
1101 /* If the explicit initializers are in sorted order, then
1102 SUBOBJECT will be NEXT_SUBOBJECT, or something following
1103 it. */
1104 for (subobject_init = next_subobject;
1105 subobject_init;
1106 subobject_init = TREE_CHAIN (subobject_init))
1107 if (TREE_PURPOSE (subobject_init) == subobject)
1108 break;
1110 /* Issue a warning if the explicit initializer order does not
1111 match that which will actually occur.
1112 ??? Are all these on the correct lines? */
1113 if (warn_reorder && !subobject_init)
1115 if (TREE_CODE (TREE_PURPOSE (next_subobject)) == FIELD_DECL)
1116 warning_at (DECL_SOURCE_LOCATION (TREE_PURPOSE (next_subobject)),
1117 OPT_Wreorder, "%qD will be initialized after",
1118 TREE_PURPOSE (next_subobject));
1119 else
1120 warning (OPT_Wreorder, "base %qT will be initialized after",
1121 TREE_PURPOSE (next_subobject));
1122 if (TREE_CODE (subobject) == FIELD_DECL)
1123 warning_at (DECL_SOURCE_LOCATION (subobject),
1124 OPT_Wreorder, " %q#D", subobject);
1125 else
1126 warning (OPT_Wreorder, " base %qT", subobject);
1127 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1128 OPT_Wreorder, " when initialized here");
1131 /* Look again, from the beginning of the list. */
1132 if (!subobject_init)
1134 subobject_init = sorted_inits;
1135 while (TREE_PURPOSE (subobject_init) != subobject)
1136 subobject_init = TREE_CHAIN (subobject_init);
1139 /* It is invalid to initialize the same subobject more than
1140 once. */
1141 if (TREE_VALUE (subobject_init))
1143 if (TREE_CODE (subobject) == FIELD_DECL)
1144 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1145 "multiple initializations given for %qD",
1146 subobject);
1147 else
1148 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1149 "multiple initializations given for base %qT",
1150 subobject);
1153 /* Record the initialization. */
1154 TREE_VALUE (subobject_init) = TREE_VALUE (init);
1155 next_subobject = subobject_init;
1158 /* [class.base.init]
1160 If a ctor-initializer specifies more than one mem-initializer for
1161 multiple members of the same union (including members of
1162 anonymous unions), the ctor-initializer is ill-formed.
1164 Here we also splice out uninitialized union members. */
1165 if (uses_unions_or_anon_p)
1167 tree *last_p = NULL;
1168 tree *p;
1169 for (p = &sorted_inits; *p; )
1171 tree field;
1172 tree ctx;
1174 init = *p;
1176 field = TREE_PURPOSE (init);
1178 /* Skip base classes. */
1179 if (TREE_CODE (field) != FIELD_DECL)
1180 goto next;
1182 /* If this is an anonymous aggregate with no explicit initializer,
1183 splice it out. */
1184 if (!TREE_VALUE (init) && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1185 goto splice;
1187 /* See if this field is a member of a union, or a member of a
1188 structure contained in a union, etc. */
1189 ctx = innermost_aggr_scope (field);
1191 /* If this field is not a member of a union, skip it. */
1192 if (TREE_CODE (ctx) != UNION_TYPE
1193 && !ANON_AGGR_TYPE_P (ctx))
1194 goto next;
1196 /* If this union member has no explicit initializer and no NSDMI,
1197 splice it out. */
1198 if (TREE_VALUE (init) || DECL_INITIAL (field))
1199 /* OK. */;
1200 else
1201 goto splice;
1203 /* It's only an error if we have two initializers for the same
1204 union type. */
1205 if (!last_p)
1207 last_p = p;
1208 goto next;
1211 /* See if LAST_FIELD and the field initialized by INIT are
1212 members of the same union (or the union itself). If so, there's
1213 a problem, unless they're actually members of the same structure
1214 which is itself a member of a union. For example, given:
1216 union { struct { int i; int j; }; };
1218 initializing both `i' and `j' makes sense. */
1219 ctx = common_enclosing_class
1220 (innermost_aggr_scope (field),
1221 innermost_aggr_scope (TREE_PURPOSE (*last_p)));
1223 if (ctx && (TREE_CODE (ctx) == UNION_TYPE
1224 || ctx == TREE_TYPE (TREE_PURPOSE (*last_p))))
1226 /* A mem-initializer hides an NSDMI. */
1227 if (TREE_VALUE (init) && !TREE_VALUE (*last_p))
1228 *last_p = TREE_CHAIN (*last_p);
1229 else if (TREE_VALUE (*last_p) && !TREE_VALUE (init))
1230 goto splice;
1231 else
1233 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1234 "initializations for multiple members of %qT",
1235 ctx);
1236 goto splice;
1240 last_p = p;
1242 next:
1243 p = &TREE_CHAIN (*p);
1244 continue;
1245 splice:
1246 *p = TREE_CHAIN (*p);
1247 continue;
1251 return sorted_inits;
1254 /* Callback for cp_walk_tree to mark all PARM_DECLs in a tree as read. */
1256 static tree
1257 mark_exp_read_r (tree *tp, int *, void *)
1259 tree t = *tp;
1260 if (TREE_CODE (t) == PARM_DECL)
1261 mark_exp_read (t);
1262 return NULL_TREE;
1265 /* Initialize all bases and members of CURRENT_CLASS_TYPE. MEM_INITS
1266 is a TREE_LIST giving the explicit mem-initializer-list for the
1267 constructor. The TREE_PURPOSE of each entry is a subobject (a
1268 FIELD_DECL or a BINFO) of the CURRENT_CLASS_TYPE. The TREE_VALUE
1269 is a TREE_LIST giving the arguments to the constructor or
1270 void_type_node for an empty list of arguments. */
1272 void
1273 emit_mem_initializers (tree mem_inits)
1275 int flags = LOOKUP_NORMAL;
1277 /* We will already have issued an error message about the fact that
1278 the type is incomplete. */
1279 if (!COMPLETE_TYPE_P (current_class_type))
1280 return;
1282 if (mem_inits
1283 && TYPE_P (TREE_PURPOSE (mem_inits))
1284 && same_type_p (TREE_PURPOSE (mem_inits), current_class_type))
1286 /* Delegating constructor. */
1287 gcc_assert (TREE_CHAIN (mem_inits) == NULL_TREE);
1288 perform_target_ctor (TREE_VALUE (mem_inits));
1289 return;
1292 if (DECL_DEFAULTED_FN (current_function_decl)
1293 && ! DECL_INHERITED_CTOR (current_function_decl))
1294 flags |= LOOKUP_DEFAULTED;
1296 /* Sort the mem-initializers into the order in which the
1297 initializations should be performed. */
1298 mem_inits = sort_mem_initializers (current_class_type, mem_inits);
1300 in_base_initializer = 1;
1302 /* Initialize base classes. */
1303 for (; (mem_inits
1304 && TREE_CODE (TREE_PURPOSE (mem_inits)) != FIELD_DECL);
1305 mem_inits = TREE_CHAIN (mem_inits))
1307 tree subobject = TREE_PURPOSE (mem_inits);
1308 tree arguments = TREE_VALUE (mem_inits);
1310 /* We already have issued an error message. */
1311 if (arguments == error_mark_node)
1312 continue;
1314 /* Suppress access control when calling the inherited ctor. */
1315 bool inherited_base = (DECL_INHERITED_CTOR (current_function_decl)
1316 && flag_new_inheriting_ctors
1317 && arguments);
1318 if (inherited_base)
1319 push_deferring_access_checks (dk_deferred);
1321 if (arguments == NULL_TREE)
1323 /* If these initializations are taking place in a copy constructor,
1324 the base class should probably be explicitly initialized if there
1325 is a user-defined constructor in the base class (other than the
1326 default constructor, which will be called anyway). */
1327 if (extra_warnings
1328 && DECL_COPY_CONSTRUCTOR_P (current_function_decl)
1329 && type_has_user_nondefault_constructor (BINFO_TYPE (subobject)))
1330 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1331 OPT_Wextra, "base class %q#T should be explicitly "
1332 "initialized in the copy constructor",
1333 BINFO_TYPE (subobject));
1336 /* Initialize the base. */
1337 if (!BINFO_VIRTUAL_P (subobject))
1339 tree base_addr;
1341 base_addr = build_base_path (PLUS_EXPR, current_class_ptr,
1342 subobject, 1, tf_warning_or_error);
1343 expand_aggr_init_1 (subobject, NULL_TREE,
1344 cp_build_fold_indirect_ref (base_addr),
1345 arguments,
1346 flags,
1347 tf_warning_or_error);
1348 expand_cleanup_for_base (subobject, NULL_TREE);
1350 else if (!ABSTRACT_CLASS_TYPE_P (current_class_type))
1351 /* C++14 DR1658 Means we do not have to construct vbases of
1352 abstract classes. */
1353 construct_virtual_base (subobject, arguments);
1354 else
1355 /* When not constructing vbases of abstract classes, at least mark
1356 the arguments expressions as read to avoid
1357 -Wunused-but-set-parameter false positives. */
1358 cp_walk_tree (&arguments, mark_exp_read_r, NULL, NULL);
1360 if (inherited_base)
1361 pop_deferring_access_checks ();
1363 in_base_initializer = 0;
1365 /* Initialize the vptrs. */
1366 initialize_vtbl_ptrs (current_class_ptr);
1368 /* Initialize the data members. */
1369 while (mem_inits)
1371 perform_member_init (TREE_PURPOSE (mem_inits),
1372 TREE_VALUE (mem_inits));
1373 mem_inits = TREE_CHAIN (mem_inits);
1377 /* Returns the address of the vtable (i.e., the value that should be
1378 assigned to the vptr) for BINFO. */
1380 tree
1381 build_vtbl_address (tree binfo)
1383 tree binfo_for = binfo;
1384 tree vtbl;
1386 if (BINFO_VPTR_INDEX (binfo) && BINFO_VIRTUAL_P (binfo))
1387 /* If this is a virtual primary base, then the vtable we want to store
1388 is that for the base this is being used as the primary base of. We
1389 can't simply skip the initialization, because we may be expanding the
1390 inits of a subobject constructor where the virtual base layout
1391 can be different. */
1392 while (BINFO_PRIMARY_P (binfo_for))
1393 binfo_for = BINFO_INHERITANCE_CHAIN (binfo_for);
1395 /* Figure out what vtable BINFO's vtable is based on, and mark it as
1396 used. */
1397 vtbl = get_vtbl_decl_for_binfo (binfo_for);
1398 TREE_USED (vtbl) = true;
1400 /* Now compute the address to use when initializing the vptr. */
1401 vtbl = unshare_expr (BINFO_VTABLE (binfo_for));
1402 if (VAR_P (vtbl))
1403 vtbl = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (vtbl)), vtbl);
1405 return vtbl;
1408 /* This code sets up the virtual function tables appropriate for
1409 the pointer DECL. It is a one-ply initialization.
1411 BINFO is the exact type that DECL is supposed to be. In
1412 multiple inheritance, this might mean "C's A" if C : A, B. */
1414 static void
1415 expand_virtual_init (tree binfo, tree decl)
1417 tree vtbl, vtbl_ptr;
1418 tree vtt_index;
1420 /* Compute the initializer for vptr. */
1421 vtbl = build_vtbl_address (binfo);
1423 /* We may get this vptr from a VTT, if this is a subobject
1424 constructor or subobject destructor. */
1425 vtt_index = BINFO_VPTR_INDEX (binfo);
1426 if (vtt_index)
1428 tree vtbl2;
1429 tree vtt_parm;
1431 /* Compute the value to use, when there's a VTT. */
1432 vtt_parm = current_vtt_parm;
1433 vtbl2 = fold_build_pointer_plus (vtt_parm, vtt_index);
1434 vtbl2 = cp_build_fold_indirect_ref (vtbl2);
1435 vtbl2 = convert (TREE_TYPE (vtbl), vtbl2);
1437 /* The actual initializer is the VTT value only in the subobject
1438 constructor. In maybe_clone_body we'll substitute NULL for
1439 the vtt_parm in the case of the non-subobject constructor. */
1440 vtbl = build_if_in_charge (vtbl, vtbl2);
1443 /* Compute the location of the vtpr. */
1444 vtbl_ptr = build_vfield_ref (cp_build_fold_indirect_ref (decl),
1445 TREE_TYPE (binfo));
1446 gcc_assert (vtbl_ptr != error_mark_node);
1448 /* Assign the vtable to the vptr. */
1449 vtbl = convert_force (TREE_TYPE (vtbl_ptr), vtbl, 0, tf_warning_or_error);
1450 finish_expr_stmt (cp_build_modify_expr (input_location, vtbl_ptr, NOP_EXPR,
1451 vtbl, tf_warning_or_error));
1454 /* If an exception is thrown in a constructor, those base classes already
1455 constructed must be destroyed. This function creates the cleanup
1456 for BINFO, which has just been constructed. If FLAG is non-NULL,
1457 it is a DECL which is nonzero when this base needs to be
1458 destroyed. */
1460 static void
1461 expand_cleanup_for_base (tree binfo, tree flag)
1463 tree expr;
1465 if (!type_build_dtor_call (BINFO_TYPE (binfo)))
1466 return;
1468 /* Call the destructor. */
1469 expr = build_special_member_call (current_class_ref,
1470 base_dtor_identifier,
1471 NULL,
1472 binfo,
1473 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
1474 tf_warning_or_error);
1476 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (BINFO_TYPE (binfo)))
1477 return;
1479 if (flag)
1480 expr = fold_build3_loc (input_location,
1481 COND_EXPR, void_type_node,
1482 c_common_truthvalue_conversion (input_location, flag),
1483 expr, integer_zero_node);
1485 finish_eh_cleanup (expr);
1488 /* Construct the virtual base-class VBASE passing the ARGUMENTS to its
1489 constructor. */
1491 static void
1492 construct_virtual_base (tree vbase, tree arguments)
1494 tree inner_if_stmt;
1495 tree exp;
1496 tree flag;
1498 /* If there are virtual base classes with destructors, we need to
1499 emit cleanups to destroy them if an exception is thrown during
1500 the construction process. These exception regions (i.e., the
1501 period during which the cleanups must occur) begin from the time
1502 the construction is complete to the end of the function. If we
1503 create a conditional block in which to initialize the
1504 base-classes, then the cleanup region for the virtual base begins
1505 inside a block, and ends outside of that block. This situation
1506 confuses the sjlj exception-handling code. Therefore, we do not
1507 create a single conditional block, but one for each
1508 initialization. (That way the cleanup regions always begin
1509 in the outer block.) We trust the back end to figure out
1510 that the FLAG will not change across initializations, and
1511 avoid doing multiple tests. */
1512 flag = DECL_CHAIN (DECL_ARGUMENTS (current_function_decl));
1513 inner_if_stmt = begin_if_stmt ();
1514 finish_if_stmt_cond (flag, inner_if_stmt);
1516 /* Compute the location of the virtual base. If we're
1517 constructing virtual bases, then we must be the most derived
1518 class. Therefore, we don't have to look up the virtual base;
1519 we already know where it is. */
1520 exp = convert_to_base_statically (current_class_ref, vbase);
1522 expand_aggr_init_1 (vbase, current_class_ref, exp, arguments,
1523 0, tf_warning_or_error);
1524 finish_then_clause (inner_if_stmt);
1525 finish_if_stmt (inner_if_stmt);
1527 expand_cleanup_for_base (vbase, flag);
1530 /* Find the context in which this FIELD can be initialized. */
1532 static tree
1533 initializing_context (tree field)
1535 tree t = DECL_CONTEXT (field);
1537 /* Anonymous union members can be initialized in the first enclosing
1538 non-anonymous union context. */
1539 while (t && ANON_AGGR_TYPE_P (t))
1540 t = TYPE_CONTEXT (t);
1541 return t;
1544 /* Function to give error message if member initialization specification
1545 is erroneous. FIELD is the member we decided to initialize.
1546 TYPE is the type for which the initialization is being performed.
1547 FIELD must be a member of TYPE.
1549 MEMBER_NAME is the name of the member. */
1551 static int
1552 member_init_ok_or_else (tree field, tree type, tree member_name)
1554 if (field == error_mark_node)
1555 return 0;
1556 if (!field)
1558 error ("class %qT does not have any field named %qD", type,
1559 member_name);
1560 return 0;
1562 if (VAR_P (field))
1564 error ("%q#D is a static data member; it can only be "
1565 "initialized at its definition",
1566 field);
1567 return 0;
1569 if (TREE_CODE (field) != FIELD_DECL)
1571 error ("%q#D is not a non-static data member of %qT",
1572 field, type);
1573 return 0;
1575 if (initializing_context (field) != type)
1577 error ("class %qT does not have any field named %qD", type,
1578 member_name);
1579 return 0;
1582 return 1;
1585 /* NAME is a FIELD_DECL, an IDENTIFIER_NODE which names a field, or it
1586 is a _TYPE node or TYPE_DECL which names a base for that type.
1587 Check the validity of NAME, and return either the base _TYPE, base
1588 binfo, or the FIELD_DECL of the member. If NAME is invalid, return
1589 NULL_TREE and issue a diagnostic.
1591 An old style unnamed direct single base construction is permitted,
1592 where NAME is NULL. */
1594 tree
1595 expand_member_init (tree name)
1597 tree basetype;
1598 tree field;
1600 if (!current_class_ref)
1601 return NULL_TREE;
1603 if (!name)
1605 /* This is an obsolete unnamed base class initializer. The
1606 parser will already have warned about its use. */
1607 switch (BINFO_N_BASE_BINFOS (TYPE_BINFO (current_class_type)))
1609 case 0:
1610 error ("unnamed initializer for %qT, which has no base classes",
1611 current_class_type);
1612 return NULL_TREE;
1613 case 1:
1614 basetype = BINFO_TYPE
1615 (BINFO_BASE_BINFO (TYPE_BINFO (current_class_type), 0));
1616 break;
1617 default:
1618 error ("unnamed initializer for %qT, which uses multiple inheritance",
1619 current_class_type);
1620 return NULL_TREE;
1623 else if (TYPE_P (name))
1625 basetype = TYPE_MAIN_VARIANT (name);
1626 name = TYPE_NAME (name);
1628 else if (TREE_CODE (name) == TYPE_DECL)
1629 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (name));
1630 else
1631 basetype = NULL_TREE;
1633 if (basetype)
1635 tree class_binfo;
1636 tree direct_binfo;
1637 tree virtual_binfo;
1638 int i;
1640 if (current_template_parms
1641 || same_type_p (basetype, current_class_type))
1642 return basetype;
1644 class_binfo = TYPE_BINFO (current_class_type);
1645 direct_binfo = NULL_TREE;
1646 virtual_binfo = NULL_TREE;
1648 /* Look for a direct base. */
1649 for (i = 0; BINFO_BASE_ITERATE (class_binfo, i, direct_binfo); ++i)
1650 if (SAME_BINFO_TYPE_P (BINFO_TYPE (direct_binfo), basetype))
1651 break;
1653 /* Look for a virtual base -- unless the direct base is itself
1654 virtual. */
1655 if (!direct_binfo || !BINFO_VIRTUAL_P (direct_binfo))
1656 virtual_binfo = binfo_for_vbase (basetype, current_class_type);
1658 /* [class.base.init]
1660 If a mem-initializer-id is ambiguous because it designates
1661 both a direct non-virtual base class and an inherited virtual
1662 base class, the mem-initializer is ill-formed. */
1663 if (direct_binfo && virtual_binfo)
1665 error ("%qD is both a direct base and an indirect virtual base",
1666 basetype);
1667 return NULL_TREE;
1670 if (!direct_binfo && !virtual_binfo)
1672 if (CLASSTYPE_VBASECLASSES (current_class_type))
1673 error ("type %qT is not a direct or virtual base of %qT",
1674 basetype, current_class_type);
1675 else
1676 error ("type %qT is not a direct base of %qT",
1677 basetype, current_class_type);
1678 return NULL_TREE;
1681 return direct_binfo ? direct_binfo : virtual_binfo;
1683 else
1685 if (identifier_p (name))
1686 field = lookup_field (current_class_type, name, 1, false);
1687 else
1688 field = name;
1690 if (member_init_ok_or_else (field, current_class_type, name))
1691 return field;
1694 return NULL_TREE;
1697 /* This is like `expand_member_init', only it stores one aggregate
1698 value into another.
1700 INIT comes in two flavors: it is either a value which
1701 is to be stored in EXP, or it is a parameter list
1702 to go to a constructor, which will operate on EXP.
1703 If INIT is not a parameter list for a constructor, then set
1704 LOOKUP_ONLYCONVERTING.
1705 If FLAGS is LOOKUP_ONLYCONVERTING then it is the = init form of
1706 the initializer, if FLAGS is 0, then it is the (init) form.
1707 If `init' is a CONSTRUCTOR, then we emit a warning message,
1708 explaining that such initializations are invalid.
1710 If INIT resolves to a CALL_EXPR which happens to return
1711 something of the type we are looking for, then we know
1712 that we can safely use that call to perform the
1713 initialization.
1715 The virtual function table pointer cannot be set up here, because
1716 we do not really know its type.
1718 This never calls operator=().
1720 When initializing, nothing is CONST.
1722 A default copy constructor may have to be used to perform the
1723 initialization.
1725 A constructor or a conversion operator may have to be used to
1726 perform the initialization, but not both, as it would be ambiguous. */
1728 tree
1729 build_aggr_init (tree exp, tree init, int flags, tsubst_flags_t complain)
1731 tree stmt_expr;
1732 tree compound_stmt;
1733 int destroy_temps;
1734 tree type = TREE_TYPE (exp);
1735 int was_const = TREE_READONLY (exp);
1736 int was_volatile = TREE_THIS_VOLATILE (exp);
1737 int is_global;
1739 if (init == error_mark_node)
1740 return error_mark_node;
1742 location_t init_loc = (init
1743 ? EXPR_LOC_OR_LOC (init, input_location)
1744 : location_of (exp));
1746 TREE_READONLY (exp) = 0;
1747 TREE_THIS_VOLATILE (exp) = 0;
1749 if (TREE_CODE (type) == ARRAY_TYPE)
1751 tree itype = init ? TREE_TYPE (init) : NULL_TREE;
1752 int from_array = 0;
1754 if (VAR_P (exp) && DECL_DECOMPOSITION_P (exp))
1756 from_array = 1;
1757 init = mark_rvalue_use (init);
1758 if (init && DECL_P (init)
1759 && !(flags & LOOKUP_ONLYCONVERTING))
1761 /* Wrap the initializer in a CONSTRUCTOR so that build_vec_init
1762 recognizes it as direct-initialization. */
1763 init = build_constructor_single (init_list_type_node,
1764 NULL_TREE, init);
1765 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
1768 else
1770 /* Must arrange to initialize each element of EXP
1771 from elements of INIT. */
1772 if (cv_qualified_p (type))
1773 TREE_TYPE (exp) = cv_unqualified (type);
1774 if (itype && cv_qualified_p (itype))
1775 TREE_TYPE (init) = cv_unqualified (itype);
1776 from_array = (itype && same_type_p (TREE_TYPE (init),
1777 TREE_TYPE (exp)));
1779 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init)
1780 && (!from_array
1781 || (TREE_CODE (init) != CONSTRUCTOR
1782 /* Can happen, eg, handling the compound-literals
1783 extension (ext/complit12.C). */
1784 && TREE_CODE (init) != TARGET_EXPR)))
1786 if (complain & tf_error)
1787 error_at (init_loc, "array must be initialized "
1788 "with a brace-enclosed initializer");
1789 return error_mark_node;
1793 stmt_expr = build_vec_init (exp, NULL_TREE, init,
1794 /*explicit_value_init_p=*/false,
1795 from_array,
1796 complain);
1797 TREE_READONLY (exp) = was_const;
1798 TREE_THIS_VOLATILE (exp) = was_volatile;
1799 TREE_TYPE (exp) = type;
1800 /* Restore the type of init unless it was used directly. */
1801 if (init && TREE_CODE (stmt_expr) != INIT_EXPR)
1802 TREE_TYPE (init) = itype;
1803 return stmt_expr;
1806 if (init && init != void_type_node
1807 && TREE_CODE (init) != TREE_LIST
1808 && !(TREE_CODE (init) == TARGET_EXPR
1809 && TARGET_EXPR_DIRECT_INIT_P (init))
1810 && !DIRECT_LIST_INIT_P (init))
1811 flags |= LOOKUP_ONLYCONVERTING;
1813 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
1814 destroy_temps = stmts_are_full_exprs_p ();
1815 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
1816 expand_aggr_init_1 (TYPE_BINFO (type), exp, exp,
1817 init, LOOKUP_NORMAL|flags, complain);
1818 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
1819 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
1820 TREE_READONLY (exp) = was_const;
1821 TREE_THIS_VOLATILE (exp) = was_volatile;
1823 if ((VAR_P (exp) || TREE_CODE (exp) == PARM_DECL)
1824 && TREE_SIDE_EFFECTS (stmt_expr)
1825 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (type)))
1826 /* Just know that we've seen something for this node. */
1827 TREE_USED (exp) = 1;
1829 return stmt_expr;
1832 static void
1833 expand_default_init (tree binfo, tree true_exp, tree exp, tree init, int flags,
1834 tsubst_flags_t complain)
1836 tree type = TREE_TYPE (exp);
1838 /* It fails because there may not be a constructor which takes
1839 its own type as the first (or only parameter), but which does
1840 take other types via a conversion. So, if the thing initializing
1841 the expression is a unit element of type X, first try X(X&),
1842 followed by initialization by X. If neither of these work
1843 out, then look hard. */
1844 tree rval;
1845 vec<tree, va_gc> *parms;
1847 /* If we have direct-initialization from an initializer list, pull
1848 it out of the TREE_LIST so the code below can see it. */
1849 if (init && TREE_CODE (init) == TREE_LIST
1850 && DIRECT_LIST_INIT_P (TREE_VALUE (init)))
1852 gcc_checking_assert ((flags & LOOKUP_ONLYCONVERTING) == 0
1853 && TREE_CHAIN (init) == NULL_TREE);
1854 init = TREE_VALUE (init);
1855 /* Only call reshape_init if it has not been called earlier
1856 by the callers. */
1857 if (BRACE_ENCLOSED_INITIALIZER_P (init) && CP_AGGREGATE_TYPE_P (type))
1858 init = reshape_init (type, init, complain);
1861 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
1862 && CP_AGGREGATE_TYPE_P (type))
1863 /* A brace-enclosed initializer for an aggregate. In C++0x this can
1864 happen for direct-initialization, too. */
1865 init = digest_init (type, init, complain);
1867 /* A CONSTRUCTOR of the target's type is a previously digested
1868 initializer, whether that happened just above or in
1869 cp_parser_late_parsing_nsdmi.
1871 A TARGET_EXPR with TARGET_EXPR_DIRECT_INIT_P or TARGET_EXPR_LIST_INIT_P
1872 set represents the whole initialization, so we shouldn't build up
1873 another ctor call. */
1874 if (init
1875 && (TREE_CODE (init) == CONSTRUCTOR
1876 || (TREE_CODE (init) == TARGET_EXPR
1877 && (TARGET_EXPR_DIRECT_INIT_P (init)
1878 || TARGET_EXPR_LIST_INIT_P (init))))
1879 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
1881 /* Early initialization via a TARGET_EXPR only works for
1882 complete objects. */
1883 gcc_assert (TREE_CODE (init) == CONSTRUCTOR || true_exp == exp);
1885 init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
1886 TREE_SIDE_EFFECTS (init) = 1;
1887 finish_expr_stmt (init);
1888 return;
1891 if (init && TREE_CODE (init) != TREE_LIST
1892 && (flags & LOOKUP_ONLYCONVERTING))
1894 /* Base subobjects should only get direct-initialization. */
1895 gcc_assert (true_exp == exp);
1897 if (flags & DIRECT_BIND)
1898 /* Do nothing. We hit this in two cases: Reference initialization,
1899 where we aren't initializing a real variable, so we don't want
1900 to run a new constructor; and catching an exception, where we
1901 have already built up the constructor call so we could wrap it
1902 in an exception region. */;
1903 else
1904 init = ocp_convert (type, init, CONV_IMPLICIT|CONV_FORCE_TEMP,
1905 flags, complain);
1907 if (TREE_CODE (init) == MUST_NOT_THROW_EXPR)
1908 /* We need to protect the initialization of a catch parm with a
1909 call to terminate(), which shows up as a MUST_NOT_THROW_EXPR
1910 around the TARGET_EXPR for the copy constructor. See
1911 initialize_handler_parm. */
1913 TREE_OPERAND (init, 0) = build2 (INIT_EXPR, TREE_TYPE (exp), exp,
1914 TREE_OPERAND (init, 0));
1915 TREE_TYPE (init) = void_type_node;
1917 else
1918 init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
1919 TREE_SIDE_EFFECTS (init) = 1;
1920 finish_expr_stmt (init);
1921 return;
1924 if (init == NULL_TREE)
1925 parms = NULL;
1926 else if (TREE_CODE (init) == TREE_LIST && !TREE_TYPE (init))
1928 parms = make_tree_vector ();
1929 for (; init != NULL_TREE; init = TREE_CHAIN (init))
1930 vec_safe_push (parms, TREE_VALUE (init));
1932 else
1933 parms = make_tree_vector_single (init);
1935 if (exp == current_class_ref && current_function_decl
1936 && DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
1938 /* Delegating constructor. */
1939 tree complete;
1940 tree base;
1941 tree elt; unsigned i;
1943 /* Unshare the arguments for the second call. */
1944 vec<tree, va_gc> *parms2 = make_tree_vector ();
1945 FOR_EACH_VEC_SAFE_ELT (parms, i, elt)
1947 elt = break_out_target_exprs (elt);
1948 vec_safe_push (parms2, elt);
1950 complete = build_special_member_call (exp, complete_ctor_identifier,
1951 &parms2, binfo, flags,
1952 complain);
1953 complete = fold_build_cleanup_point_expr (void_type_node, complete);
1954 release_tree_vector (parms2);
1956 base = build_special_member_call (exp, base_ctor_identifier,
1957 &parms, binfo, flags,
1958 complain);
1959 base = fold_build_cleanup_point_expr (void_type_node, base);
1960 rval = build_if_in_charge (complete, base);
1962 else
1964 tree ctor_name = (true_exp == exp
1965 ? complete_ctor_identifier : base_ctor_identifier);
1967 rval = build_special_member_call (exp, ctor_name, &parms, binfo, flags,
1968 complain);
1971 if (parms != NULL)
1972 release_tree_vector (parms);
1974 if (exp == true_exp && TREE_CODE (rval) == CALL_EXPR)
1976 tree fn = get_callee_fndecl (rval);
1977 if (fn && DECL_DECLARED_CONSTEXPR_P (fn))
1979 tree e = maybe_constant_init (rval, exp);
1980 if (TREE_CONSTANT (e))
1981 rval = build2 (INIT_EXPR, type, exp, e);
1985 /* FIXME put back convert_to_void? */
1986 if (TREE_SIDE_EFFECTS (rval))
1987 finish_expr_stmt (rval);
1990 /* This function is responsible for initializing EXP with INIT
1991 (if any).
1993 BINFO is the binfo of the type for who we are performing the
1994 initialization. For example, if W is a virtual base class of A and B,
1995 and C : A, B.
1996 If we are initializing B, then W must contain B's W vtable, whereas
1997 were we initializing C, W must contain C's W vtable.
1999 TRUE_EXP is nonzero if it is the true expression being initialized.
2000 In this case, it may be EXP, or may just contain EXP. The reason we
2001 need this is because if EXP is a base element of TRUE_EXP, we
2002 don't necessarily know by looking at EXP where its virtual
2003 baseclass fields should really be pointing. But we do know
2004 from TRUE_EXP. In constructors, we don't know anything about
2005 the value being initialized.
2007 FLAGS is just passed to `build_new_method_call'. See that function
2008 for its description. */
2010 static void
2011 expand_aggr_init_1 (tree binfo, tree true_exp, tree exp, tree init, int flags,
2012 tsubst_flags_t complain)
2014 tree type = TREE_TYPE (exp);
2016 gcc_assert (init != error_mark_node && type != error_mark_node);
2017 gcc_assert (building_stmt_list_p ());
2019 /* Use a function returning the desired type to initialize EXP for us.
2020 If the function is a constructor, and its first argument is
2021 NULL_TREE, know that it was meant for us--just slide exp on
2022 in and expand the constructor. Constructors now come
2023 as TARGET_EXPRs. */
2025 if (init && VAR_P (exp)
2026 && COMPOUND_LITERAL_P (init))
2028 vec<tree, va_gc> *cleanups = NULL;
2029 /* If store_init_value returns NULL_TREE, the INIT has been
2030 recorded as the DECL_INITIAL for EXP. That means there's
2031 nothing more we have to do. */
2032 init = store_init_value (exp, init, &cleanups, flags);
2033 if (init)
2034 finish_expr_stmt (init);
2035 gcc_assert (!cleanups);
2036 return;
2039 /* List-initialization from {} becomes value-initialization for non-aggregate
2040 classes with default constructors. Handle this here when we're
2041 initializing a base, so protected access works. */
2042 if (exp != true_exp && init && TREE_CODE (init) == TREE_LIST)
2044 tree elt = TREE_VALUE (init);
2045 if (DIRECT_LIST_INIT_P (elt)
2046 && CONSTRUCTOR_ELTS (elt) == 0
2047 && CLASSTYPE_NON_AGGREGATE (type)
2048 && TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
2049 init = void_type_node;
2052 /* If an explicit -- but empty -- initializer list was present,
2053 that's value-initialization. */
2054 if (init == void_type_node)
2056 /* If the type has data but no user-provided ctor, we need to zero
2057 out the object. */
2058 if (!type_has_user_provided_constructor (type)
2059 && !is_really_empty_class (type))
2061 tree field_size = NULL_TREE;
2062 if (exp != true_exp && CLASSTYPE_AS_BASE (type) != type)
2063 /* Don't clobber already initialized virtual bases. */
2064 field_size = TYPE_SIZE (CLASSTYPE_AS_BASE (type));
2065 init = build_zero_init_1 (type, NULL_TREE, /*static_storage_p=*/false,
2066 field_size);
2067 init = build2 (INIT_EXPR, type, exp, init);
2068 finish_expr_stmt (init);
2071 /* If we don't need to mess with the constructor at all,
2072 then we're done. */
2073 if (! type_build_ctor_call (type))
2074 return;
2076 /* Otherwise fall through and call the constructor. */
2077 init = NULL_TREE;
2080 /* We know that expand_default_init can handle everything we want
2081 at this point. */
2082 expand_default_init (binfo, true_exp, exp, init, flags, complain);
2085 /* Report an error if TYPE is not a user-defined, class type. If
2086 OR_ELSE is nonzero, give an error message. */
2089 is_class_type (tree type, int or_else)
2091 if (type == error_mark_node)
2092 return 0;
2094 if (! CLASS_TYPE_P (type))
2096 if (or_else)
2097 error ("%qT is not a class type", type);
2098 return 0;
2100 return 1;
2103 tree
2104 get_type_value (tree name)
2106 if (name == error_mark_node)
2107 return NULL_TREE;
2109 if (IDENTIFIER_HAS_TYPE_VALUE (name))
2110 return IDENTIFIER_TYPE_VALUE (name);
2111 else
2112 return NULL_TREE;
2115 /* Build a reference to a member of an aggregate. This is not a C++
2116 `&', but really something which can have its address taken, and
2117 then act as a pointer to member, for example TYPE :: FIELD can have
2118 its address taken by saying & TYPE :: FIELD. ADDRESS_P is true if
2119 this expression is the operand of "&".
2121 @@ Prints out lousy diagnostics for operator <typename>
2122 @@ fields.
2124 @@ This function should be rewritten and placed in search.c. */
2126 tree
2127 build_offset_ref (tree type, tree member, bool address_p,
2128 tsubst_flags_t complain)
2130 tree decl;
2131 tree basebinfo = NULL_TREE;
2133 /* class templates can come in as TEMPLATE_DECLs here. */
2134 if (TREE_CODE (member) == TEMPLATE_DECL)
2135 return member;
2137 if (dependent_scope_p (type) || type_dependent_expression_p (member))
2138 return build_qualified_name (NULL_TREE, type, member,
2139 /*template_p=*/false);
2141 gcc_assert (TYPE_P (type));
2142 if (! is_class_type (type, 1))
2143 return error_mark_node;
2145 gcc_assert (DECL_P (member) || BASELINK_P (member));
2146 /* Callers should call mark_used before this point. */
2147 gcc_assert (!DECL_P (member) || TREE_USED (member));
2149 type = TYPE_MAIN_VARIANT (type);
2150 if (!COMPLETE_OR_OPEN_TYPE_P (complete_type (type)))
2152 if (complain & tf_error)
2153 error ("incomplete type %qT does not have member %qD", type, member);
2154 return error_mark_node;
2157 /* Entities other than non-static members need no further
2158 processing. */
2159 if (TREE_CODE (member) == TYPE_DECL)
2160 return member;
2161 if (VAR_P (member) || TREE_CODE (member) == CONST_DECL)
2162 return convert_from_reference (member);
2164 if (TREE_CODE (member) == FIELD_DECL && DECL_C_BIT_FIELD (member))
2166 if (complain & tf_error)
2167 error ("invalid pointer to bit-field %qD", member);
2168 return error_mark_node;
2171 /* Set up BASEBINFO for member lookup. */
2172 decl = maybe_dummy_object (type, &basebinfo);
2174 /* A lot of this logic is now handled in lookup_member. */
2175 if (BASELINK_P (member))
2177 /* Go from the TREE_BASELINK to the member function info. */
2178 tree t = BASELINK_FUNCTIONS (member);
2180 if (TREE_CODE (t) != TEMPLATE_ID_EXPR && !really_overloaded_fn (t))
2182 /* Get rid of a potential OVERLOAD around it. */
2183 t = OVL_FIRST (t);
2185 /* Unique functions are handled easily. */
2187 /* For non-static member of base class, we need a special rule
2188 for access checking [class.protected]:
2190 If the access is to form a pointer to member, the
2191 nested-name-specifier shall name the derived class
2192 (or any class derived from that class). */
2193 bool ok;
2194 if (address_p && DECL_P (t)
2195 && DECL_NONSTATIC_MEMBER_P (t))
2196 ok = perform_or_defer_access_check (TYPE_BINFO (type), t, t,
2197 complain);
2198 else
2199 ok = perform_or_defer_access_check (basebinfo, t, t,
2200 complain);
2201 if (!ok)
2202 return error_mark_node;
2203 if (DECL_STATIC_FUNCTION_P (t))
2204 return t;
2205 member = t;
2207 else
2208 TREE_TYPE (member) = unknown_type_node;
2210 else if (address_p && TREE_CODE (member) == FIELD_DECL)
2212 /* We need additional test besides the one in
2213 check_accessibility_of_qualified_id in case it is
2214 a pointer to non-static member. */
2215 if (!perform_or_defer_access_check (TYPE_BINFO (type), member, member,
2216 complain))
2217 return error_mark_node;
2220 if (!address_p)
2222 /* If MEMBER is non-static, then the program has fallen afoul of
2223 [expr.prim]:
2225 An id-expression that denotes a nonstatic data member or
2226 nonstatic member function of a class can only be used:
2228 -- as part of a class member access (_expr.ref_) in which the
2229 object-expression refers to the member's class or a class
2230 derived from that class, or
2232 -- to form a pointer to member (_expr.unary.op_), or
2234 -- in the body of a nonstatic member function of that class or
2235 of a class derived from that class (_class.mfct.nonstatic_), or
2237 -- in a mem-initializer for a constructor for that class or for
2238 a class derived from that class (_class.base.init_). */
2239 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (member))
2241 /* Build a representation of the qualified name suitable
2242 for use as the operand to "&" -- even though the "&" is
2243 not actually present. */
2244 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2245 /* In Microsoft mode, treat a non-static member function as if
2246 it were a pointer-to-member. */
2247 if (flag_ms_extensions)
2249 PTRMEM_OK_P (member) = 1;
2250 return cp_build_addr_expr (member, complain);
2252 if (complain & tf_error)
2253 error ("invalid use of non-static member function %qD",
2254 TREE_OPERAND (member, 1));
2255 return error_mark_node;
2257 else if (TREE_CODE (member) == FIELD_DECL)
2259 if (complain & tf_error)
2260 error ("invalid use of non-static data member %qD", member);
2261 return error_mark_node;
2263 return member;
2266 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2267 PTRMEM_OK_P (member) = 1;
2268 return member;
2271 /* If DECL is a scalar enumeration constant or variable with a
2272 constant initializer, return the initializer (or, its initializers,
2273 recursively); otherwise, return DECL. If STRICT_P, the
2274 initializer is only returned if DECL is a
2275 constant-expression. If RETURN_AGGREGATE_CST_OK_P, it is ok to
2276 return an aggregate constant. */
2278 static tree
2279 constant_value_1 (tree decl, bool strict_p, bool return_aggregate_cst_ok_p)
2281 while (TREE_CODE (decl) == CONST_DECL
2282 || decl_constant_var_p (decl)
2283 || (!strict_p && VAR_P (decl)
2284 && CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (decl))))
2286 tree init;
2287 /* If DECL is a static data member in a template
2288 specialization, we must instantiate it here. The
2289 initializer for the static data member is not processed
2290 until needed; we need it now. */
2291 mark_used (decl, tf_none);
2292 init = DECL_INITIAL (decl);
2293 if (init == error_mark_node)
2295 if (TREE_CODE (decl) == CONST_DECL
2296 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2297 /* Treat the error as a constant to avoid cascading errors on
2298 excessively recursive template instantiation (c++/9335). */
2299 return init;
2300 else
2301 return decl;
2303 /* Initializers in templates are generally expanded during
2304 instantiation, so before that for const int i(2)
2305 INIT is a TREE_LIST with the actual initializer as
2306 TREE_VALUE. */
2307 if (processing_template_decl
2308 && init
2309 && TREE_CODE (init) == TREE_LIST
2310 && TREE_CHAIN (init) == NULL_TREE)
2311 init = TREE_VALUE (init);
2312 /* Instantiate a non-dependent initializer for user variables. We
2313 mustn't do this for the temporary for an array compound literal;
2314 trying to instatiate the initializer will keep creating new
2315 temporaries until we crash. Probably it's not useful to do it for
2316 other artificial variables, either. */
2317 if (!DECL_ARTIFICIAL (decl))
2318 init = instantiate_non_dependent_or_null (init);
2319 if (!init
2320 || !TREE_TYPE (init)
2321 || !TREE_CONSTANT (init)
2322 || (!return_aggregate_cst_ok_p
2323 /* Unless RETURN_AGGREGATE_CST_OK_P is true, do not
2324 return an aggregate constant (of which string
2325 literals are a special case), as we do not want
2326 to make inadvertent copies of such entities, and
2327 we must be sure that their addresses are the
2328 same everywhere. */
2329 && (TREE_CODE (init) == CONSTRUCTOR
2330 || TREE_CODE (init) == STRING_CST)))
2331 break;
2332 /* Don't return a CONSTRUCTOR for a variable with partial run-time
2333 initialization, since it doesn't represent the entire value. */
2334 if (TREE_CODE (init) == CONSTRUCTOR
2335 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2336 break;
2337 /* If the variable has a dynamic initializer, don't use its
2338 DECL_INITIAL which doesn't reflect the real value. */
2339 if (VAR_P (decl)
2340 && TREE_STATIC (decl)
2341 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)
2342 && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2343 break;
2344 decl = unshare_expr (init);
2346 return decl;
2349 /* If DECL is a CONST_DECL, or a constant VAR_DECL initialized by constant
2350 of integral or enumeration type, or a constexpr variable of scalar type,
2351 then return that value. These are those variables permitted in constant
2352 expressions by [5.19/1]. */
2354 tree
2355 scalar_constant_value (tree decl)
2357 return constant_value_1 (decl, /*strict_p=*/true,
2358 /*return_aggregate_cst_ok_p=*/false);
2361 /* Like scalar_constant_value, but can also return aggregate initializers. */
2363 tree
2364 decl_really_constant_value (tree decl)
2366 return constant_value_1 (decl, /*strict_p=*/true,
2367 /*return_aggregate_cst_ok_p=*/true);
2370 /* A more relaxed version of scalar_constant_value, used by the
2371 common C/C++ code. */
2373 tree
2374 decl_constant_value (tree decl)
2376 return constant_value_1 (decl, /*strict_p=*/processing_template_decl,
2377 /*return_aggregate_cst_ok_p=*/true);
2380 /* Common subroutines of build_new and build_vec_delete. */
2382 /* Build and return a NEW_EXPR. If NELTS is non-NULL, TYPE[NELTS] is
2383 the type of the object being allocated; otherwise, it's just TYPE.
2384 INIT is the initializer, if any. USE_GLOBAL_NEW is true if the
2385 user explicitly wrote "::operator new". PLACEMENT, if non-NULL, is
2386 a vector of arguments to be provided as arguments to a placement
2387 new operator. This routine performs no semantic checks; it just
2388 creates and returns a NEW_EXPR. */
2390 static tree
2391 build_raw_new_expr (vec<tree, va_gc> *placement, tree type, tree nelts,
2392 vec<tree, va_gc> *init, int use_global_new)
2394 tree init_list;
2395 tree new_expr;
2397 /* If INIT is NULL, the we want to store NULL_TREE in the NEW_EXPR.
2398 If INIT is not NULL, then we want to store VOID_ZERO_NODE. This
2399 permits us to distinguish the case of a missing initializer "new
2400 int" from an empty initializer "new int()". */
2401 if (init == NULL)
2402 init_list = NULL_TREE;
2403 else if (init->is_empty ())
2404 init_list = void_node;
2405 else
2407 init_list = build_tree_list_vec (init);
2408 for (tree v = init_list; v; v = TREE_CHAIN (v))
2409 if (TREE_CODE (TREE_VALUE (v)) == OVERLOAD)
2410 lookup_keep (TREE_VALUE (v), true);
2413 new_expr = build4 (NEW_EXPR, build_pointer_type (type),
2414 build_tree_list_vec (placement), type, nelts,
2415 init_list);
2416 NEW_EXPR_USE_GLOBAL (new_expr) = use_global_new;
2417 TREE_SIDE_EFFECTS (new_expr) = 1;
2419 return new_expr;
2422 /* Diagnose uninitialized const members or reference members of type
2423 TYPE. USING_NEW is used to disambiguate the diagnostic between a
2424 new expression without a new-initializer and a declaration. Returns
2425 the error count. */
2427 static int
2428 diagnose_uninitialized_cst_or_ref_member_1 (tree type, tree origin,
2429 bool using_new, bool complain)
2431 tree field;
2432 int error_count = 0;
2434 if (type_has_user_provided_constructor (type))
2435 return 0;
2437 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
2439 tree field_type;
2441 if (TREE_CODE (field) != FIELD_DECL)
2442 continue;
2444 field_type = strip_array_types (TREE_TYPE (field));
2446 if (type_has_user_provided_constructor (field_type))
2447 continue;
2449 if (TYPE_REF_P (field_type))
2451 ++ error_count;
2452 if (complain)
2454 if (DECL_CONTEXT (field) == origin)
2456 if (using_new)
2457 error ("uninitialized reference member in %q#T "
2458 "using %<new%> without new-initializer", origin);
2459 else
2460 error ("uninitialized reference member in %q#T", origin);
2462 else
2464 if (using_new)
2465 error ("uninitialized reference member in base %q#T "
2466 "of %q#T using %<new%> without new-initializer",
2467 DECL_CONTEXT (field), origin);
2468 else
2469 error ("uninitialized reference member in base %q#T "
2470 "of %q#T", DECL_CONTEXT (field), origin);
2472 inform (DECL_SOURCE_LOCATION (field),
2473 "%q#D should be initialized", field);
2477 if (CP_TYPE_CONST_P (field_type))
2479 ++ error_count;
2480 if (complain)
2482 if (DECL_CONTEXT (field) == origin)
2484 if (using_new)
2485 error ("uninitialized const member in %q#T "
2486 "using %<new%> without new-initializer", origin);
2487 else
2488 error ("uninitialized const member in %q#T", origin);
2490 else
2492 if (using_new)
2493 error ("uninitialized const member in base %q#T "
2494 "of %q#T using %<new%> without new-initializer",
2495 DECL_CONTEXT (field), origin);
2496 else
2497 error ("uninitialized const member in base %q#T "
2498 "of %q#T", DECL_CONTEXT (field), origin);
2500 inform (DECL_SOURCE_LOCATION (field),
2501 "%q#D should be initialized", field);
2505 if (CLASS_TYPE_P (field_type))
2506 error_count
2507 += diagnose_uninitialized_cst_or_ref_member_1 (field_type, origin,
2508 using_new, complain);
2510 return error_count;
2514 diagnose_uninitialized_cst_or_ref_member (tree type, bool using_new, bool complain)
2516 return diagnose_uninitialized_cst_or_ref_member_1 (type, type, using_new, complain);
2519 /* Call __cxa_bad_array_new_length to indicate that the size calculation
2520 overflowed. Pretend it returns sizetype so that it plays nicely in the
2521 COND_EXPR. */
2523 tree
2524 throw_bad_array_new_length (void)
2526 if (!fn)
2528 tree name = get_identifier ("__cxa_throw_bad_array_new_length");
2530 fn = get_global_binding (name);
2531 if (!fn)
2532 fn = push_throw_library_fn
2533 (name, build_function_type_list (sizetype, NULL_TREE));
2536 return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
2539 /* Attempt to find the initializer for flexible array field T in the
2540 initializer INIT, when non-null. Returns the initializer when
2541 successful and NULL otherwise. */
2542 static tree
2543 find_flexarray_init (tree t, tree init)
2545 if (!init || init == error_mark_node)
2546 return NULL_TREE;
2548 unsigned HOST_WIDE_INT idx;
2549 tree field, elt;
2551 /* Iterate over all top-level initializer elements. */
2552 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
2553 /* If the member T is found, return it. */
2554 if (field == t)
2555 return elt;
2557 return NULL_TREE;
2560 /* Attempt to verify that the argument, OPER, of a placement new expression
2561 refers to an object sufficiently large for an object of TYPE or an array
2562 of NELTS of such objects when NELTS is non-null, and issue a warning when
2563 it does not. SIZE specifies the size needed to construct the object or
2564 array and captures the result of NELTS * sizeof (TYPE). (SIZE could be
2565 greater when the array under construction requires a cookie to store
2566 NELTS. GCC's placement new expression stores the cookie when invoking
2567 a user-defined placement new operator function but not the default one.
2568 Placement new expressions with user-defined placement new operator are
2569 not diagnosed since we don't know how they use the buffer (this could
2570 be a future extension). */
2571 static void
2572 warn_placement_new_too_small (tree type, tree nelts, tree size, tree oper)
2574 location_t loc = EXPR_LOC_OR_LOC (oper, input_location);
2576 /* The number of bytes to add to or subtract from the size of the provided
2577 buffer based on an offset into an array or an array element reference.
2578 Although intermediate results may be negative (as in a[3] - 2) a valid
2579 final result cannot be. */
2580 offset_int adjust = 0;
2581 /* True when the size of the entire destination object should be used
2582 to compute the possibly optimistic estimate of the available space. */
2583 bool use_obj_size = false;
2584 /* True when the reference to the destination buffer is an ADDR_EXPR. */
2585 bool addr_expr = false;
2587 STRIP_NOPS (oper);
2589 /* Using a function argument or a (non-array) variable as an argument
2590 to placement new is not checked since it's unknown what it might
2591 point to. */
2592 if (TREE_CODE (oper) == PARM_DECL
2593 || VAR_P (oper)
2594 || TREE_CODE (oper) == COMPONENT_REF)
2595 return;
2597 /* Evaluate any constant expressions. */
2598 size = fold_non_dependent_expr (size);
2600 /* Handle the common case of array + offset expression when the offset
2601 is a constant. */
2602 if (TREE_CODE (oper) == POINTER_PLUS_EXPR)
2604 /* If the offset is compile-time constant, use it to compute a more
2605 accurate estimate of the size of the buffer. Since the operand
2606 of POINTER_PLUS_EXPR is represented as an unsigned type, convert
2607 it to signed first.
2608 Otherwise, use the size of the entire array as an optimistic
2609 estimate (this may lead to false negatives). */
2610 tree adj = TREE_OPERAND (oper, 1);
2611 if (CONSTANT_CLASS_P (adj))
2612 adjust += wi::to_offset (convert (ssizetype, adj));
2613 else
2614 use_obj_size = true;
2616 oper = TREE_OPERAND (oper, 0);
2618 STRIP_NOPS (oper);
2621 if (TREE_CODE (oper) == TARGET_EXPR)
2622 oper = TREE_OPERAND (oper, 1);
2623 else if (TREE_CODE (oper) == ADDR_EXPR)
2625 addr_expr = true;
2626 oper = TREE_OPERAND (oper, 0);
2629 STRIP_NOPS (oper);
2631 if (TREE_CODE (oper) == ARRAY_REF
2632 && (addr_expr || TREE_CODE (TREE_TYPE (oper)) == ARRAY_TYPE))
2634 /* Similar to the offset computed above, see if the array index
2635 is a compile-time constant. If so, and unless the offset was
2636 not a compile-time constant, use the index to determine the
2637 size of the buffer. Otherwise, use the entire array as
2638 an optimistic estimate of the size. */
2639 const_tree adj = fold_non_dependent_expr (TREE_OPERAND (oper, 1));
2640 if (!use_obj_size && CONSTANT_CLASS_P (adj))
2641 adjust += wi::to_offset (adj);
2642 else
2644 use_obj_size = true;
2645 adjust = 0;
2648 oper = TREE_OPERAND (oper, 0);
2651 /* Refers to the declared object that constains the subobject referenced
2652 by OPER. When the object is initialized, makes it possible to determine
2653 the actual size of a flexible array member used as the buffer passed
2654 as OPER to placement new. */
2655 tree var_decl = NULL_TREE;
2656 /* True when operand is a COMPONENT_REF, to distinguish flexible array
2657 members from arrays of unspecified size. */
2658 bool compref = TREE_CODE (oper) == COMPONENT_REF;
2660 /* For COMPONENT_REF (i.e., a struct member) the size of the entire
2661 enclosing struct. Used to validate the adjustment (offset) into
2662 an array at the end of a struct. */
2663 offset_int compsize = 0;
2665 /* Descend into a struct or union to find the member whose address
2666 is being used as the argument. */
2667 if (TREE_CODE (oper) == COMPONENT_REF)
2669 tree comptype = TREE_TYPE (TREE_OPERAND (oper, 0));
2670 compsize = wi::to_offset (TYPE_SIZE_UNIT (comptype));
2672 tree op0 = oper;
2673 while (TREE_CODE (op0 = TREE_OPERAND (op0, 0)) == COMPONENT_REF);
2674 if (VAR_P (op0))
2675 var_decl = op0;
2676 oper = TREE_OPERAND (oper, 1);
2679 tree opertype = TREE_TYPE (oper);
2680 if ((addr_expr || !INDIRECT_TYPE_P (opertype))
2681 && (VAR_P (oper)
2682 || TREE_CODE (oper) == FIELD_DECL
2683 || TREE_CODE (oper) == PARM_DECL))
2685 /* A possibly optimistic estimate of the number of bytes available
2686 in the destination buffer. */
2687 offset_int bytes_avail = 0;
2688 /* True when the estimate above is in fact the exact size
2689 of the destination buffer rather than an estimate. */
2690 bool exact_size = true;
2692 /* Treat members of unions and members of structs uniformly, even
2693 though the size of a member of a union may be viewed as extending
2694 to the end of the union itself (it is by __builtin_object_size). */
2695 if ((VAR_P (oper) || use_obj_size)
2696 && DECL_SIZE_UNIT (oper)
2697 && tree_fits_uhwi_p (DECL_SIZE_UNIT (oper)))
2699 /* Use the size of the entire array object when the expression
2700 refers to a variable or its size depends on an expression
2701 that's not a compile-time constant. */
2702 bytes_avail = wi::to_offset (DECL_SIZE_UNIT (oper));
2703 exact_size = !use_obj_size;
2705 else if (tree opersize = TYPE_SIZE_UNIT (opertype))
2707 /* Use the size of the type of the destination buffer object
2708 as the optimistic estimate of the available space in it.
2709 Use the maximum possible size for zero-size arrays and
2710 flexible array members (except of initialized objects
2711 thereof). */
2712 if (TREE_CODE (opersize) == INTEGER_CST)
2713 bytes_avail = wi::to_offset (opersize);
2716 if (bytes_avail == 0)
2718 if (var_decl)
2720 /* Constructing into a buffer provided by the flexible array
2721 member of a declared object (which is permitted as a G++
2722 extension). If the array member has been initialized,
2723 determine its size from the initializer. Otherwise,
2724 the array size is zero. */
2725 if (tree init = find_flexarray_init (oper,
2726 DECL_INITIAL (var_decl)))
2727 bytes_avail = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (init)));
2729 else
2730 bytes_avail = (wi::to_offset (TYPE_MAX_VALUE (ptrdiff_type_node))
2731 - compsize);
2734 tree_code oper_code = TREE_CODE (opertype);
2736 if (compref && oper_code == ARRAY_TYPE)
2738 tree nelts = array_type_nelts_top (opertype);
2739 tree nelts_cst = maybe_constant_value (nelts);
2740 if (TREE_CODE (nelts_cst) == INTEGER_CST
2741 && integer_onep (nelts_cst)
2742 && !var_decl
2743 && warn_placement_new < 2)
2744 return;
2747 /* Reduce the size of the buffer by the adjustment computed above
2748 from the offset and/or the index into the array. */
2749 if (bytes_avail < adjust || adjust < 0)
2750 bytes_avail = 0;
2751 else
2753 tree elttype = (TREE_CODE (opertype) == ARRAY_TYPE
2754 ? TREE_TYPE (opertype) : opertype);
2755 if (tree eltsize = TYPE_SIZE_UNIT (elttype))
2757 bytes_avail -= adjust * wi::to_offset (eltsize);
2758 if (bytes_avail < 0)
2759 bytes_avail = 0;
2763 /* The minimum amount of space needed for the allocation. This
2764 is an optimistic estimate that makes it possible to detect
2765 placement new invocation for some undersize buffers but not
2766 others. */
2767 offset_int bytes_need;
2769 if (CONSTANT_CLASS_P (size))
2770 bytes_need = wi::to_offset (size);
2771 else if (nelts && CONSTANT_CLASS_P (nelts))
2772 bytes_need = (wi::to_offset (nelts)
2773 * wi::to_offset (TYPE_SIZE_UNIT (type)));
2774 else if (tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2775 bytes_need = wi::to_offset (TYPE_SIZE_UNIT (type));
2776 else
2778 /* The type is a VLA. */
2779 return;
2782 if (bytes_avail < bytes_need)
2784 if (nelts)
2785 if (CONSTANT_CLASS_P (nelts))
2786 warning_at (loc, OPT_Wplacement_new_,
2787 exact_size ?
2788 "placement new constructing an object of type "
2789 "%<%T [%wu]%> and size %qwu in a region of type %qT "
2790 "and size %qwi"
2791 : "placement new constructing an object of type "
2792 "%<%T [%wu]%> and size %qwu in a region of type %qT "
2793 "and size at most %qwu",
2794 type, tree_to_uhwi (nelts), bytes_need.to_uhwi (),
2795 opertype, bytes_avail.to_uhwi ());
2796 else
2797 warning_at (loc, OPT_Wplacement_new_,
2798 exact_size ?
2799 "placement new constructing an array of objects "
2800 "of type %qT and size %qwu in a region of type %qT "
2801 "and size %qwi"
2802 : "placement new constructing an array of objects "
2803 "of type %qT and size %qwu in a region of type %qT "
2804 "and size at most %qwu",
2805 type, bytes_need.to_uhwi (), opertype,
2806 bytes_avail.to_uhwi ());
2807 else
2808 warning_at (loc, OPT_Wplacement_new_,
2809 exact_size ?
2810 "placement new constructing an object of type %qT "
2811 "and size %qwu in a region of type %qT and size %qwi"
2812 : "placement new constructing an object of type %qT "
2813 "and size %qwu in a region of type %qT and size "
2814 "at most %qwu",
2815 type, bytes_need.to_uhwi (), opertype,
2816 bytes_avail.to_uhwi ());
2821 /* True if alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__. */
2823 bool
2824 type_has_new_extended_alignment (tree t)
2826 return (aligned_new_threshold
2827 && TYPE_ALIGN_UNIT (t) > (unsigned)aligned_new_threshold);
2830 /* Return the alignment we expect malloc to guarantee. This should just be
2831 MALLOC_ABI_ALIGNMENT, but that macro defaults to only BITS_PER_WORD for some
2832 reason, so don't let the threshold be smaller than max_align_t_align. */
2834 unsigned
2835 malloc_alignment ()
2837 return MAX (max_align_t_align(), MALLOC_ABI_ALIGNMENT);
2840 /* Determine whether an allocation function is a namespace-scope
2841 non-replaceable placement new function. See DR 1748.
2842 TODO: Enable in all standard modes. */
2843 static bool
2844 std_placement_new_fn_p (tree alloc_fn)
2846 if (DECL_NAMESPACE_SCOPE_P (alloc_fn))
2848 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (alloc_fn)));
2849 if ((TREE_VALUE (first_arg) == ptr_type_node)
2850 && TREE_CHAIN (first_arg) == void_list_node)
2851 return true;
2853 return false;
2856 /* Generate code for a new-expression, including calling the "operator
2857 new" function, initializing the object, and, if an exception occurs
2858 during construction, cleaning up. The arguments are as for
2859 build_raw_new_expr. This may change PLACEMENT and INIT.
2860 TYPE is the type of the object being constructed, possibly an array
2861 of NELTS elements when NELTS is non-null (in "new T[NELTS]", T may
2862 be an array of the form U[inner], with the whole expression being
2863 "new U[NELTS][inner]"). */
2865 static tree
2866 build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts,
2867 vec<tree, va_gc> **init, bool globally_qualified_p,
2868 tsubst_flags_t complain)
2870 tree size, rval;
2871 /* True iff this is a call to "operator new[]" instead of just
2872 "operator new". */
2873 bool array_p = false;
2874 /* If ARRAY_P is true, the element type of the array. This is never
2875 an ARRAY_TYPE; for something like "new int[3][4]", the
2876 ELT_TYPE is "int". If ARRAY_P is false, this is the same type as
2877 TYPE. */
2878 tree elt_type;
2879 /* The type of the new-expression. (This type is always a pointer
2880 type.) */
2881 tree pointer_type;
2882 tree non_const_pointer_type;
2883 /* The most significant array bound in int[OUTER_NELTS][inner]. */
2884 tree outer_nelts = NULL_TREE;
2885 /* For arrays with a non-constant number of elements, a bounds checks
2886 on the NELTS parameter to avoid integer overflow at runtime. */
2887 tree outer_nelts_check = NULL_TREE;
2888 bool outer_nelts_from_type = false;
2889 /* Number of the "inner" elements in "new T[OUTER_NELTS][inner]". */
2890 offset_int inner_nelts_count = 1;
2891 tree alloc_call, alloc_expr;
2892 /* Size of the inner array elements (those with constant dimensions). */
2893 offset_int inner_size;
2894 /* The address returned by the call to "operator new". This node is
2895 a VAR_DECL and is therefore reusable. */
2896 tree alloc_node;
2897 tree alloc_fn;
2898 tree cookie_expr, init_expr;
2899 int nothrow, check_new;
2900 /* If non-NULL, the number of extra bytes to allocate at the
2901 beginning of the storage allocated for an array-new expression in
2902 order to store the number of elements. */
2903 tree cookie_size = NULL_TREE;
2904 tree placement_first;
2905 tree placement_expr = NULL_TREE;
2906 /* True if the function we are calling is a placement allocation
2907 function. */
2908 bool placement_allocation_fn_p;
2909 /* True if the storage must be initialized, either by a constructor
2910 or due to an explicit new-initializer. */
2911 bool is_initialized;
2912 /* The address of the thing allocated, not including any cookie. In
2913 particular, if an array cookie is in use, DATA_ADDR is the
2914 address of the first array element. This node is a VAR_DECL, and
2915 is therefore reusable. */
2916 tree data_addr;
2917 tree init_preeval_expr = NULL_TREE;
2918 tree orig_type = type;
2920 if (nelts)
2922 outer_nelts = nelts;
2923 array_p = true;
2925 else if (TREE_CODE (type) == ARRAY_TYPE)
2927 /* Transforms new (T[N]) to new T[N]. The former is a GNU
2928 extension for variable N. (This also covers new T where T is
2929 a VLA typedef.) */
2930 array_p = true;
2931 nelts = array_type_nelts_top (type);
2932 outer_nelts = nelts;
2933 type = TREE_TYPE (type);
2934 outer_nelts_from_type = true;
2937 /* Lots of logic below depends on whether we have a constant number of
2938 elements, so go ahead and fold it now. */
2939 const_tree cst_outer_nelts = fold_non_dependent_expr (outer_nelts);
2941 /* If our base type is an array, then make sure we know how many elements
2942 it has. */
2943 for (elt_type = type;
2944 TREE_CODE (elt_type) == ARRAY_TYPE;
2945 elt_type = TREE_TYPE (elt_type))
2947 tree inner_nelts = array_type_nelts_top (elt_type);
2948 tree inner_nelts_cst = maybe_constant_value (inner_nelts);
2949 if (TREE_CODE (inner_nelts_cst) == INTEGER_CST)
2951 bool overflow;
2952 offset_int result = wi::mul (wi::to_offset (inner_nelts_cst),
2953 inner_nelts_count, SIGNED, &overflow);
2954 if (overflow)
2956 if (complain & tf_error)
2957 error ("integer overflow in array size");
2958 nelts = error_mark_node;
2960 inner_nelts_count = result;
2962 else
2964 if (complain & tf_error)
2966 error_at (EXPR_LOC_OR_LOC (inner_nelts, input_location),
2967 "array size in new-expression must be constant");
2968 cxx_constant_value(inner_nelts);
2970 nelts = error_mark_node;
2972 if (nelts != error_mark_node)
2973 nelts = cp_build_binary_op (input_location,
2974 MULT_EXPR, nelts,
2975 inner_nelts_cst,
2976 complain);
2979 if (variably_modified_type_p (elt_type, NULL_TREE) && (complain & tf_error))
2981 error ("variably modified type not allowed in new-expression");
2982 return error_mark_node;
2985 if (nelts == error_mark_node)
2986 return error_mark_node;
2988 /* Warn if we performed the (T[N]) to T[N] transformation and N is
2989 variable. */
2990 if (outer_nelts_from_type
2991 && !TREE_CONSTANT (cst_outer_nelts))
2993 if (complain & tf_warning_or_error)
2995 pedwarn (EXPR_LOC_OR_LOC (outer_nelts, input_location), OPT_Wvla,
2996 typedef_variant_p (orig_type)
2997 ? G_("non-constant array new length must be specified "
2998 "directly, not by typedef")
2999 : G_("non-constant array new length must be specified "
3000 "without parentheses around the type-id"));
3002 else
3003 return error_mark_node;
3006 if (VOID_TYPE_P (elt_type))
3008 if (complain & tf_error)
3009 error ("invalid type %<void%> for new");
3010 return error_mark_node;
3013 if (is_std_init_list (elt_type))
3014 warning (OPT_Winit_list_lifetime,
3015 "%<new%> of initializer_list does not "
3016 "extend the lifetime of the underlying array");
3018 if (abstract_virtuals_error_sfinae (ACU_NEW, elt_type, complain))
3019 return error_mark_node;
3021 is_initialized = (type_build_ctor_call (elt_type) || *init != NULL);
3023 if (*init == NULL && cxx_dialect < cxx11)
3025 bool maybe_uninitialized_error = false;
3026 /* A program that calls for default-initialization [...] of an
3027 entity of reference type is ill-formed. */
3028 if (CLASSTYPE_REF_FIELDS_NEED_INIT (elt_type))
3029 maybe_uninitialized_error = true;
3031 /* A new-expression that creates an object of type T initializes
3032 that object as follows:
3033 - If the new-initializer is omitted:
3034 -- If T is a (possibly cv-qualified) non-POD class type
3035 (or array thereof), the object is default-initialized (8.5).
3036 [...]
3037 -- Otherwise, the object created has indeterminate
3038 value. If T is a const-qualified type, or a (possibly
3039 cv-qualified) POD class type (or array thereof)
3040 containing (directly or indirectly) a member of
3041 const-qualified type, the program is ill-formed; */
3043 if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (elt_type))
3044 maybe_uninitialized_error = true;
3046 if (maybe_uninitialized_error
3047 && diagnose_uninitialized_cst_or_ref_member (elt_type,
3048 /*using_new=*/true,
3049 complain & tf_error))
3050 return error_mark_node;
3053 if (CP_TYPE_CONST_P (elt_type) && *init == NULL
3054 && default_init_uninitialized_part (elt_type))
3056 if (complain & tf_error)
3057 error ("uninitialized const in %<new%> of %q#T", elt_type);
3058 return error_mark_node;
3061 size = size_in_bytes (elt_type);
3062 if (array_p)
3064 /* Maximum available size in bytes. Half of the address space
3065 minus the cookie size. */
3066 offset_int max_size
3067 = wi::set_bit_in_zero <offset_int> (TYPE_PRECISION (sizetype) - 1);
3068 /* Maximum number of outer elements which can be allocated. */
3069 offset_int max_outer_nelts;
3070 tree max_outer_nelts_tree;
3072 gcc_assert (TREE_CODE (size) == INTEGER_CST);
3073 cookie_size = targetm.cxx.get_cookie_size (elt_type);
3074 gcc_assert (TREE_CODE (cookie_size) == INTEGER_CST);
3075 gcc_checking_assert (wi::ltu_p (wi::to_offset (cookie_size), max_size));
3076 /* Unconditionally subtract the cookie size. This decreases the
3077 maximum object size and is safe even if we choose not to use
3078 a cookie after all. */
3079 max_size -= wi::to_offset (cookie_size);
3080 bool overflow;
3081 inner_size = wi::mul (wi::to_offset (size), inner_nelts_count, SIGNED,
3082 &overflow);
3083 if (overflow || wi::gtu_p (inner_size, max_size))
3085 if (complain & tf_error)
3086 error ("size of array is too large");
3087 return error_mark_node;
3090 max_outer_nelts = wi::udiv_trunc (max_size, inner_size);
3091 max_outer_nelts_tree = wide_int_to_tree (sizetype, max_outer_nelts);
3093 size = size_binop (MULT_EXPR, size, fold_convert (sizetype, nelts));
3095 if (TREE_CODE (cst_outer_nelts) == INTEGER_CST)
3097 if (tree_int_cst_lt (max_outer_nelts_tree, cst_outer_nelts))
3099 /* When the array size is constant, check it at compile time
3100 to make sure it doesn't exceed the implementation-defined
3101 maximum, as required by C++ 14 (in C++ 11 this requirement
3102 isn't explicitly stated but it's enforced anyway -- see
3103 grokdeclarator in cp/decl.c). */
3104 if (complain & tf_error)
3105 error ("size of array is too large");
3106 return error_mark_node;
3109 else
3111 /* When a runtime check is necessary because the array size
3112 isn't constant, keep only the top-most seven bits (starting
3113 with the most significant non-zero bit) of the maximum size
3114 to compare the array size against, to simplify encoding the
3115 constant maximum size in the instruction stream. */
3117 unsigned shift = (max_outer_nelts.get_precision ()) - 7
3118 - wi::clz (max_outer_nelts);
3119 max_outer_nelts = (max_outer_nelts >> shift) << shift;
3121 outer_nelts_check = fold_build2 (LE_EXPR, boolean_type_node,
3122 outer_nelts,
3123 max_outer_nelts_tree);
3127 tree align_arg = NULL_TREE;
3128 if (type_has_new_extended_alignment (elt_type))
3129 align_arg = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (elt_type));
3131 alloc_fn = NULL_TREE;
3133 /* If PLACEMENT is a single simple pointer type not passed by
3134 reference, prepare to capture it in a temporary variable. Do
3135 this now, since PLACEMENT will change in the calls below. */
3136 placement_first = NULL_TREE;
3137 if (vec_safe_length (*placement) == 1
3138 && (TYPE_PTR_P (TREE_TYPE ((**placement)[0]))))
3139 placement_first = (**placement)[0];
3141 bool member_new_p = false;
3143 /* Allocate the object. */
3144 tree fnname;
3145 tree fns;
3147 fnname = ovl_op_identifier (false, array_p ? VEC_NEW_EXPR : NEW_EXPR);
3149 member_new_p = !globally_qualified_p
3150 && CLASS_TYPE_P (elt_type)
3151 && (array_p
3152 ? TYPE_HAS_ARRAY_NEW_OPERATOR (elt_type)
3153 : TYPE_HAS_NEW_OPERATOR (elt_type));
3155 if (member_new_p)
3157 /* Use a class-specific operator new. */
3158 /* If a cookie is required, add some extra space. */
3159 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3160 size = size_binop (PLUS_EXPR, size, cookie_size);
3161 else
3163 cookie_size = NULL_TREE;
3164 /* No size arithmetic necessary, so the size check is
3165 not needed. */
3166 if (outer_nelts_check != NULL && inner_size == 1)
3167 outer_nelts_check = NULL_TREE;
3169 /* Perform the overflow check. */
3170 tree errval = TYPE_MAX_VALUE (sizetype);
3171 if (cxx_dialect >= cxx11 && flag_exceptions)
3172 errval = throw_bad_array_new_length ();
3173 if (outer_nelts_check != NULL_TREE)
3174 size = fold_build3 (COND_EXPR, sizetype, outer_nelts_check,
3175 size, errval);
3176 /* Create the argument list. */
3177 vec_safe_insert (*placement, 0, size);
3178 /* Do name-lookup to find the appropriate operator. */
3179 fns = lookup_fnfields (elt_type, fnname, /*protect=*/2);
3180 if (fns == NULL_TREE)
3182 if (complain & tf_error)
3183 error ("no suitable %qD found in class %qT", fnname, elt_type);
3184 return error_mark_node;
3186 if (TREE_CODE (fns) == TREE_LIST)
3188 if (complain & tf_error)
3190 error ("request for member %qD is ambiguous", fnname);
3191 print_candidates (fns);
3193 return error_mark_node;
3195 tree dummy = build_dummy_object (elt_type);
3196 alloc_call = NULL_TREE;
3197 if (align_arg)
3199 vec<tree, va_gc> *align_args
3200 = vec_copy_and_insert (*placement, align_arg, 1);
3201 alloc_call
3202 = build_new_method_call (dummy, fns, &align_args,
3203 /*conversion_path=*/NULL_TREE,
3204 LOOKUP_NORMAL, &alloc_fn, tf_none);
3205 /* If no matching function is found and the allocated object type
3206 has new-extended alignment, the alignment argument is removed
3207 from the argument list, and overload resolution is performed
3208 again. */
3209 if (alloc_call == error_mark_node)
3210 alloc_call = NULL_TREE;
3212 if (!alloc_call)
3213 alloc_call = build_new_method_call (dummy, fns, placement,
3214 /*conversion_path=*/NULL_TREE,
3215 LOOKUP_NORMAL,
3216 &alloc_fn, complain);
3218 else
3220 /* Use a global operator new. */
3221 /* See if a cookie might be required. */
3222 if (!(array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type)))
3224 cookie_size = NULL_TREE;
3225 /* No size arithmetic necessary, so the size check is
3226 not needed. */
3227 if (outer_nelts_check != NULL && inner_size == 1)
3228 outer_nelts_check = NULL_TREE;
3231 alloc_call = build_operator_new_call (fnname, placement,
3232 &size, &cookie_size,
3233 align_arg, outer_nelts_check,
3234 &alloc_fn, complain);
3237 if (alloc_call == error_mark_node)
3238 return error_mark_node;
3240 gcc_assert (alloc_fn != NULL_TREE);
3242 /* Now, check to see if this function is actually a placement
3243 allocation function. This can happen even when PLACEMENT is NULL
3244 because we might have something like:
3246 struct S { void* operator new (size_t, int i = 0); };
3248 A call to `new S' will get this allocation function, even though
3249 there is no explicit placement argument. If there is more than
3250 one argument, or there are variable arguments, then this is a
3251 placement allocation function. */
3252 placement_allocation_fn_p
3253 = (type_num_arguments (TREE_TYPE (alloc_fn)) > 1
3254 || varargs_function_p (alloc_fn));
3256 if (warn_aligned_new
3257 && !placement_allocation_fn_p
3258 && TYPE_ALIGN (elt_type) > malloc_alignment ()
3259 && (warn_aligned_new > 1
3260 || CP_DECL_CONTEXT (alloc_fn) == global_namespace)
3261 && !aligned_allocation_fn_p (alloc_fn))
3263 if (warning (OPT_Waligned_new_, "%<new%> of type %qT with extended "
3264 "alignment %d", elt_type, TYPE_ALIGN_UNIT (elt_type)))
3266 inform (input_location, "uses %qD, which does not have an alignment "
3267 "parameter", alloc_fn);
3268 if (!aligned_new_threshold)
3269 inform (input_location, "use %<-faligned-new%> to enable C++17 "
3270 "over-aligned new support");
3274 /* If we found a simple case of PLACEMENT_EXPR above, then copy it
3275 into a temporary variable. */
3276 if (!processing_template_decl
3277 && TREE_CODE (alloc_call) == CALL_EXPR
3278 && call_expr_nargs (alloc_call) == 2
3279 && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 0))) == INTEGER_TYPE
3280 && TYPE_PTR_P (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1))))
3282 tree placement = CALL_EXPR_ARG (alloc_call, 1);
3284 if (placement_first != NULL_TREE
3285 && (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))
3286 || VOID_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))))
3288 placement_expr = get_target_expr (placement_first);
3289 CALL_EXPR_ARG (alloc_call, 1)
3290 = fold_convert (TREE_TYPE (placement), placement_expr);
3293 if (!member_new_p
3294 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1)))))
3296 /* Attempt to make the warning point at the operator new argument. */
3297 if (placement_first)
3298 placement = placement_first;
3300 warn_placement_new_too_small (orig_type, nelts, size, placement);
3304 /* In the simple case, we can stop now. */
3305 pointer_type = build_pointer_type (type);
3306 if (!cookie_size && !is_initialized)
3307 return build_nop (pointer_type, alloc_call);
3309 /* Store the result of the allocation call in a variable so that we can
3310 use it more than once. */
3311 alloc_expr = get_target_expr (alloc_call);
3312 alloc_node = TARGET_EXPR_SLOT (alloc_expr);
3314 /* Strip any COMPOUND_EXPRs from ALLOC_CALL. */
3315 while (TREE_CODE (alloc_call) == COMPOUND_EXPR)
3316 alloc_call = TREE_OPERAND (alloc_call, 1);
3318 /* Preevaluate the placement args so that we don't reevaluate them for a
3319 placement delete. */
3320 if (placement_allocation_fn_p)
3322 tree inits;
3323 stabilize_call (alloc_call, &inits);
3324 if (inits)
3325 alloc_expr = build2 (COMPOUND_EXPR, TREE_TYPE (alloc_expr), inits,
3326 alloc_expr);
3329 /* unless an allocation function is declared with an empty excep-
3330 tion-specification (_except.spec_), throw(), it indicates failure to
3331 allocate storage by throwing a bad_alloc exception (clause _except_,
3332 _lib.bad.alloc_); it returns a non-null pointer otherwise If the allo-
3333 cation function is declared with an empty exception-specification,
3334 throw(), it returns null to indicate failure to allocate storage and a
3335 non-null pointer otherwise.
3337 So check for a null exception spec on the op new we just called. */
3339 nothrow = TYPE_NOTHROW_P (TREE_TYPE (alloc_fn));
3340 check_new
3341 = flag_check_new || (nothrow && !std_placement_new_fn_p (alloc_fn));
3343 if (cookie_size)
3345 tree cookie;
3346 tree cookie_ptr;
3347 tree size_ptr_type;
3349 /* Adjust so we're pointing to the start of the object. */
3350 data_addr = fold_build_pointer_plus (alloc_node, cookie_size);
3352 /* Store the number of bytes allocated so that we can know how
3353 many elements to destroy later. We use the last sizeof
3354 (size_t) bytes to store the number of elements. */
3355 cookie_ptr = size_binop (MINUS_EXPR, cookie_size, size_in_bytes (sizetype));
3356 cookie_ptr = fold_build_pointer_plus_loc (input_location,
3357 alloc_node, cookie_ptr);
3358 size_ptr_type = build_pointer_type (sizetype);
3359 cookie_ptr = fold_convert (size_ptr_type, cookie_ptr);
3360 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3362 cookie_expr = build2 (MODIFY_EXPR, sizetype, cookie, nelts);
3364 if (targetm.cxx.cookie_has_size ())
3366 /* Also store the element size. */
3367 cookie_ptr = fold_build_pointer_plus (cookie_ptr,
3368 fold_build1_loc (input_location,
3369 NEGATE_EXPR, sizetype,
3370 size_in_bytes (sizetype)));
3372 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3373 cookie = build2 (MODIFY_EXPR, sizetype, cookie,
3374 size_in_bytes (elt_type));
3375 cookie_expr = build2 (COMPOUND_EXPR, TREE_TYPE (cookie_expr),
3376 cookie, cookie_expr);
3379 else
3381 cookie_expr = NULL_TREE;
3382 data_addr = alloc_node;
3385 /* Now use a pointer to the type we've actually allocated. */
3387 /* But we want to operate on a non-const version to start with,
3388 since we'll be modifying the elements. */
3389 non_const_pointer_type = build_pointer_type
3390 (cp_build_qualified_type (type, cp_type_quals (type) & ~TYPE_QUAL_CONST));
3392 data_addr = fold_convert (non_const_pointer_type, data_addr);
3393 /* Any further uses of alloc_node will want this type, too. */
3394 alloc_node = fold_convert (non_const_pointer_type, alloc_node);
3396 /* Now initialize the allocated object. Note that we preevaluate the
3397 initialization expression, apart from the actual constructor call or
3398 assignment--we do this because we want to delay the allocation as long
3399 as possible in order to minimize the size of the exception region for
3400 placement delete. */
3401 if (is_initialized)
3403 bool stable;
3404 bool explicit_value_init_p = false;
3406 if (*init != NULL && (*init)->is_empty ())
3408 *init = NULL;
3409 explicit_value_init_p = true;
3412 if (processing_template_decl && explicit_value_init_p)
3414 /* build_value_init doesn't work in templates, and we don't need
3415 the initializer anyway since we're going to throw it away and
3416 rebuild it at instantiation time, so just build up a single
3417 constructor call to get any appropriate diagnostics. */
3418 init_expr = cp_build_fold_indirect_ref (data_addr);
3419 if (type_build_ctor_call (elt_type))
3420 init_expr = build_special_member_call (init_expr,
3421 complete_ctor_identifier,
3422 init, elt_type,
3423 LOOKUP_NORMAL,
3424 complain);
3425 stable = stabilize_init (init_expr, &init_preeval_expr);
3427 else if (array_p)
3429 tree vecinit = NULL_TREE;
3430 if (vec_safe_length (*init) == 1
3431 && DIRECT_LIST_INIT_P ((**init)[0]))
3433 vecinit = (**init)[0];
3434 if (CONSTRUCTOR_NELTS (vecinit) == 0)
3435 /* List-value-initialization, leave it alone. */;
3436 else
3438 tree arraytype, domain;
3439 if (TREE_CONSTANT (nelts))
3440 domain = compute_array_index_type (NULL_TREE, nelts,
3441 complain);
3442 else
3443 /* We'll check the length at runtime. */
3444 domain = NULL_TREE;
3445 arraytype = build_cplus_array_type (type, domain);
3446 vecinit = digest_init (arraytype, vecinit, complain);
3449 else if (*init)
3451 if (complain & tf_error)
3452 error ("parenthesized initializer in array new");
3453 return error_mark_node;
3455 init_expr
3456 = build_vec_init (data_addr,
3457 cp_build_binary_op (input_location,
3458 MINUS_EXPR, outer_nelts,
3459 integer_one_node,
3460 complain),
3461 vecinit,
3462 explicit_value_init_p,
3463 /*from_array=*/0,
3464 complain);
3466 /* An array initialization is stable because the initialization
3467 of each element is a full-expression, so the temporaries don't
3468 leak out. */
3469 stable = true;
3471 else
3473 init_expr = cp_build_fold_indirect_ref (data_addr);
3475 if (type_build_ctor_call (type) && !explicit_value_init_p)
3477 init_expr = build_special_member_call (init_expr,
3478 complete_ctor_identifier,
3479 init, elt_type,
3480 LOOKUP_NORMAL,
3481 complain);
3483 else if (explicit_value_init_p)
3485 /* Something like `new int()'. NO_CLEANUP is needed so
3486 we don't try and build a (possibly ill-formed)
3487 destructor. */
3488 tree val = build_value_init (type, complain | tf_no_cleanup);
3489 if (val == error_mark_node)
3490 return error_mark_node;
3491 init_expr = build2 (INIT_EXPR, type, init_expr, val);
3493 else
3495 tree ie;
3497 /* We are processing something like `new int (10)', which
3498 means allocate an int, and initialize it with 10. */
3500 ie = build_x_compound_expr_from_vec (*init, "new initializer",
3501 complain);
3502 init_expr = cp_build_modify_expr (input_location, init_expr,
3503 INIT_EXPR, ie, complain);
3505 /* If the initializer uses C++14 aggregate NSDMI that refer to the
3506 object being initialized, replace them now and don't try to
3507 preevaluate. */
3508 bool had_placeholder = false;
3509 if (!processing_template_decl
3510 && TREE_CODE (init_expr) == INIT_EXPR)
3511 TREE_OPERAND (init_expr, 1)
3512 = replace_placeholders (TREE_OPERAND (init_expr, 1),
3513 TREE_OPERAND (init_expr, 0),
3514 &had_placeholder);
3515 stable = (!had_placeholder
3516 && stabilize_init (init_expr, &init_preeval_expr));
3519 if (init_expr == error_mark_node)
3520 return error_mark_node;
3522 /* If any part of the object initialization terminates by throwing an
3523 exception and a suitable deallocation function can be found, the
3524 deallocation function is called to free the memory in which the
3525 object was being constructed, after which the exception continues
3526 to propagate in the context of the new-expression. If no
3527 unambiguous matching deallocation function can be found,
3528 propagating the exception does not cause the object's memory to be
3529 freed. */
3530 if (flag_exceptions)
3532 enum tree_code dcode = array_p ? VEC_DELETE_EXPR : DELETE_EXPR;
3533 tree cleanup;
3535 /* The Standard is unclear here, but the right thing to do
3536 is to use the same method for finding deallocation
3537 functions that we use for finding allocation functions. */
3538 cleanup = (build_op_delete_call
3539 (dcode,
3540 alloc_node,
3541 size,
3542 globally_qualified_p,
3543 placement_allocation_fn_p ? alloc_call : NULL_TREE,
3544 alloc_fn,
3545 complain));
3547 if (!cleanup)
3548 /* We're done. */;
3549 else if (stable)
3550 /* This is much simpler if we were able to preevaluate all of
3551 the arguments to the constructor call. */
3553 /* CLEANUP is compiler-generated, so no diagnostics. */
3554 TREE_NO_WARNING (cleanup) = true;
3555 init_expr = build2 (TRY_CATCH_EXPR, void_type_node,
3556 init_expr, cleanup);
3557 /* Likewise, this try-catch is compiler-generated. */
3558 TREE_NO_WARNING (init_expr) = true;
3560 else
3561 /* Ack! First we allocate the memory. Then we set our sentry
3562 variable to true, and expand a cleanup that deletes the
3563 memory if sentry is true. Then we run the constructor, and
3564 finally clear the sentry.
3566 We need to do this because we allocate the space first, so
3567 if there are any temporaries with cleanups in the
3568 constructor args and we weren't able to preevaluate them, we
3569 need this EH region to extend until end of full-expression
3570 to preserve nesting. */
3572 tree end, sentry, begin;
3574 begin = get_target_expr (boolean_true_node);
3575 CLEANUP_EH_ONLY (begin) = 1;
3577 sentry = TARGET_EXPR_SLOT (begin);
3579 /* CLEANUP is compiler-generated, so no diagnostics. */
3580 TREE_NO_WARNING (cleanup) = true;
3582 TARGET_EXPR_CLEANUP (begin)
3583 = build3 (COND_EXPR, void_type_node, sentry,
3584 cleanup, void_node);
3586 end = build2 (MODIFY_EXPR, TREE_TYPE (sentry),
3587 sentry, boolean_false_node);
3589 init_expr
3590 = build2 (COMPOUND_EXPR, void_type_node, begin,
3591 build2 (COMPOUND_EXPR, void_type_node, init_expr,
3592 end));
3593 /* Likewise, this is compiler-generated. */
3594 TREE_NO_WARNING (init_expr) = true;
3598 else
3599 init_expr = NULL_TREE;
3601 /* Now build up the return value in reverse order. */
3603 rval = data_addr;
3605 if (init_expr)
3606 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_expr, rval);
3607 if (cookie_expr)
3608 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), cookie_expr, rval);
3610 if (rval == data_addr)
3611 /* If we don't have an initializer or a cookie, strip the TARGET_EXPR
3612 and return the call (which doesn't need to be adjusted). */
3613 rval = TARGET_EXPR_INITIAL (alloc_expr);
3614 else
3616 if (check_new)
3618 tree ifexp = cp_build_binary_op (input_location,
3619 NE_EXPR, alloc_node,
3620 nullptr_node,
3621 complain);
3622 rval = build_conditional_expr (input_location, ifexp, rval,
3623 alloc_node, complain);
3626 /* Perform the allocation before anything else, so that ALLOC_NODE
3627 has been initialized before we start using it. */
3628 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), alloc_expr, rval);
3631 if (init_preeval_expr)
3632 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_preeval_expr, rval);
3634 /* A new-expression is never an lvalue. */
3635 gcc_assert (!obvalue_p (rval));
3637 return convert (pointer_type, rval);
3640 /* Generate a representation for a C++ "new" expression. *PLACEMENT
3641 is a vector of placement-new arguments (or NULL if none). If NELTS
3642 is NULL, TYPE is the type of the storage to be allocated. If NELTS
3643 is not NULL, then this is an array-new allocation; TYPE is the type
3644 of the elements in the array and NELTS is the number of elements in
3645 the array. *INIT, if non-NULL, is the initializer for the new
3646 object, or an empty vector to indicate an initializer of "()". If
3647 USE_GLOBAL_NEW is true, then the user explicitly wrote "::new"
3648 rather than just "new". This may change PLACEMENT and INIT. */
3650 tree
3651 build_new (vec<tree, va_gc> **placement, tree type, tree nelts,
3652 vec<tree, va_gc> **init, int use_global_new, tsubst_flags_t complain)
3654 tree rval;
3655 vec<tree, va_gc> *orig_placement = NULL;
3656 tree orig_nelts = NULL_TREE;
3657 vec<tree, va_gc> *orig_init = NULL;
3659 if (type == error_mark_node)
3660 return error_mark_node;
3662 if (nelts == NULL_TREE
3663 /* Don't do auto deduction where it might affect mangling. */
3664 && (!processing_template_decl || at_function_scope_p ()))
3666 tree auto_node = type_uses_auto (type);
3667 if (auto_node)
3669 tree d_init = NULL_TREE;
3670 const size_t len = vec_safe_length (*init);
3671 /* E.g. new auto(x) must have exactly one element, or
3672 a {} initializer will have one element. */
3673 if (len == 1)
3675 d_init = (**init)[0];
3676 d_init = resolve_nondeduced_context (d_init, complain);
3678 /* For the rest, e.g. new A(1, 2, 3), create a list. */
3679 else if (len > 1)
3681 unsigned int n;
3682 tree t;
3683 tree *pp = &d_init;
3684 FOR_EACH_VEC_ELT (**init, n, t)
3686 t = resolve_nondeduced_context (t, complain);
3687 *pp = build_tree_list (NULL_TREE, t);
3688 pp = &TREE_CHAIN (*pp);
3691 type = do_auto_deduction (type, d_init, auto_node, complain);
3695 if (processing_template_decl)
3697 if (dependent_type_p (type)
3698 || any_type_dependent_arguments_p (*placement)
3699 || (nelts && type_dependent_expression_p (nelts))
3700 || (nelts && *init)
3701 || any_type_dependent_arguments_p (*init))
3702 return build_raw_new_expr (*placement, type, nelts, *init,
3703 use_global_new);
3705 orig_placement = make_tree_vector_copy (*placement);
3706 orig_nelts = nelts;
3707 if (*init)
3709 orig_init = make_tree_vector_copy (*init);
3710 /* Also copy any CONSTRUCTORs in *init, since reshape_init and
3711 digest_init clobber them in place. */
3712 for (unsigned i = 0; i < orig_init->length(); ++i)
3714 tree e = (**init)[i];
3715 if (TREE_CODE (e) == CONSTRUCTOR)
3716 (**init)[i] = copy_node (e);
3720 make_args_non_dependent (*placement);
3721 if (nelts)
3722 nelts = build_non_dependent_expr (nelts);
3723 make_args_non_dependent (*init);
3726 if (nelts)
3728 if (!build_expr_type_conversion (WANT_INT | WANT_ENUM, nelts, false))
3730 if (complain & tf_error)
3731 permerror (input_location, "size in array new must have integral type");
3732 else
3733 return error_mark_node;
3736 /* Try to determine the constant value only for the purposes
3737 of the diagnostic below but continue to use the original
3738 value and handle const folding later. */
3739 const_tree cst_nelts = fold_non_dependent_expr (nelts);
3741 /* The expression in a noptr-new-declarator is erroneous if it's of
3742 non-class type and its value before converting to std::size_t is
3743 less than zero. ... If the expression is a constant expression,
3744 the program is ill-fomed. */
3745 if (TREE_CODE (cst_nelts) == INTEGER_CST
3746 && tree_int_cst_sgn (cst_nelts) == -1)
3748 if (complain & tf_error)
3749 error ("size of array is negative");
3750 return error_mark_node;
3753 nelts = mark_rvalue_use (nelts);
3754 nelts = cp_save_expr (cp_convert (sizetype, nelts, complain));
3757 /* ``A reference cannot be created by the new operator. A reference
3758 is not an object (8.2.2, 8.4.3), so a pointer to it could not be
3759 returned by new.'' ARM 5.3.3 */
3760 if (TYPE_REF_P (type))
3762 if (complain & tf_error)
3763 error ("new cannot be applied to a reference type");
3764 else
3765 return error_mark_node;
3766 type = TREE_TYPE (type);
3769 if (TREE_CODE (type) == FUNCTION_TYPE)
3771 if (complain & tf_error)
3772 error ("new cannot be applied to a function type");
3773 return error_mark_node;
3776 /* The type allocated must be complete. If the new-type-id was
3777 "T[N]" then we are just checking that "T" is complete here, but
3778 that is equivalent, since the value of "N" doesn't matter. */
3779 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
3780 return error_mark_node;
3782 rval = build_new_1 (placement, type, nelts, init, use_global_new, complain);
3783 if (rval == error_mark_node)
3784 return error_mark_node;
3786 if (processing_template_decl)
3788 tree ret = build_raw_new_expr (orig_placement, type, orig_nelts,
3789 orig_init, use_global_new);
3790 release_tree_vector (orig_placement);
3791 release_tree_vector (orig_init);
3792 return ret;
3795 /* Wrap it in a NOP_EXPR so warn_if_unused_value doesn't complain. */
3796 rval = build1 (NOP_EXPR, TREE_TYPE (rval), rval);
3797 TREE_NO_WARNING (rval) = 1;
3799 return rval;
3802 static tree
3803 build_vec_delete_1 (tree base, tree maxindex, tree type,
3804 special_function_kind auto_delete_vec,
3805 int use_global_delete, tsubst_flags_t complain)
3807 tree virtual_size;
3808 tree ptype = build_pointer_type (type = complete_type (type));
3809 tree size_exp;
3811 /* Temporary variables used by the loop. */
3812 tree tbase, tbase_init;
3814 /* This is the body of the loop that implements the deletion of a
3815 single element, and moves temp variables to next elements. */
3816 tree body;
3818 /* This is the LOOP_EXPR that governs the deletion of the elements. */
3819 tree loop = 0;
3821 /* This is the thing that governs what to do after the loop has run. */
3822 tree deallocate_expr = 0;
3824 /* This is the BIND_EXPR which holds the outermost iterator of the
3825 loop. It is convenient to set this variable up and test it before
3826 executing any other code in the loop.
3827 This is also the containing expression returned by this function. */
3828 tree controller = NULL_TREE;
3829 tree tmp;
3831 /* We should only have 1-D arrays here. */
3832 gcc_assert (TREE_CODE (type) != ARRAY_TYPE);
3834 if (base == error_mark_node || maxindex == error_mark_node)
3835 return error_mark_node;
3837 if (!COMPLETE_TYPE_P (type))
3839 if ((complain & tf_warning)
3840 && warning (OPT_Wdelete_incomplete,
3841 "possible problem detected in invocation of "
3842 "delete [] operator:"))
3844 cxx_incomplete_type_diagnostic (base, type, DK_WARNING);
3845 inform (input_location, "neither the destructor nor the "
3846 "class-specific operator delete [] will be called, "
3847 "even if they are declared when the class is defined");
3849 /* This size won't actually be used. */
3850 size_exp = size_one_node;
3851 goto no_destructor;
3854 size_exp = size_in_bytes (type);
3856 if (! MAYBE_CLASS_TYPE_P (type))
3857 goto no_destructor;
3858 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
3860 /* Make sure the destructor is callable. */
3861 if (type_build_dtor_call (type))
3863 tmp = build_delete (ptype, base, sfk_complete_destructor,
3864 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
3865 complain);
3866 if (tmp == error_mark_node)
3867 return error_mark_node;
3869 goto no_destructor;
3872 /* The below is short by the cookie size. */
3873 virtual_size = size_binop (MULT_EXPR, size_exp,
3874 fold_convert (sizetype, maxindex));
3876 tbase = create_temporary_var (ptype);
3877 tbase_init
3878 = cp_build_modify_expr (input_location, tbase, NOP_EXPR,
3879 fold_build_pointer_plus_loc (input_location,
3880 fold_convert (ptype,
3881 base),
3882 virtual_size),
3883 complain);
3884 if (tbase_init == error_mark_node)
3885 return error_mark_node;
3886 controller = build3 (BIND_EXPR, void_type_node, tbase,
3887 NULL_TREE, NULL_TREE);
3888 TREE_SIDE_EFFECTS (controller) = 1;
3890 body = build1 (EXIT_EXPR, void_type_node,
3891 build2 (EQ_EXPR, boolean_type_node, tbase,
3892 fold_convert (ptype, base)));
3893 tmp = fold_build1_loc (input_location, NEGATE_EXPR, sizetype, size_exp);
3894 tmp = fold_build_pointer_plus (tbase, tmp);
3895 tmp = cp_build_modify_expr (input_location, tbase, NOP_EXPR, tmp, complain);
3896 if (tmp == error_mark_node)
3897 return error_mark_node;
3898 body = build_compound_expr (input_location, body, tmp);
3899 tmp = build_delete (ptype, tbase, sfk_complete_destructor,
3900 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
3901 complain);
3902 if (tmp == error_mark_node)
3903 return error_mark_node;
3904 body = build_compound_expr (input_location, body, tmp);
3906 loop = build1 (LOOP_EXPR, void_type_node, body);
3907 loop = build_compound_expr (input_location, tbase_init, loop);
3909 no_destructor:
3910 /* Delete the storage if appropriate. */
3911 if (auto_delete_vec == sfk_deleting_destructor)
3913 tree base_tbd;
3915 /* The below is short by the cookie size. */
3916 virtual_size = size_binop (MULT_EXPR, size_exp,
3917 fold_convert (sizetype, maxindex));
3919 if (! TYPE_VEC_NEW_USES_COOKIE (type))
3920 /* no header */
3921 base_tbd = base;
3922 else
3924 tree cookie_size;
3926 cookie_size = targetm.cxx.get_cookie_size (type);
3927 base_tbd = cp_build_binary_op (input_location,
3928 MINUS_EXPR,
3929 cp_convert (string_type_node,
3930 base, complain),
3931 cookie_size,
3932 complain);
3933 if (base_tbd == error_mark_node)
3934 return error_mark_node;
3935 base_tbd = cp_convert (ptype, base_tbd, complain);
3936 /* True size with header. */
3937 virtual_size = size_binop (PLUS_EXPR, virtual_size, cookie_size);
3940 deallocate_expr = build_op_delete_call (VEC_DELETE_EXPR,
3941 base_tbd, virtual_size,
3942 use_global_delete & 1,
3943 /*placement=*/NULL_TREE,
3944 /*alloc_fn=*/NULL_TREE,
3945 complain);
3948 body = loop;
3949 if (!deallocate_expr)
3951 else if (!body)
3952 body = deallocate_expr;
3953 else
3954 /* The delete operator mist be called, even if a destructor
3955 throws. */
3956 body = build2 (TRY_FINALLY_EXPR, void_type_node, body, deallocate_expr);
3958 if (!body)
3959 body = integer_zero_node;
3961 /* Outermost wrapper: If pointer is null, punt. */
3962 tree cond = build2_loc (input_location, NE_EXPR, boolean_type_node, base,
3963 fold_convert (TREE_TYPE (base), nullptr_node));
3964 /* This is a compiler generated comparison, don't emit
3965 e.g. -Wnonnull-compare warning for it. */
3966 TREE_NO_WARNING (cond) = 1;
3967 body = build3_loc (input_location, COND_EXPR, void_type_node,
3968 cond, body, integer_zero_node);
3969 COND_EXPR_IS_VEC_DELETE (body) = true;
3970 body = build1 (NOP_EXPR, void_type_node, body);
3972 if (controller)
3974 TREE_OPERAND (controller, 1) = body;
3975 body = controller;
3978 if (TREE_CODE (base) == SAVE_EXPR)
3979 /* Pre-evaluate the SAVE_EXPR outside of the BIND_EXPR. */
3980 body = build2 (COMPOUND_EXPR, void_type_node, base, body);
3982 return convert_to_void (body, ICV_CAST, complain);
3985 /* Create an unnamed variable of the indicated TYPE. */
3987 tree
3988 create_temporary_var (tree type)
3990 tree decl;
3992 decl = build_decl (input_location,
3993 VAR_DECL, NULL_TREE, type);
3994 TREE_USED (decl) = 1;
3995 DECL_ARTIFICIAL (decl) = 1;
3996 DECL_IGNORED_P (decl) = 1;
3997 DECL_CONTEXT (decl) = current_function_decl;
3999 return decl;
4002 /* Create a new temporary variable of the indicated TYPE, initialized
4003 to INIT.
4005 It is not entered into current_binding_level, because that breaks
4006 things when it comes time to do final cleanups (which take place
4007 "outside" the binding contour of the function). */
4009 tree
4010 get_temp_regvar (tree type, tree init)
4012 tree decl;
4014 decl = create_temporary_var (type);
4015 add_decl_expr (decl);
4017 finish_expr_stmt (cp_build_modify_expr (input_location, decl, INIT_EXPR,
4018 init, tf_warning_or_error));
4020 return decl;
4023 /* Subroutine of build_vec_init. Returns true if assigning to an array of
4024 INNER_ELT_TYPE from INIT is trivial. */
4026 static bool
4027 vec_copy_assign_is_trivial (tree inner_elt_type, tree init)
4029 tree fromtype = inner_elt_type;
4030 if (lvalue_p (init))
4031 fromtype = cp_build_reference_type (fromtype, /*rval*/false);
4032 return is_trivially_xible (MODIFY_EXPR, inner_elt_type, fromtype);
4035 /* Subroutine of build_vec_init: Check that the array has at least N
4036 elements. Other parameters are local variables in build_vec_init. */
4038 void
4039 finish_length_check (tree atype, tree iterator, tree obase, unsigned n)
4041 tree nelts = build_int_cst (ptrdiff_type_node, n - 1);
4042 if (TREE_CODE (atype) != ARRAY_TYPE)
4044 if (flag_exceptions)
4046 tree c = fold_build2 (LT_EXPR, boolean_type_node, iterator,
4047 nelts);
4048 c = build3 (COND_EXPR, void_type_node, c,
4049 throw_bad_array_new_length (), void_node);
4050 finish_expr_stmt (c);
4052 /* Don't check an array new when -fno-exceptions. */
4054 else if (sanitize_flags_p (SANITIZE_BOUNDS)
4055 && current_function_decl != NULL_TREE)
4057 /* Make sure the last element of the initializer is in bounds. */
4058 finish_expr_stmt
4059 (ubsan_instrument_bounds
4060 (input_location, obase, &nelts, /*ignore_off_by_one*/false));
4064 /* `build_vec_init' returns tree structure that performs
4065 initialization of a vector of aggregate types.
4067 BASE is a reference to the vector, of ARRAY_TYPE, or a pointer
4068 to the first element, of POINTER_TYPE.
4069 MAXINDEX is the maximum index of the array (one less than the
4070 number of elements). It is only used if BASE is a pointer or
4071 TYPE_DOMAIN (TREE_TYPE (BASE)) == NULL_TREE.
4073 INIT is the (possibly NULL) initializer.
4075 If EXPLICIT_VALUE_INIT_P is true, then INIT must be NULL. All
4076 elements in the array are value-initialized.
4078 FROM_ARRAY is 0 if we should init everything with INIT
4079 (i.e., every element initialized from INIT).
4080 FROM_ARRAY is 1 if we should index into INIT in parallel
4081 with initialization of DECL.
4082 FROM_ARRAY is 2 if we should index into INIT in parallel,
4083 but use assignment instead of initialization. */
4085 tree
4086 build_vec_init (tree base, tree maxindex, tree init,
4087 bool explicit_value_init_p,
4088 int from_array, tsubst_flags_t complain)
4090 tree rval;
4091 tree base2 = NULL_TREE;
4092 tree itype = NULL_TREE;
4093 tree iterator;
4094 /* The type of BASE. */
4095 tree atype = TREE_TYPE (base);
4096 /* The type of an element in the array. */
4097 tree type = TREE_TYPE (atype);
4098 /* The element type reached after removing all outer array
4099 types. */
4100 tree inner_elt_type;
4101 /* The type of a pointer to an element in the array. */
4102 tree ptype;
4103 tree stmt_expr;
4104 tree compound_stmt;
4105 int destroy_temps;
4106 tree try_block = NULL_TREE;
4107 int num_initialized_elts = 0;
4108 bool is_global;
4109 tree obase = base;
4110 bool xvalue = false;
4111 bool errors = false;
4112 location_t loc = (init ? EXPR_LOC_OR_LOC (init, input_location)
4113 : location_of (base));
4115 if (TREE_CODE (atype) == ARRAY_TYPE && TYPE_DOMAIN (atype))
4116 maxindex = array_type_nelts (atype);
4118 if (maxindex == NULL_TREE || maxindex == error_mark_node)
4119 return error_mark_node;
4121 maxindex = maybe_constant_value (maxindex);
4122 if (explicit_value_init_p)
4123 gcc_assert (!init);
4125 inner_elt_type = strip_array_types (type);
4127 /* Look through the TARGET_EXPR around a compound literal. */
4128 if (init && TREE_CODE (init) == TARGET_EXPR
4129 && TREE_CODE (TARGET_EXPR_INITIAL (init)) == CONSTRUCTOR
4130 && from_array != 2)
4131 init = TARGET_EXPR_INITIAL (init);
4133 bool direct_init = false;
4134 if (from_array && init && BRACE_ENCLOSED_INITIALIZER_P (init)
4135 && CONSTRUCTOR_NELTS (init) == 1)
4137 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
4138 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE)
4140 direct_init = DIRECT_LIST_INIT_P (init);
4141 init = elt;
4145 /* If we have a braced-init-list or string constant, make sure that the array
4146 is big enough for all the initializers. */
4147 bool length_check = (init
4148 && (TREE_CODE (init) == STRING_CST
4149 || (TREE_CODE (init) == CONSTRUCTOR
4150 && CONSTRUCTOR_NELTS (init) > 0))
4151 && !TREE_CONSTANT (maxindex));
4153 if (init
4154 && TREE_CODE (atype) == ARRAY_TYPE
4155 && TREE_CONSTANT (maxindex)
4156 && (from_array == 2
4157 ? vec_copy_assign_is_trivial (inner_elt_type, init)
4158 : !TYPE_NEEDS_CONSTRUCTING (type))
4159 && ((TREE_CODE (init) == CONSTRUCTOR
4160 && (BRACE_ENCLOSED_INITIALIZER_P (init)
4161 || (same_type_ignoring_top_level_qualifiers_p
4162 (atype, TREE_TYPE (init))))
4163 /* Don't do this if the CONSTRUCTOR might contain something
4164 that might throw and require us to clean up. */
4165 && (vec_safe_is_empty (CONSTRUCTOR_ELTS (init))
4166 || ! TYPE_HAS_NONTRIVIAL_DESTRUCTOR (inner_elt_type)))
4167 || from_array))
4169 /* Do non-default initialization of trivial arrays resulting from
4170 brace-enclosed initializers. In this case, digest_init and
4171 store_constructor will handle the semantics for us. */
4173 if (BRACE_ENCLOSED_INITIALIZER_P (init))
4174 init = digest_init (atype, init, complain);
4175 stmt_expr = build2 (INIT_EXPR, atype, base, init);
4176 return stmt_expr;
4179 maxindex = cp_convert (ptrdiff_type_node, maxindex, complain);
4180 maxindex = fold_simple (maxindex);
4182 if (TREE_CODE (atype) == ARRAY_TYPE)
4184 ptype = build_pointer_type (type);
4185 base = decay_conversion (base, complain);
4186 if (base == error_mark_node)
4187 return error_mark_node;
4188 base = cp_convert (ptype, base, complain);
4190 else
4191 ptype = atype;
4193 /* The code we are generating looks like:
4195 T* t1 = (T*) base;
4196 T* rval = t1;
4197 ptrdiff_t iterator = maxindex;
4198 try {
4199 for (; iterator != -1; --iterator) {
4200 ... initialize *t1 ...
4201 ++t1;
4203 } catch (...) {
4204 ... destroy elements that were constructed ...
4206 rval;
4209 We can omit the try and catch blocks if we know that the
4210 initialization will never throw an exception, or if the array
4211 elements do not have destructors. We can omit the loop completely if
4212 the elements of the array do not have constructors.
4214 We actually wrap the entire body of the above in a STMT_EXPR, for
4215 tidiness.
4217 When copying from array to another, when the array elements have
4218 only trivial copy constructors, we should use __builtin_memcpy
4219 rather than generating a loop. That way, we could take advantage
4220 of whatever cleverness the back end has for dealing with copies
4221 of blocks of memory. */
4223 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
4224 destroy_temps = stmts_are_full_exprs_p ();
4225 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4226 rval = get_temp_regvar (ptype, base);
4227 base = get_temp_regvar (ptype, rval);
4228 iterator = get_temp_regvar (ptrdiff_type_node, maxindex);
4230 /* If initializing one array from another, initialize element by
4231 element. We rely upon the below calls to do the argument
4232 checking. Evaluate the initializer before entering the try block. */
4233 if (from_array && init && TREE_CODE (init) != CONSTRUCTOR)
4235 if (lvalue_kind (init) & clk_rvalueref)
4236 xvalue = true;
4237 base2 = decay_conversion (init, complain);
4238 if (base2 == error_mark_node)
4239 return error_mark_node;
4240 itype = TREE_TYPE (base2);
4241 base2 = get_temp_regvar (itype, base2);
4242 itype = TREE_TYPE (itype);
4245 /* Protect the entire array initialization so that we can destroy
4246 the partially constructed array if an exception is thrown.
4247 But don't do this if we're assigning. */
4248 if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4249 && from_array != 2)
4251 try_block = begin_try_block ();
4254 /* Should we try to create a constant initializer? */
4255 bool try_const = (TREE_CODE (atype) == ARRAY_TYPE
4256 && TREE_CONSTANT (maxindex)
4257 && (init ? TREE_CODE (init) == CONSTRUCTOR
4258 : (type_has_constexpr_default_constructor
4259 (inner_elt_type)))
4260 && (literal_type_p (inner_elt_type)
4261 || TYPE_HAS_CONSTEXPR_CTOR (inner_elt_type)));
4262 vec<constructor_elt, va_gc> *const_vec = NULL;
4263 bool saw_non_const = false;
4264 /* If we're initializing a static array, we want to do static
4265 initialization of any elements with constant initializers even if
4266 some are non-constant. */
4267 bool do_static_init = (DECL_P (obase) && TREE_STATIC (obase));
4269 bool empty_list = false;
4270 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
4271 && CONSTRUCTOR_NELTS (init) == 0)
4272 /* Skip over the handling of non-empty init lists. */
4273 empty_list = true;
4275 /* Maybe pull out constant value when from_array? */
4277 else if (init != NULL_TREE && TREE_CODE (init) == CONSTRUCTOR)
4279 /* Do non-default initialization of non-trivial arrays resulting from
4280 brace-enclosed initializers. */
4281 unsigned HOST_WIDE_INT idx;
4282 tree field, elt;
4283 /* If the constructor already has the array type, it's been through
4284 digest_init, so we shouldn't try to do anything more. */
4285 bool digested = same_type_p (atype, TREE_TYPE (init));
4286 from_array = 0;
4288 if (length_check)
4289 finish_length_check (atype, iterator, obase, CONSTRUCTOR_NELTS (init));
4291 if (try_const)
4292 vec_alloc (const_vec, CONSTRUCTOR_NELTS (init));
4294 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
4296 tree baseref = build1 (INDIRECT_REF, type, base);
4297 tree one_init;
4299 num_initialized_elts++;
4301 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
4302 if (digested)
4303 one_init = build2 (INIT_EXPR, type, baseref, elt);
4304 else if (MAYBE_CLASS_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE)
4305 one_init = build_aggr_init (baseref, elt, 0, complain);
4306 else
4307 one_init = cp_build_modify_expr (input_location, baseref,
4308 NOP_EXPR, elt, complain);
4309 if (one_init == error_mark_node)
4310 errors = true;
4311 if (try_const)
4313 tree e = maybe_constant_init (one_init);
4314 if (reduced_constant_expression_p (e))
4316 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4317 if (do_static_init)
4318 one_init = NULL_TREE;
4319 else
4320 one_init = build2 (INIT_EXPR, type, baseref, e);
4322 else
4324 if (do_static_init)
4326 tree value = build_zero_init (TREE_TYPE (e), NULL_TREE,
4327 true);
4328 if (value)
4329 CONSTRUCTOR_APPEND_ELT (const_vec, field, value);
4331 saw_non_const = true;
4335 if (one_init)
4336 finish_expr_stmt (one_init);
4337 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4339 one_init = cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4340 complain);
4341 if (one_init == error_mark_node)
4342 errors = true;
4343 else
4344 finish_expr_stmt (one_init);
4346 one_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4347 complain);
4348 if (one_init == error_mark_node)
4349 errors = true;
4350 else
4351 finish_expr_stmt (one_init);
4354 /* Any elements without explicit initializers get T{}. */
4355 empty_list = true;
4357 else if (init && TREE_CODE (init) == STRING_CST)
4359 /* Check that the array is at least as long as the string. */
4360 if (length_check)
4361 finish_length_check (atype, iterator, obase,
4362 TREE_STRING_LENGTH (init));
4363 tree length = build_int_cst (ptrdiff_type_node,
4364 TREE_STRING_LENGTH (init));
4366 /* Copy the string to the first part of the array. */
4367 tree alias_set = build_int_cst (build_pointer_type (type), 0);
4368 tree lhs = build2 (MEM_REF, TREE_TYPE (init), base, alias_set);
4369 tree stmt = build2 (MODIFY_EXPR, void_type_node, lhs, init);
4370 finish_expr_stmt (stmt);
4372 /* Adjust the counter and pointer. */
4373 stmt = cp_build_binary_op (loc, MINUS_EXPR, iterator, length, complain);
4374 stmt = build2 (MODIFY_EXPR, void_type_node, iterator, stmt);
4375 finish_expr_stmt (stmt);
4377 stmt = cp_build_binary_op (loc, PLUS_EXPR, base, length, complain);
4378 stmt = build2 (MODIFY_EXPR, void_type_node, base, stmt);
4379 finish_expr_stmt (stmt);
4381 /* And set the rest of the array to NUL. */
4382 from_array = 0;
4383 explicit_value_init_p = true;
4385 else if (from_array)
4387 if (init)
4388 /* OK, we set base2 above. */;
4389 else if (CLASS_TYPE_P (type)
4390 && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
4392 if (complain & tf_error)
4393 error ("initializer ends prematurely");
4394 errors = true;
4398 /* Now, default-initialize any remaining elements. We don't need to
4399 do that if a) the type does not need constructing, or b) we've
4400 already initialized all the elements.
4402 We do need to keep going if we're copying an array. */
4404 if (try_const && !init)
4405 /* With a constexpr default constructor, which we checked for when
4406 setting try_const above, default-initialization is equivalent to
4407 value-initialization, and build_value_init gives us something more
4408 friendly to maybe_constant_init. */
4409 explicit_value_init_p = true;
4410 if (from_array
4411 || ((type_build_ctor_call (type) || init || explicit_value_init_p)
4412 && ! (tree_fits_shwi_p (maxindex)
4413 && (num_initialized_elts
4414 == tree_to_shwi (maxindex) + 1))))
4416 /* If the ITERATOR is lesser or equal to -1, then we don't have to loop;
4417 we've already initialized all the elements. */
4418 tree for_stmt;
4419 tree elt_init;
4420 tree to;
4422 for_stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
4423 finish_init_stmt (for_stmt);
4424 finish_for_cond (build2 (GT_EXPR, boolean_type_node, iterator,
4425 build_int_cst (TREE_TYPE (iterator), -1)),
4426 for_stmt, false, 0);
4427 elt_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4428 complain);
4429 if (elt_init == error_mark_node)
4430 errors = true;
4431 finish_for_expr (elt_init, for_stmt);
4433 to = build1 (INDIRECT_REF, type, base);
4435 /* If the initializer is {}, then all elements are initialized from T{}.
4436 But for non-classes, that's the same as value-initialization. */
4437 if (empty_list)
4439 if (cxx_dialect >= cxx11 && AGGREGATE_TYPE_P (type))
4441 init = build_constructor (init_list_type_node, NULL);
4443 else
4445 init = NULL_TREE;
4446 explicit_value_init_p = true;
4450 if (from_array)
4452 tree from;
4454 if (base2)
4456 from = build1 (INDIRECT_REF, itype, base2);
4457 if (xvalue)
4458 from = move (from);
4459 if (direct_init)
4460 from = build_tree_list (NULL_TREE, from);
4462 else
4463 from = NULL_TREE;
4465 if (TREE_CODE (type) == ARRAY_TYPE)
4466 elt_init = build_vec_init (to, NULL_TREE, from, /*val_init*/false,
4467 from_array, complain);
4468 else if (from_array == 2)
4469 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR,
4470 from, complain);
4471 else if (type_build_ctor_call (type))
4472 elt_init = build_aggr_init (to, from, 0, complain);
4473 else if (from)
4474 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR, from,
4475 complain);
4476 else
4477 gcc_unreachable ();
4479 else if (TREE_CODE (type) == ARRAY_TYPE)
4481 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init))
4483 if ((complain & tf_error))
4484 error_at (loc, "array must be initialized "
4485 "with a brace-enclosed initializer");
4486 elt_init = error_mark_node;
4488 else
4489 elt_init = build_vec_init (build1 (INDIRECT_REF, type, base),
4490 0, init,
4491 explicit_value_init_p,
4492 0, complain);
4494 else if (explicit_value_init_p)
4496 elt_init = build_value_init (type, complain);
4497 if (elt_init != error_mark_node)
4498 elt_init = build2 (INIT_EXPR, type, to, elt_init);
4500 else
4502 gcc_assert (type_build_ctor_call (type) || init);
4503 if (CLASS_TYPE_P (type))
4504 elt_init = build_aggr_init (to, init, 0, complain);
4505 else
4507 if (TREE_CODE (init) == TREE_LIST)
4508 init = build_x_compound_expr_from_list (init, ELK_INIT,
4509 complain);
4510 elt_init = (init == error_mark_node
4511 ? error_mark_node
4512 : build2 (INIT_EXPR, type, to, init));
4516 if (elt_init == error_mark_node)
4517 errors = true;
4519 if (try_const)
4521 /* FIXME refs to earlier elts */
4522 tree e = maybe_constant_init (elt_init);
4523 if (reduced_constant_expression_p (e))
4525 if (initializer_zerop (e))
4526 /* Don't fill the CONSTRUCTOR with zeros. */
4527 e = NULL_TREE;
4528 if (do_static_init)
4529 elt_init = NULL_TREE;
4531 else
4533 saw_non_const = true;
4534 if (do_static_init)
4535 e = build_zero_init (TREE_TYPE (e), NULL_TREE, true);
4536 else
4537 e = NULL_TREE;
4540 if (e)
4542 int max = tree_to_shwi (maxindex)+1;
4543 for (; num_initialized_elts < max; ++num_initialized_elts)
4545 tree field = size_int (num_initialized_elts);
4546 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4551 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
4552 if (elt_init && !errors)
4553 finish_expr_stmt (elt_init);
4554 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4556 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4557 complain));
4558 if (base2)
4559 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base2, false,
4560 complain));
4562 finish_for_stmt (for_stmt);
4565 /* Make sure to cleanup any partially constructed elements. */
4566 if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4567 && from_array != 2)
4569 tree e;
4570 tree m = cp_build_binary_op (input_location,
4571 MINUS_EXPR, maxindex, iterator,
4572 complain);
4574 /* Flatten multi-dimensional array since build_vec_delete only
4575 expects one-dimensional array. */
4576 if (TREE_CODE (type) == ARRAY_TYPE)
4577 m = cp_build_binary_op (input_location,
4578 MULT_EXPR, m,
4579 /* Avoid mixing signed and unsigned. */
4580 convert (TREE_TYPE (m),
4581 array_type_nelts_total (type)),
4582 complain);
4584 finish_cleanup_try_block (try_block);
4585 e = build_vec_delete_1 (rval, m,
4586 inner_elt_type, sfk_complete_destructor,
4587 /*use_global_delete=*/0, complain);
4588 if (e == error_mark_node)
4589 errors = true;
4590 finish_cleanup (e, try_block);
4593 /* The value of the array initialization is the array itself, RVAL
4594 is a pointer to the first element. */
4595 finish_stmt_expr_expr (rval, stmt_expr);
4597 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
4599 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
4601 if (errors)
4602 return error_mark_node;
4604 if (try_const)
4606 if (!saw_non_const)
4608 tree const_init = build_constructor (atype, const_vec);
4609 return build2 (INIT_EXPR, atype, obase, const_init);
4611 else if (do_static_init && !vec_safe_is_empty (const_vec))
4612 DECL_INITIAL (obase) = build_constructor (atype, const_vec);
4613 else
4614 vec_free (const_vec);
4617 /* Now make the result have the correct type. */
4618 if (TREE_CODE (atype) == ARRAY_TYPE)
4620 atype = build_pointer_type (atype);
4621 stmt_expr = build1 (NOP_EXPR, atype, stmt_expr);
4622 stmt_expr = cp_build_fold_indirect_ref (stmt_expr);
4623 TREE_NO_WARNING (stmt_expr) = 1;
4626 return stmt_expr;
4629 /* Call the DTOR_KIND destructor for EXP. FLAGS are as for
4630 build_delete. */
4632 static tree
4633 build_dtor_call (tree exp, special_function_kind dtor_kind, int flags,
4634 tsubst_flags_t complain)
4636 tree name;
4637 switch (dtor_kind)
4639 case sfk_complete_destructor:
4640 name = complete_dtor_identifier;
4641 break;
4643 case sfk_base_destructor:
4644 name = base_dtor_identifier;
4645 break;
4647 case sfk_deleting_destructor:
4648 name = deleting_dtor_identifier;
4649 break;
4651 default:
4652 gcc_unreachable ();
4655 return build_special_member_call (exp, name,
4656 /*args=*/NULL,
4657 /*binfo=*/TREE_TYPE (exp),
4658 flags,
4659 complain);
4662 /* Generate a call to a destructor. TYPE is the type to cast ADDR to.
4663 ADDR is an expression which yields the store to be destroyed.
4664 AUTO_DELETE is the name of the destructor to call, i.e., either
4665 sfk_complete_destructor, sfk_base_destructor, or
4666 sfk_deleting_destructor.
4668 FLAGS is the logical disjunction of zero or more LOOKUP_
4669 flags. See cp-tree.h for more info. */
4671 tree
4672 build_delete (tree otype, tree addr, special_function_kind auto_delete,
4673 int flags, int use_global_delete, tsubst_flags_t complain)
4675 tree expr;
4677 if (addr == error_mark_node)
4678 return error_mark_node;
4680 tree type = TYPE_MAIN_VARIANT (otype);
4682 /* Can happen when CURRENT_EXCEPTION_OBJECT gets its type
4683 set to `error_mark_node' before it gets properly cleaned up. */
4684 if (type == error_mark_node)
4685 return error_mark_node;
4687 if (TYPE_PTR_P (type))
4688 type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
4690 if (TREE_CODE (type) == ARRAY_TYPE)
4692 if (TYPE_DOMAIN (type) == NULL_TREE)
4694 if (complain & tf_error)
4695 error ("unknown array size in delete");
4696 return error_mark_node;
4698 return build_vec_delete (addr, array_type_nelts (type),
4699 auto_delete, use_global_delete, complain);
4702 bool deleting = (auto_delete == sfk_deleting_destructor);
4703 gcc_assert (deleting == !(flags & LOOKUP_DESTRUCTOR));
4705 if (TYPE_PTR_P (otype))
4707 addr = mark_rvalue_use (addr);
4709 /* We don't want to warn about delete of void*, only other
4710 incomplete types. Deleting other incomplete types
4711 invokes undefined behavior, but it is not ill-formed, so
4712 compile to something that would even do The Right Thing
4713 (TM) should the type have a trivial dtor and no delete
4714 operator. */
4715 if (!VOID_TYPE_P (type))
4717 complete_type (type);
4718 if (!COMPLETE_TYPE_P (type))
4720 if ((complain & tf_warning)
4721 && warning (OPT_Wdelete_incomplete,
4722 "possible problem detected in invocation of "
4723 "delete operator:"))
4725 cxx_incomplete_type_diagnostic (addr, type, DK_WARNING);
4726 inform (input_location,
4727 "neither the destructor nor the class-specific "
4728 "operator delete will be called, even if they are "
4729 "declared when the class is defined");
4732 else if (deleting && warn_delnonvdtor
4733 && MAYBE_CLASS_TYPE_P (type) && !CLASSTYPE_FINAL (type)
4734 && TYPE_POLYMORPHIC_P (type))
4736 tree dtor = CLASSTYPE_DESTRUCTOR (type);
4737 if (!dtor || !DECL_VINDEX (dtor))
4739 if (CLASSTYPE_PURE_VIRTUALS (type))
4740 warning (OPT_Wdelete_non_virtual_dtor,
4741 "deleting object of abstract class type %qT"
4742 " which has non-virtual destructor"
4743 " will cause undefined behavior", type);
4744 else
4745 warning (OPT_Wdelete_non_virtual_dtor,
4746 "deleting object of polymorphic class type %qT"
4747 " which has non-virtual destructor"
4748 " might cause undefined behavior", type);
4753 /* Throw away const and volatile on target type of addr. */
4754 addr = convert_force (build_pointer_type (type), addr, 0, complain);
4756 else
4758 /* Don't check PROTECT here; leave that decision to the
4759 destructor. If the destructor is accessible, call it,
4760 else report error. */
4761 addr = cp_build_addr_expr (addr, complain);
4762 if (addr == error_mark_node)
4763 return error_mark_node;
4765 addr = convert_force (build_pointer_type (type), addr, 0, complain);
4768 if (deleting)
4769 /* We will use ADDR multiple times so we must save it. */
4770 addr = save_expr (addr);
4772 bool virtual_p = false;
4773 if (type_build_dtor_call (type))
4775 if (CLASSTYPE_LAZY_DESTRUCTOR (type))
4776 lazily_declare_fn (sfk_destructor, type);
4777 virtual_p = DECL_VIRTUAL_P (CLASSTYPE_DESTRUCTOR (type));
4780 tree head = NULL_TREE;
4781 tree do_delete = NULL_TREE;
4783 if (!deleting)
4785 /* Leave do_delete null. */
4787 /* For `::delete x', we must not use the deleting destructor
4788 since then we would not be sure to get the global `operator
4789 delete'. */
4790 else if (use_global_delete)
4792 head = get_target_expr (build_headof (addr));
4793 /* Delete the object. */
4794 do_delete = build_op_delete_call (DELETE_EXPR,
4795 head,
4796 cxx_sizeof_nowarn (type),
4797 /*global_p=*/true,
4798 /*placement=*/NULL_TREE,
4799 /*alloc_fn=*/NULL_TREE,
4800 complain);
4801 /* Otherwise, treat this like a complete object destructor
4802 call. */
4803 auto_delete = sfk_complete_destructor;
4805 /* If the destructor is non-virtual, there is no deleting
4806 variant. Instead, we must explicitly call the appropriate
4807 `operator delete' here. */
4808 else if (!virtual_p)
4810 /* Build the call. */
4811 do_delete = build_op_delete_call (DELETE_EXPR,
4812 addr,
4813 cxx_sizeof_nowarn (type),
4814 /*global_p=*/false,
4815 /*placement=*/NULL_TREE,
4816 /*alloc_fn=*/NULL_TREE,
4817 complain);
4818 /* Call the complete object destructor. */
4819 auto_delete = sfk_complete_destructor;
4821 else if (TYPE_GETS_REG_DELETE (type))
4823 /* Make sure we have access to the member op delete, even though
4824 we'll actually be calling it from the destructor. */
4825 build_op_delete_call (DELETE_EXPR, addr, cxx_sizeof_nowarn (type),
4826 /*global_p=*/false,
4827 /*placement=*/NULL_TREE,
4828 /*alloc_fn=*/NULL_TREE,
4829 complain);
4832 if (type_build_dtor_call (type))
4833 expr = build_dtor_call (cp_build_fold_indirect_ref (addr),
4834 auto_delete, flags, complain);
4835 else
4836 expr = build_trivial_dtor_call (addr);
4837 if (expr == error_mark_node)
4838 return error_mark_node;
4840 if (!deleting)
4841 return expr;
4843 if (do_delete && !TREE_SIDE_EFFECTS (expr))
4844 expr = do_delete;
4845 else if (do_delete)
4846 /* The delete operator must be called, regardless of whether
4847 the destructor throws.
4849 [expr.delete]/7 The deallocation function is called
4850 regardless of whether the destructor for the object or some
4851 element of the array throws an exception. */
4852 expr = build2 (TRY_FINALLY_EXPR, void_type_node, expr, do_delete);
4854 /* We need to calculate this before the dtor changes the vptr. */
4855 if (head)
4856 expr = build2 (COMPOUND_EXPR, void_type_node, head, expr);
4858 /* Handle deleting a null pointer. */
4859 warning_sentinel s (warn_address);
4860 tree ifexp = cp_build_binary_op (input_location, NE_EXPR, addr,
4861 nullptr_node, complain);
4862 ifexp = cp_fully_fold (ifexp);
4864 if (ifexp == error_mark_node)
4865 return error_mark_node;
4866 /* This is a compiler generated comparison, don't emit
4867 e.g. -Wnonnull-compare warning for it. */
4868 else if (TREE_CODE (ifexp) == NE_EXPR)
4869 TREE_NO_WARNING (ifexp) = 1;
4871 if (!integer_nonzerop (ifexp))
4872 expr = build3 (COND_EXPR, void_type_node, ifexp, expr, void_node);
4874 return expr;
4877 /* At the beginning of a destructor, push cleanups that will call the
4878 destructors for our base classes and members.
4880 Called from begin_destructor_body. */
4882 void
4883 push_base_cleanups (void)
4885 tree binfo, base_binfo;
4886 int i;
4887 tree member;
4888 tree expr;
4889 vec<tree, va_gc> *vbases;
4891 /* Run destructors for all virtual baseclasses. */
4892 if (!ABSTRACT_CLASS_TYPE_P (current_class_type)
4893 && CLASSTYPE_VBASECLASSES (current_class_type))
4895 tree cond = (condition_conversion
4896 (build2 (BIT_AND_EXPR, integer_type_node,
4897 current_in_charge_parm,
4898 integer_two_node)));
4900 /* The CLASSTYPE_VBASECLASSES vector is in initialization
4901 order, which is also the right order for pushing cleanups. */
4902 for (vbases = CLASSTYPE_VBASECLASSES (current_class_type), i = 0;
4903 vec_safe_iterate (vbases, i, &base_binfo); i++)
4905 if (type_build_dtor_call (BINFO_TYPE (base_binfo)))
4907 expr = build_special_member_call (current_class_ref,
4908 base_dtor_identifier,
4909 NULL,
4910 base_binfo,
4911 (LOOKUP_NORMAL
4912 | LOOKUP_NONVIRTUAL),
4913 tf_warning_or_error);
4914 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
4916 expr = build3 (COND_EXPR, void_type_node, cond,
4917 expr, void_node);
4918 finish_decl_cleanup (NULL_TREE, expr);
4924 /* Take care of the remaining baseclasses. */
4925 for (binfo = TYPE_BINFO (current_class_type), i = 0;
4926 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
4928 if (BINFO_VIRTUAL_P (base_binfo)
4929 || !type_build_dtor_call (BINFO_TYPE (base_binfo)))
4930 continue;
4932 expr = build_special_member_call (current_class_ref,
4933 base_dtor_identifier,
4934 NULL, base_binfo,
4935 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
4936 tf_warning_or_error);
4937 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
4938 finish_decl_cleanup (NULL_TREE, expr);
4941 /* Don't automatically destroy union members. */
4942 if (TREE_CODE (current_class_type) == UNION_TYPE)
4943 return;
4945 for (member = TYPE_FIELDS (current_class_type); member;
4946 member = DECL_CHAIN (member))
4948 tree this_type = TREE_TYPE (member);
4949 if (this_type == error_mark_node
4950 || TREE_CODE (member) != FIELD_DECL
4951 || DECL_ARTIFICIAL (member))
4952 continue;
4953 if (ANON_AGGR_TYPE_P (this_type))
4954 continue;
4955 if (type_build_dtor_call (this_type))
4957 tree this_member = (build_class_member_access_expr
4958 (current_class_ref, member,
4959 /*access_path=*/NULL_TREE,
4960 /*preserve_reference=*/false,
4961 tf_warning_or_error));
4962 expr = build_delete (this_type, this_member,
4963 sfk_complete_destructor,
4964 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR|LOOKUP_NORMAL,
4965 0, tf_warning_or_error);
4966 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (this_type))
4967 finish_decl_cleanup (NULL_TREE, expr);
4972 /* Build a C++ vector delete expression.
4973 MAXINDEX is the number of elements to be deleted.
4974 ELT_SIZE is the nominal size of each element in the vector.
4975 BASE is the expression that should yield the store to be deleted.
4976 This function expands (or synthesizes) these calls itself.
4977 AUTO_DELETE_VEC says whether the container (vector) should be deallocated.
4979 This also calls delete for virtual baseclasses of elements of the vector.
4981 Update: MAXINDEX is no longer needed. The size can be extracted from the
4982 start of the vector for pointers, and from the type for arrays. We still
4983 use MAXINDEX for arrays because it happens to already have one of the
4984 values we'd have to extract. (We could use MAXINDEX with pointers to
4985 confirm the size, and trap if the numbers differ; not clear that it'd
4986 be worth bothering.) */
4988 tree
4989 build_vec_delete (tree base, tree maxindex,
4990 special_function_kind auto_delete_vec,
4991 int use_global_delete, tsubst_flags_t complain)
4993 tree type;
4994 tree rval;
4995 tree base_init = NULL_TREE;
4997 type = TREE_TYPE (base);
4999 if (TYPE_PTR_P (type))
5001 /* Step back one from start of vector, and read dimension. */
5002 tree cookie_addr;
5003 tree size_ptr_type = build_pointer_type (sizetype);
5005 base = mark_rvalue_use (base);
5006 if (TREE_SIDE_EFFECTS (base))
5008 base_init = get_target_expr (base);
5009 base = TARGET_EXPR_SLOT (base_init);
5011 type = strip_array_types (TREE_TYPE (type));
5012 cookie_addr = fold_build1_loc (input_location, NEGATE_EXPR,
5013 sizetype, TYPE_SIZE_UNIT (sizetype));
5014 cookie_addr = fold_build_pointer_plus (fold_convert (size_ptr_type, base),
5015 cookie_addr);
5016 maxindex = cp_build_fold_indirect_ref (cookie_addr);
5018 else if (TREE_CODE (type) == ARRAY_TYPE)
5020 /* Get the total number of things in the array, maxindex is a
5021 bad name. */
5022 maxindex = array_type_nelts_total (type);
5023 type = strip_array_types (type);
5024 base = decay_conversion (base, complain);
5025 if (base == error_mark_node)
5026 return error_mark_node;
5027 if (TREE_SIDE_EFFECTS (base))
5029 base_init = get_target_expr (base);
5030 base = TARGET_EXPR_SLOT (base_init);
5033 else
5035 if (base != error_mark_node && !(complain & tf_error))
5036 error ("type to vector delete is neither pointer or array type");
5037 return error_mark_node;
5040 rval = build_vec_delete_1 (base, maxindex, type, auto_delete_vec,
5041 use_global_delete, complain);
5042 if (base_init && rval != error_mark_node)
5043 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), base_init, rval);
5045 return rval;
5048 #include "gt-cp-init.h"