c++, coroutines: Simplify separation of the user function body and ramp.
[official-gcc.git] / gcc / cp / init.cc
blobde82152bd1d378c86012ea5602ac1a7e0807f5f1
1 /* Handle initialization things in -*- C++ -*-
2 Copyright (C) 1987-2024 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"
36 #include "stor-layout.h"
37 #include "pointer-query.h"
39 static bool begin_init_stmts (tree *, tree *);
40 static tree finish_init_stmts (bool, tree, tree);
41 static void construct_virtual_base (tree, tree);
42 static bool expand_aggr_init_1 (tree, tree, tree, tree, int, tsubst_flags_t);
43 static bool expand_default_init (tree, tree, tree, tree, int, tsubst_flags_t);
44 static int member_init_ok_or_else (tree, tree, tree);
45 static void expand_virtual_init (tree, tree);
46 static tree sort_mem_initializers (tree, tree);
47 static tree initializing_context (tree);
48 static void expand_cleanup_for_base (tree, tree);
49 static tree dfs_initialize_vtbl_ptrs (tree, void *);
50 static tree build_field_list (tree, tree, int *);
51 static int diagnose_uninitialized_cst_or_ref_member_1 (tree, tree, bool, bool);
53 static GTY(()) tree fn;
55 /* We are about to generate some complex initialization code.
56 Conceptually, it is all a single expression. However, we may want
57 to include conditionals, loops, and other such statement-level
58 constructs. Therefore, we build the initialization code inside a
59 statement-expression. This function starts such an expression.
60 STMT_EXPR_P and COMPOUND_STMT_P are filled in by this function;
61 pass them back to finish_init_stmts when the expression is
62 complete. */
64 static bool
65 begin_init_stmts (tree *stmt_expr_p, tree *compound_stmt_p)
67 bool is_global = !building_stmt_list_p ();
69 *stmt_expr_p = begin_stmt_expr ();
70 *compound_stmt_p = begin_compound_stmt (BCS_NO_SCOPE);
72 return is_global;
75 /* Finish out the statement-expression begun by the previous call to
76 begin_init_stmts. Returns the statement-expression itself. */
78 static tree
79 finish_init_stmts (bool is_global, tree stmt_expr, tree compound_stmt)
81 finish_compound_stmt (compound_stmt);
83 stmt_expr = finish_stmt_expr (stmt_expr, true);
85 gcc_assert (!building_stmt_list_p () == is_global);
87 return stmt_expr;
90 /* Constructors */
92 /* Called from initialize_vtbl_ptrs via dfs_walk. BINFO is the base
93 which we want to initialize the vtable pointer for, DATA is
94 TREE_LIST whose TREE_VALUE is the this ptr expression. */
96 static tree
97 dfs_initialize_vtbl_ptrs (tree binfo, void *data)
99 if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
100 return dfs_skip_bases;
102 if (!BINFO_PRIMARY_P (binfo) || BINFO_VIRTUAL_P (binfo))
104 tree base_ptr = TREE_VALUE ((tree) data);
106 base_ptr = build_base_path (PLUS_EXPR, base_ptr, binfo, /*nonnull=*/1,
107 tf_warning_or_error);
109 expand_virtual_init (binfo, base_ptr);
112 return NULL_TREE;
115 /* Initialize all the vtable pointers in the object pointed to by
116 ADDR. */
118 void
119 initialize_vtbl_ptrs (tree addr)
121 tree list;
122 tree type;
124 type = TREE_TYPE (TREE_TYPE (addr));
125 list = build_tree_list (type, addr);
127 /* Walk through the hierarchy, initializing the vptr in each base
128 class. We do these in pre-order because we can't find the virtual
129 bases for a class until we've initialized the vtbl for that
130 class. */
131 dfs_walk_once (TYPE_BINFO (type), dfs_initialize_vtbl_ptrs, NULL, list);
134 /* Return an expression for the zero-initialization of an object with
135 type T. This expression will either be a constant (in the case
136 that T is a scalar), or a CONSTRUCTOR (in the case that T is an
137 aggregate), or NULL (in the case that T does not require
138 initialization). In either case, the value can be used as
139 DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
140 initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
141 is the number of elements in the array. If STATIC_STORAGE_P is
142 TRUE, initializers are only generated for entities for which
143 zero-initialization does not simply mean filling the storage with
144 zero bytes. FIELD_SIZE, if non-NULL, is the bit size of the field,
145 subfields with bit positions at or above that bit size shouldn't
146 be added. Note that this only works when the result is assigned
147 to a base COMPONENT_REF; if we only have a pointer to the base subobject,
148 expand_assignment will end up clearing the full size of TYPE. */
150 static tree
151 build_zero_init_1 (tree type, tree nelts, bool static_storage_p,
152 tree field_size)
154 tree init = NULL_TREE;
156 /* [dcl.init]
158 To zero-initialize an object of type T means:
160 -- if T is a scalar type, the storage is set to the value of zero
161 converted to T.
163 -- if T is a non-union class type, the storage for each non-static
164 data member and each base-class subobject is zero-initialized.
166 -- if T is a union type, the storage for its first data member is
167 zero-initialized.
169 -- if T is an array type, the storage for each element is
170 zero-initialized.
172 -- if T is a reference type, no initialization is performed. */
174 gcc_assert (nelts == NULL_TREE || TREE_CODE (nelts) == INTEGER_CST);
176 if (type == error_mark_node)
178 else if (static_storage_p && zero_init_p (type))
179 /* In order to save space, we do not explicitly build initializers
180 for items that do not need them. GCC's semantics are that
181 items with static storage duration that are not otherwise
182 initialized are initialized to zero. */
184 else if (TYPE_PTR_OR_PTRMEM_P (type))
185 init = fold (convert (type, nullptr_node));
186 else if (NULLPTR_TYPE_P (type))
187 init = build_int_cst (type, 0);
188 else if (SCALAR_TYPE_P (type))
189 init = build_zero_cst (type);
190 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (type)))
192 tree field, next;
193 vec<constructor_elt, va_gc> *v = NULL;
195 /* Iterate over the fields, building initializations. */
196 for (field = TYPE_FIELDS (type); field; field = next)
198 next = DECL_CHAIN (field);
200 if (TREE_CODE (field) != FIELD_DECL)
201 continue;
203 /* For unions, only the first field is initialized. */
204 if (TREE_CODE (type) == UNION_TYPE)
205 next = NULL_TREE;
207 if (TREE_TYPE (field) == error_mark_node)
208 continue;
210 /* Don't add virtual bases for base classes if they are beyond
211 the size of the current field, that means it is present
212 somewhere else in the object. */
213 if (field_size)
215 tree bitpos = bit_position (field);
216 if (TREE_CODE (bitpos) == INTEGER_CST
217 && !tree_int_cst_lt (bitpos, field_size))
218 continue;
221 /* Don't add zero width bitfields. */
222 if (DECL_C_BIT_FIELD (field)
223 && integer_zerop (DECL_SIZE (field)))
224 continue;
226 /* Note that for class types there will be FIELD_DECLs
227 corresponding to base classes as well. Thus, iterating
228 over TYPE_FIELDs will result in correct initialization of
229 all of the subobjects. */
230 if (!static_storage_p || !zero_init_p (TREE_TYPE (field)))
232 tree new_field_size
233 = (DECL_FIELD_IS_BASE (field)
234 && DECL_SIZE (field)
235 && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
236 ? DECL_SIZE (field) : NULL_TREE;
237 tree value = build_zero_init_1 (TREE_TYPE (field),
238 /*nelts=*/NULL_TREE,
239 static_storage_p,
240 new_field_size);
241 if (value)
242 CONSTRUCTOR_APPEND_ELT(v, field, value);
246 /* Build a constructor to contain the initializations. */
247 init = build_constructor (type, v);
249 else if (TREE_CODE (type) == ARRAY_TYPE)
251 tree max_index;
252 vec<constructor_elt, va_gc> *v = NULL;
254 /* Iterate over the array elements, building initializations. */
255 if (nelts)
256 max_index = fold_build2_loc (input_location, MINUS_EXPR,
257 TREE_TYPE (nelts), nelts,
258 build_one_cst (TREE_TYPE (nelts)));
259 /* Treat flexible array members like [0] arrays. */
260 else if (TYPE_DOMAIN (type) == NULL_TREE)
261 return NULL_TREE;
262 else
263 max_index = array_type_nelts (type);
265 /* If we have an error_mark here, we should just return error mark
266 as we don't know the size of the array yet. */
267 if (max_index == error_mark_node)
268 return error_mark_node;
269 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
271 /* A zero-sized array, which is accepted as an extension, will
272 have an upper bound of -1. */
273 if (!integer_minus_onep (max_index))
275 constructor_elt ce;
277 /* If this is a one element array, we just use a regular init. */
278 if (integer_zerop (max_index))
279 ce.index = size_zero_node;
280 else
281 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node,
282 max_index);
284 ce.value = build_zero_init_1 (TREE_TYPE (type), /*nelts=*/NULL_TREE,
285 static_storage_p, NULL_TREE);
286 if (ce.value)
288 vec_alloc (v, 1);
289 v->quick_push (ce);
293 /* Build a constructor to contain the initializations. */
294 init = build_constructor (type, v);
296 else if (VECTOR_TYPE_P (type))
297 init = build_zero_cst (type);
298 else
299 gcc_assert (TYPE_REF_P (type));
301 /* In all cases, the initializer is a constant. */
302 if (init)
303 TREE_CONSTANT (init) = 1;
305 return init;
308 /* Return an expression for the zero-initialization of an object with
309 type T. This expression will either be a constant (in the case
310 that T is a scalar), or a CONSTRUCTOR (in the case that T is an
311 aggregate), or NULL (in the case that T does not require
312 initialization). In either case, the value can be used as
313 DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
314 initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
315 is the number of elements in the array. If STATIC_STORAGE_P is
316 TRUE, initializers are only generated for entities for which
317 zero-initialization does not simply mean filling the storage with
318 zero bytes. */
320 tree
321 build_zero_init (tree type, tree nelts, bool static_storage_p)
323 return build_zero_init_1 (type, nelts, static_storage_p, NULL_TREE);
326 /* Return a suitable initializer for value-initializing an object of type
327 TYPE, as described in [dcl.init]. */
329 tree
330 build_value_init (tree type, tsubst_flags_t complain)
332 /* [dcl.init]
334 To value-initialize an object of type T means:
336 - if T is a class type (clause 9) with either no default constructor
337 (12.1) or a default constructor that is user-provided or deleted,
338 then the object is default-initialized;
340 - if T is a (possibly cv-qualified) class type without a user-provided
341 or deleted default constructor, then the object is zero-initialized
342 and the semantic constraints for default-initialization are checked,
343 and if T has a non-trivial default constructor, the object is
344 default-initialized;
346 - if T is an array type, then each element is value-initialized;
348 - otherwise, the object is zero-initialized.
350 A program that calls for default-initialization or
351 value-initialization of an entity of reference type is ill-formed. */
353 if (CLASS_TYPE_P (type) && type_build_ctor_call (type))
355 tree ctor
356 = build_special_member_call (NULL_TREE, complete_ctor_identifier,
357 NULL, type, LOOKUP_NORMAL, complain);
358 if (ctor == error_mark_node || TREE_CONSTANT (ctor))
359 return ctor;
360 if (processing_template_decl)
361 /* The AGGR_INIT_EXPR tweaking below breaks in templates. */
362 return build_min (CAST_EXPR, type, NULL_TREE);
363 tree fn = NULL_TREE;
364 if (TREE_CODE (ctor) == CALL_EXPR)
365 fn = get_callee_fndecl (ctor);
366 ctor = build_aggr_init_expr (type, ctor);
367 if (fn && user_provided_p (fn))
368 return ctor;
369 else if (TYPE_HAS_COMPLEX_DFLT (type))
371 /* This is a class that needs constructing, but doesn't have
372 a user-provided constructor. So we need to zero-initialize
373 the object and then call the implicitly defined ctor.
374 This will be handled in simplify_aggr_init_expr. */
375 AGGR_INIT_ZERO_FIRST (ctor) = 1;
376 return ctor;
380 /* Discard any access checking during subobject initialization;
381 the checks are implied by the call to the ctor which we have
382 verified is OK (cpp0x/defaulted46.C). */
383 push_deferring_access_checks (dk_deferred);
384 tree r = build_value_init_noctor (type, complain);
385 pop_deferring_access_checks ();
386 return r;
389 /* Like build_value_init, but don't call the constructor for TYPE. Used
390 for base initializers. */
392 tree
393 build_value_init_noctor (tree type, tsubst_flags_t complain)
395 if (!COMPLETE_TYPE_P (type))
397 if (complain & tf_error)
398 error ("value-initialization of incomplete type %qT", type);
399 return error_mark_node;
401 /* FIXME the class and array cases should just use digest_init once it is
402 SFINAE-enabled. */
403 if (CLASS_TYPE_P (type))
405 gcc_assert (!TYPE_HAS_COMPLEX_DFLT (type)
406 || errorcount != 0);
408 if (TREE_CODE (type) != UNION_TYPE)
410 tree field;
411 vec<constructor_elt, va_gc> *v = NULL;
413 /* Iterate over the fields, building initializations. */
414 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
416 tree ftype, value;
418 if (TREE_CODE (field) != FIELD_DECL)
419 continue;
421 ftype = TREE_TYPE (field);
423 if (ftype == error_mark_node)
424 continue;
426 /* Ignore flexible array members for value initialization. */
427 if (TREE_CODE (ftype) == ARRAY_TYPE
428 && !COMPLETE_TYPE_P (ftype)
429 && !TYPE_DOMAIN (ftype)
430 && COMPLETE_TYPE_P (TREE_TYPE (ftype))
431 && (next_aggregate_field (DECL_CHAIN (field))
432 == NULL_TREE))
433 continue;
435 /* Ignore unnamed zero-width bitfields. */
436 if (DECL_UNNAMED_BIT_FIELD (field)
437 && integer_zerop (DECL_SIZE (field)))
438 continue;
440 /* We could skip vfields and fields of types with
441 user-defined constructors, but I think that won't improve
442 performance at all; it should be simpler in general just
443 to zero out the entire object than try to only zero the
444 bits that actually need it. */
446 /* Note that for class types there will be FIELD_DECLs
447 corresponding to base classes as well. Thus, iterating
448 over TYPE_FIELDs will result in correct initialization of
449 all of the subobjects. */
450 value = build_value_init (ftype, complain);
451 value = maybe_constant_init (value);
453 if (value == error_mark_node)
454 return error_mark_node;
456 CONSTRUCTOR_APPEND_ELT(v, field, value);
458 /* We shouldn't have gotten here for anything that would need
459 non-trivial initialization, and gimplify_init_ctor_preeval
460 would need to be fixed to allow it. */
461 gcc_assert (TREE_CODE (value) != TARGET_EXPR
462 && TREE_CODE (value) != AGGR_INIT_EXPR);
465 /* Build a constructor to contain the zero- initializations. */
466 return build_constructor (type, v);
469 else if (TREE_CODE (type) == ARRAY_TYPE)
471 vec<constructor_elt, va_gc> *v = NULL;
473 /* Iterate over the array elements, building initializations. */
474 tree max_index = array_type_nelts (type);
476 /* If we have an error_mark here, we should just return error mark
477 as we don't know the size of the array yet. */
478 if (max_index == error_mark_node)
480 if (complain & tf_error)
481 error ("cannot value-initialize array of unknown bound %qT",
482 type);
483 return error_mark_node;
485 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
487 /* A zero-sized array, which is accepted as an extension, will
488 have an upper bound of -1. */
489 if (!tree_int_cst_equal (max_index, integer_minus_one_node))
491 constructor_elt ce;
493 /* If this is a one element array, we just use a regular init. */
494 if (tree_int_cst_equal (size_zero_node, max_index))
495 ce.index = size_zero_node;
496 else
497 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node, max_index);
499 ce.value = build_value_init (TREE_TYPE (type), complain);
500 ce.value = maybe_constant_init (ce.value);
501 if (ce.value == error_mark_node)
502 return error_mark_node;
504 vec_alloc (v, 1);
505 v->quick_push (ce);
507 /* We shouldn't have gotten here for anything that would need
508 non-trivial initialization, and gimplify_init_ctor_preeval
509 would need to be fixed to allow it. */
510 gcc_assert (TREE_CODE (ce.value) != TARGET_EXPR
511 && TREE_CODE (ce.value) != AGGR_INIT_EXPR);
514 /* Build a constructor to contain the initializations. */
515 return build_constructor (type, v);
517 else if (TREE_CODE (type) == FUNCTION_TYPE)
519 if (complain & tf_error)
520 error ("value-initialization of function type %qT", type);
521 return error_mark_node;
523 else if (TYPE_REF_P (type))
525 if (complain & tf_error)
526 error ("value-initialization of reference type %qT", type);
527 return error_mark_node;
530 return build_zero_init (type, NULL_TREE, /*static_storage_p=*/false);
533 /* Initialize current class with INIT, a TREE_LIST of arguments for
534 a target constructor. If TREE_LIST is void_type_node, an empty
535 initializer list was given. Return the target constructor. */
537 static tree
538 perform_target_ctor (tree init)
540 tree decl = current_class_ref;
541 tree type = current_class_type;
543 init = build_aggr_init (decl, init, LOOKUP_NORMAL|LOOKUP_DELEGATING_CONS,
544 tf_warning_or_error);
545 finish_expr_stmt (init);
546 if (type_build_dtor_call (type))
548 tree expr = build_delete (input_location,
549 type, decl, sfk_complete_destructor,
550 LOOKUP_NORMAL
551 |LOOKUP_NONVIRTUAL
552 |LOOKUP_DESTRUCTOR,
553 0, tf_warning_or_error);
554 if (DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
556 tree base = build_delete (input_location,
557 type, decl, sfk_base_destructor,
558 LOOKUP_NORMAL
559 |LOOKUP_NONVIRTUAL
560 |LOOKUP_DESTRUCTOR,
561 0, tf_warning_or_error);
562 expr = build_if_in_charge (expr, base);
564 if (expr != error_mark_node
565 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
566 finish_eh_cleanup (expr);
568 return init;
571 /* Instantiate the default member initializer of MEMBER, if needed.
572 Only get_nsdmi should use the return value of this function. */
574 tree
575 maybe_instantiate_nsdmi_init (tree member, tsubst_flags_t complain)
577 tree init = DECL_INITIAL (member);
579 /* tsubst_decl uses void_node to indicate an uninstantiated DMI. */
580 if (init == void_node)
582 /* Clear any special tsubst flags; the result of NSDMI instantiation
583 should be independent of the substitution context. */
584 complain &= tf_warning_or_error;
586 init = DECL_INITIAL (DECL_TI_TEMPLATE (member));
587 location_t expr_loc
588 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (member));
589 if (TREE_CODE (init) == DEFERRED_PARSE)
590 /* Unparsed. */;
591 /* Check recursive instantiation. */
592 else if (DECL_INSTANTIATING_NSDMI_P (member))
594 if (complain & tf_error)
595 error_at (expr_loc, "recursive instantiation of default member "
596 "initializer for %qD", member);
597 init = error_mark_node;
599 else
601 cp_evaluated ev;
603 location_t sloc = input_location;
604 input_location = expr_loc;
606 DECL_INSTANTIATING_NSDMI_P (member) = 1;
608 bool pushed = false;
609 tree ctx = type_context_for_name_lookup (member);
611 bool push_to_top = maybe_push_to_top_level (member);
612 if (!currently_open_class (ctx))
614 push_nested_class (ctx);
615 push_deferring_access_checks (dk_no_deferred);
616 pushed = true;
619 inject_this_parameter (ctx, TYPE_UNQUALIFIED);
621 start_lambda_scope (member);
623 /* Do deferred instantiation of the NSDMI. */
624 init = tsubst_expr (init, DECL_TI_ARGS (member), complain, member);
625 init = digest_nsdmi_init (member, init, complain);
627 finish_lambda_scope ();
629 DECL_INSTANTIATING_NSDMI_P (member) = 0;
631 if (init != error_mark_node)
632 DECL_INITIAL (member) = init;
634 if (pushed)
636 pop_deferring_access_checks ();
637 pop_nested_class ();
639 maybe_pop_from_top_level (push_to_top);
641 input_location = sloc;
645 return init;
648 /* Return the non-static data initializer for FIELD_DECL MEMBER. */
650 tree
651 get_nsdmi (tree member, bool in_ctor, tsubst_flags_t complain)
653 tree save_ccp = current_class_ptr;
654 tree save_ccr = current_class_ref;
656 tree init = maybe_instantiate_nsdmi_init (member, complain);
658 if (init && TREE_CODE (init) == DEFERRED_PARSE)
660 if (complain & tf_error)
662 error ("default member initializer for %qD required before the end "
663 "of its enclosing class", member);
664 inform (location_of (init), "defined here");
665 DECL_INITIAL (member) = error_mark_node;
667 init = error_mark_node;
670 if (in_ctor)
672 current_class_ptr = save_ccp;
673 current_class_ref = save_ccr;
675 else
677 /* Use a PLACEHOLDER_EXPR when we don't have a 'this' parameter to
678 refer to; constexpr evaluation knows what to do with it. */
679 current_class_ref = build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (member));
680 current_class_ptr = build_address (current_class_ref);
683 /* Clear processing_template_decl for sake of break_out_target_exprs;
684 INIT is always non-templated. */
685 processing_template_decl_sentinel ptds;
687 /* Strip redundant TARGET_EXPR so we don't need to remap it, and
688 so the aggregate init code below will see a CONSTRUCTOR. */
689 bool simple_target = (init && SIMPLE_TARGET_EXPR_P (init));
690 if (simple_target)
691 init = TARGET_EXPR_INITIAL (init);
692 init = break_out_target_exprs (init, /*loc*/true);
693 if (init && TREE_CODE (init) == TARGET_EXPR)
694 /* In a constructor, this expresses the full initialization, prevent
695 perform_member_init from calling another constructor (58162). */
696 TARGET_EXPR_DIRECT_INIT_P (init) = in_ctor;
697 if (simple_target && TREE_CODE (init) != CONSTRUCTOR)
698 /* Now put it back so C++17 copy elision works. */
699 init = get_target_expr (init);
701 set_target_expr_eliding (init);
703 current_class_ptr = save_ccp;
704 current_class_ref = save_ccr;
705 return init;
708 /* Diagnose the flexible array MEMBER if its INITializer is non-null
709 and return true if so. Otherwise return false. */
711 bool
712 maybe_reject_flexarray_init (tree member, tree init)
714 tree type = TREE_TYPE (member);
716 if (!init
717 || TREE_CODE (type) != ARRAY_TYPE
718 || TYPE_DOMAIN (type))
719 return false;
721 /* Point at the flexible array member declaration if it's initialized
722 in-class, and at the ctor if it's initialized in a ctor member
723 initializer list. */
724 location_t loc;
725 if (DECL_INITIAL (member) == init
726 || !current_function_decl
727 || DECL_DEFAULTED_FN (current_function_decl))
728 loc = DECL_SOURCE_LOCATION (member);
729 else
730 loc = DECL_SOURCE_LOCATION (current_function_decl);
732 error_at (loc, "initializer for flexible array member %q#D", member);
733 return true;
736 /* If INIT's value can come from a call to std::initializer_list<T>::begin,
737 return that function. Otherwise, NULL_TREE. */
739 static tree
740 find_list_begin (tree init)
742 STRIP_NOPS (init);
743 while (TREE_CODE (init) == COMPOUND_EXPR)
744 init = TREE_OPERAND (init, 1);
745 STRIP_NOPS (init);
746 if (TREE_CODE (init) == COND_EXPR)
748 tree left = TREE_OPERAND (init, 1);
749 if (!left)
750 left = TREE_OPERAND (init, 0);
751 left = find_list_begin (left);
752 if (left)
753 return left;
754 return find_list_begin (TREE_OPERAND (init, 2));
756 if (TREE_CODE (init) == CALL_EXPR)
757 if (tree fn = get_callee_fndecl (init))
758 if (id_equal (DECL_NAME (fn), "begin")
759 && is_std_init_list (DECL_CONTEXT (fn)))
760 return fn;
761 return NULL_TREE;
764 /* If INIT initializing MEMBER is copying the address of the underlying array
765 of an initializer_list, warn. */
767 static void
768 maybe_warn_list_ctor (tree member, tree init)
770 tree memtype = TREE_TYPE (member);
771 if (!init || !TYPE_PTR_P (memtype)
772 || !is_list_ctor (current_function_decl))
773 return;
775 tree parm = FUNCTION_FIRST_USER_PARMTYPE (current_function_decl);
776 parm = TREE_VALUE (parm);
777 tree initlist = non_reference (parm);
779 /* Do not warn if the parameter is an lvalue reference to non-const. */
780 if (TYPE_REF_P (parm) && !TYPE_REF_IS_RVALUE (parm)
781 && !CP_TYPE_CONST_P (initlist))
782 return;
784 tree targs = CLASSTYPE_TI_ARGS (initlist);
785 tree elttype = TREE_VEC_ELT (targs, 0);
787 if (!same_type_ignoring_top_level_qualifiers_p
788 (TREE_TYPE (memtype), elttype))
789 return;
791 tree begin = find_list_begin (init);
792 if (!begin)
793 return;
795 location_t loc = cp_expr_loc_or_input_loc (init);
796 warning_at (loc, OPT_Winit_list_lifetime,
797 "initializing %qD from %qE does not extend the lifetime "
798 "of the underlying array", member, begin);
801 /* Data structure for find_uninit_fields_r, below. */
803 struct find_uninit_data {
804 /* The set tracking the yet-uninitialized members. */
805 hash_set<tree> *uninitialized;
806 /* The data member we are currently initializing. It can be either
807 a type (initializing a base class/delegating constructors), or
808 a COMPONENT_REF. */
809 tree member;
812 /* walk_tree callback that warns about using uninitialized data in
813 a member-initializer-list. */
815 static tree
816 find_uninit_fields_r (tree *tp, int *walk_subtrees, void *data)
818 find_uninit_data *d = static_cast<find_uninit_data *>(data);
819 hash_set<tree> *uninitialized = d->uninitialized;
820 tree init = *tp;
821 const tree_code code = TREE_CODE (init);
823 /* No need to look into types or unevaluated operands. */
824 if (TYPE_P (init) || unevaluated_p (code))
826 *walk_subtrees = false;
827 return NULL_TREE;
830 switch (code)
832 /* We'd need data flow info to avoid false positives. */
833 case COND_EXPR:
834 case VEC_COND_EXPR:
835 case BIND_EXPR:
836 /* We might see a MODIFY_EXPR in cases like S() : a((b = 42)), c(b) { }
837 where the initializer for 'a' surreptitiously initializes 'b'. Let's
838 not bother with these complicated scenarios in the front end. */
839 case MODIFY_EXPR:
840 /* Don't attempt to handle statement-expressions, either. */
841 case STATEMENT_LIST:
842 uninitialized->empty ();
843 gcc_fallthrough ();
844 /* If we're just taking the address of an object, it doesn't matter
845 whether it's been initialized. */
846 case ADDR_EXPR:
847 *walk_subtrees = false;
848 return NULL_TREE;
849 default:
850 break;
853 /* We'd need data flow info to avoid false positives. */
854 if (truth_value_p (code))
855 goto give_up;
856 /* Attempt to handle a simple a{b}, but no more. */
857 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
859 if (CONSTRUCTOR_NELTS (init) == 1
860 && !BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (init, 0)->value))
861 init = CONSTRUCTOR_ELT (init, 0)->value;
862 else
863 goto give_up;
865 /* Warn about uninitialized 'this'. */
866 else if (code == CALL_EXPR)
868 tree fn = get_callee_fndecl (init);
869 if (fn && DECL_IOBJ_MEMBER_FUNCTION_P (fn))
871 tree op = CALL_EXPR_ARG (init, 0);
872 if (TREE_CODE (op) == ADDR_EXPR)
873 op = TREE_OPERAND (op, 0);
874 temp_override<tree> ovr (d->member, DECL_ARGUMENTS (fn));
875 cp_walk_tree_without_duplicates (&op, find_uninit_fields_r, data);
877 /* Functions (whether static or nonstatic member) may have side effects
878 and initialize other members; it's not the front end's job to try to
879 figure it out. But don't give up for constructors: we still want to
880 warn when initializing base classes:
882 struct D : public B {
883 int x;
884 D() : B(x) {}
887 so carry on to detect that 'x' is used uninitialized. */
888 if (!fn || !DECL_CONSTRUCTOR_P (fn))
889 goto give_up;
892 /* If we find FIELD in the uninitialized set, we warn. */
893 if (code == COMPONENT_REF)
895 tree field = TREE_OPERAND (init, 1);
896 tree type = TYPE_P (d->member) ? d->member : TREE_TYPE (d->member);
898 /* We're initializing a reference member with itself. */
899 if (TYPE_REF_P (type) && cp_tree_equal (d->member, init))
900 warning_at (EXPR_LOCATION (init), OPT_Winit_self,
901 "%qD is initialized with itself", field);
902 else if (cp_tree_equal (TREE_OPERAND (init, 0), current_class_ref)
903 && uninitialized->contains (field))
905 if (TYPE_REF_P (TREE_TYPE (field)))
906 warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
907 "reference %qD is not yet bound to a value when used "
908 "here", field);
909 else if ((!INDIRECT_TYPE_P (type) || is_this_parameter (d->member))
910 && !conv_binds_to_reference_parm_p (type, init))
911 warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
912 "member %qD is used uninitialized", field);
913 *walk_subtrees = false;
917 return NULL_TREE;
919 give_up:
920 *walk_subtrees = false;
921 uninitialized->empty ();
922 return integer_zero_node;
925 /* Wrapper around find_uninit_fields_r above. */
927 static void
928 find_uninit_fields (tree *t, hash_set<tree> *uninitialized, tree member)
930 if (!uninitialized->is_empty ())
932 find_uninit_data data = { uninitialized, member };
933 cp_walk_tree_without_duplicates (t, find_uninit_fields_r, &data);
937 /* Return true if it's OK to initialize an array TYPE from INIT. Mere mortals
938 can't copy arrays, but the compiler can do so with a VEC_INIT_EXPR in
939 certain cases. */
941 static bool
942 can_init_array_with_p (tree type, tree init)
944 if (!init)
945 /* Value-init, OK. */
946 return true;
947 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init)))
948 return false;
949 /* We're called from synthesize_method, and we're processing the
950 mem-initializers of a constructor. */
951 if (DECL_DEFAULTED_FN (current_function_decl))
952 return true;
953 if (TREE_CODE (init) == TARGET_EXPR)
955 init = TARGET_EXPR_INITIAL (init);
956 /* As an extension, we allow copying from a compound literal. */
957 if (TREE_CODE (init) == CONSTRUCTOR)
958 return CONSTRUCTOR_C99_COMPOUND_LITERAL (init);
959 /* VEC_INIT_EXPR is used for non-constant initialization of trailing
960 elements with no explicit initializers. */
961 else if (TREE_CODE (init) == VEC_INIT_EXPR)
962 return true;
965 return false;
968 /* Initialize MEMBER, a FIELD_DECL, with INIT, a TREE_LIST of
969 arguments. If TREE_LIST is void_type_node, an empty initializer
970 list was given; if NULL_TREE no initializer was given. UNINITIALIZED
971 is the hash set that tracks uninitialized fields. */
973 static void
974 perform_member_init (tree member, tree init, hash_set<tree> &uninitialized)
976 tree decl;
977 tree type = TREE_TYPE (member);
979 /* Use the non-static data member initializer if there was no
980 mem-initializer for this field. */
981 if (init == NULL_TREE)
982 init = get_nsdmi (member, /*ctor*/true, tf_warning_or_error);
984 if (init == error_mark_node)
985 return;
987 /* Effective C++ rule 12 requires that all data members be
988 initialized. */
989 if (warn_ecpp && init == NULL_TREE && TREE_CODE (type) != ARRAY_TYPE)
990 warning_at (DECL_SOURCE_LOCATION (current_function_decl), OPT_Weffc__,
991 "%qD should be initialized in the member initialization list",
992 member);
994 /* Get an lvalue for the data member. */
995 decl = build_class_member_access_expr (current_class_ref, member,
996 /*access_path=*/NULL_TREE,
997 /*preserve_reference=*/true,
998 tf_warning_or_error);
999 if (decl == error_mark_node)
1000 return;
1002 if ((warn_init_self || warn_uninitialized || warn_self_move)
1003 && init
1004 && TREE_CODE (init) == TREE_LIST
1005 && TREE_CHAIN (init) == NULL_TREE)
1007 tree val = TREE_VALUE (init);
1008 /* Handle references. */
1009 if (REFERENCE_REF_P (val))
1010 val = TREE_OPERAND (val, 0);
1011 if (TREE_CODE (val) == COMPONENT_REF && TREE_OPERAND (val, 1) == member
1012 && TREE_OPERAND (val, 0) == current_class_ref)
1013 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1014 OPT_Winit_self, "%qD is initialized with itself",
1015 member);
1016 else if (!maybe_warn_self_move (input_location, member,
1017 TREE_VALUE (init)))
1018 find_uninit_fields (&val, &uninitialized, decl);
1021 if (array_of_unknown_bound_p (type))
1023 maybe_reject_flexarray_init (member, init);
1024 return;
1027 if (init && TREE_CODE (init) == TREE_LIST)
1029 /* A(): a{e} */
1030 if (DIRECT_LIST_INIT_P (TREE_VALUE (init)))
1031 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
1032 tf_warning_or_error);
1033 /* We are trying to initialize an array from a ()-list. If we
1034 should attempt to do so, conjure up a CONSTRUCTOR. */
1035 else if (TREE_CODE (type) == ARRAY_TYPE
1036 /* P0960 is a C++20 feature. */
1037 && cxx_dialect >= cxx20)
1038 init = do_aggregate_paren_init (init, type);
1039 else if (!CLASS_TYPE_P (type))
1040 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
1041 tf_warning_or_error);
1042 /* If we're initializing a class from a ()-list, leave the TREE_LIST
1043 alone: we might call an appropriate constructor, or (in C++20)
1044 do aggregate-initialization. */
1047 /* Assume we are initializing the member. */
1048 bool member_initialized_p = true;
1050 if (init == void_type_node)
1052 /* mem() means value-initialization. */
1053 if (TREE_CODE (type) == ARRAY_TYPE)
1055 init = build_vec_init_expr (type, init, tf_warning_or_error);
1056 init = cp_build_init_expr (decl, init);
1057 finish_expr_stmt (init);
1059 else
1061 tree value = build_value_init (type, tf_warning_or_error);
1062 if (value == error_mark_node)
1063 return;
1064 init = cp_build_init_expr (decl, value);
1065 finish_expr_stmt (init);
1068 /* Deal with this here, as we will get confused if we try to call the
1069 assignment op for an anonymous union. This can happen in a
1070 synthesized copy constructor. */
1071 else if (ANON_AGGR_TYPE_P (type))
1073 if (init)
1075 init = cp_build_init_expr (decl, TREE_VALUE (init));
1076 finish_expr_stmt (init);
1079 else if (init
1080 && (TYPE_REF_P (type)
1081 || (TREE_CODE (init) == CONSTRUCTOR
1082 && (CP_AGGREGATE_TYPE_P (type)
1083 || is_std_init_list (type)))))
1085 /* With references and list-initialization, we need to deal with
1086 extending temporary lifetimes. 12.2p5: "A temporary bound to a
1087 reference member in a constructor’s ctor-initializer (12.6.2)
1088 persists until the constructor exits." */
1089 unsigned i; tree t;
1090 releasing_vec cleanups;
1091 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
1093 if (BRACE_ENCLOSED_INITIALIZER_P (init)
1094 && CP_AGGREGATE_TYPE_P (type))
1095 init = reshape_init (type, init, tf_warning_or_error);
1096 init = digest_init (type, init, tf_warning_or_error);
1098 if (init == error_mark_node)
1099 return;
1100 if (is_empty_field (member)
1101 && !TREE_SIDE_EFFECTS (init))
1102 /* Don't add trivial initialization of an empty base/field, as they
1103 might not be ordered the way the back-end expects. */
1104 return;
1105 /* A FIELD_DECL doesn't really have a suitable lifetime, but
1106 make_temporary_var_for_ref_to_temp will treat it as automatic and
1107 set_up_extended_ref_temp wants to use the decl in a warning. */
1108 init = extend_ref_init_temps (member, init, &cleanups);
1109 if (TREE_CODE (type) == ARRAY_TYPE
1110 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (type)))
1111 init = build_vec_init_expr (type, init, tf_warning_or_error);
1112 init = cp_build_init_expr (decl, init);
1113 finish_expr_stmt (init);
1114 FOR_EACH_VEC_ELT (*cleanups, i, t)
1115 push_cleanup (NULL_TREE, t, false);
1117 else if (type_build_ctor_call (type)
1118 || (init && CLASS_TYPE_P (strip_array_types (type))))
1120 if (TREE_CODE (type) == ARRAY_TYPE)
1122 if (can_init_array_with_p (type, init))
1124 if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
1126 /* Initialize the array only if it's not a flexible
1127 array member (i.e., if it has an upper bound). */
1128 init = build_vec_init_expr (type, init, tf_warning_or_error);
1129 init = cp_build_init_expr (decl, init);
1130 finish_expr_stmt (init);
1133 else
1134 error ("invalid initializer for array member %q#D", member);
1136 else
1138 int flags = LOOKUP_NORMAL;
1139 if (DECL_DEFAULTED_FN (current_function_decl))
1140 flags |= LOOKUP_DEFAULTED;
1141 if (CP_TYPE_CONST_P (type)
1142 && init == NULL_TREE
1143 && default_init_uninitialized_part (type))
1145 /* TYPE_NEEDS_CONSTRUCTING can be set just because we have a
1146 vtable; still give this diagnostic. */
1147 auto_diagnostic_group d;
1148 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1149 "uninitialized const member in %q#T", type))
1150 inform (DECL_SOURCE_LOCATION (member),
1151 "%q#D should be initialized", member );
1153 finish_expr_stmt (build_aggr_init (decl, init, flags,
1154 tf_warning_or_error));
1157 else
1159 if (init == NULL_TREE)
1161 tree core_type;
1162 /* member traversal: note it leaves init NULL */
1163 if (TYPE_REF_P (type))
1165 auto_diagnostic_group d;
1166 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1167 "uninitialized reference member in %q#T", type))
1168 inform (DECL_SOURCE_LOCATION (member),
1169 "%q#D should be initialized", member);
1171 else if (CP_TYPE_CONST_P (type))
1173 auto_diagnostic_group d;
1174 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1175 "uninitialized const member in %q#T", type))
1176 inform (DECL_SOURCE_LOCATION (member),
1177 "%q#D should be initialized", member );
1180 core_type = strip_array_types (type);
1182 if (CLASS_TYPE_P (core_type)
1183 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
1184 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
1185 diagnose_uninitialized_cst_or_ref_member (core_type,
1186 /*using_new=*/false,
1187 /*complain=*/true);
1189 /* We left the member uninitialized. */
1190 member_initialized_p = false;
1193 maybe_warn_list_ctor (member, init);
1195 if (init)
1196 finish_expr_stmt (cp_build_modify_expr (input_location, decl,
1197 INIT_EXPR, init,
1198 tf_warning_or_error));
1201 if (member_initialized_p && warn_uninitialized)
1202 /* This member is now initialized, remove it from the uninitialized
1203 set. */
1204 uninitialized.remove (member);
1206 if (type_build_dtor_call (type))
1208 tree expr;
1210 expr = build_class_member_access_expr (current_class_ref, member,
1211 /*access_path=*/NULL_TREE,
1212 /*preserve_reference=*/false,
1213 tf_warning_or_error);
1214 expr = build_delete (input_location,
1215 type, expr, sfk_complete_destructor,
1216 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0,
1217 tf_warning_or_error);
1219 if (expr != error_mark_node
1220 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1221 finish_eh_cleanup (expr);
1225 /* Returns a TREE_LIST containing (as the TREE_PURPOSE of each node) all
1226 the FIELD_DECLs on the TYPE_FIELDS list for T, in reverse order. */
1228 static tree
1229 build_field_list (tree t, tree list, int *uses_unions_or_anon_p)
1231 tree fields;
1233 /* Note whether or not T is a union. */
1234 if (TREE_CODE (t) == UNION_TYPE)
1235 *uses_unions_or_anon_p = 1;
1237 for (fields = TYPE_FIELDS (t); fields; fields = DECL_CHAIN (fields))
1239 tree fieldtype;
1241 /* Skip CONST_DECLs for enumeration constants and so forth. */
1242 if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
1243 continue;
1245 fieldtype = TREE_TYPE (fields);
1247 /* For an anonymous struct or union, we must recursively
1248 consider the fields of the anonymous type. They can be
1249 directly initialized from the constructor. */
1250 if (ANON_AGGR_TYPE_P (fieldtype))
1252 /* Add this field itself. Synthesized copy constructors
1253 initialize the entire aggregate. */
1254 list = tree_cons (fields, NULL_TREE, list);
1255 /* And now add the fields in the anonymous aggregate. */
1256 list = build_field_list (fieldtype, list, uses_unions_or_anon_p);
1257 *uses_unions_or_anon_p = 1;
1259 /* Add this field. */
1260 else if (DECL_NAME (fields))
1261 list = tree_cons (fields, NULL_TREE, list);
1264 return list;
1267 /* Return the innermost aggregate scope for FIELD, whether that is
1268 the enclosing class or an anonymous aggregate within it. */
1270 static tree
1271 innermost_aggr_scope (tree field)
1273 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1274 return TREE_TYPE (field);
1275 else
1276 return DECL_CONTEXT (field);
1279 /* The MEM_INITS are a TREE_LIST. The TREE_PURPOSE of each list gives
1280 a FIELD_DECL or BINFO in T that needs initialization. The
1281 TREE_VALUE gives the initializer, or list of initializer arguments.
1283 Return a TREE_LIST containing all of the initializations required
1284 for T, in the order in which they should be performed. The output
1285 list has the same format as the input. */
1287 static tree
1288 sort_mem_initializers (tree t, tree mem_inits)
1290 tree init;
1291 tree base, binfo, base_binfo;
1292 tree sorted_inits;
1293 tree next_subobject;
1294 vec<tree, va_gc> *vbases;
1295 int i;
1296 int uses_unions_or_anon_p = 0;
1298 /* Build up a list of initializations. The TREE_PURPOSE of entry
1299 will be the subobject (a FIELD_DECL or BINFO) to initialize. The
1300 TREE_VALUE will be the constructor arguments, or NULL if no
1301 explicit initialization was provided. */
1302 sorted_inits = NULL_TREE;
1304 /* Process the virtual bases. */
1305 for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
1306 vec_safe_iterate (vbases, i, &base); i++)
1307 sorted_inits = tree_cons (base, NULL_TREE, sorted_inits);
1309 /* Process the direct bases. */
1310 for (binfo = TYPE_BINFO (t), i = 0;
1311 BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
1312 if (!BINFO_VIRTUAL_P (base_binfo))
1313 sorted_inits = tree_cons (base_binfo, NULL_TREE, sorted_inits);
1315 /* Process the non-static data members. */
1316 sorted_inits = build_field_list (t, sorted_inits, &uses_unions_or_anon_p);
1317 /* Reverse the entire list of initializations, so that they are in
1318 the order that they will actually be performed. */
1319 sorted_inits = nreverse (sorted_inits);
1321 /* If the user presented the initializers in an order different from
1322 that in which they will actually occur, we issue a warning. Keep
1323 track of the next subobject which can be explicitly initialized
1324 without issuing a warning. */
1325 next_subobject = sorted_inits;
1327 /* Go through the explicit initializers, filling in TREE_PURPOSE in
1328 the SORTED_INITS. */
1329 for (init = mem_inits; init; init = TREE_CHAIN (init))
1331 tree subobject;
1332 tree subobject_init;
1334 subobject = TREE_PURPOSE (init);
1336 /* If the explicit initializers are in sorted order, then
1337 SUBOBJECT will be NEXT_SUBOBJECT, or something following
1338 it. */
1339 for (subobject_init = next_subobject;
1340 subobject_init;
1341 subobject_init = TREE_CHAIN (subobject_init))
1342 if (TREE_PURPOSE (subobject_init) == subobject)
1343 break;
1345 /* Issue a warning if the explicit initializer order does not
1346 match that which will actually occur.
1347 ??? Are all these on the correct lines? */
1348 if (warn_reorder && !subobject_init)
1350 if (TREE_CODE (TREE_PURPOSE (next_subobject)) == FIELD_DECL)
1351 warning_at (DECL_SOURCE_LOCATION (TREE_PURPOSE (next_subobject)),
1352 OPT_Wreorder, "%qD will be initialized after",
1353 TREE_PURPOSE (next_subobject));
1354 else
1355 warning (OPT_Wreorder, "base %qT will be initialized after",
1356 TREE_PURPOSE (next_subobject));
1357 if (TREE_CODE (subobject) == FIELD_DECL)
1358 warning_at (DECL_SOURCE_LOCATION (subobject),
1359 OPT_Wreorder, " %q#D", subobject);
1360 else
1361 warning (OPT_Wreorder, " base %qT", subobject);
1362 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1363 OPT_Wreorder, " when initialized here");
1366 /* Look again, from the beginning of the list. */
1367 if (!subobject_init)
1369 subobject_init = sorted_inits;
1370 while (TREE_PURPOSE (subobject_init) != subobject)
1371 subobject_init = TREE_CHAIN (subobject_init);
1374 /* It is invalid to initialize the same subobject more than
1375 once. */
1376 if (TREE_VALUE (subobject_init))
1378 if (TREE_CODE (subobject) == FIELD_DECL)
1379 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1380 "multiple initializations given for %qD",
1381 subobject);
1382 else
1383 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1384 "multiple initializations given for base %qT",
1385 subobject);
1388 /* Record the initialization. */
1389 TREE_VALUE (subobject_init) = TREE_VALUE (init);
1390 /* Carry over the dummy TREE_TYPE node containing the source location. */
1391 TREE_TYPE (subobject_init) = TREE_TYPE (init);
1392 next_subobject = subobject_init;
1395 /* [class.base.init]
1397 If a ctor-initializer specifies more than one mem-initializer for
1398 multiple members of the same union (including members of
1399 anonymous unions), the ctor-initializer is ill-formed.
1401 Here we also splice out uninitialized union members. */
1402 if (uses_unions_or_anon_p)
1404 tree *last_p = NULL;
1405 tree *p;
1406 for (p = &sorted_inits; *p; )
1408 tree field;
1409 tree ctx;
1411 init = *p;
1413 field = TREE_PURPOSE (init);
1415 /* Skip base classes. */
1416 if (TREE_CODE (field) != FIELD_DECL)
1417 goto next;
1419 /* If this is an anonymous aggregate with no explicit initializer,
1420 splice it out. */
1421 if (!TREE_VALUE (init) && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1422 goto splice;
1424 /* See if this field is a member of a union, or a member of a
1425 structure contained in a union, etc. */
1426 ctx = innermost_aggr_scope (field);
1428 /* If this field is not a member of a union, skip it. */
1429 if (TREE_CODE (ctx) != UNION_TYPE
1430 && !ANON_AGGR_TYPE_P (ctx))
1431 goto next;
1433 /* If this union member has no explicit initializer and no NSDMI,
1434 splice it out. */
1435 if (TREE_VALUE (init) || DECL_INITIAL (field))
1436 /* OK. */;
1437 else
1438 goto splice;
1440 /* It's only an error if we have two initializers for the same
1441 union type. */
1442 if (!last_p)
1444 last_p = p;
1445 goto next;
1448 /* See if LAST_FIELD and the field initialized by INIT are
1449 members of the same union (or the union itself). If so, there's
1450 a problem, unless they're actually members of the same structure
1451 which is itself a member of a union. For example, given:
1453 union { struct { int i; int j; }; };
1455 initializing both `i' and `j' makes sense. */
1456 ctx = common_enclosing_class
1457 (innermost_aggr_scope (field),
1458 innermost_aggr_scope (TREE_PURPOSE (*last_p)));
1460 if (ctx && (TREE_CODE (ctx) == UNION_TYPE
1461 || ctx == TREE_TYPE (TREE_PURPOSE (*last_p))))
1463 /* A mem-initializer hides an NSDMI. */
1464 if (TREE_VALUE (init) && !TREE_VALUE (*last_p))
1465 *last_p = TREE_CHAIN (*last_p);
1466 else if (TREE_VALUE (*last_p) && !TREE_VALUE (init))
1467 goto splice;
1468 else
1470 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1471 "initializations for multiple members of %qT",
1472 ctx);
1473 goto splice;
1477 last_p = p;
1479 next:
1480 p = &TREE_CHAIN (*p);
1481 continue;
1482 splice:
1483 *p = TREE_CHAIN (*p);
1487 return sorted_inits;
1490 /* Callback for cp_walk_tree to mark all PARM_DECLs in a tree as read. */
1492 static tree
1493 mark_exp_read_r (tree *tp, int *, void *)
1495 tree t = *tp;
1496 if (TREE_CODE (t) == PARM_DECL)
1497 mark_exp_read (t);
1498 return NULL_TREE;
1501 /* Initialize all bases and members of CURRENT_CLASS_TYPE. MEM_INITS
1502 is a TREE_LIST giving the explicit mem-initializer-list for the
1503 constructor. The TREE_PURPOSE of each entry is a subobject (a
1504 FIELD_DECL or a BINFO) of the CURRENT_CLASS_TYPE. The TREE_VALUE
1505 is a TREE_LIST giving the arguments to the constructor or
1506 void_type_node for an empty list of arguments. */
1508 void
1509 emit_mem_initializers (tree mem_inits)
1511 int flags = LOOKUP_NORMAL;
1513 /* We will already have issued an error message about the fact that
1514 the type is incomplete. */
1515 if (!COMPLETE_TYPE_P (current_class_type))
1516 return;
1518 /* Keep a set holding fields that are not initialized. */
1519 hash_set<tree> uninitialized;
1521 /* Initially that is all of them. */
1522 if (warn_uninitialized)
1523 for (tree f = next_aggregate_field (TYPE_FIELDS (current_class_type));
1524 f != NULL_TREE;
1525 f = next_aggregate_field (DECL_CHAIN (f)))
1526 if (!DECL_ARTIFICIAL (f)
1527 && !is_really_empty_class (TREE_TYPE (f), /*ignore_vptr*/false))
1528 uninitialized.add (f);
1530 if (mem_inits
1531 && TYPE_P (TREE_PURPOSE (mem_inits))
1532 && same_type_p (TREE_PURPOSE (mem_inits), current_class_type))
1534 /* Delegating constructor. */
1535 gcc_assert (TREE_CHAIN (mem_inits) == NULL_TREE);
1536 tree ctor = perform_target_ctor (TREE_VALUE (mem_inits));
1537 find_uninit_fields (&ctor, &uninitialized, current_class_type);
1538 return;
1541 if (DECL_DEFAULTED_FN (current_function_decl)
1542 && ! DECL_INHERITED_CTOR (current_function_decl))
1543 flags |= LOOKUP_DEFAULTED;
1545 /* Sort the mem-initializers into the order in which the
1546 initializations should be performed. */
1547 mem_inits = sort_mem_initializers (current_class_type, mem_inits);
1549 in_base_initializer = 1;
1551 /* Initialize base classes. */
1552 for (; (mem_inits
1553 && TREE_CODE (TREE_PURPOSE (mem_inits)) != FIELD_DECL);
1554 mem_inits = TREE_CHAIN (mem_inits))
1556 tree subobject = TREE_PURPOSE (mem_inits);
1557 tree arguments = TREE_VALUE (mem_inits);
1559 /* We already have issued an error message. */
1560 if (arguments == error_mark_node)
1561 continue;
1563 /* Suppress access control when calling the inherited ctor. */
1564 bool inherited_base = (DECL_INHERITED_CTOR (current_function_decl)
1565 && flag_new_inheriting_ctors
1566 && arguments);
1567 if (inherited_base)
1568 push_deferring_access_checks (dk_deferred);
1570 if (arguments == NULL_TREE)
1572 /* If these initializations are taking place in a copy constructor,
1573 the base class should probably be explicitly initialized if there
1574 is a user-defined constructor in the base class (other than the
1575 default constructor, which will be called anyway). */
1576 if (extra_warnings
1577 && DECL_COPY_CONSTRUCTOR_P (current_function_decl)
1578 && type_has_user_nondefault_constructor (BINFO_TYPE (subobject)))
1579 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1580 OPT_Wextra, "base class %q#T should be explicitly "
1581 "initialized in the copy constructor",
1582 BINFO_TYPE (subobject));
1585 /* Initialize the base. */
1586 if (!BINFO_VIRTUAL_P (subobject))
1588 tree base_addr;
1590 base_addr = build_base_path (PLUS_EXPR, current_class_ptr,
1591 subobject, 1, tf_warning_or_error);
1592 expand_aggr_init_1 (subobject, NULL_TREE,
1593 cp_build_fold_indirect_ref (base_addr),
1594 arguments,
1595 flags,
1596 tf_warning_or_error);
1597 expand_cleanup_for_base (subobject, NULL_TREE);
1598 if (STATEMENT_LIST_TAIL (cur_stmt_list))
1599 find_uninit_fields (&STATEMENT_LIST_TAIL (cur_stmt_list)->stmt,
1600 &uninitialized, BINFO_TYPE (subobject));
1602 else if (!ABSTRACT_CLASS_TYPE_P (current_class_type))
1603 /* C++14 DR1658 Means we do not have to construct vbases of
1604 abstract classes. */
1605 construct_virtual_base (subobject, arguments);
1606 else
1607 /* When not constructing vbases of abstract classes, at least mark
1608 the arguments expressions as read to avoid
1609 -Wunused-but-set-parameter false positives. */
1610 cp_walk_tree (&arguments, mark_exp_read_r, NULL, NULL);
1612 if (inherited_base)
1613 pop_deferring_access_checks ();
1615 in_base_initializer = 0;
1617 /* Initialize the vptrs. */
1618 initialize_vtbl_ptrs (current_class_ptr);
1620 /* Initialize the data members. */
1621 while (mem_inits)
1623 /* If this initializer was explicitly provided, then the dummy TREE_TYPE
1624 node contains the source location. */
1625 iloc_sentinel ils (EXPR_LOCATION (TREE_TYPE (mem_inits)));
1627 perform_member_init (TREE_PURPOSE (mem_inits),
1628 TREE_VALUE (mem_inits),
1629 uninitialized);
1631 mem_inits = TREE_CHAIN (mem_inits);
1635 /* Returns the address of the vtable (i.e., the value that should be
1636 assigned to the vptr) for BINFO. */
1638 tree
1639 build_vtbl_address (tree binfo)
1641 tree binfo_for = binfo;
1642 tree vtbl;
1644 if (BINFO_VPTR_INDEX (binfo) && BINFO_VIRTUAL_P (binfo))
1645 /* If this is a virtual primary base, then the vtable we want to store
1646 is that for the base this is being used as the primary base of. We
1647 can't simply skip the initialization, because we may be expanding the
1648 inits of a subobject constructor where the virtual base layout
1649 can be different. */
1650 while (BINFO_PRIMARY_P (binfo_for))
1651 binfo_for = BINFO_INHERITANCE_CHAIN (binfo_for);
1653 /* Figure out what vtable BINFO's vtable is based on, and mark it as
1654 used. */
1655 vtbl = get_vtbl_decl_for_binfo (binfo_for);
1656 TREE_USED (vtbl) = true;
1658 /* Now compute the address to use when initializing the vptr. */
1659 vtbl = unshare_expr (BINFO_VTABLE (binfo_for));
1660 if (VAR_P (vtbl))
1661 vtbl = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (vtbl)), vtbl);
1663 return vtbl;
1666 /* This code sets up the virtual function tables appropriate for
1667 the pointer DECL. It is a one-ply initialization.
1669 BINFO is the exact type that DECL is supposed to be. In
1670 multiple inheritance, this might mean "C's A" if C : A, B. */
1672 static void
1673 expand_virtual_init (tree binfo, tree decl)
1675 tree vtbl, vtbl_ptr;
1676 tree vtt_index;
1678 /* Compute the initializer for vptr. */
1679 vtbl = build_vtbl_address (binfo);
1681 /* We may get this vptr from a VTT, if this is a subobject
1682 constructor or subobject destructor. */
1683 vtt_index = BINFO_VPTR_INDEX (binfo);
1684 if (vtt_index)
1686 tree vtbl2;
1687 tree vtt_parm;
1689 /* Compute the value to use, when there's a VTT. */
1690 vtt_parm = current_vtt_parm;
1691 vtbl2 = fold_build_pointer_plus (vtt_parm, vtt_index);
1692 vtbl2 = cp_build_fold_indirect_ref (vtbl2);
1693 vtbl2 = convert (TREE_TYPE (vtbl), vtbl2);
1695 /* The actual initializer is the VTT value only in the subobject
1696 constructor. In maybe_clone_body we'll substitute NULL for
1697 the vtt_parm in the case of the non-subobject constructor. */
1698 vtbl = build_if_in_charge (vtbl, vtbl2);
1701 /* Compute the location of the vtpr. */
1702 vtbl_ptr = build_vfield_ref (cp_build_fold_indirect_ref (decl),
1703 TREE_TYPE (binfo));
1704 gcc_assert (vtbl_ptr != error_mark_node);
1706 /* Assign the vtable to the vptr. */
1707 vtbl = convert_force (TREE_TYPE (vtbl_ptr), vtbl, 0, tf_warning_or_error);
1708 finish_expr_stmt (cp_build_modify_expr (input_location, vtbl_ptr, NOP_EXPR,
1709 vtbl, tf_warning_or_error));
1712 /* If an exception is thrown in a constructor, those base classes already
1713 constructed must be destroyed. This function creates the cleanup
1714 for BINFO, which has just been constructed. If FLAG is non-NULL,
1715 it is a DECL which is nonzero when this base needs to be
1716 destroyed. */
1718 static void
1719 expand_cleanup_for_base (tree binfo, tree flag)
1721 tree expr;
1723 if (!type_build_dtor_call (BINFO_TYPE (binfo)))
1724 return;
1726 /* Call the destructor. */
1727 expr = build_special_member_call (current_class_ref,
1728 base_dtor_identifier,
1729 NULL,
1730 binfo,
1731 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
1732 tf_warning_or_error);
1734 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (BINFO_TYPE (binfo)))
1735 return;
1737 if (flag)
1738 expr = fold_build3_loc (input_location,
1739 COND_EXPR, void_type_node,
1740 c_common_truthvalue_conversion (input_location, flag),
1741 expr, integer_zero_node);
1743 finish_eh_cleanup (expr);
1746 /* Construct the virtual base-class VBASE passing the ARGUMENTS to its
1747 constructor. */
1749 static void
1750 construct_virtual_base (tree vbase, tree arguments)
1752 tree inner_if_stmt;
1753 tree exp;
1754 tree flag;
1756 /* If there are virtual base classes with destructors, we need to
1757 emit cleanups to destroy them if an exception is thrown during
1758 the construction process. These exception regions (i.e., the
1759 period during which the cleanups must occur) begin from the time
1760 the construction is complete to the end of the function. If we
1761 create a conditional block in which to initialize the
1762 base-classes, then the cleanup region for the virtual base begins
1763 inside a block, and ends outside of that block. This situation
1764 confuses the sjlj exception-handling code. Therefore, we do not
1765 create a single conditional block, but one for each
1766 initialization. (That way the cleanup regions always begin
1767 in the outer block.) We trust the back end to figure out
1768 that the FLAG will not change across initializations, and
1769 avoid doing multiple tests. */
1770 flag = DECL_CHAIN (DECL_ARGUMENTS (current_function_decl));
1771 inner_if_stmt = begin_if_stmt ();
1772 finish_if_stmt_cond (flag, inner_if_stmt);
1774 /* Compute the location of the virtual base. If we're
1775 constructing virtual bases, then we must be the most derived
1776 class. Therefore, we don't have to look up the virtual base;
1777 we already know where it is. */
1778 exp = convert_to_base_statically (current_class_ref, vbase);
1780 expand_aggr_init_1 (vbase, current_class_ref, exp, arguments,
1781 0, tf_warning_or_error);
1782 finish_then_clause (inner_if_stmt);
1783 finish_if_stmt (inner_if_stmt);
1785 expand_cleanup_for_base (vbase, flag);
1788 /* Find the context in which this FIELD can be initialized. */
1790 static tree
1791 initializing_context (tree field)
1793 tree t = DECL_CONTEXT (field);
1795 /* Anonymous union members can be initialized in the first enclosing
1796 non-anonymous union context. */
1797 while (t && ANON_AGGR_TYPE_P (t))
1798 t = TYPE_CONTEXT (t);
1799 return t;
1802 /* Function to give error message if member initialization specification
1803 is erroneous. FIELD is the member we decided to initialize.
1804 TYPE is the type for which the initialization is being performed.
1805 FIELD must be a member of TYPE.
1807 MEMBER_NAME is the name of the member. */
1809 static int
1810 member_init_ok_or_else (tree field, tree type, tree member_name)
1812 if (field == error_mark_node)
1813 return 0;
1814 if (!field)
1816 error ("class %qT does not have any field named %qD", type,
1817 member_name);
1818 return 0;
1820 if (VAR_P (field))
1822 error ("%q#D is a static data member; it can only be "
1823 "initialized at its definition",
1824 field);
1825 return 0;
1827 if (TREE_CODE (field) != FIELD_DECL)
1829 error ("%q#D is not a non-static data member of %qT",
1830 field, type);
1831 return 0;
1833 if (initializing_context (field) != type)
1835 error ("class %qT does not have any field named %qD", type,
1836 member_name);
1837 return 0;
1840 return 1;
1843 /* NAME is a FIELD_DECL, an IDENTIFIER_NODE which names a field, or it
1844 is a _TYPE node or TYPE_DECL which names a base for that type.
1845 Check the validity of NAME, and return either the base _TYPE, base
1846 binfo, or the FIELD_DECL of the member. If NAME is invalid, return
1847 NULL_TREE and issue a diagnostic.
1849 An old style unnamed direct single base construction is permitted,
1850 where NAME is NULL. */
1852 tree
1853 expand_member_init (tree name)
1855 tree basetype;
1856 tree field;
1858 if (!current_class_ref)
1859 return NULL_TREE;
1861 if (!name)
1863 /* This is an obsolete unnamed base class initializer. The
1864 parser will already have warned about its use. */
1865 switch (BINFO_N_BASE_BINFOS (TYPE_BINFO (current_class_type)))
1867 case 0:
1868 error ("unnamed initializer for %qT, which has no base classes",
1869 current_class_type);
1870 return NULL_TREE;
1871 case 1:
1872 basetype = BINFO_TYPE
1873 (BINFO_BASE_BINFO (TYPE_BINFO (current_class_type), 0));
1874 break;
1875 default:
1876 error ("unnamed initializer for %qT, which uses multiple inheritance",
1877 current_class_type);
1878 return NULL_TREE;
1881 else if (TYPE_P (name))
1883 basetype = TYPE_MAIN_VARIANT (name);
1884 name = TYPE_NAME (name);
1886 else if (TREE_CODE (name) == TYPE_DECL)
1887 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (name));
1888 else
1889 basetype = NULL_TREE;
1891 if (basetype)
1893 tree class_binfo;
1894 tree direct_binfo;
1895 tree virtual_binfo;
1896 int i;
1898 if (current_template_parms
1899 || same_type_p (basetype, current_class_type))
1900 return basetype;
1902 class_binfo = TYPE_BINFO (current_class_type);
1903 direct_binfo = NULL_TREE;
1904 virtual_binfo = NULL_TREE;
1906 /* Look for a direct base. */
1907 for (i = 0; BINFO_BASE_ITERATE (class_binfo, i, direct_binfo); ++i)
1908 if (SAME_BINFO_TYPE_P (BINFO_TYPE (direct_binfo), basetype))
1909 break;
1911 /* Look for a virtual base -- unless the direct base is itself
1912 virtual. */
1913 if (!direct_binfo || !BINFO_VIRTUAL_P (direct_binfo))
1914 virtual_binfo = binfo_for_vbase (basetype, current_class_type);
1916 /* [class.base.init]
1918 If a mem-initializer-id is ambiguous because it designates
1919 both a direct non-virtual base class and an inherited virtual
1920 base class, the mem-initializer is ill-formed. */
1921 if (direct_binfo && virtual_binfo)
1923 error ("%qD is both a direct base and an indirect virtual base",
1924 basetype);
1925 return NULL_TREE;
1928 if (!direct_binfo && !virtual_binfo)
1930 if (CLASSTYPE_VBASECLASSES (current_class_type))
1931 error ("type %qT is not a direct or virtual base of %qT",
1932 basetype, current_class_type);
1933 else
1934 error ("type %qT is not a direct base of %qT",
1935 basetype, current_class_type);
1936 return NULL_TREE;
1939 return direct_binfo ? direct_binfo : virtual_binfo;
1941 else
1943 if (identifier_p (name))
1944 field = lookup_field (current_class_type, name, 1, false);
1945 else
1946 field = name;
1948 if (member_init_ok_or_else (field, current_class_type, name))
1949 return field;
1952 return NULL_TREE;
1955 /* This is like `expand_member_init', only it stores one aggregate
1956 value into another.
1958 INIT comes in two flavors: it is either a value which
1959 is to be stored in EXP, or it is a parameter list
1960 to go to a constructor, which will operate on EXP.
1961 If INIT is not a parameter list for a constructor, then set
1962 LOOKUP_ONLYCONVERTING.
1963 If FLAGS is LOOKUP_ONLYCONVERTING then it is the = init form of
1964 the initializer, if FLAGS is 0, then it is the (init) form.
1965 If `init' is a CONSTRUCTOR, then we emit a warning message,
1966 explaining that such initializations are invalid.
1968 If INIT resolves to a CALL_EXPR which happens to return
1969 something of the type we are looking for, then we know
1970 that we can safely use that call to perform the
1971 initialization.
1973 The virtual function table pointer cannot be set up here, because
1974 we do not really know its type.
1976 This never calls operator=().
1978 When initializing, nothing is CONST.
1980 A default copy constructor may have to be used to perform the
1981 initialization.
1983 A constructor or a conversion operator may have to be used to
1984 perform the initialization, but not both, as it would be ambiguous. */
1986 tree
1987 build_aggr_init (tree exp, tree init, int flags, tsubst_flags_t complain)
1989 tree stmt_expr;
1990 tree compound_stmt;
1991 int destroy_temps;
1992 tree type = TREE_TYPE (exp);
1993 int was_const = TREE_READONLY (exp);
1994 int was_volatile = TREE_THIS_VOLATILE (exp);
1995 int is_global;
1997 if (init == error_mark_node)
1998 return error_mark_node;
2000 location_t init_loc = (init
2001 ? cp_expr_loc_or_input_loc (init)
2002 : location_of (exp));
2004 TREE_READONLY (exp) = 0;
2005 TREE_THIS_VOLATILE (exp) = 0;
2007 if (TREE_CODE (type) == ARRAY_TYPE)
2009 tree itype = init ? TREE_TYPE (init) : NULL_TREE;
2010 int from_array = 0;
2012 if (DECL_DECOMPOSITION_P (exp))
2014 from_array = 1;
2015 init = mark_rvalue_use (init);
2016 if (init
2017 && DECL_P (tree_strip_any_location_wrapper (init))
2018 && !(flags & LOOKUP_ONLYCONVERTING))
2020 /* Wrap the initializer in a CONSTRUCTOR so that build_vec_init
2021 recognizes it as direct-initialization. */
2022 init = build_constructor_single (init_list_type_node,
2023 NULL_TREE, init);
2024 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
2027 else
2029 /* Must arrange to initialize each element of EXP
2030 from elements of INIT. */
2031 if (cv_qualified_p (type))
2032 TREE_TYPE (exp) = cv_unqualified (type);
2033 if (itype && cv_qualified_p (itype))
2034 TREE_TYPE (init) = cv_unqualified (itype);
2035 from_array = (itype && same_type_p (TREE_TYPE (init),
2036 TREE_TYPE (exp)));
2038 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init)
2039 && (!from_array
2040 || (TREE_CODE (init) != CONSTRUCTOR
2041 /* Can happen, eg, handling the compound-literals
2042 extension (ext/complit12.C). */
2043 && TREE_CODE (init) != TARGET_EXPR)))
2045 if (complain & tf_error)
2046 error_at (init_loc, "array must be initialized "
2047 "with a brace-enclosed initializer");
2048 return error_mark_node;
2052 stmt_expr = build_vec_init (exp, NULL_TREE, init,
2053 /*explicit_value_init_p=*/false,
2054 from_array,
2055 complain);
2056 TREE_READONLY (exp) = was_const;
2057 TREE_THIS_VOLATILE (exp) = was_volatile;
2058 TREE_TYPE (exp) = type;
2059 /* Restore the type of init unless it was used directly. */
2060 if (init && TREE_CODE (stmt_expr) != INIT_EXPR)
2061 TREE_TYPE (init) = itype;
2062 return stmt_expr;
2065 if (is_copy_initialization (init))
2066 flags |= LOOKUP_ONLYCONVERTING;
2068 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
2069 destroy_temps = stmts_are_full_exprs_p ();
2070 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
2071 bool ok = expand_aggr_init_1 (TYPE_BINFO (type), exp, exp,
2072 init, LOOKUP_NORMAL|flags, complain);
2073 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
2074 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
2075 TREE_READONLY (exp) = was_const;
2076 TREE_THIS_VOLATILE (exp) = was_volatile;
2077 if (!ok)
2078 return error_mark_node;
2080 if ((VAR_P (exp) || TREE_CODE (exp) == PARM_DECL)
2081 && TREE_SIDE_EFFECTS (stmt_expr)
2082 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (type)))
2083 /* Just know that we've seen something for this node. */
2084 TREE_USED (exp) = 1;
2086 return stmt_expr;
2089 static bool
2090 expand_default_init (tree binfo, tree true_exp, tree exp, tree init, int flags,
2091 tsubst_flags_t complain)
2093 tree type = TREE_TYPE (exp);
2095 /* It fails because there may not be a constructor which takes
2096 its own type as the first (or only parameter), but which does
2097 take other types via a conversion. So, if the thing initializing
2098 the expression is a unit element of type X, first try X(X&),
2099 followed by initialization by X. If neither of these work
2100 out, then look hard. */
2101 tree rval;
2102 vec<tree, va_gc> *parms;
2104 /* If we have direct-initialization from an initializer list, pull
2105 it out of the TREE_LIST so the code below can see it. */
2106 if (init && TREE_CODE (init) == TREE_LIST
2107 && DIRECT_LIST_INIT_P (TREE_VALUE (init)))
2109 gcc_checking_assert ((flags & LOOKUP_ONLYCONVERTING) == 0
2110 && TREE_CHAIN (init) == NULL_TREE);
2111 init = TREE_VALUE (init);
2112 /* Only call reshape_init if it has not been called earlier
2113 by the callers. */
2114 if (BRACE_ENCLOSED_INITIALIZER_P (init) && CP_AGGREGATE_TYPE_P (type))
2115 init = reshape_init (type, init, complain);
2118 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
2119 && CP_AGGREGATE_TYPE_P (type))
2120 /* A brace-enclosed initializer for an aggregate. In C++0x this can
2121 happen for direct-initialization, too. */
2122 init = digest_init (type, init, complain);
2124 if (init == error_mark_node)
2125 return false;
2127 /* A CONSTRUCTOR of the target's type is a previously digested
2128 initializer, whether that happened just above or in
2129 cp_parser_late_parsing_nsdmi.
2131 A TARGET_EXPR with TARGET_EXPR_DIRECT_INIT_P or TARGET_EXPR_LIST_INIT_P
2132 set represents the whole initialization, so we shouldn't build up
2133 another ctor call. */
2134 if (init
2135 && (TREE_CODE (init) == CONSTRUCTOR
2136 || (TREE_CODE (init) == TARGET_EXPR
2137 && (TARGET_EXPR_DIRECT_INIT_P (init)
2138 || TARGET_EXPR_LIST_INIT_P (init))))
2139 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
2141 /* Early initialization via a TARGET_EXPR only works for
2142 complete objects. */
2143 gcc_assert (TREE_CODE (init) == CONSTRUCTOR || true_exp == exp);
2145 init = cp_build_init_expr (exp, init);
2146 TREE_SIDE_EFFECTS (init) = 1;
2147 finish_expr_stmt (init);
2148 return true;
2151 if (init && TREE_CODE (init) != TREE_LIST
2152 && (flags & LOOKUP_ONLYCONVERTING)
2153 && !unsafe_return_slot_p (exp))
2155 /* Base subobjects should only get direct-initialization. */
2156 gcc_assert (true_exp == exp);
2158 if (flags & DIRECT_BIND)
2159 /* Do nothing. We hit this in two cases: Reference initialization,
2160 where we aren't initializing a real variable, so we don't want
2161 to run a new constructor; and catching an exception, where we
2162 have already built up the constructor call so we could wrap it
2163 in an exception region. */;
2164 else
2166 init = ocp_convert (type, init, CONV_IMPLICIT|CONV_FORCE_TEMP,
2167 flags, complain | tf_no_cleanup);
2168 if (init == error_mark_node)
2169 return false;
2172 /* We need to protect the initialization of a catch parm with a
2173 call to terminate(), which shows up as a MUST_NOT_THROW_EXPR
2174 around the TARGET_EXPR for the copy constructor. See
2175 initialize_handler_parm. */
2176 tree *p = &init;
2177 while (TREE_CODE (*p) == MUST_NOT_THROW_EXPR
2178 || TREE_CODE (*p) == CLEANUP_POINT_EXPR)
2180 /* Avoid voidify_wrapper_expr making a temporary. */
2181 TREE_TYPE (*p) = void_type_node;
2182 p = &TREE_OPERAND (*p, 0);
2184 *p = cp_build_init_expr (exp, *p);
2185 finish_expr_stmt (init);
2186 return true;
2189 if (init == NULL_TREE)
2190 parms = NULL;
2191 else if (TREE_CODE (init) == TREE_LIST && !TREE_TYPE (init))
2193 parms = make_tree_vector ();
2194 for (; init != NULL_TREE; init = TREE_CHAIN (init))
2195 vec_safe_push (parms, TREE_VALUE (init));
2197 else
2198 parms = make_tree_vector_single (init);
2200 if (exp == current_class_ref && current_function_decl
2201 && DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
2203 /* Delegating constructor. */
2204 tree complete;
2205 tree base;
2206 tree elt; unsigned i;
2208 /* Unshare the arguments for the second call. */
2209 releasing_vec parms2;
2210 FOR_EACH_VEC_SAFE_ELT (parms, i, elt)
2212 elt = break_out_target_exprs (elt);
2213 vec_safe_push (parms2, elt);
2215 complete = build_special_member_call (exp, complete_ctor_identifier,
2216 &parms2, binfo, flags,
2217 complain);
2218 complete = fold_build_cleanup_point_expr (void_type_node, complete);
2220 base = build_special_member_call (exp, base_ctor_identifier,
2221 &parms, binfo, flags,
2222 complain);
2223 base = fold_build_cleanup_point_expr (void_type_node, base);
2224 if (complete == error_mark_node || base == error_mark_node)
2225 return false;
2226 rval = build_if_in_charge (complete, base);
2228 else
2230 tree ctor_name = (true_exp == exp
2231 ? complete_ctor_identifier : base_ctor_identifier);
2233 rval = build_special_member_call (exp, ctor_name, &parms, binfo, flags,
2234 complain);
2235 if (rval == error_mark_node)
2236 return false;
2239 if (parms != NULL)
2240 release_tree_vector (parms);
2242 if (exp == true_exp && TREE_CODE (rval) == CALL_EXPR)
2244 tree fn = get_callee_fndecl (rval);
2245 if (fn && DECL_DECLARED_CONSTEXPR_P (fn))
2247 tree e = maybe_constant_init (rval, exp);
2248 if (TREE_CONSTANT (e))
2249 rval = cp_build_init_expr (exp, e);
2253 /* FIXME put back convert_to_void? */
2254 if (TREE_SIDE_EFFECTS (rval))
2255 finish_expr_stmt (rval);
2257 return true;
2260 /* This function is responsible for initializing EXP with INIT
2261 (if any). Returns true on success, false on failure.
2263 BINFO is the binfo of the type for who we are performing the
2264 initialization. For example, if W is a virtual base class of A and B,
2265 and C : A, B.
2266 If we are initializing B, then W must contain B's W vtable, whereas
2267 were we initializing C, W must contain C's W vtable.
2269 TRUE_EXP is nonzero if it is the true expression being initialized.
2270 In this case, it may be EXP, or may just contain EXP. The reason we
2271 need this is because if EXP is a base element of TRUE_EXP, we
2272 don't necessarily know by looking at EXP where its virtual
2273 baseclass fields should really be pointing. But we do know
2274 from TRUE_EXP. In constructors, we don't know anything about
2275 the value being initialized.
2277 FLAGS is just passed to `build_new_method_call'. See that function
2278 for its description. */
2280 static bool
2281 expand_aggr_init_1 (tree binfo, tree true_exp, tree exp, tree init, int flags,
2282 tsubst_flags_t complain)
2284 tree type = TREE_TYPE (exp);
2286 gcc_assert (init != error_mark_node && type != error_mark_node);
2287 gcc_assert (building_stmt_list_p ());
2289 /* Use a function returning the desired type to initialize EXP for us.
2290 If the function is a constructor, and its first argument is
2291 NULL_TREE, know that it was meant for us--just slide exp on
2292 in and expand the constructor. Constructors now come
2293 as TARGET_EXPRs. */
2295 if (init && VAR_P (exp)
2296 && COMPOUND_LITERAL_P (init))
2298 vec<tree, va_gc> *cleanups = NULL;
2299 /* If store_init_value returns NULL_TREE, the INIT has been
2300 recorded as the DECL_INITIAL for EXP. That means there's
2301 nothing more we have to do. */
2302 init = store_init_value (exp, init, &cleanups, flags);
2303 if (init)
2304 finish_expr_stmt (init);
2305 gcc_assert (!cleanups);
2306 return true;
2309 /* List-initialization from {} becomes value-initialization for non-aggregate
2310 classes with default constructors. Handle this here when we're
2311 initializing a base, so protected access works. */
2312 if (exp != true_exp && init && TREE_CODE (init) == TREE_LIST)
2314 tree elt = TREE_VALUE (init);
2315 if (DIRECT_LIST_INIT_P (elt)
2316 && CONSTRUCTOR_ELTS (elt) == 0
2317 && CLASSTYPE_NON_AGGREGATE (type)
2318 && TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
2319 init = void_type_node;
2322 /* If an explicit -- but empty -- initializer list was present,
2323 that's value-initialization. */
2324 if (init == void_type_node)
2326 /* If the type has data but no user-provided default ctor, we need to zero
2327 out the object. */
2328 if (type_has_non_user_provided_default_constructor (type)
2329 && !is_really_empty_class (type, /*ignore_vptr*/true))
2331 tree field_size = NULL_TREE;
2332 if (exp != true_exp && CLASSTYPE_AS_BASE (type) != type)
2333 /* Don't clobber already initialized virtual bases. */
2334 field_size = TYPE_SIZE (CLASSTYPE_AS_BASE (type));
2335 init = build_zero_init_1 (type, NULL_TREE, /*static_storage_p=*/false,
2336 field_size);
2337 init = cp_build_init_expr (exp, init);
2338 finish_expr_stmt (init);
2341 /* If we don't need to mess with the constructor at all,
2342 then we're done. */
2343 if (! type_build_ctor_call (type))
2344 return true;
2346 /* Otherwise fall through and call the constructor. */
2347 init = NULL_TREE;
2350 /* We know that expand_default_init can handle everything we want
2351 at this point. */
2352 return expand_default_init (binfo, true_exp, exp, init, flags, complain);
2355 /* Report an error if TYPE is not a user-defined, class type. If
2356 OR_ELSE is nonzero, give an error message. */
2359 is_class_type (tree type, int or_else)
2361 if (type == error_mark_node)
2362 return 0;
2364 if (! CLASS_TYPE_P (type))
2366 if (or_else)
2367 error ("%qT is not a class type", type);
2368 return 0;
2370 return 1;
2373 /* Returns true iff the initializer INIT represents copy-initialization
2374 (and therefore we must set LOOKUP_ONLYCONVERTING when processing it). */
2376 bool
2377 is_copy_initialization (tree init)
2379 return (init && init != void_type_node
2380 && TREE_CODE (init) != TREE_LIST
2381 && !(TREE_CODE (init) == TARGET_EXPR
2382 && TARGET_EXPR_DIRECT_INIT_P (init))
2383 && !DIRECT_LIST_INIT_P (init));
2386 /* Build a reference to a member of an aggregate. This is not a C++
2387 `&', but really something which can have its address taken, and
2388 then act as a pointer to member, for example TYPE :: FIELD can have
2389 its address taken by saying & TYPE :: FIELD. ADDRESS_P is true if
2390 this expression is the operand of "&".
2392 @@ Prints out lousy diagnostics for operator <typename>
2393 @@ fields.
2395 @@ This function should be rewritten and placed in search.cc. */
2397 tree
2398 build_offset_ref (tree type, tree member, bool address_p,
2399 tsubst_flags_t complain)
2401 tree decl;
2402 tree basebinfo = NULL_TREE;
2404 /* class templates can come in as TEMPLATE_DECLs here. */
2405 if (TREE_CODE (member) == TEMPLATE_DECL)
2406 return member;
2408 if (dependent_scope_p (type) || type_dependent_expression_p (member))
2409 return build_qualified_name (NULL_TREE, type, member,
2410 /*template_p=*/false);
2412 gcc_assert (TYPE_P (type));
2413 if (! is_class_type (type, 1))
2414 return error_mark_node;
2416 gcc_assert (DECL_P (member) || BASELINK_P (member));
2417 /* Callers should call mark_used before this point, except for functions. */
2418 gcc_assert (!DECL_P (member) || TREE_USED (member)
2419 || TREE_CODE (member) == FUNCTION_DECL);
2421 type = TYPE_MAIN_VARIANT (type);
2422 if (!COMPLETE_OR_OPEN_TYPE_P (complete_type (type)))
2424 if (complain & tf_error)
2425 error ("incomplete type %qT does not have member %qD", type, member);
2426 return error_mark_node;
2429 /* Entities other than non-static members need no further
2430 processing. */
2431 if (TREE_CODE (member) == TYPE_DECL)
2432 return member;
2433 if (VAR_P (member) || TREE_CODE (member) == CONST_DECL)
2434 return convert_from_reference (member);
2436 if (TREE_CODE (member) == FIELD_DECL && DECL_C_BIT_FIELD (member))
2438 if (complain & tf_error)
2439 error ("invalid pointer to bit-field %qD", member);
2440 return error_mark_node;
2443 /* Set up BASEBINFO for member lookup. */
2444 decl = maybe_dummy_object (type, &basebinfo);
2446 /* A lot of this logic is now handled in lookup_member. */
2447 if (BASELINK_P (member))
2449 /* Go from the TREE_BASELINK to the member function info. */
2450 tree t = BASELINK_FUNCTIONS (member);
2452 if (TREE_CODE (t) != TEMPLATE_ID_EXPR && !really_overloaded_fn (t))
2454 /* Get rid of a potential OVERLOAD around it. */
2455 t = OVL_FIRST (t);
2457 /* Unique functions are handled easily. */
2459 /* For non-static member of base class, we need a special rule
2460 for access checking [class.protected]:
2462 If the access is to form a pointer to member, the
2463 nested-name-specifier shall name the derived class
2464 (or any class derived from that class). */
2465 bool ok;
2466 if (address_p && DECL_P (t)
2467 && DECL_NONSTATIC_MEMBER_P (t))
2468 ok = perform_or_defer_access_check (TYPE_BINFO (type), t, t,
2469 complain);
2470 else
2471 ok = perform_or_defer_access_check (basebinfo, t, t,
2472 complain);
2473 if (!ok)
2474 return error_mark_node;
2475 if (DECL_STATIC_FUNCTION_P (t))
2476 return member;
2477 member = t;
2479 else
2480 TREE_TYPE (member) = unknown_type_node;
2482 else if (address_p && TREE_CODE (member) == FIELD_DECL)
2484 /* We need additional test besides the one in
2485 check_accessibility_of_qualified_id in case it is
2486 a pointer to non-static member. */
2487 if (!perform_or_defer_access_check (TYPE_BINFO (type), member, member,
2488 complain))
2489 return error_mark_node;
2492 if (!address_p)
2494 /* If MEMBER is non-static, then the program has fallen afoul of
2495 [expr.prim]:
2497 An id-expression that denotes a non-static data member or
2498 non-static member function of a class can only be used:
2500 -- as part of a class member access (_expr.ref_) in which the
2501 object-expression refers to the member's class or a class
2502 derived from that class, or
2504 -- to form a pointer to member (_expr.unary.op_), or
2506 -- in the body of a non-static member function of that class or
2507 of a class derived from that class (_class.mfct.non-static_), or
2509 -- in a mem-initializer for a constructor for that class or for
2510 a class derived from that class (_class.base.init_). */
2511 if (DECL_OBJECT_MEMBER_FUNCTION_P (member))
2513 /* Build a representation of the qualified name suitable
2514 for use as the operand to "&" -- even though the "&" is
2515 not actually present. */
2516 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2517 /* In Microsoft mode, treat a non-static member function as if
2518 it were a pointer-to-member. */
2519 if (flag_ms_extensions)
2521 PTRMEM_OK_P (member) = 1;
2522 return cp_build_addr_expr (member, complain);
2524 if (complain & tf_error)
2525 error ("invalid use of non-static member function %qD",
2526 TREE_OPERAND (member, 1));
2527 return error_mark_node;
2529 else if (TREE_CODE (member) == FIELD_DECL)
2531 if (complain & tf_error)
2532 error ("invalid use of non-static data member %qD", member);
2533 return error_mark_node;
2535 return member;
2538 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2539 PTRMEM_OK_P (member) = 1;
2540 return member;
2543 /* If DECL is a scalar enumeration constant or variable with a
2544 constant initializer, return the initializer (or, its initializers,
2545 recursively); otherwise, return DECL. If STRICT_P, the
2546 initializer is only returned if DECL is a
2547 constant-expression. If RETURN_AGGREGATE_CST_OK_P, it is ok to
2548 return an aggregate constant. If UNSHARE_P, return an unshared
2549 copy of the initializer. */
2551 static tree
2552 constant_value_1 (tree decl, bool strict_p, bool return_aggregate_cst_ok_p,
2553 bool unshare_p)
2555 while (TREE_CODE (decl) == CONST_DECL
2556 || decl_constant_var_p (decl)
2557 || (!strict_p && VAR_P (decl)
2558 && CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (decl))))
2560 tree init;
2561 /* If DECL is a static data member in a template
2562 specialization, we must instantiate it here. The
2563 initializer for the static data member is not processed
2564 until needed; we need it now. */
2565 mark_used (decl, tf_none);
2566 init = DECL_INITIAL (decl);
2567 if (init == error_mark_node)
2569 if (TREE_CODE (decl) == CONST_DECL
2570 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2571 /* Treat the error as a constant to avoid cascading errors on
2572 excessively recursive template instantiation (c++/9335). */
2573 return init;
2574 else
2575 return decl;
2577 /* Initializers in templates are generally expanded during
2578 instantiation, so before that for const int i(2)
2579 INIT is a TREE_LIST with the actual initializer as
2580 TREE_VALUE. */
2581 if (processing_template_decl
2582 && init
2583 && TREE_CODE (init) == TREE_LIST
2584 && TREE_CHAIN (init) == NULL_TREE)
2585 init = TREE_VALUE (init);
2586 /* Instantiate a non-dependent initializer for user variables. We
2587 mustn't do this for the temporary for an array compound literal;
2588 trying to instatiate the initializer will keep creating new
2589 temporaries until we crash. Probably it's not useful to do it for
2590 other artificial variables, either. */
2591 if (!DECL_ARTIFICIAL (decl))
2592 init = instantiate_non_dependent_or_null (init);
2593 if (!init
2594 || !TREE_TYPE (init)
2595 || !TREE_CONSTANT (init)
2596 || (!return_aggregate_cst_ok_p
2597 /* Unless RETURN_AGGREGATE_CST_OK_P is true, do not
2598 return an aggregate constant (of which string
2599 literals are a special case), as we do not want
2600 to make inadvertent copies of such entities, and
2601 we must be sure that their addresses are the
2602 same everywhere. */
2603 && (TREE_CODE (init) == CONSTRUCTOR
2604 || TREE_CODE (init) == STRING_CST)))
2605 break;
2606 /* Don't return a CONSTRUCTOR for a variable with partial run-time
2607 initialization, since it doesn't represent the entire value.
2608 Similarly for VECTOR_CSTs created by cp_folding those
2609 CONSTRUCTORs. */
2610 if ((TREE_CODE (init) == CONSTRUCTOR
2611 || TREE_CODE (init) == VECTOR_CST)
2612 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2613 break;
2614 /* If the variable has a dynamic initializer, don't use its
2615 DECL_INITIAL which doesn't reflect the real value. */
2616 if (VAR_P (decl)
2617 && TREE_STATIC (decl)
2618 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)
2619 && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2620 break;
2621 decl = init;
2623 return unshare_p ? unshare_expr (decl) : decl;
2626 /* If DECL is a CONST_DECL, or a constant VAR_DECL initialized by constant
2627 of integral or enumeration type, or a constexpr variable of scalar type,
2628 then return that value. These are those variables permitted in constant
2629 expressions by [5.19/1]. */
2631 tree
2632 scalar_constant_value (tree decl)
2634 return constant_value_1 (decl, /*strict_p=*/true,
2635 /*return_aggregate_cst_ok_p=*/false,
2636 /*unshare_p=*/true);
2639 /* Like scalar_constant_value, but can also return aggregate initializers.
2640 If UNSHARE_P, return an unshared copy of the initializer. */
2642 tree
2643 decl_really_constant_value (tree decl, bool unshare_p /*= true*/)
2645 return constant_value_1 (decl, /*strict_p=*/true,
2646 /*return_aggregate_cst_ok_p=*/true,
2647 /*unshare_p=*/unshare_p);
2650 /* A more relaxed version of decl_really_constant_value, used by the
2651 common C/C++ code. */
2653 tree
2654 decl_constant_value (tree decl, bool unshare_p)
2656 return constant_value_1 (decl, /*strict_p=*/processing_template_decl,
2657 /*return_aggregate_cst_ok_p=*/true,
2658 /*unshare_p=*/unshare_p);
2661 tree
2662 decl_constant_value (tree decl)
2664 return decl_constant_value (decl, /*unshare_p=*/true);
2667 /* Common subroutines of build_new and build_vec_delete. */
2669 /* Build and return a NEW_EXPR. If NELTS is non-NULL, TYPE[NELTS] is
2670 the type of the object being allocated; otherwise, it's just TYPE.
2671 INIT is the initializer, if any. USE_GLOBAL_NEW is true if the
2672 user explicitly wrote "::operator new". PLACEMENT, if non-NULL, is
2673 a vector of arguments to be provided as arguments to a placement
2674 new operator. This routine performs no semantic checks; it just
2675 creates and returns a NEW_EXPR. */
2677 static tree
2678 build_raw_new_expr (location_t loc, vec<tree, va_gc> *placement, tree type,
2679 tree nelts, vec<tree, va_gc> *init, int use_global_new)
2681 tree init_list;
2682 tree new_expr;
2684 /* If INIT is NULL, the we want to store NULL_TREE in the NEW_EXPR.
2685 If INIT is not NULL, then we want to store VOID_ZERO_NODE. This
2686 permits us to distinguish the case of a missing initializer "new
2687 int" from an empty initializer "new int()". */
2688 if (init == NULL)
2689 init_list = NULL_TREE;
2690 else if (init->is_empty ())
2691 init_list = void_node;
2692 else
2693 init_list = build_tree_list_vec (init);
2695 new_expr = build4_loc (loc, NEW_EXPR, build_pointer_type (type),
2696 build_tree_list_vec (placement), type, nelts,
2697 init_list);
2698 NEW_EXPR_USE_GLOBAL (new_expr) = use_global_new;
2699 TREE_SIDE_EFFECTS (new_expr) = 1;
2701 return new_expr;
2704 /* Diagnose uninitialized const members or reference members of type
2705 TYPE. USING_NEW is used to disambiguate the diagnostic between a
2706 new expression without a new-initializer and a declaration. Returns
2707 the error count. */
2709 static int
2710 diagnose_uninitialized_cst_or_ref_member_1 (tree type, tree origin,
2711 bool using_new, bool complain)
2713 tree field;
2714 int error_count = 0;
2716 if (type_has_user_provided_constructor (type))
2717 return 0;
2719 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
2721 tree field_type;
2723 if (TREE_CODE (field) != FIELD_DECL)
2724 continue;
2726 field_type = strip_array_types (TREE_TYPE (field));
2728 if (type_has_user_provided_constructor (field_type))
2729 continue;
2731 if (TYPE_REF_P (field_type))
2733 ++ error_count;
2734 if (complain)
2736 if (DECL_CONTEXT (field) == origin)
2738 if (using_new)
2739 error ("uninitialized reference member in %q#T "
2740 "using %<new%> without new-initializer", origin);
2741 else
2742 error ("uninitialized reference member in %q#T", origin);
2744 else
2746 if (using_new)
2747 error ("uninitialized reference member in base %q#T "
2748 "of %q#T using %<new%> without new-initializer",
2749 DECL_CONTEXT (field), origin);
2750 else
2751 error ("uninitialized reference member in base %q#T "
2752 "of %q#T", DECL_CONTEXT (field), origin);
2754 inform (DECL_SOURCE_LOCATION (field),
2755 "%q#D should be initialized", field);
2759 if (CP_TYPE_CONST_P (field_type))
2761 ++ error_count;
2762 if (complain)
2764 if (DECL_CONTEXT (field) == origin)
2766 if (using_new)
2767 error ("uninitialized const member in %q#T "
2768 "using %<new%> without new-initializer", origin);
2769 else
2770 error ("uninitialized const member in %q#T", origin);
2772 else
2774 if (using_new)
2775 error ("uninitialized const member in base %q#T "
2776 "of %q#T using %<new%> without new-initializer",
2777 DECL_CONTEXT (field), origin);
2778 else
2779 error ("uninitialized const member in base %q#T "
2780 "of %q#T", DECL_CONTEXT (field), origin);
2782 inform (DECL_SOURCE_LOCATION (field),
2783 "%q#D should be initialized", field);
2787 if (CLASS_TYPE_P (field_type))
2788 error_count
2789 += diagnose_uninitialized_cst_or_ref_member_1 (field_type, origin,
2790 using_new, complain);
2792 return error_count;
2796 diagnose_uninitialized_cst_or_ref_member (tree type, bool using_new, bool complain)
2798 return diagnose_uninitialized_cst_or_ref_member_1 (type, type, using_new, complain);
2801 /* Call __cxa_bad_array_new_length to indicate that the size calculation
2802 overflowed. Pretend it returns sizetype so that it plays nicely in the
2803 COND_EXPR. */
2805 tree
2806 throw_bad_array_new_length (void)
2808 if (!fn)
2810 tree name = get_identifier ("__cxa_throw_bad_array_new_length");
2812 fn = get_global_binding (name);
2813 if (!fn)
2814 fn = push_throw_library_fn
2815 (name, build_function_type_list (sizetype, NULL_TREE));
2818 return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
2821 /* Attempt to verify that the argument, OPER, of a placement new expression
2822 refers to an object sufficiently large for an object of TYPE or an array
2823 of NELTS of such objects when NELTS is non-null, and issue a warning when
2824 it does not. SIZE specifies the size needed to construct the object or
2825 array and captures the result of NELTS * sizeof (TYPE). (SIZE could be
2826 greater when the array under construction requires a cookie to store
2827 NELTS. GCC's placement new expression stores the cookie when invoking
2828 a user-defined placement new operator function but not the default one.
2829 Placement new expressions with user-defined placement new operator are
2830 not diagnosed since we don't know how they use the buffer (this could
2831 be a future extension). */
2832 static void
2833 warn_placement_new_too_small (tree type, tree nelts, tree size, tree oper)
2835 location_t loc = cp_expr_loc_or_input_loc (oper);
2837 STRIP_NOPS (oper);
2839 /* Using a function argument or a (non-array) variable as an argument
2840 to placement new is not checked since it's unknown what it might
2841 point to. */
2842 if (TREE_CODE (oper) == PARM_DECL
2843 || VAR_P (oper)
2844 || TREE_CODE (oper) == COMPONENT_REF)
2845 return;
2847 /* Evaluate any constant expressions. */
2848 size = fold_non_dependent_expr (size);
2850 access_ref ref;
2851 ref.eval = [](tree x){ return fold_non_dependent_expr (x); };
2852 ref.trail1special = warn_placement_new < 2;
2853 tree objsize = compute_objsize (oper, 1, &ref);
2854 if (!objsize)
2855 return;
2857 /* We can only draw conclusions if ref.deref == -1,
2858 i.e. oper is the address of the object. */
2859 if (ref.deref != -1)
2860 return;
2862 offset_int bytes_avail = wi::to_offset (objsize);
2863 offset_int bytes_need;
2865 if (CONSTANT_CLASS_P (size))
2866 bytes_need = wi::to_offset (size);
2867 else if (nelts && CONSTANT_CLASS_P (nelts))
2868 bytes_need = (wi::to_offset (nelts)
2869 * wi::to_offset (TYPE_SIZE_UNIT (type)));
2870 else if (tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2871 bytes_need = wi::to_offset (TYPE_SIZE_UNIT (type));
2872 else
2874 /* The type is a VLA. */
2875 return;
2878 if (bytes_avail >= bytes_need)
2879 return;
2881 /* True when the size to mention in the warning is exact as opposed
2882 to "at least N". */
2883 const bool exact_size = (ref.offrng[0] == ref.offrng[1]
2884 || ref.sizrng[1] - ref.offrng[0] == 0);
2886 tree opertype = ref.ref ? TREE_TYPE (ref.ref) : TREE_TYPE (oper);
2887 bool warned = false;
2888 if (nelts)
2889 nelts = fold_for_warn (nelts);
2890 if (nelts)
2891 if (CONSTANT_CLASS_P (nelts))
2892 warned = warning_at (loc, OPT_Wplacement_new_,
2893 (exact_size
2894 ? G_("placement new constructing an object "
2895 "of type %<%T [%wu]%> and size %qwu "
2896 "in a region of type %qT and size %qwi")
2897 : G_("placement new constructing an object "
2898 "of type %<%T [%wu]%> and size %qwu "
2899 "in a region of type %qT and size "
2900 "at most %qwu")),
2901 type, tree_to_uhwi (nelts),
2902 bytes_need.to_uhwi (),
2903 opertype, bytes_avail.to_uhwi ());
2904 else
2905 warned = warning_at (loc, OPT_Wplacement_new_,
2906 (exact_size
2907 ? G_("placement new constructing an array "
2908 "of objects of type %qT and size %qwu "
2909 "in a region of type %qT and size %qwi")
2910 : G_("placement new constructing an array "
2911 "of objects of type %qT and size %qwu "
2912 "in a region of type %qT and size "
2913 "at most %qwu")),
2914 type, bytes_need.to_uhwi (), opertype,
2915 bytes_avail.to_uhwi ());
2916 else
2917 warned = warning_at (loc, OPT_Wplacement_new_,
2918 (exact_size
2919 ? G_("placement new constructing an object "
2920 "of type %qT and size %qwu in a region "
2921 "of type %qT and size %qwi")
2922 : G_("placement new constructing an object "
2923 "of type %qT "
2924 "and size %qwu in a region of type %qT "
2925 "and size at most %qwu")),
2926 type, bytes_need.to_uhwi (), opertype,
2927 bytes_avail.to_uhwi ());
2929 if (!warned || !ref.ref)
2930 return;
2932 if (ref.offrng[0] == 0 || !ref.offset_bounded ())
2933 /* Avoid mentioning the offset when its lower bound is zero
2934 or when it's impossibly large. */
2935 inform (DECL_SOURCE_LOCATION (ref.ref),
2936 "%qD declared here", ref.ref);
2937 else if (ref.offrng[0] == ref.offrng[1])
2938 inform (DECL_SOURCE_LOCATION (ref.ref),
2939 "at offset %wi from %qD declared here",
2940 ref.offrng[0].to_shwi (), ref.ref);
2941 else
2942 inform (DECL_SOURCE_LOCATION (ref.ref),
2943 "at offset [%wi, %wi] from %qD declared here",
2944 ref.offrng[0].to_shwi (), ref.offrng[1].to_shwi (), ref.ref);
2947 /* True if alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__. */
2949 bool
2950 type_has_new_extended_alignment (tree t)
2952 return (aligned_new_threshold
2953 && TYPE_ALIGN_UNIT (t) > (unsigned)aligned_new_threshold);
2956 /* Return the alignment we expect malloc to guarantee. This should just be
2957 MALLOC_ABI_ALIGNMENT, but that macro defaults to only BITS_PER_WORD for some
2958 reason, so don't let the threshold be smaller than max_align_t_align. */
2960 unsigned
2961 malloc_alignment ()
2963 return MAX (max_align_t_align(), MALLOC_ABI_ALIGNMENT);
2966 /* Determine whether an allocation function is a namespace-scope
2967 non-replaceable placement new function. See DR 1748. */
2968 static bool
2969 std_placement_new_fn_p (tree alloc_fn)
2971 if (DECL_NAMESPACE_SCOPE_P (alloc_fn))
2973 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (alloc_fn)));
2974 if ((TREE_VALUE (first_arg) == ptr_type_node)
2975 && TREE_CHAIN (first_arg) == void_list_node)
2976 return true;
2978 return false;
2981 /* For element type ELT_TYPE, return the appropriate type of the heap object
2982 containing such element(s). COOKIE_SIZE is the size of cookie in bytes.
2983 Return
2984 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
2985 where N is nothing (flexible array member) if ITYPE2 is NULL, otherwise
2986 the array has ITYPE2 as its TYPE_DOMAIN. */
2988 tree
2989 build_new_constexpr_heap_type (tree elt_type, tree cookie_size, tree itype2)
2991 gcc_assert (tree_fits_uhwi_p (cookie_size));
2992 unsigned HOST_WIDE_INT csz = tree_to_uhwi (cookie_size);
2993 csz /= int_size_in_bytes (sizetype);
2994 tree itype1 = build_index_type (size_int (csz - 1));
2995 tree atype1 = build_cplus_array_type (sizetype, itype1);
2996 tree atype2 = build_cplus_array_type (elt_type, itype2);
2997 tree rtype = cxx_make_type (RECORD_TYPE);
2998 TYPE_NAME (rtype) = heap_identifier;
2999 tree fld1 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype1);
3000 tree fld2 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype2);
3001 DECL_FIELD_CONTEXT (fld1) = rtype;
3002 DECL_FIELD_CONTEXT (fld2) = rtype;
3003 DECL_ARTIFICIAL (fld1) = true;
3004 DECL_ARTIFICIAL (fld2) = true;
3005 TYPE_FIELDS (rtype) = fld1;
3006 DECL_CHAIN (fld1) = fld2;
3007 layout_type (rtype);
3008 return rtype;
3011 /* Help the constexpr code to find the right type for the heap variable
3012 by adding a NOP_EXPR around ALLOC_CALL if needed for cookie_size.
3013 Return ALLOC_CALL or ALLOC_CALL cast to a pointer to
3014 struct { size_t[cookie_size/sizeof(size_t)]; elt_type[]; }. */
3016 static tree
3017 maybe_wrap_new_for_constexpr (tree alloc_call, tree elt_type, tree cookie_size)
3019 if (cxx_dialect < cxx20)
3020 return alloc_call;
3022 if (current_function_decl != NULL_TREE
3023 && !DECL_DECLARED_CONSTEXPR_P (current_function_decl))
3024 return alloc_call;
3026 tree call_expr = extract_call_expr (alloc_call);
3027 if (call_expr == error_mark_node)
3028 return alloc_call;
3030 tree alloc_call_fndecl = cp_get_callee_fndecl_nofold (call_expr);
3031 if (alloc_call_fndecl == NULL_TREE
3032 || !IDENTIFIER_NEW_OP_P (DECL_NAME (alloc_call_fndecl))
3033 || CP_DECL_CONTEXT (alloc_call_fndecl) != global_namespace)
3034 return alloc_call;
3036 tree rtype = build_new_constexpr_heap_type (elt_type, cookie_size,
3037 NULL_TREE);
3038 return build_nop (build_pointer_type (rtype), alloc_call);
3041 /* Generate code for a new-expression, including calling the "operator
3042 new" function, initializing the object, and, if an exception occurs
3043 during construction, cleaning up. The arguments are as for
3044 build_raw_new_expr. This may change PLACEMENT and INIT.
3045 TYPE is the type of the object being constructed, possibly an array
3046 of NELTS elements when NELTS is non-null (in "new T[NELTS]", T may
3047 be an array of the form U[inner], with the whole expression being
3048 "new U[NELTS][inner]"). */
3050 static tree
3051 build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts,
3052 vec<tree, va_gc> **init, bool globally_qualified_p,
3053 tsubst_flags_t complain)
3055 tree size, rval;
3056 /* True iff this is a call to "operator new[]" instead of just
3057 "operator new". */
3058 bool array_p = false;
3059 /* If ARRAY_P is true, the element type of the array. This is never
3060 an ARRAY_TYPE; for something like "new int[3][4]", the
3061 ELT_TYPE is "int". If ARRAY_P is false, this is the same type as
3062 TYPE. */
3063 tree elt_type;
3064 /* The type of the new-expression. (This type is always a pointer
3065 type.) */
3066 tree pointer_type;
3067 tree non_const_pointer_type;
3068 /* The most significant array bound in int[OUTER_NELTS][inner]. */
3069 tree outer_nelts = NULL_TREE;
3070 /* For arrays with a non-constant number of elements, a bounds checks
3071 on the NELTS parameter to avoid integer overflow at runtime. */
3072 tree outer_nelts_check = NULL_TREE;
3073 bool outer_nelts_from_type = false;
3074 /* Number of the "inner" elements in "new T[OUTER_NELTS][inner]". */
3075 offset_int inner_nelts_count = 1;
3076 tree alloc_call, alloc_expr;
3077 /* Size of the inner array elements (those with constant dimensions). */
3078 offset_int inner_size;
3079 /* The address returned by the call to "operator new". This node is
3080 a VAR_DECL and is therefore reusable. */
3081 tree alloc_node;
3082 tree alloc_fn;
3083 tree cookie_expr, init_expr;
3084 int nothrow, check_new;
3085 /* If non-NULL, the number of extra bytes to allocate at the
3086 beginning of the storage allocated for an array-new expression in
3087 order to store the number of elements. */
3088 tree cookie_size = NULL_TREE;
3089 tree placement_first;
3090 tree placement_expr = NULL_TREE;
3091 /* True if the function we are calling is a placement allocation
3092 function. */
3093 bool placement_allocation_fn_p;
3094 /* True if the storage must be initialized, either by a constructor
3095 or due to an explicit new-initializer. */
3096 bool is_initialized;
3097 /* The address of the thing allocated, not including any cookie. In
3098 particular, if an array cookie is in use, DATA_ADDR is the
3099 address of the first array element. This node is a VAR_DECL, and
3100 is therefore reusable. */
3101 tree data_addr;
3102 tree orig_type = type;
3104 if (nelts)
3106 outer_nelts = nelts;
3107 array_p = true;
3109 else if (TREE_CODE (type) == ARRAY_TYPE)
3111 /* Transforms new (T[N]) to new T[N]. The former is a GNU
3112 extension for variable N. (This also covers new T where T is
3113 a VLA typedef.) */
3114 array_p = true;
3115 nelts = array_type_nelts_top (type);
3116 outer_nelts = nelts;
3117 type = TREE_TYPE (type);
3118 outer_nelts_from_type = true;
3121 /* Lots of logic below depends on whether we have a constant number of
3122 elements, so go ahead and fold it now. */
3123 const_tree cst_outer_nelts = fold_non_dependent_expr (outer_nelts, complain);
3125 /* If our base type is an array, then make sure we know how many elements
3126 it has. */
3127 for (elt_type = type;
3128 TREE_CODE (elt_type) == ARRAY_TYPE;
3129 elt_type = TREE_TYPE (elt_type))
3131 tree inner_nelts = array_type_nelts_top (elt_type);
3132 tree inner_nelts_cst = maybe_constant_value (inner_nelts);
3133 if (TREE_CODE (inner_nelts_cst) == INTEGER_CST)
3135 wi::overflow_type overflow;
3136 offset_int result = wi::mul (wi::to_offset (inner_nelts_cst),
3137 inner_nelts_count, SIGNED, &overflow);
3138 if (overflow)
3140 if (complain & tf_error)
3141 error ("integer overflow in array size");
3142 nelts = error_mark_node;
3144 inner_nelts_count = result;
3146 else
3148 if (complain & tf_error)
3150 error_at (cp_expr_loc_or_input_loc (inner_nelts),
3151 "array size in new-expression must be constant");
3152 cxx_constant_value(inner_nelts);
3154 nelts = error_mark_node;
3156 if (nelts != error_mark_node)
3157 nelts = cp_build_binary_op (input_location,
3158 MULT_EXPR, nelts,
3159 inner_nelts_cst,
3160 complain);
3163 if (!verify_type_context (input_location, TCTX_ALLOCATION, elt_type,
3164 !(complain & tf_error)))
3165 return error_mark_node;
3167 if (variably_modified_type_p (elt_type, NULL_TREE) && (complain & tf_error))
3169 error ("variably modified type not allowed in new-expression");
3170 return error_mark_node;
3173 if (nelts == error_mark_node)
3174 return error_mark_node;
3176 /* Warn if we performed the (T[N]) to T[N] transformation and N is
3177 variable. */
3178 if (outer_nelts_from_type
3179 && !TREE_CONSTANT (cst_outer_nelts))
3181 if (complain & tf_warning_or_error)
3183 pedwarn (cp_expr_loc_or_input_loc (outer_nelts), OPT_Wvla,
3184 typedef_variant_p (orig_type)
3185 ? G_("non-constant array new length must be specified "
3186 "directly, not by %<typedef%>")
3187 : G_("non-constant array new length must be specified "
3188 "without parentheses around the type-id"));
3190 else
3191 return error_mark_node;
3194 if (VOID_TYPE_P (elt_type))
3196 if (complain & tf_error)
3197 error ("invalid type %<void%> for %<new%>");
3198 return error_mark_node;
3201 if (is_std_init_list (elt_type) && !cp_unevaluated_operand)
3202 warning (OPT_Winit_list_lifetime,
3203 "%<new%> of %<initializer_list%> does not "
3204 "extend the lifetime of the underlying array");
3206 if (abstract_virtuals_error (ACU_NEW, elt_type, complain))
3207 return error_mark_node;
3209 is_initialized = (type_build_ctor_call (elt_type) || *init != NULL);
3211 if (*init == NULL && cxx_dialect < cxx11)
3213 bool maybe_uninitialized_error = false;
3214 /* A program that calls for default-initialization [...] of an
3215 entity of reference type is ill-formed. */
3216 if (CLASSTYPE_REF_FIELDS_NEED_INIT (elt_type))
3217 maybe_uninitialized_error = true;
3219 /* A new-expression that creates an object of type T initializes
3220 that object as follows:
3221 - If the new-initializer is omitted:
3222 -- If T is a (possibly cv-qualified) non-POD class type
3223 (or array thereof), the object is default-initialized (8.5).
3224 [...]
3225 -- Otherwise, the object created has indeterminate
3226 value. If T is a const-qualified type, or a (possibly
3227 cv-qualified) POD class type (or array thereof)
3228 containing (directly or indirectly) a member of
3229 const-qualified type, the program is ill-formed; */
3231 if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (elt_type))
3232 maybe_uninitialized_error = true;
3234 if (maybe_uninitialized_error
3235 && diagnose_uninitialized_cst_or_ref_member (elt_type,
3236 /*using_new=*/true,
3237 complain & tf_error))
3238 return error_mark_node;
3241 if (CP_TYPE_CONST_P (elt_type) && *init == NULL
3242 && default_init_uninitialized_part (elt_type))
3244 if (complain & tf_error)
3245 error ("uninitialized const in %<new%> of %q#T", elt_type);
3246 return error_mark_node;
3249 size = size_in_bytes (elt_type);
3250 if (array_p)
3252 /* Maximum available size in bytes. Half of the address space
3253 minus the cookie size. */
3254 offset_int max_size
3255 = wi::set_bit_in_zero <offset_int> (TYPE_PRECISION (sizetype) - 1);
3256 /* Maximum number of outer elements which can be allocated. */
3257 offset_int max_outer_nelts;
3258 tree max_outer_nelts_tree;
3260 gcc_assert (TREE_CODE (size) == INTEGER_CST);
3261 cookie_size = targetm.cxx.get_cookie_size (elt_type);
3262 gcc_assert (TREE_CODE (cookie_size) == INTEGER_CST);
3263 gcc_checking_assert (wi::ltu_p (wi::to_offset (cookie_size), max_size));
3264 /* Unconditionally subtract the cookie size. This decreases the
3265 maximum object size and is safe even if we choose not to use
3266 a cookie after all. */
3267 max_size -= wi::to_offset (cookie_size);
3268 wi::overflow_type overflow;
3269 inner_size = wi::mul (wi::to_offset (size), inner_nelts_count, SIGNED,
3270 &overflow);
3271 if (overflow || wi::gtu_p (inner_size, max_size))
3273 if (complain & tf_error)
3275 cst_size_error error;
3276 if (overflow)
3277 error = cst_size_overflow;
3278 else
3280 error = cst_size_too_big;
3281 size = size_binop (MULT_EXPR, size,
3282 wide_int_to_tree (sizetype,
3283 inner_nelts_count));
3284 size = cp_fully_fold (size);
3286 invalid_array_size_error (input_location, error, size,
3287 /*name=*/NULL_TREE);
3289 return error_mark_node;
3292 max_outer_nelts = wi::udiv_trunc (max_size, inner_size);
3293 max_outer_nelts_tree = wide_int_to_tree (sizetype, max_outer_nelts);
3295 size = build2 (MULT_EXPR, sizetype, size, nelts);
3297 if (TREE_CODE (cst_outer_nelts) == INTEGER_CST)
3299 if (tree_int_cst_lt (max_outer_nelts_tree, cst_outer_nelts))
3301 /* When the array size is constant, check it at compile time
3302 to make sure it doesn't exceed the implementation-defined
3303 maximum, as required by C++ 14 (in C++ 11 this requirement
3304 isn't explicitly stated but it's enforced anyway -- see
3305 grokdeclarator in cp/decl.cc). */
3306 if (complain & tf_error)
3308 size = cp_fully_fold (size);
3309 invalid_array_size_error (input_location, cst_size_too_big,
3310 size, NULL_TREE);
3312 return error_mark_node;
3315 else
3317 /* When a runtime check is necessary because the array size
3318 isn't constant, keep only the top-most seven bits (starting
3319 with the most significant non-zero bit) of the maximum size
3320 to compare the array size against, to simplify encoding the
3321 constant maximum size in the instruction stream. */
3323 unsigned shift = (max_outer_nelts.get_precision ()) - 7
3324 - wi::clz (max_outer_nelts);
3325 max_outer_nelts = (max_outer_nelts >> shift) << shift;
3327 outer_nelts_check = build2 (LE_EXPR, boolean_type_node,
3328 outer_nelts,
3329 max_outer_nelts_tree);
3333 tree align_arg = NULL_TREE;
3334 if (type_has_new_extended_alignment (elt_type))
3336 unsigned align = TYPE_ALIGN_UNIT (elt_type);
3337 /* Also consider the alignment of the cookie, if any. */
3338 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3339 align = MAX (align, TYPE_ALIGN_UNIT (size_type_node));
3340 align_arg = build_int_cst (align_type_node, align);
3343 alloc_fn = NULL_TREE;
3345 /* If PLACEMENT is a single simple pointer type not passed by
3346 reference, prepare to capture it in a temporary variable. Do
3347 this now, since PLACEMENT will change in the calls below. */
3348 placement_first = NULL_TREE;
3349 if (vec_safe_length (*placement) == 1
3350 && (TYPE_PTR_P (TREE_TYPE ((**placement)[0]))))
3351 placement_first = (**placement)[0];
3353 bool member_new_p = false;
3355 /* Allocate the object. */
3356 tree fnname;
3357 tree fns;
3359 fnname = ovl_op_identifier (false, array_p ? VEC_NEW_EXPR : NEW_EXPR);
3361 member_new_p = !globally_qualified_p
3362 && CLASS_TYPE_P (elt_type)
3363 && (array_p
3364 ? TYPE_HAS_ARRAY_NEW_OPERATOR (elt_type)
3365 : TYPE_HAS_NEW_OPERATOR (elt_type));
3367 bool member_delete_p = (!globally_qualified_p
3368 && CLASS_TYPE_P (elt_type)
3369 && (array_p
3370 ? TYPE_GETS_VEC_DELETE (elt_type)
3371 : TYPE_GETS_REG_DELETE (elt_type)));
3373 if (member_new_p)
3375 /* Use a class-specific operator new. */
3376 /* If a cookie is required, add some extra space. */
3377 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3378 size = build2 (PLUS_EXPR, sizetype, size, cookie_size);
3379 else
3381 cookie_size = NULL_TREE;
3382 /* No size arithmetic necessary, so the size check is
3383 not needed. */
3384 if (outer_nelts_check != NULL && inner_size == 1)
3385 outer_nelts_check = NULL_TREE;
3387 /* Perform the overflow check. */
3388 tree errval = TYPE_MAX_VALUE (sizetype);
3389 if (cxx_dialect >= cxx11 && flag_exceptions)
3390 errval = throw_bad_array_new_length ();
3391 if (outer_nelts_check != NULL_TREE)
3392 size = build3 (COND_EXPR, sizetype, outer_nelts_check, size, errval);
3393 size = cp_fully_fold (size);
3394 /* Create the argument list. */
3395 vec_safe_insert (*placement, 0, size);
3396 /* Do name-lookup to find the appropriate operator. */
3397 fns = lookup_fnfields (elt_type, fnname, /*protect=*/2, complain);
3398 if (fns == NULL_TREE)
3400 if (complain & tf_error)
3401 error ("no suitable %qD found in class %qT", fnname, elt_type);
3402 return error_mark_node;
3404 if (TREE_CODE (fns) == TREE_LIST)
3406 if (complain & tf_error)
3408 error ("request for member %qD is ambiguous", fnname);
3409 print_candidates (fns);
3411 return error_mark_node;
3413 tree dummy = build_dummy_object (elt_type);
3414 alloc_call = NULL_TREE;
3415 if (align_arg)
3417 vec<tree, va_gc> *align_args
3418 = vec_copy_and_insert (*placement, align_arg, 1);
3419 alloc_call
3420 = build_new_method_call (dummy, fns, &align_args,
3421 /*conversion_path=*/NULL_TREE,
3422 LOOKUP_NORMAL, &alloc_fn, tf_none);
3423 /* If no matching function is found and the allocated object type
3424 has new-extended alignment, the alignment argument is removed
3425 from the argument list, and overload resolution is performed
3426 again. */
3427 if (alloc_call == error_mark_node)
3428 alloc_call = NULL_TREE;
3430 if (!alloc_call)
3431 alloc_call = build_new_method_call (dummy, fns, placement,
3432 /*conversion_path=*/NULL_TREE,
3433 LOOKUP_NORMAL,
3434 &alloc_fn, complain);
3436 else
3438 /* Use a global operator new. */
3439 /* See if a cookie might be required. */
3440 if (!(array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type)))
3442 cookie_size = NULL_TREE;
3443 /* No size arithmetic necessary, so the size check is
3444 not needed. */
3445 if (outer_nelts_check != NULL && inner_size == 1)
3446 outer_nelts_check = NULL_TREE;
3449 size = cp_fully_fold (size);
3450 /* If size is zero e.g. due to type having zero size, try to
3451 preserve outer_nelts for constant expression evaluation
3452 purposes. */
3453 if (integer_zerop (size) && outer_nelts)
3454 size = build2 (MULT_EXPR, TREE_TYPE (size), size, outer_nelts);
3456 alloc_call = build_operator_new_call (fnname, placement,
3457 &size, &cookie_size,
3458 align_arg, outer_nelts_check,
3459 &alloc_fn, complain);
3462 if (alloc_call == error_mark_node)
3463 return error_mark_node;
3465 gcc_assert (alloc_fn != NULL_TREE);
3467 /* Now, check to see if this function is actually a placement
3468 allocation function. This can happen even when PLACEMENT is NULL
3469 because we might have something like:
3471 struct S { void* operator new (size_t, int i = 0); };
3473 A call to `new S' will get this allocation function, even though
3474 there is no explicit placement argument. If there is more than
3475 one argument, or there are variable arguments, then this is a
3476 placement allocation function. */
3477 placement_allocation_fn_p
3478 = (type_num_arguments (TREE_TYPE (alloc_fn)) > 1
3479 || varargs_function_p (alloc_fn));
3481 if (complain & tf_warning_or_error
3482 && warn_aligned_new
3483 && !placement_allocation_fn_p
3484 && TYPE_ALIGN (elt_type) > malloc_alignment ()
3485 && (warn_aligned_new > 1
3486 || CP_DECL_CONTEXT (alloc_fn) == global_namespace)
3487 && !aligned_allocation_fn_p (alloc_fn))
3489 auto_diagnostic_group d;
3490 if (warning (OPT_Waligned_new_, "%<new%> of type %qT with extended "
3491 "alignment %d", elt_type, TYPE_ALIGN_UNIT (elt_type)))
3493 inform (input_location, "uses %qD, which does not have an alignment "
3494 "parameter", alloc_fn);
3495 if (!aligned_new_threshold)
3496 inform (input_location, "use %<-faligned-new%> to enable C++17 "
3497 "over-aligned new support");
3501 /* If we found a simple case of PLACEMENT_EXPR above, then copy it
3502 into a temporary variable. */
3503 if (!processing_template_decl
3504 && TREE_CODE (alloc_call) == CALL_EXPR
3505 && call_expr_nargs (alloc_call) == 2
3506 && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 0))) == INTEGER_TYPE
3507 && TYPE_PTR_P (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1))))
3509 tree placement = CALL_EXPR_ARG (alloc_call, 1);
3511 if (placement_first != NULL_TREE
3512 && (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))
3513 || VOID_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))))
3515 placement_expr = get_target_expr (placement_first);
3516 CALL_EXPR_ARG (alloc_call, 1)
3517 = fold_convert (TREE_TYPE (placement), placement_expr);
3520 if (!member_new_p
3521 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1)))))
3523 /* Attempt to make the warning point at the operator new argument. */
3524 if (placement_first)
3525 placement = placement_first;
3527 warn_placement_new_too_small (orig_type, nelts, size, placement);
3531 alloc_expr = alloc_call;
3532 if (cookie_size)
3533 alloc_expr = maybe_wrap_new_for_constexpr (alloc_expr, type,
3534 cookie_size);
3536 /* In the simple case, we can stop now. */
3537 pointer_type = build_pointer_type (type);
3538 if (!cookie_size && !is_initialized && !member_delete_p)
3539 return build_nop (pointer_type, alloc_expr);
3541 /* Store the result of the allocation call in a variable so that we can
3542 use it more than once. */
3543 alloc_expr = get_target_expr (alloc_expr);
3544 alloc_node = TARGET_EXPR_SLOT (alloc_expr);
3546 /* Strip any COMPOUND_EXPRs from ALLOC_CALL. */
3547 while (TREE_CODE (alloc_call) == COMPOUND_EXPR)
3548 alloc_call = TREE_OPERAND (alloc_call, 1);
3550 /* Preevaluate the placement args so that we don't reevaluate them for a
3551 placement delete. */
3552 if (placement_allocation_fn_p)
3554 tree inits;
3555 stabilize_call (alloc_call, &inits);
3556 if (inits)
3557 alloc_expr = build2 (COMPOUND_EXPR, TREE_TYPE (alloc_expr), inits,
3558 alloc_expr);
3561 /* unless an allocation function is declared with an empty excep-
3562 tion-specification (_except.spec_), throw(), it indicates failure to
3563 allocate storage by throwing a bad_alloc exception (clause _except_,
3564 _lib.bad.alloc_); it returns a non-null pointer otherwise If the allo-
3565 cation function is declared with an empty exception-specification,
3566 throw(), it returns null to indicate failure to allocate storage and a
3567 non-null pointer otherwise.
3569 So check for a null exception spec on the op new we just called. */
3571 nothrow = TYPE_NOTHROW_P (TREE_TYPE (alloc_fn));
3572 check_new
3573 = flag_check_new || (nothrow && !std_placement_new_fn_p (alloc_fn));
3575 if (cookie_size)
3577 tree cookie;
3578 tree cookie_ptr;
3579 tree size_ptr_type;
3581 /* Adjust so we're pointing to the start of the object. */
3582 data_addr = fold_build_pointer_plus (alloc_node, cookie_size);
3584 /* Store the number of bytes allocated so that we can know how
3585 many elements to destroy later. We use the last sizeof
3586 (size_t) bytes to store the number of elements. */
3587 cookie_ptr = size_binop (MINUS_EXPR, cookie_size, size_in_bytes (sizetype));
3588 cookie_ptr = fold_build_pointer_plus_loc (input_location,
3589 alloc_node, cookie_ptr);
3590 size_ptr_type = build_pointer_type (sizetype);
3591 cookie_ptr = fold_convert (size_ptr_type, cookie_ptr);
3592 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3594 cookie_expr = build2 (MODIFY_EXPR, sizetype, cookie, nelts);
3596 if (targetm.cxx.cookie_has_size ())
3598 /* Also store the element size. */
3599 cookie_ptr = fold_build_pointer_plus (cookie_ptr,
3600 fold_build1_loc (input_location,
3601 NEGATE_EXPR, sizetype,
3602 size_in_bytes (sizetype)));
3604 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3605 cookie = build2 (MODIFY_EXPR, sizetype, cookie,
3606 size_in_bytes (elt_type));
3607 cookie_expr = build2 (COMPOUND_EXPR, TREE_TYPE (cookie_expr),
3608 cookie, cookie_expr);
3611 else
3613 cookie_expr = NULL_TREE;
3614 data_addr = alloc_node;
3617 /* Now use a pointer to the type we've actually allocated. */
3619 /* But we want to operate on a non-const version to start with,
3620 since we'll be modifying the elements. */
3621 non_const_pointer_type = build_pointer_type
3622 (cp_build_qualified_type (type, cp_type_quals (type) & ~TYPE_QUAL_CONST));
3624 data_addr = fold_convert (non_const_pointer_type, data_addr);
3625 /* Any further uses of alloc_node will want this type, too. */
3626 alloc_node = fold_convert (non_const_pointer_type, alloc_node);
3628 /* Now initialize the allocated object. Note that we preevaluate the
3629 initialization expression, apart from the actual constructor call or
3630 assignment--we do this because we want to delay the allocation as long
3631 as possible in order to minimize the size of the exception region for
3632 placement delete. */
3633 if (is_initialized)
3635 bool explicit_value_init_p = false;
3637 if (*init != NULL && (*init)->is_empty ())
3639 *init = NULL;
3640 explicit_value_init_p = true;
3643 if (processing_template_decl)
3645 /* Avoid an ICE when converting to a base in build_simple_base_path.
3646 We'll throw this all away anyway, and build_new will create
3647 a NEW_EXPR. */
3648 tree t = fold_convert (build_pointer_type (elt_type), data_addr);
3649 /* build_value_init doesn't work in templates, and we don't need
3650 the initializer anyway since we're going to throw it away and
3651 rebuild it at instantiation time, so just build up a single
3652 constructor call to get any appropriate diagnostics. */
3653 init_expr = cp_build_fold_indirect_ref (t);
3654 if (type_build_ctor_call (elt_type))
3655 init_expr = build_special_member_call (init_expr,
3656 complete_ctor_identifier,
3657 init, elt_type,
3658 LOOKUP_NORMAL,
3659 complain);
3661 else if (array_p)
3663 tree vecinit = NULL_TREE;
3664 const size_t len = vec_safe_length (*init);
3665 if (len == 1 && DIRECT_LIST_INIT_P ((**init)[0]))
3667 vecinit = (**init)[0];
3668 if (CONSTRUCTOR_NELTS (vecinit) == 0)
3669 /* List-value-initialization, leave it alone. */;
3670 else
3672 tree arraytype, domain;
3673 if (TREE_CONSTANT (nelts))
3674 domain = compute_array_index_type (NULL_TREE, nelts,
3675 complain);
3676 else
3677 /* We'll check the length at runtime. */
3678 domain = NULL_TREE;
3679 arraytype = build_cplus_array_type (type, domain);
3680 /* If we have new char[4]{"foo"}, we have to reshape
3681 so that the STRING_CST isn't wrapped in { }. */
3682 vecinit = reshape_init (arraytype, vecinit, complain);
3683 /* The middle end doesn't cope with the location wrapper
3684 around a STRING_CST. */
3685 STRIP_ANY_LOCATION_WRAPPER (vecinit);
3686 vecinit = digest_init (arraytype, vecinit, complain);
3689 else if (*init)
3691 if (complain & tf_error)
3692 error ("parenthesized initializer in array new");
3693 return error_mark_node;
3695 init_expr
3696 = build_vec_init (data_addr,
3697 cp_build_binary_op (input_location,
3698 MINUS_EXPR, outer_nelts,
3699 integer_one_node,
3700 complain),
3701 vecinit,
3702 explicit_value_init_p,
3703 /*from_array=*/0,
3704 complain);
3706 else
3708 init_expr = cp_build_fold_indirect_ref (data_addr);
3710 if (type_build_ctor_call (type) && !explicit_value_init_p)
3712 init_expr = build_special_member_call (init_expr,
3713 complete_ctor_identifier,
3714 init, elt_type,
3715 LOOKUP_NORMAL,
3716 complain|tf_no_cleanup);
3718 else if (explicit_value_init_p)
3720 /* Something like `new int()'. NO_CLEANUP is needed so
3721 we don't try and build a (possibly ill-formed)
3722 destructor. */
3723 tree val = build_value_init (type, complain | tf_no_cleanup);
3724 if (val == error_mark_node)
3725 return error_mark_node;
3726 init_expr = cp_build_init_expr (init_expr, val);
3728 else
3730 tree ie;
3732 /* We are processing something like `new int (10)', which
3733 means allocate an int, and initialize it with 10.
3735 In C++20, also handle `new A(1, 2)'. */
3736 if (cxx_dialect >= cxx20
3737 && AGGREGATE_TYPE_P (type)
3738 && (*init)->length () > 1)
3740 ie = build_constructor_from_vec (init_list_type_node, *init);
3741 CONSTRUCTOR_IS_DIRECT_INIT (ie) = true;
3742 CONSTRUCTOR_IS_PAREN_INIT (ie) = true;
3743 ie = digest_init (type, ie, complain);
3745 else
3746 ie = build_x_compound_expr_from_vec (*init, "new initializer",
3747 complain);
3748 init_expr = cp_build_modify_expr (input_location, init_expr,
3749 INIT_EXPR, ie, complain);
3751 /* If the initializer uses C++14 aggregate NSDMI that refer to the
3752 object being initialized, replace them now and don't try to
3753 preevaluate. */
3754 bool had_placeholder = false;
3755 if (!processing_template_decl
3756 && TREE_CODE (init_expr) == INIT_EXPR)
3757 TREE_OPERAND (init_expr, 1)
3758 = replace_placeholders (TREE_OPERAND (init_expr, 1),
3759 TREE_OPERAND (init_expr, 0),
3760 &had_placeholder);
3763 if (init_expr == error_mark_node)
3764 return error_mark_node;
3766 else
3767 init_expr = NULL_TREE;
3769 /* If any part of the object initialization terminates by throwing an
3770 exception and a suitable deallocation function can be found, the
3771 deallocation function is called to free the memory in which the
3772 object was being constructed, after which the exception continues
3773 to propagate in the context of the new-expression. If no
3774 unambiguous matching deallocation function can be found,
3775 propagating the exception does not cause the object's memory to be
3776 freed. */
3777 if (flag_exceptions && (init_expr || member_delete_p))
3779 enum tree_code dcode = array_p ? VEC_DELETE_EXPR : DELETE_EXPR;
3780 tree cleanup;
3782 /* The Standard is unclear here, but the right thing to do
3783 is to use the same method for finding deallocation
3784 functions that we use for finding allocation functions. */
3785 cleanup = (build_op_delete_call
3786 (dcode,
3787 alloc_node,
3788 size,
3789 globally_qualified_p,
3790 placement_allocation_fn_p ? alloc_call : NULL_TREE,
3791 alloc_fn,
3792 complain));
3794 if (cleanup && init_expr && !processing_template_decl)
3795 /* Ack! First we allocate the memory. Then we set our sentry
3796 variable to true, and expand a cleanup that deletes the
3797 memory if sentry is true. Then we run the constructor, and
3798 finally clear the sentry.
3800 We need to do this because we allocate the space first, so
3801 if there are any temporaries with cleanups in the
3802 constructor args, we need this EH region to extend until
3803 end of full-expression to preserve nesting.
3805 We used to try to evaluate the args first to avoid this, but
3806 since C++17 [expr.new] says that "The invocation of the
3807 allocation function is sequenced before the evaluations of
3808 expressions in the new-initializer." */
3810 tree end, sentry, begin;
3812 begin = get_target_expr (boolean_true_node);
3813 CLEANUP_EH_ONLY (begin) = 1;
3815 sentry = TARGET_EXPR_SLOT (begin);
3817 /* CLEANUP is compiler-generated, so no diagnostics. */
3818 suppress_warning (cleanup);
3820 TARGET_EXPR_CLEANUP (begin)
3821 = build3 (COND_EXPR, void_type_node, sentry,
3822 cleanup, void_node);
3824 end = build2 (MODIFY_EXPR, TREE_TYPE (sentry),
3825 sentry, boolean_false_node);
3827 init_expr
3828 = build2 (COMPOUND_EXPR, void_type_node, begin,
3829 build2 (COMPOUND_EXPR, void_type_node, init_expr,
3830 end));
3831 /* Likewise, this is compiler-generated. */
3832 suppress_warning (init_expr);
3836 /* Now build up the return value in reverse order. */
3838 rval = data_addr;
3840 if (init_expr)
3841 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_expr, rval);
3842 if (cookie_expr)
3843 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), cookie_expr, rval);
3845 suppress_warning (rval, OPT_Wunused_value);
3847 if (rval == data_addr && TREE_CODE (alloc_expr) == TARGET_EXPR)
3848 /* If we don't have an initializer or a cookie, strip the TARGET_EXPR
3849 and return the call (which doesn't need to be adjusted). */
3850 rval = TARGET_EXPR_INITIAL (alloc_expr);
3851 else
3853 if (check_new)
3855 tree ifexp = cp_build_binary_op (input_location,
3856 NE_EXPR, alloc_node,
3857 nullptr_node,
3858 complain);
3859 rval = build_conditional_expr (input_location, ifexp, rval,
3860 alloc_node, complain);
3863 /* Perform the allocation before anything else, so that ALLOC_NODE
3864 has been initialized before we start using it. */
3865 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), alloc_expr, rval);
3868 /* A new-expression is never an lvalue. */
3869 gcc_assert (!obvalue_p (rval));
3871 return convert (pointer_type, rval);
3874 /* Generate a representation for a C++ "new" expression. *PLACEMENT
3875 is a vector of placement-new arguments (or NULL if none). If NELTS
3876 is NULL, TYPE is the type of the storage to be allocated. If NELTS
3877 is not NULL, then this is an array-new allocation; TYPE is the type
3878 of the elements in the array and NELTS is the number of elements in
3879 the array. *INIT, if non-NULL, is the initializer for the new
3880 object, or an empty vector to indicate an initializer of "()". If
3881 USE_GLOBAL_NEW is true, then the user explicitly wrote "::new"
3882 rather than just "new". This may change PLACEMENT and INIT. */
3884 tree
3885 build_new (location_t loc, vec<tree, va_gc> **placement, tree type,
3886 tree nelts, vec<tree, va_gc> **init, int use_global_new,
3887 tsubst_flags_t complain)
3889 tree rval;
3890 vec<tree, va_gc> *orig_placement = NULL;
3891 tree orig_nelts = NULL_TREE;
3892 vec<tree, va_gc> *orig_init = NULL;
3894 if (type == error_mark_node)
3895 return error_mark_node;
3897 if (nelts == NULL_TREE
3898 /* Don't do auto deduction where it might affect mangling. */
3899 && (!processing_template_decl || at_function_scope_p ()))
3901 tree auto_node = type_uses_auto (type);
3902 if (auto_node)
3904 tree d_init = NULL_TREE;
3905 const size_t len = vec_safe_length (*init);
3906 /* E.g. new auto(x) must have exactly one element, or
3907 a {} initializer will have one element. */
3908 if (len == 1)
3910 d_init = (**init)[0];
3911 d_init = resolve_nondeduced_context (d_init, complain);
3913 /* For the rest, e.g. new A(1, 2, 3), create a list. */
3914 else if (len > 1)
3916 unsigned int n;
3917 tree t;
3918 tree *pp = &d_init;
3919 FOR_EACH_VEC_ELT (**init, n, t)
3921 t = resolve_nondeduced_context (t, complain);
3922 *pp = build_tree_list (NULL_TREE, t);
3923 pp = &TREE_CHAIN (*pp);
3926 type = do_auto_deduction (type, d_init, auto_node, complain);
3930 if (processing_template_decl)
3932 if (dependent_type_p (type)
3933 || any_type_dependent_arguments_p (*placement)
3934 || (nelts && type_dependent_expression_p (nelts))
3935 || (nelts && *init)
3936 || any_type_dependent_arguments_p (*init))
3937 return build_raw_new_expr (loc, *placement, type, nelts, *init,
3938 use_global_new);
3940 orig_placement = make_tree_vector_copy (*placement);
3941 orig_nelts = nelts;
3942 if (*init)
3944 orig_init = make_tree_vector_copy (*init);
3945 /* Also copy any CONSTRUCTORs in *init, since reshape_init and
3946 digest_init clobber them in place. */
3947 for (unsigned i = 0; i < orig_init->length(); ++i)
3949 tree e = (**init)[i];
3950 if (TREE_CODE (e) == CONSTRUCTOR)
3951 (**init)[i] = copy_node (e);
3956 if (nelts)
3958 location_t nelts_loc = cp_expr_loc_or_loc (nelts, loc);
3959 if (!build_expr_type_conversion (WANT_INT | WANT_ENUM, nelts, false))
3961 if (complain & tf_error)
3962 permerror (nelts_loc,
3963 "size in array new must have integral type");
3964 else
3965 return error_mark_node;
3968 /* Try to determine the constant value only for the purposes
3969 of the diagnostic below but continue to use the original
3970 value and handle const folding later. */
3971 const_tree cst_nelts = fold_non_dependent_expr (nelts, complain);
3973 /* The expression in a noptr-new-declarator is erroneous if it's of
3974 non-class type and its value before converting to std::size_t is
3975 less than zero. ... If the expression is a constant expression,
3976 the program is ill-fomed. */
3977 if (TREE_CODE (cst_nelts) == INTEGER_CST
3978 && !valid_array_size_p (nelts_loc, cst_nelts, NULL_TREE,
3979 complain & tf_error))
3980 return error_mark_node;
3982 nelts = mark_rvalue_use (nelts);
3983 nelts = cp_save_expr (cp_convert (sizetype, nelts, complain));
3986 /* ``A reference cannot be created by the new operator. A reference
3987 is not an object (8.2.2, 8.4.3), so a pointer to it could not be
3988 returned by new.'' ARM 5.3.3 */
3989 if (TYPE_REF_P (type))
3991 if (complain & tf_error)
3992 error_at (loc, "new cannot be applied to a reference type");
3993 else
3994 return error_mark_node;
3995 type = TREE_TYPE (type);
3998 if (TREE_CODE (type) == FUNCTION_TYPE)
4000 if (complain & tf_error)
4001 error_at (loc, "new cannot be applied to a function type");
4002 return error_mark_node;
4005 /* P1009: Array size deduction in new-expressions. */
4006 const bool array_p = TREE_CODE (type) == ARRAY_TYPE;
4007 if (*init
4008 /* If the array didn't specify its bound, we have to deduce it. */
4009 && ((array_p && !TYPE_DOMAIN (type))
4010 /* For C++20 array with parenthesized-init, we have to process
4011 the parenthesized-list. But don't do it for (), which is
4012 value-initialization, and INIT should stay empty. */
4013 || (cxx_dialect >= cxx20
4014 && (array_p || nelts)
4015 && !(*init)->is_empty ())))
4017 /* This means we have 'new T[]()'. */
4018 if ((*init)->is_empty ())
4020 tree ctor = build_constructor (init_list_type_node, NULL);
4021 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
4022 vec_safe_push (*init, ctor);
4024 tree &elt = (**init)[0];
4025 /* The C++20 'new T[](e_0, ..., e_k)' case allowed by P0960. */
4026 if (!DIRECT_LIST_INIT_P (elt) && cxx_dialect >= cxx20)
4028 tree ctor = build_constructor_from_vec (init_list_type_node, *init);
4029 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
4030 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
4031 elt = ctor;
4032 /* We've squashed all the vector elements into the first one;
4033 truncate the rest. */
4034 (*init)->truncate (1);
4036 /* Otherwise we should have 'new T[]{e_0, ..., e_k}'. */
4037 if (array_p && !TYPE_DOMAIN (type))
4039 /* We need to reshape before deducing the bounds to handle code like
4041 struct S { int x, y; };
4042 new S[]{1, 2, 3, 4};
4044 which should deduce S[2]. But don't change ELT itself: we want to
4045 pass a list-initializer to build_new_1, even for STRING_CSTs. */
4046 tree e = elt;
4047 if (BRACE_ENCLOSED_INITIALIZER_P (e))
4048 e = reshape_init (type, e, complain);
4049 cp_complete_array_type (&type, e, /*do_default*/false);
4053 /* The type allocated must be complete. If the new-type-id was
4054 "T[N]" then we are just checking that "T" is complete here, but
4055 that is equivalent, since the value of "N" doesn't matter. */
4056 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
4057 return error_mark_node;
4059 rval = build_new_1 (placement, type, nelts, init, use_global_new, complain);
4060 if (rval == error_mark_node)
4061 return error_mark_node;
4063 if (processing_template_decl)
4065 tree ret = build_raw_new_expr (loc, orig_placement, type, orig_nelts,
4066 orig_init, use_global_new);
4067 release_tree_vector (orig_placement);
4068 release_tree_vector (orig_init);
4069 return ret;
4072 /* Wrap it in a NOP_EXPR so warn_if_unused_value doesn't complain. */
4073 rval = build1_loc (loc, NOP_EXPR, TREE_TYPE (rval), rval);
4074 suppress_warning (rval, OPT_Wunused_value);
4076 return rval;
4079 static tree
4080 build_vec_delete_1 (location_t loc, tree base, tree maxindex, tree type,
4081 special_function_kind auto_delete_vec,
4082 int use_global_delete, tsubst_flags_t complain,
4083 bool in_cleanup = false)
4085 tree virtual_size;
4086 tree ptype = build_pointer_type (type = complete_type (type));
4087 tree size_exp;
4089 /* Temporary variables used by the loop. */
4090 tree tbase, tbase_init;
4092 /* This is the body of the loop that implements the deletion of a
4093 single element, and moves temp variables to next elements. */
4094 tree body;
4096 /* This is the LOOP_EXPR that governs the deletion of the elements. */
4097 tree loop = 0;
4099 /* This is the thing that governs what to do after the loop has run. */
4100 tree deallocate_expr = 0;
4102 /* This is the BIND_EXPR which holds the outermost iterator of the
4103 loop. It is convenient to set this variable up and test it before
4104 executing any other code in the loop.
4105 This is also the containing expression returned by this function. */
4106 tree controller = NULL_TREE;
4107 tree tmp;
4109 /* We should only have 1-D arrays here. */
4110 gcc_assert (TREE_CODE (type) != ARRAY_TYPE);
4112 if (base == error_mark_node || maxindex == error_mark_node)
4113 return error_mark_node;
4115 if (!verify_type_context (loc, TCTX_DEALLOCATION, type,
4116 !(complain & tf_error)))
4117 return error_mark_node;
4119 if (!COMPLETE_TYPE_P (type))
4121 if (cxx_dialect > cxx23)
4123 if (complain & tf_error)
4125 int saved_errorcount = errorcount;
4126 if (permerror_opt (loc, OPT_Wdelete_incomplete,
4127 "operator %<delete []%> used on "
4128 "incomplete type"))
4130 cxx_incomplete_type_inform (type);
4131 if (errorcount != saved_errorcount)
4132 return error_mark_node;
4135 else
4136 return error_mark_node;
4138 else if (complain & tf_warning)
4140 auto_diagnostic_group d;
4141 if (warning_at (loc, OPT_Wdelete_incomplete,
4142 "possible problem detected in invocation of "
4143 "operator %<delete []%>"))
4145 cxx_incomplete_type_diagnostic (base, type, DK_WARNING);
4146 inform (loc, "neither the destructor nor the "
4147 "class-specific operator %<delete []%> will be called, "
4148 "even if they are declared when the class is defined");
4151 /* This size won't actually be used. */
4152 size_exp = size_one_node;
4153 goto no_destructor;
4156 size_exp = size_in_bytes (type);
4158 if (! MAYBE_CLASS_TYPE_P (type))
4159 goto no_destructor;
4160 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
4162 /* Make sure the destructor is callable. */
4163 if (type_build_dtor_call (type))
4165 tmp = build_delete (loc, ptype, base, sfk_complete_destructor,
4166 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR|LOOKUP_NONVIRTUAL,
4167 1, complain);
4168 if (tmp == error_mark_node)
4169 return error_mark_node;
4171 goto no_destructor;
4174 /* The below is short by the cookie size. */
4175 virtual_size = size_binop (MULT_EXPR, size_exp,
4176 fold_convert (sizetype, maxindex));
4178 tbase = create_temporary_var (ptype);
4179 DECL_INITIAL (tbase)
4180 = fold_build_pointer_plus_loc (loc, fold_convert (ptype, base),
4181 virtual_size);
4182 tbase_init = build_stmt (loc, DECL_EXPR, tbase);
4183 controller = build3 (BIND_EXPR, void_type_node, tbase, NULL_TREE, NULL_TREE);
4184 TREE_SIDE_EFFECTS (controller) = 1;
4185 BIND_EXPR_VEC_DTOR (controller) = true;
4187 body = build1 (EXIT_EXPR, void_type_node,
4188 build2 (EQ_EXPR, boolean_type_node, tbase,
4189 fold_convert (ptype, base)));
4190 tmp = fold_build1_loc (loc, NEGATE_EXPR, sizetype, size_exp);
4191 tmp = fold_build_pointer_plus (tbase, tmp);
4192 tmp = cp_build_modify_expr (loc, tbase, NOP_EXPR, tmp, complain);
4193 if (tmp == error_mark_node)
4194 return error_mark_node;
4195 body = build_compound_expr (loc, body, tmp);
4196 /* [expr.delete]/3: "In an array delete expression, if the dynamic type of
4197 the object to be deleted is not similar to its static type, the behavior
4198 is undefined." So we can set LOOKUP_NONVIRTUAL. */
4199 tmp = build_delete (loc, ptype, tbase, sfk_complete_destructor,
4200 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR|LOOKUP_NONVIRTUAL,
4201 1, complain);
4202 if (tmp == error_mark_node)
4203 return error_mark_node;
4204 body = build_compound_expr (loc, body, tmp);
4206 loop = build1 (LOOP_EXPR, void_type_node, body);
4208 /* If one destructor throws, keep trying to clean up the rest, unless we're
4209 already in a build_vec_init cleanup. */
4210 if (flag_exceptions && !in_cleanup && !processing_template_decl
4211 && !expr_noexcept_p (tmp, tf_none))
4213 loop = build2 (TRY_CATCH_EXPR, void_type_node, loop,
4214 unshare_expr (loop));
4215 /* Tell honor_protect_cleanup_actions to discard this on the
4216 exceptional path. */
4217 TRY_CATCH_IS_CLEANUP (loop) = true;
4220 loop = build_compound_expr (loc, tbase_init, loop);
4222 no_destructor:
4223 /* Delete the storage if appropriate. */
4224 if (auto_delete_vec == sfk_deleting_destructor)
4226 tree base_tbd;
4228 /* The below is short by the cookie size. */
4229 virtual_size = size_binop (MULT_EXPR, size_exp,
4230 fold_convert (sizetype, maxindex));
4232 if (! TYPE_VEC_NEW_USES_COOKIE (type))
4233 /* no header */
4234 base_tbd = base;
4235 else
4237 tree cookie_size;
4239 cookie_size = targetm.cxx.get_cookie_size (type);
4240 base_tbd = cp_build_binary_op (loc,
4241 MINUS_EXPR,
4242 cp_convert (string_type_node,
4243 base, complain),
4244 cookie_size,
4245 complain);
4246 if (base_tbd == error_mark_node)
4247 return error_mark_node;
4248 base_tbd = cp_convert (ptype, base_tbd, complain);
4249 /* True size with header. */
4250 virtual_size = size_binop (PLUS_EXPR, virtual_size, cookie_size);
4253 deallocate_expr = build_op_delete_call (VEC_DELETE_EXPR,
4254 base_tbd, virtual_size,
4255 use_global_delete & 1,
4256 /*placement=*/NULL_TREE,
4257 /*alloc_fn=*/NULL_TREE,
4258 complain);
4261 body = loop;
4262 if (deallocate_expr == error_mark_node)
4263 return error_mark_node;
4264 else if (!deallocate_expr)
4266 else if (!body)
4267 body = deallocate_expr;
4268 else
4269 /* The delete operator must be called, even if a destructor
4270 throws. */
4271 body = build2 (TRY_FINALLY_EXPR, void_type_node, body, deallocate_expr);
4273 if (!body)
4274 body = integer_zero_node;
4276 /* Outermost wrapper: If pointer is null, punt. */
4277 tree cond = build2_loc (loc, NE_EXPR, boolean_type_node, base,
4278 fold_convert (TREE_TYPE (base), nullptr_node));
4279 /* This is a compiler generated comparison, don't emit
4280 e.g. -Wnonnull-compare warning for it. */
4281 suppress_warning (cond, OPT_Wnonnull_compare);
4282 body = build3_loc (loc, COND_EXPR, void_type_node,
4283 cond, body, integer_zero_node);
4284 COND_EXPR_IS_VEC_DELETE (body) = true;
4285 body = build1 (NOP_EXPR, void_type_node, body);
4287 if (controller)
4289 TREE_OPERAND (controller, 1) = body;
4290 body = controller;
4293 if (TREE_CODE (base) == SAVE_EXPR)
4294 /* Pre-evaluate the SAVE_EXPR outside of the BIND_EXPR. */
4295 body = build2 (COMPOUND_EXPR, void_type_node, base, body);
4297 return convert_to_void (body, ICV_CAST, complain);
4300 /* Create an unnamed variable of the indicated TYPE. */
4302 tree
4303 create_temporary_var (tree type)
4305 tree decl;
4307 decl = build_decl (input_location,
4308 VAR_DECL, NULL_TREE, type);
4309 TREE_USED (decl) = 1;
4310 DECL_ARTIFICIAL (decl) = 1;
4311 DECL_IGNORED_P (decl) = 1;
4312 DECL_CONTEXT (decl) = current_function_decl;
4314 return decl;
4317 /* Create a new temporary variable of the indicated TYPE, initialized
4318 to INIT.
4320 It is not entered into current_binding_level, because that breaks
4321 things when it comes time to do final cleanups (which take place
4322 "outside" the binding contour of the function). */
4324 tree
4325 get_temp_regvar (tree type, tree init)
4327 tree decl;
4329 decl = create_temporary_var (type);
4330 add_decl_expr (decl);
4332 finish_expr_stmt (cp_build_modify_expr (input_location, decl, INIT_EXPR,
4333 init, tf_warning_or_error));
4335 return decl;
4338 /* Subroutine of build_vec_init. Returns true if assigning to an array of
4339 INNER_ELT_TYPE from INIT is trivial. */
4341 static bool
4342 vec_copy_assign_is_trivial (tree inner_elt_type, tree init)
4344 tree fromtype = inner_elt_type;
4345 if (lvalue_p (init))
4346 fromtype = cp_build_reference_type (fromtype, /*rval*/false);
4347 return is_trivially_xible (MODIFY_EXPR, inner_elt_type, fromtype);
4350 /* Subroutine of build_vec_init: Check that the array has at least N
4351 elements. Other parameters are local variables in build_vec_init. */
4353 void
4354 finish_length_check (tree atype, tree iterator, tree obase, unsigned n)
4356 tree nelts = build_int_cst (ptrdiff_type_node, n - 1);
4357 if (TREE_CODE (atype) != ARRAY_TYPE)
4359 if (flag_exceptions)
4361 tree c = fold_build2 (LT_EXPR, boolean_type_node, iterator,
4362 nelts);
4363 c = build3 (COND_EXPR, void_type_node, c,
4364 throw_bad_array_new_length (), void_node);
4365 finish_expr_stmt (c);
4367 /* Don't check an array new when -fno-exceptions. */
4369 else if (sanitize_flags_p (SANITIZE_BOUNDS)
4370 && current_function_decl != NULL_TREE)
4372 /* Make sure the last element of the initializer is in bounds. */
4373 finish_expr_stmt
4374 (ubsan_instrument_bounds
4375 (input_location, obase, &nelts, /*ignore_off_by_one*/false));
4379 /* walk_tree callback to collect temporaries in an expression. */
4381 tree
4382 find_temps_r (tree *tp, int *walk_subtrees, void *data)
4384 vec<tree*> &temps = *static_cast<auto_vec<tree*> *>(data);
4385 tree t = *tp;
4386 if (TREE_CODE (t) == TARGET_EXPR
4387 && !TARGET_EXPR_ELIDING_P (t))
4388 temps.safe_push (tp);
4389 else if (TYPE_P (t))
4390 *walk_subtrees = 0;
4392 return NULL_TREE;
4395 /* walk_tree callback to collect temporaries in an expression that
4396 are allocator arguments to standard library classes. */
4398 static tree
4399 find_allocator_temps_r (tree *tp, int *walk_subtrees, void *data)
4401 vec<tree*> &temps = *static_cast<auto_vec<tree*> *>(data);
4402 tree t = *tp;
4403 if (TYPE_P (t))
4405 *walk_subtrees = 0;
4406 return NULL_TREE;
4409 /* If this is a call to a constructor for a std:: class, look for
4410 a reference-to-allocator argument. */
4411 tree fn = cp_get_callee_fndecl_nofold (t);
4412 if (fn && DECL_CONSTRUCTOR_P (fn)
4413 && decl_in_std_namespace_p (TYPE_NAME (DECL_CONTEXT (fn))))
4415 int nargs = call_expr_nargs (t);
4416 for (int i = 1; i < nargs; ++i)
4418 tree arg = get_nth_callarg (t, i);
4419 tree atype = TREE_TYPE (arg);
4420 if (TREE_CODE (atype) == REFERENCE_TYPE
4421 && is_std_allocator (TREE_TYPE (atype)))
4423 STRIP_NOPS (arg);
4424 if (TREE_CODE (arg) == ADDR_EXPR)
4426 tree *ap = &TREE_OPERAND (arg, 0);
4427 if (TREE_CODE (*ap) == TARGET_EXPR)
4428 temps.safe_push (ap);
4434 return NULL_TREE;
4437 /* If INIT initializes a standard library class, and involves a temporary
4438 std::allocator<T>, use ALLOC_OBJ for all such temporaries.
4440 Note that this can clobber the input to build_vec_init; no unsharing is
4441 done. To make this safe we use the TARGET_EXPR in all places rather than
4442 pulling out the TARGET_EXPR_SLOT.
4444 Used by build_vec_init when initializing an array of e.g. strings to reuse
4445 the same temporary allocator for all of the strings. We can do this because
4446 std::allocator has no data and the standard library doesn't care about the
4447 address of allocator objects.
4449 ??? Add an attribute to allow users to assert the same property for other
4450 classes, i.e. one object of the type is interchangeable with any other? */
4452 static void
4453 combine_allocator_temps (tree &init, tree &alloc_obj)
4455 auto_vec<tree*> temps;
4456 cp_walk_tree_without_duplicates (&init, find_allocator_temps_r, &temps);
4457 for (tree *p : temps)
4459 if (!alloc_obj)
4460 alloc_obj = *p;
4461 else
4462 *p = alloc_obj;
4466 /* `build_vec_init' returns tree structure that performs
4467 initialization of a vector of aggregate types.
4469 BASE is a reference to the vector, of ARRAY_TYPE, or a pointer
4470 to the first element, of POINTER_TYPE.
4471 MAXINDEX is the maximum index of the array (one less than the
4472 number of elements). It is only used if BASE is a pointer or
4473 TYPE_DOMAIN (TREE_TYPE (BASE)) == NULL_TREE.
4475 INIT is the (possibly NULL) initializer.
4477 If EXPLICIT_VALUE_INIT_P is true, then INIT must be NULL. All
4478 elements in the array are value-initialized.
4480 FROM_ARRAY is 0 if we should init everything with INIT
4481 (i.e., every element initialized from INIT).
4482 FROM_ARRAY is 1 if we should index into INIT in parallel
4483 with initialization of DECL.
4484 FROM_ARRAY is 2 if we should index into INIT in parallel,
4485 but use assignment instead of initialization. */
4487 tree
4488 build_vec_init (tree base, tree maxindex, tree init,
4489 bool explicit_value_init_p,
4490 int from_array,
4491 tsubst_flags_t complain,
4492 vec<tree, va_gc>** cleanup_flags /* = nullptr */)
4494 tree rval;
4495 tree base2 = NULL_TREE;
4496 tree itype = NULL_TREE;
4497 tree iterator;
4498 /* The type of BASE. */
4499 tree atype = TREE_TYPE (base);
4500 /* The type of an element in the array. */
4501 tree type = TREE_TYPE (atype);
4502 /* The element type reached after removing all outer array
4503 types. */
4504 tree inner_elt_type;
4505 /* The type of a pointer to an element in the array. */
4506 tree ptype;
4507 tree stmt_expr;
4508 tree compound_stmt;
4509 int destroy_temps;
4510 HOST_WIDE_INT num_initialized_elts = 0;
4511 bool is_global;
4512 tree obase = base;
4513 bool xvalue = false;
4514 bool errors = false;
4515 location_t loc = (init ? cp_expr_loc_or_input_loc (init)
4516 : location_of (base));
4518 if (TREE_CODE (atype) == ARRAY_TYPE && TYPE_DOMAIN (atype))
4519 maxindex = array_type_nelts (atype);
4521 if (maxindex == NULL_TREE || maxindex == error_mark_node)
4522 return error_mark_node;
4524 maxindex = maybe_constant_value (maxindex);
4525 if (explicit_value_init_p)
4526 gcc_assert (!init);
4528 inner_elt_type = strip_array_types (type);
4530 /* Look through the TARGET_EXPR around a compound literal. */
4531 if (init && TREE_CODE (init) == TARGET_EXPR
4532 && TREE_CODE (TARGET_EXPR_INITIAL (init)) == CONSTRUCTOR
4533 && from_array != 2
4534 && (same_type_ignoring_top_level_qualifiers_p
4535 (TREE_TYPE (init), atype)))
4536 init = TARGET_EXPR_INITIAL (init);
4538 if (tree vi = get_vec_init_expr (init))
4539 init = VEC_INIT_EXPR_INIT (vi);
4541 bool direct_init = false;
4542 if (from_array && init && BRACE_ENCLOSED_INITIALIZER_P (init)
4543 && CONSTRUCTOR_NELTS (init) == 1)
4545 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
4546 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
4547 && TREE_CODE (elt) != VEC_INIT_EXPR)
4549 direct_init = DIRECT_LIST_INIT_P (init);
4550 init = elt;
4554 /* from_array doesn't apply to initialization from CONSTRUCTOR. */
4555 if (init && TREE_CODE (init) == CONSTRUCTOR)
4556 from_array = 0;
4558 /* If we have a braced-init-list or string constant, make sure that the array
4559 is big enough for all the initializers. */
4560 bool length_check = (init
4561 && (TREE_CODE (init) == STRING_CST
4562 || (TREE_CODE (init) == CONSTRUCTOR
4563 && CONSTRUCTOR_NELTS (init) > 0))
4564 && !TREE_CONSTANT (maxindex));
4566 if (init
4567 && TREE_CODE (atype) == ARRAY_TYPE
4568 && TREE_CONSTANT (maxindex)
4569 && !vla_type_p (type)
4570 && (from_array == 2
4571 ? vec_copy_assign_is_trivial (inner_elt_type, init)
4572 : !TYPE_NEEDS_CONSTRUCTING (type))
4573 && ((TREE_CODE (init) == CONSTRUCTOR
4574 && (BRACE_ENCLOSED_INITIALIZER_P (init)
4575 || (same_type_ignoring_top_level_qualifiers_p
4576 (atype, TREE_TYPE (init))))
4577 /* Don't do this if the CONSTRUCTOR might contain something
4578 that might throw and require us to clean up. */
4579 && (vec_safe_is_empty (CONSTRUCTOR_ELTS (init))
4580 || ! TYPE_HAS_NONTRIVIAL_DESTRUCTOR (inner_elt_type)))
4581 || from_array))
4583 /* Do non-default initialization of trivial arrays resulting from
4584 brace-enclosed initializers. In this case, digest_init and
4585 store_constructor will handle the semantics for us. */
4587 if (BRACE_ENCLOSED_INITIALIZER_P (init))
4588 init = digest_init (atype, init, complain);
4589 stmt_expr = cp_build_init_expr (base, init);
4590 return stmt_expr;
4593 maxindex = cp_convert (ptrdiff_type_node, maxindex, complain);
4594 maxindex = fold_simple (maxindex);
4596 if (TREE_CODE (atype) == ARRAY_TYPE)
4598 ptype = build_pointer_type (type);
4599 base = decay_conversion (base, complain);
4600 if (base == error_mark_node)
4601 return error_mark_node;
4602 base = cp_convert (ptype, base, complain);
4604 else
4605 ptype = atype;
4607 if (integer_all_onesp (maxindex))
4609 /* Shortcut zero element case to avoid unneeded constructor synthesis. */
4610 if (init && TREE_SIDE_EFFECTS (init))
4611 base = build2 (COMPOUND_EXPR, ptype, init, base);
4612 return base;
4615 /* The code we are generating looks like:
4617 T* t1 = (T*) base;
4618 T* rval = t1;
4619 ptrdiff_t iterator = maxindex;
4620 try {
4621 for (; iterator != -1; --iterator) {
4622 ... initialize *t1 ...
4623 ++t1;
4625 } catch (...) {
4626 ... destroy elements that were constructed ...
4628 rval;
4631 We can omit the try and catch blocks if we know that the
4632 initialization will never throw an exception, or if the array
4633 elements do not have destructors. We can omit the loop completely if
4634 the elements of the array do not have constructors.
4636 We actually wrap the entire body of the above in a STMT_EXPR, for
4637 tidiness.
4639 When copying from array to another, when the array elements have
4640 only trivial copy constructors, we should use __builtin_memcpy
4641 rather than generating a loop. That way, we could take advantage
4642 of whatever cleverness the back end has for dealing with copies
4643 of blocks of memory. */
4645 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
4646 destroy_temps = stmts_are_full_exprs_p ();
4647 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4648 rval = get_temp_regvar (ptype, base);
4649 base = get_temp_regvar (ptype, rval);
4650 tree iterator_targ = get_target_expr (maxindex);
4651 add_stmt (iterator_targ);
4652 iterator = TARGET_EXPR_SLOT (iterator_targ);
4654 /* If initializing one array from another, initialize element by
4655 element. We rely upon the below calls to do the argument
4656 checking. Evaluate the initializer before entering the try block. */
4657 if (from_array)
4659 if (lvalue_kind (init) & clk_rvalueref)
4660 xvalue = true;
4661 if (TREE_CODE (init) == TARGET_EXPR)
4663 /* Avoid error in decay_conversion. */
4664 base2 = decay_conversion (TARGET_EXPR_SLOT (init), complain);
4665 base2 = cp_build_compound_expr (init, base2, tf_none);
4667 else
4668 base2 = decay_conversion (init, complain);
4669 if (base2 == error_mark_node)
4670 return error_mark_node;
4671 itype = TREE_TYPE (base2);
4672 base2 = get_temp_regvar (itype, base2);
4673 itype = TREE_TYPE (itype);
4676 /* Protect the entire array initialization so that we can destroy
4677 the partially constructed array if an exception is thrown.
4678 But don't do this if we're assigning. */
4679 if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4680 && from_array != 2)
4682 tree e;
4683 tree m = cp_build_binary_op (input_location,
4684 MINUS_EXPR, maxindex, iterator,
4685 complain);
4687 /* Flatten multi-dimensional array since build_vec_delete only
4688 expects one-dimensional array. */
4689 if (TREE_CODE (type) == ARRAY_TYPE)
4690 m = cp_build_binary_op (input_location,
4691 MULT_EXPR, m,
4692 /* Avoid mixing signed and unsigned. */
4693 convert (TREE_TYPE (m),
4694 array_type_nelts_total (type)),
4695 complain);
4697 e = build_vec_delete_1 (input_location, rval, m,
4698 inner_elt_type, sfk_complete_destructor,
4699 /*use_global_delete=*/0, complain,
4700 /*in_cleanup*/true);
4701 if (e == error_mark_node)
4702 errors = true;
4703 TARGET_EXPR_CLEANUP (iterator_targ) = e;
4704 CLEANUP_EH_ONLY (iterator_targ) = true;
4706 /* Since we push this cleanup before doing any initialization, cleanups
4707 for any temporaries in the initialization are naturally within our
4708 cleanup region, so we don't want wrap_temporary_cleanups to do
4709 anything for arrays. But if the array is a subobject, we need to
4710 tell split_nonconstant_init or cp_genericize_target_expr how to turn
4711 off this cleanup in favor of the cleanup for the complete object.
4713 ??? For an array temporary such as an initializer_list backing array,
4714 it would avoid redundancy to leave this cleanup active, clear
4715 CLEANUP_EH_ONLY, and not build another cleanup for the temporary
4716 itself. But that breaks when gimplify_target_expr adds a clobber
4717 cleanup that runs before the build_vec_init cleanup. */
4718 if (cleanup_flags)
4719 vec_safe_push (*cleanup_flags, build_tree_list (iterator, maxindex));
4722 /* Should we try to create a constant initializer? */
4723 bool try_const = (TREE_CODE (atype) == ARRAY_TYPE
4724 && TREE_CONSTANT (maxindex)
4725 && (init ? TREE_CODE (init) == CONSTRUCTOR
4726 : (type_has_constexpr_default_constructor
4727 (inner_elt_type)
4728 /* Value-initialization of scalars is constexpr. */
4729 || (explicit_value_init_p
4730 && SCALAR_TYPE_P (inner_elt_type))))
4731 && (literal_type_p (inner_elt_type)
4732 || TYPE_HAS_CONSTEXPR_CTOR (inner_elt_type)));
4733 vec<constructor_elt, va_gc> *const_vec = NULL;
4734 bool saw_non_const = false;
4735 /* If we're initializing a static array, we want to do static
4736 initialization of any elements with constant initializers even if
4737 some are non-constant. */
4738 bool do_static_init = (DECL_P (obase) && TREE_STATIC (obase));
4740 bool empty_list = false;
4741 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
4742 && CONSTRUCTOR_NELTS (init) == 0)
4743 /* Skip over the handling of non-empty init lists. */
4744 empty_list = true;
4746 /* Maybe pull out constant value when from_array? */
4748 else if (init != NULL_TREE && TREE_CODE (init) == CONSTRUCTOR)
4750 /* Do non-default initialization of non-trivial arrays resulting from
4751 brace-enclosed initializers. */
4752 unsigned HOST_WIDE_INT idx;
4753 tree field, elt;
4754 /* If the constructor already has the array type, it's been through
4755 digest_init, so we shouldn't try to do anything more. */
4756 bool digested = same_type_p (atype, TREE_TYPE (init));
4757 from_array = 0;
4759 if (length_check)
4760 finish_length_check (atype, iterator, obase, CONSTRUCTOR_NELTS (init));
4762 if (try_const)
4763 vec_alloc (const_vec, CONSTRUCTOR_NELTS (init));
4765 tree alloc_obj = NULL_TREE;
4767 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
4769 tree baseref = build1 (INDIRECT_REF, type, base);
4770 tree one_init;
4772 num_initialized_elts++;
4774 /* We need to see sub-array TARGET_EXPR before cp_fold_r so we can
4775 handle cleanup flags properly. */
4776 gcc_checking_assert (!target_expr_needs_replace (elt));
4778 if (digested)
4779 one_init = cp_build_init_expr (baseref, elt);
4780 else if (tree vi = get_vec_init_expr (elt))
4781 one_init = expand_vec_init_expr (baseref, vi, complain,
4782 cleanup_flags);
4783 else if (MAYBE_CLASS_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE)
4784 one_init = build_aggr_init (baseref, elt, 0, complain);
4785 else
4786 one_init = cp_build_modify_expr (input_location, baseref,
4787 NOP_EXPR, elt, complain);
4788 if (one_init == error_mark_node)
4789 errors = true;
4790 if (try_const)
4792 if (!field)
4793 field = size_int (idx);
4794 tree e = maybe_constant_init (one_init);
4795 if (reduced_constant_expression_p (e))
4797 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4798 if (do_static_init)
4799 one_init = NULL_TREE;
4800 else
4801 one_init = cp_build_init_expr (baseref, e);
4803 else
4805 if (do_static_init)
4807 tree value = build_zero_init (TREE_TYPE (e), NULL_TREE,
4808 true);
4809 if (value)
4810 CONSTRUCTOR_APPEND_ELT (const_vec, field, value);
4812 saw_non_const = true;
4816 if (one_init)
4818 /* Only create one std::allocator temporary. */
4819 combine_allocator_temps (one_init, alloc_obj);
4820 finish_expr_stmt (one_init);
4823 one_init = cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4824 complain);
4825 if (one_init == error_mark_node)
4826 errors = true;
4827 else
4828 finish_expr_stmt (one_init);
4830 one_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4831 complain);
4832 if (one_init == error_mark_node)
4833 errors = true;
4834 else
4835 finish_expr_stmt (one_init);
4838 /* Any elements without explicit initializers get T{}. */
4839 empty_list = true;
4841 else if (init && TREE_CODE (init) == STRING_CST)
4843 /* Check that the array is at least as long as the string. */
4844 if (length_check)
4845 finish_length_check (atype, iterator, obase,
4846 TREE_STRING_LENGTH (init));
4847 tree length = build_int_cst (ptrdiff_type_node,
4848 TREE_STRING_LENGTH (init));
4850 /* Copy the string to the first part of the array. */
4851 tree alias_set = build_int_cst (build_pointer_type (type), 0);
4852 tree lhs = build2 (MEM_REF, TREE_TYPE (init), base, alias_set);
4853 tree stmt = build2 (MODIFY_EXPR, void_type_node, lhs, init);
4854 finish_expr_stmt (stmt);
4856 /* Adjust the counter and pointer. */
4857 stmt = cp_build_binary_op (loc, MINUS_EXPR, iterator, length, complain);
4858 stmt = build2 (MODIFY_EXPR, void_type_node, iterator, stmt);
4859 finish_expr_stmt (stmt);
4861 stmt = cp_build_binary_op (loc, PLUS_EXPR, base, length, complain);
4862 stmt = build2 (MODIFY_EXPR, void_type_node, base, stmt);
4863 finish_expr_stmt (stmt);
4865 /* And set the rest of the array to NUL. */
4866 from_array = 0;
4867 explicit_value_init_p = true;
4869 else if (from_array)
4871 if (init)
4872 /* OK, we set base2 above. */;
4873 else if (CLASS_TYPE_P (type)
4874 && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
4876 if (complain & tf_error)
4877 error ("initializer ends prematurely");
4878 errors = true;
4882 /* Now, default-initialize any remaining elements. We don't need to
4883 do that if a) the type does not need constructing, or b) we've
4884 already initialized all the elements.
4886 We do need to keep going if we're copying an array. */
4888 if (try_const && !init
4889 && (cxx_dialect < cxx20
4890 || !default_init_uninitialized_part (inner_elt_type)))
4891 /* With a constexpr default constructor, which we checked for when
4892 setting try_const above, default-initialization is equivalent to
4893 value-initialization, and build_value_init gives us something more
4894 friendly to maybe_constant_init. Except in C++20 and up a constexpr
4895 constructor need not initialize all the members. */
4896 explicit_value_init_p = true;
4897 if (from_array
4898 || ((type_build_ctor_call (type) || init || explicit_value_init_p)
4899 && ! (tree_fits_shwi_p (maxindex)
4900 && (num_initialized_elts
4901 == tree_to_shwi (maxindex) + 1))))
4903 /* If the ITERATOR is lesser or equal to -1, then we don't have to loop;
4904 we've already initialized all the elements. */
4905 tree for_stmt;
4906 tree elt_init;
4907 tree to;
4909 for_stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
4910 finish_init_stmt (for_stmt);
4911 finish_for_cond (build2 (GT_EXPR, boolean_type_node, iterator,
4912 build_int_cst (TREE_TYPE (iterator), -1)),
4913 for_stmt, false, 0, false);
4914 /* We used to pass this decrement to finish_for_expr; now we add it to
4915 elt_init below so it's part of the same full-expression as the
4916 initialization, and thus happens before any potentially throwing
4917 temporary cleanups. */
4918 tree decr = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4919 complain);
4922 to = build1 (INDIRECT_REF, type, base);
4924 /* If the initializer is {}, then all elements are initialized from T{}.
4925 But for non-classes, that's the same as value-initialization. */
4926 if (empty_list)
4928 if (cxx_dialect >= cxx11
4929 && (CLASS_TYPE_P (type)
4930 || TREE_CODE (type) == ARRAY_TYPE))
4932 init = build_constructor (init_list_type_node, NULL);
4934 else
4936 init = NULL_TREE;
4937 explicit_value_init_p = true;
4941 if (from_array)
4943 tree from;
4945 if (base2)
4947 from = build1 (INDIRECT_REF, itype, base2);
4948 if (xvalue)
4949 from = move (from);
4950 if (direct_init)
4951 from = build_tree_list (NULL_TREE, from);
4953 else
4954 from = NULL_TREE;
4956 if (TREE_CODE (type) == ARRAY_TYPE)
4957 elt_init = build_vec_init (to, NULL_TREE, from, /*val_init*/false,
4958 from_array, complain);
4959 else if (from_array == 2)
4960 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR,
4961 from, complain);
4962 else if (type_build_ctor_call (type))
4963 elt_init = build_aggr_init (to, from, 0, complain);
4964 else if (from)
4965 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR, from,
4966 complain);
4967 else
4968 gcc_unreachable ();
4970 else if (TREE_CODE (type) == ARRAY_TYPE)
4972 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init))
4974 if ((complain & tf_error))
4975 error_at (loc, "array must be initialized "
4976 "with a brace-enclosed initializer");
4977 elt_init = error_mark_node;
4979 else
4980 elt_init = build_vec_init (build1 (INDIRECT_REF, type, base),
4981 0, init,
4982 explicit_value_init_p,
4983 0, complain);
4985 else if (explicit_value_init_p)
4987 elt_init = build_value_init (type, complain);
4988 if (elt_init != error_mark_node)
4989 elt_init = cp_build_init_expr (to, elt_init);
4991 else
4993 gcc_assert (type_build_ctor_call (type) || init);
4994 if (CLASS_TYPE_P (type))
4995 elt_init = build_aggr_init (to, init, 0, complain);
4996 else
4998 if (TREE_CODE (init) == TREE_LIST)
4999 init = build_x_compound_expr_from_list (init, ELK_INIT,
5000 complain);
5001 elt_init = (init == error_mark_node
5002 ? error_mark_node
5003 : build2 (INIT_EXPR, type, to, init));
5007 if (elt_init == error_mark_node)
5008 errors = true;
5010 if (try_const)
5012 /* FIXME refs to earlier elts */
5013 tree e = maybe_constant_init (elt_init);
5014 if (reduced_constant_expression_p (e))
5016 if (initializer_zerop (e))
5017 /* Don't fill the CONSTRUCTOR with zeros. */
5018 e = NULL_TREE;
5019 if (do_static_init)
5020 elt_init = NULL_TREE;
5022 else
5024 saw_non_const = true;
5025 if (do_static_init)
5026 e = build_zero_init (TREE_TYPE (e), NULL_TREE, true);
5027 else
5028 e = NULL_TREE;
5031 if (e)
5033 HOST_WIDE_INT last = tree_to_shwi (maxindex);
5034 if (num_initialized_elts <= last)
5036 tree field = size_int (num_initialized_elts);
5037 if (num_initialized_elts != last)
5038 field = build2 (RANGE_EXPR, sizetype, field,
5039 size_int (last));
5040 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
5045 /* [class.temporary]: "There are three contexts in which temporaries are
5046 destroyed at a different point than the end of the full-
5047 expression. The first context is when a default constructor is called
5048 to initialize an element of an array with no corresponding
5049 initializer. The second context is when a copy constructor is called
5050 to copy an element of an array while the entire array is copied. In
5051 either case, if the constructor has one or more default arguments, the
5052 destruction of every temporary created in a default argument is
5053 sequenced before the construction of the next array element, if any."
5055 So, for this loop, statements are full-expressions. */
5056 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
5057 if (elt_init && !errors)
5058 elt_init = build2 (COMPOUND_EXPR, void_type_node, elt_init, decr);
5059 else
5060 elt_init = decr;
5061 finish_expr_stmt (elt_init);
5062 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
5064 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base, false,
5065 complain));
5066 if (base2)
5067 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base2, false,
5068 complain));
5070 finish_for_stmt (for_stmt);
5073 /* The value of the array initialization is the array itself, RVAL
5074 is a pointer to the first element. */
5075 finish_stmt_expr_expr (rval, stmt_expr);
5077 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
5079 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
5081 if (errors)
5082 return error_mark_node;
5084 if (try_const)
5086 if (!saw_non_const)
5088 tree const_init = build_constructor (atype, const_vec);
5089 return build2 (INIT_EXPR, atype, obase, const_init);
5091 else if (do_static_init && !vec_safe_is_empty (const_vec))
5092 DECL_INITIAL (obase) = build_constructor (atype, const_vec);
5093 else
5094 vec_free (const_vec);
5097 /* Now make the result have the correct type. */
5098 if (TREE_CODE (atype) == ARRAY_TYPE)
5100 atype = build_reference_type (atype);
5101 stmt_expr = build1 (NOP_EXPR, atype, stmt_expr);
5102 stmt_expr = convert_from_reference (stmt_expr);
5105 return stmt_expr;
5108 /* Call the DTOR_KIND destructor for EXP. FLAGS are as for
5109 build_delete. */
5111 static tree
5112 build_dtor_call (tree exp, special_function_kind dtor_kind, int flags,
5113 tsubst_flags_t complain)
5115 tree name;
5116 switch (dtor_kind)
5118 case sfk_complete_destructor:
5119 name = complete_dtor_identifier;
5120 break;
5122 case sfk_base_destructor:
5123 name = base_dtor_identifier;
5124 break;
5126 case sfk_deleting_destructor:
5127 name = deleting_dtor_identifier;
5128 break;
5130 default:
5131 gcc_unreachable ();
5134 return build_special_member_call (exp, name,
5135 /*args=*/NULL,
5136 /*binfo=*/TREE_TYPE (exp),
5137 flags,
5138 complain);
5141 /* Generate a call to a destructor. TYPE is the type to cast ADDR to.
5142 ADDR is an expression which yields the store to be destroyed.
5143 AUTO_DELETE is the name of the destructor to call, i.e., either
5144 sfk_complete_destructor, sfk_base_destructor, or
5145 sfk_deleting_destructor.
5147 FLAGS is the logical disjunction of zero or more LOOKUP_
5148 flags. See cp-tree.h for more info. */
5150 tree
5151 build_delete (location_t loc, tree otype, tree addr,
5152 special_function_kind auto_delete,
5153 int flags, int use_global_delete, tsubst_flags_t complain)
5155 tree expr;
5157 if (addr == error_mark_node)
5158 return error_mark_node;
5160 tree type = TYPE_MAIN_VARIANT (otype);
5162 /* Can happen when CURRENT_EXCEPTION_OBJECT gets its type
5163 set to `error_mark_node' before it gets properly cleaned up. */
5164 if (type == error_mark_node)
5165 return error_mark_node;
5167 if (TYPE_PTR_P (type))
5168 type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
5170 if (TREE_CODE (type) == ARRAY_TYPE)
5172 if (TYPE_DOMAIN (type) == NULL_TREE)
5174 if (complain & tf_error)
5175 error_at (loc, "unknown array size in delete");
5176 return error_mark_node;
5178 return build_vec_delete (loc, addr, array_type_nelts (type),
5179 auto_delete, use_global_delete, complain);
5182 bool deleting = (auto_delete == sfk_deleting_destructor);
5183 gcc_assert (deleting == !(flags & LOOKUP_DESTRUCTOR));
5185 if (TYPE_PTR_P (otype))
5187 addr = mark_rvalue_use (addr);
5189 /* We don't want to warn about delete of void*, only other
5190 incomplete types. Deleting other incomplete types
5191 invokes undefined behavior, but it is not ill-formed, so
5192 compile to something that would even do The Right Thing
5193 (TM) should the type have a trivial dtor and no delete
5194 operator. */
5195 if (!VOID_TYPE_P (type))
5197 complete_type (type);
5198 if (deleting
5199 && !verify_type_context (loc, TCTX_DEALLOCATION, type,
5200 !(complain & tf_error)))
5201 return error_mark_node;
5203 if (!COMPLETE_TYPE_P (type))
5205 if (cxx_dialect > cxx23)
5207 if (complain & tf_error)
5209 int saved_errorcount = errorcount;
5210 if (permerror_opt (loc, OPT_Wdelete_incomplete,
5211 "operator %<delete%> used on "
5212 "incomplete type"))
5214 cxx_incomplete_type_inform (type);
5215 if (errorcount != saved_errorcount)
5216 return error_mark_node;
5219 else
5220 return error_mark_node;
5222 else if (complain & tf_warning)
5224 auto_diagnostic_group d;
5225 if (warning_at (loc, OPT_Wdelete_incomplete,
5226 "possible problem detected in invocation of "
5227 "%<operator delete%>"))
5229 cxx_incomplete_type_diagnostic (addr, type, DK_WARNING);
5230 inform (loc,
5231 "neither the destructor nor the class-specific "
5232 "%<operator delete%> will be called, even if "
5233 "they are declared when the class is defined");
5237 else if (deleting && warn_delnonvdtor
5238 && MAYBE_CLASS_TYPE_P (type) && !CLASSTYPE_FINAL (type)
5239 && TYPE_POLYMORPHIC_P (type))
5241 tree dtor = CLASSTYPE_DESTRUCTOR (type);
5242 if (!dtor || !DECL_VINDEX (dtor))
5244 if (CLASSTYPE_PURE_VIRTUALS (type))
5245 warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5246 "deleting object of abstract class type %qT"
5247 " which has non-virtual destructor"
5248 " will cause undefined behavior", type);
5249 else
5250 warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5251 "deleting object of polymorphic class type %qT"
5252 " which has non-virtual destructor"
5253 " might cause undefined behavior", type);
5258 /* Throw away const and volatile on target type of addr. */
5259 addr = convert_force (build_pointer_type (type), addr, 0, complain);
5261 else
5263 /* Don't check PROTECT here; leave that decision to the
5264 destructor. If the destructor is accessible, call it,
5265 else report error. */
5266 addr = cp_build_addr_expr (addr, complain);
5267 if (addr == error_mark_node)
5268 return error_mark_node;
5270 addr = convert_force (build_pointer_type (type), addr, 0, complain);
5273 tree addr_expr = NULL_TREE;
5274 if (deleting)
5275 /* We will use ADDR multiple times so we must save it. */
5277 addr_expr = get_target_expr (addr);
5278 addr = TARGET_EXPR_SLOT (addr_expr);
5281 bool virtual_p = false;
5282 if (type_build_dtor_call (type))
5284 if (CLASSTYPE_LAZY_DESTRUCTOR (type))
5285 lazily_declare_fn (sfk_destructor, type);
5286 virtual_p = DECL_VIRTUAL_P (CLASSTYPE_DESTRUCTOR (type));
5289 tree head = NULL_TREE;
5290 tree do_delete = NULL_TREE;
5291 bool destroying_delete = false;
5293 if (!deleting)
5295 /* Leave do_delete null. */
5297 /* For `::delete x', we must not use the deleting destructor
5298 since then we would not be sure to get the global `operator
5299 delete'. */
5300 else if (use_global_delete)
5302 head = get_target_expr (build_headof (addr));
5303 /* Delete the object. */
5304 do_delete = build_op_delete_call (DELETE_EXPR,
5305 head,
5306 cxx_sizeof_nowarn (type),
5307 /*global_p=*/true,
5308 /*placement=*/NULL_TREE,
5309 /*alloc_fn=*/NULL_TREE,
5310 complain);
5311 /* Otherwise, treat this like a complete object destructor
5312 call. */
5313 auto_delete = sfk_complete_destructor;
5315 /* If the destructor is non-virtual, there is no deleting
5316 variant. Instead, we must explicitly call the appropriate
5317 `operator delete' here. */
5318 else if (!virtual_p)
5320 /* Build the call. */
5321 do_delete = build_op_delete_call (DELETE_EXPR,
5322 addr,
5323 cxx_sizeof_nowarn (type),
5324 /*global_p=*/false,
5325 /*placement=*/NULL_TREE,
5326 /*alloc_fn=*/NULL_TREE,
5327 complain);
5328 /* Call the complete object destructor. */
5329 auto_delete = sfk_complete_destructor;
5330 if (do_delete != error_mark_node)
5332 tree fn = get_callee_fndecl (do_delete);
5333 destroying_delete = destroying_delete_p (fn);
5336 else if (TYPE_GETS_REG_DELETE (type))
5338 /* Make sure we have access to the member op delete, even though
5339 we'll actually be calling it from the destructor. */
5340 build_op_delete_call (DELETE_EXPR, addr, cxx_sizeof_nowarn (type),
5341 /*global_p=*/false,
5342 /*placement=*/NULL_TREE,
5343 /*alloc_fn=*/NULL_TREE,
5344 complain);
5347 if (destroying_delete)
5348 /* The operator delete will call the destructor. */
5349 expr = addr;
5350 else if (type_build_dtor_call (type))
5351 expr = build_dtor_call (cp_build_fold_indirect_ref (addr),
5352 auto_delete, flags, complain);
5353 else
5354 expr = build_trivial_dtor_call (addr);
5355 if (expr == error_mark_node)
5356 return error_mark_node;
5358 if (!deleting)
5360 protected_set_expr_location (expr, loc);
5361 return expr;
5364 if (do_delete == error_mark_node)
5365 return error_mark_node;
5367 if (do_delete && !TREE_SIDE_EFFECTS (expr))
5368 expr = do_delete;
5369 else if (do_delete)
5370 /* The delete operator must be called, regardless of whether
5371 the destructor throws.
5373 [expr.delete]/7 The deallocation function is called
5374 regardless of whether the destructor for the object or some
5375 element of the array throws an exception. */
5376 expr = build2 (TRY_FINALLY_EXPR, void_type_node, expr, do_delete);
5378 /* We need to calculate this before the dtor changes the vptr. */
5379 if (head)
5380 expr = build2 (COMPOUND_EXPR, void_type_node, head, expr);
5382 /* Handle deleting a null pointer. */
5383 warning_sentinel s (warn_address);
5384 tree ifexp = cp_build_binary_op (loc, NE_EXPR, addr,
5385 nullptr_node, complain);
5386 ifexp = cp_fully_fold (ifexp);
5388 if (ifexp == error_mark_node)
5389 return error_mark_node;
5390 /* This is a compiler generated comparison, don't emit
5391 e.g. -Wnonnull-compare warning for it. */
5392 else if (TREE_CODE (ifexp) == NE_EXPR)
5393 suppress_warning (ifexp, OPT_Wnonnull_compare);
5395 if (!integer_nonzerop (ifexp))
5396 expr = build3 (COND_EXPR, void_type_node, ifexp, expr, void_node);
5398 if (addr_expr)
5399 expr = cp_build_compound_expr (addr_expr, expr, tf_none);
5401 protected_set_expr_location (expr, loc);
5402 return expr;
5405 /* At the beginning of a destructor, push cleanups that will call the
5406 destructors for our base classes and members.
5408 Called from begin_destructor_body. */
5410 void
5411 push_base_cleanups (void)
5413 tree binfo, base_binfo;
5414 int i;
5415 tree member;
5416 tree expr;
5417 vec<tree, va_gc> *vbases;
5419 /* Run destructors for all virtual baseclasses. */
5420 if (!ABSTRACT_CLASS_TYPE_P (current_class_type)
5421 && CLASSTYPE_VBASECLASSES (current_class_type))
5423 tree cond = (condition_conversion
5424 (build2 (BIT_AND_EXPR, integer_type_node,
5425 current_in_charge_parm,
5426 integer_two_node)));
5428 /* The CLASSTYPE_VBASECLASSES vector is in initialization
5429 order, which is also the right order for pushing cleanups. */
5430 for (vbases = CLASSTYPE_VBASECLASSES (current_class_type), i = 0;
5431 vec_safe_iterate (vbases, i, &base_binfo); i++)
5433 if (type_build_dtor_call (BINFO_TYPE (base_binfo)))
5435 expr = build_special_member_call (current_class_ref,
5436 base_dtor_identifier,
5437 NULL,
5438 base_binfo,
5439 (LOOKUP_NORMAL
5440 | LOOKUP_NONVIRTUAL),
5441 tf_warning_or_error);
5442 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5444 expr = build3 (COND_EXPR, void_type_node, cond,
5445 expr, void_node);
5446 finish_decl_cleanup (NULL_TREE, expr);
5452 /* Take care of the remaining baseclasses. */
5453 for (binfo = TYPE_BINFO (current_class_type), i = 0;
5454 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5456 if (BINFO_VIRTUAL_P (base_binfo)
5457 || !type_build_dtor_call (BINFO_TYPE (base_binfo)))
5458 continue;
5460 expr = build_special_member_call (current_class_ref,
5461 base_dtor_identifier,
5462 NULL, base_binfo,
5463 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
5464 tf_warning_or_error);
5465 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5466 finish_decl_cleanup (NULL_TREE, expr);
5469 /* Don't automatically destroy union members. */
5470 if (TREE_CODE (current_class_type) == UNION_TYPE)
5471 return;
5473 for (member = TYPE_FIELDS (current_class_type); member;
5474 member = DECL_CHAIN (member))
5476 tree this_type = TREE_TYPE (member);
5477 if (this_type == error_mark_node
5478 || TREE_CODE (member) != FIELD_DECL
5479 || DECL_ARTIFICIAL (member))
5480 continue;
5481 if (ANON_AGGR_TYPE_P (this_type))
5482 continue;
5483 if (type_build_dtor_call (this_type))
5485 tree this_member = (build_class_member_access_expr
5486 (current_class_ref, member,
5487 /*access_path=*/NULL_TREE,
5488 /*preserve_reference=*/false,
5489 tf_warning_or_error));
5490 expr = build_delete (input_location, this_type, this_member,
5491 sfk_complete_destructor,
5492 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR|LOOKUP_NORMAL,
5493 0, tf_warning_or_error);
5494 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (this_type))
5495 finish_decl_cleanup (NULL_TREE, expr);
5500 /* Build a C++ vector delete expression.
5501 MAXINDEX is the number of elements to be deleted.
5502 ELT_SIZE is the nominal size of each element in the vector.
5503 BASE is the expression that should yield the store to be deleted.
5504 This function expands (or synthesizes) these calls itself.
5505 AUTO_DELETE_VEC says whether the container (vector) should be deallocated.
5507 This also calls delete for virtual baseclasses of elements of the vector.
5509 Update: MAXINDEX is no longer needed. The size can be extracted from the
5510 start of the vector for pointers, and from the type for arrays. We still
5511 use MAXINDEX for arrays because it happens to already have one of the
5512 values we'd have to extract. (We could use MAXINDEX with pointers to
5513 confirm the size, and trap if the numbers differ; not clear that it'd
5514 be worth bothering.) */
5516 tree
5517 build_vec_delete (location_t loc, tree base, tree maxindex,
5518 special_function_kind auto_delete_vec,
5519 int use_global_delete, tsubst_flags_t complain)
5521 tree type;
5522 tree rval;
5523 tree base_init = NULL_TREE;
5525 type = TREE_TYPE (base);
5527 if (TYPE_PTR_P (type))
5529 /* Step back one from start of vector, and read dimension. */
5530 tree cookie_addr;
5531 tree size_ptr_type = build_pointer_type (sizetype);
5533 base = mark_rvalue_use (base);
5534 if (TREE_SIDE_EFFECTS (base))
5536 base_init = get_target_expr (base);
5537 base = TARGET_EXPR_SLOT (base_init);
5539 type = strip_array_types (TREE_TYPE (type));
5540 cookie_addr = fold_build1_loc (loc, NEGATE_EXPR,
5541 sizetype, TYPE_SIZE_UNIT (sizetype));
5542 cookie_addr = fold_build_pointer_plus (fold_convert (size_ptr_type, base),
5543 cookie_addr);
5544 maxindex = cp_build_fold_indirect_ref (cookie_addr);
5546 else if (TREE_CODE (type) == ARRAY_TYPE)
5548 /* Get the total number of things in the array, maxindex is a
5549 bad name. */
5550 maxindex = array_type_nelts_total (type);
5551 type = strip_array_types (type);
5552 base = decay_conversion (base, complain);
5553 if (base == error_mark_node)
5554 return error_mark_node;
5555 if (TREE_SIDE_EFFECTS (base))
5557 base_init = get_target_expr (base);
5558 base = TARGET_EXPR_SLOT (base_init);
5561 else
5563 if (base != error_mark_node && !(complain & tf_error))
5564 error_at (loc,
5565 "type to vector delete is neither pointer or array type");
5566 return error_mark_node;
5569 rval = build_vec_delete_1 (loc, base, maxindex, type, auto_delete_vec,
5570 use_global_delete, complain);
5571 if (base_init && rval != error_mark_node)
5572 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), base_init, rval);
5574 protected_set_expr_location (rval, loc);
5575 return rval;
5578 #include "gt-cp-init.h"