c++: fix throwing cleanup with label
[official-gcc.git] / gcc / cp / init.cc
blob6ccda365b048f7f4594b6c2ec7a0433b1ca4494e
1 /* Handle initialization things in -*- C++ -*-
2 Copyright (C) 1987-2023 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 init = DECL_INITIAL (DECL_TI_TEMPLATE (member));
583 location_t expr_loc
584 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (member));
585 if (TREE_CODE (init) == DEFERRED_PARSE)
586 /* Unparsed. */;
587 /* Check recursive instantiation. */
588 else if (DECL_INSTANTIATING_NSDMI_P (member))
590 if (complain & tf_error)
591 error_at (expr_loc, "recursive instantiation of default member "
592 "initializer for %qD", member);
593 init = error_mark_node;
595 else
597 cp_evaluated ev;
599 location_t sloc = input_location;
600 input_location = expr_loc;
602 DECL_INSTANTIATING_NSDMI_P (member) = 1;
604 bool pushed = false;
605 tree ctx = type_context_for_name_lookup (member);
607 bool push_to_top = maybe_push_to_top_level (member);
608 if (!currently_open_class (ctx))
610 push_nested_class (ctx);
611 push_deferring_access_checks (dk_no_deferred);
612 pushed = true;
615 inject_this_parameter (ctx, TYPE_UNQUALIFIED);
617 start_lambda_scope (member);
619 /* Do deferred instantiation of the NSDMI. */
620 init = tsubst_copy_and_build (init, DECL_TI_ARGS (member),
621 complain, member);
622 init = digest_nsdmi_init (member, init, complain);
624 finish_lambda_scope ();
626 DECL_INSTANTIATING_NSDMI_P (member) = 0;
628 if (init != error_mark_node)
629 DECL_INITIAL (member) = init;
631 if (pushed)
633 pop_deferring_access_checks ();
634 pop_nested_class ();
636 maybe_pop_from_top_level (push_to_top);
638 input_location = sloc;
642 return init;
645 /* Return the non-static data initializer for FIELD_DECL MEMBER. */
647 tree
648 get_nsdmi (tree member, bool in_ctor, tsubst_flags_t complain)
650 tree save_ccp = current_class_ptr;
651 tree save_ccr = current_class_ref;
653 tree init = maybe_instantiate_nsdmi_init (member, complain);
655 if (init && TREE_CODE (init) == DEFERRED_PARSE)
657 if (complain & tf_error)
659 error ("default member initializer for %qD required before the end "
660 "of its enclosing class", member);
661 inform (location_of (init), "defined here");
662 DECL_INITIAL (member) = error_mark_node;
664 init = error_mark_node;
667 if (in_ctor)
669 current_class_ptr = save_ccp;
670 current_class_ref = save_ccr;
672 else
674 /* Use a PLACEHOLDER_EXPR when we don't have a 'this' parameter to
675 refer to; constexpr evaluation knows what to do with it. */
676 current_class_ref = build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (member));
677 current_class_ptr = build_address (current_class_ref);
680 /* Clear processing_template_decl for sake of break_out_target_exprs;
681 INIT is always non-templated. */
682 processing_template_decl_sentinel ptds;
684 /* Strip redundant TARGET_EXPR so we don't need to remap it, and
685 so the aggregate init code below will see a CONSTRUCTOR. */
686 bool simple_target = (init && SIMPLE_TARGET_EXPR_P (init));
687 if (simple_target)
688 init = TARGET_EXPR_INITIAL (init);
689 init = break_out_target_exprs (init, /*loc*/true);
690 if (init && TREE_CODE (init) == TARGET_EXPR)
691 /* In a constructor, this expresses the full initialization, prevent
692 perform_member_init from calling another constructor (58162). */
693 TARGET_EXPR_DIRECT_INIT_P (init) = in_ctor;
694 if (simple_target && TREE_CODE (init) != CONSTRUCTOR)
695 /* Now put it back so C++17 copy elision works. */
696 init = get_target_expr (init);
698 set_target_expr_eliding (init);
700 current_class_ptr = save_ccp;
701 current_class_ref = save_ccr;
702 return init;
705 /* Diagnose the flexible array MEMBER if its INITializer is non-null
706 and return true if so. Otherwise return false. */
708 bool
709 maybe_reject_flexarray_init (tree member, tree init)
711 tree type = TREE_TYPE (member);
713 if (!init
714 || TREE_CODE (type) != ARRAY_TYPE
715 || TYPE_DOMAIN (type))
716 return false;
718 /* Point at the flexible array member declaration if it's initialized
719 in-class, and at the ctor if it's initialized in a ctor member
720 initializer list. */
721 location_t loc;
722 if (DECL_INITIAL (member) == init
723 || !current_function_decl
724 || DECL_DEFAULTED_FN (current_function_decl))
725 loc = DECL_SOURCE_LOCATION (member);
726 else
727 loc = DECL_SOURCE_LOCATION (current_function_decl);
729 error_at (loc, "initializer for flexible array member %q#D", member);
730 return true;
733 /* If INIT's value can come from a call to std::initializer_list<T>::begin,
734 return that function. Otherwise, NULL_TREE. */
736 static tree
737 find_list_begin (tree init)
739 STRIP_NOPS (init);
740 while (TREE_CODE (init) == COMPOUND_EXPR)
741 init = TREE_OPERAND (init, 1);
742 STRIP_NOPS (init);
743 if (TREE_CODE (init) == COND_EXPR)
745 tree left = TREE_OPERAND (init, 1);
746 if (!left)
747 left = TREE_OPERAND (init, 0);
748 left = find_list_begin (left);
749 if (left)
750 return left;
751 return find_list_begin (TREE_OPERAND (init, 2));
753 if (TREE_CODE (init) == CALL_EXPR)
754 if (tree fn = get_callee_fndecl (init))
755 if (id_equal (DECL_NAME (fn), "begin")
756 && is_std_init_list (DECL_CONTEXT (fn)))
757 return fn;
758 return NULL_TREE;
761 /* If INIT initializing MEMBER is copying the address of the underlying array
762 of an initializer_list, warn. */
764 static void
765 maybe_warn_list_ctor (tree member, tree init)
767 tree memtype = TREE_TYPE (member);
768 if (!init || !TYPE_PTR_P (memtype)
769 || !is_list_ctor (current_function_decl))
770 return;
772 tree parm = FUNCTION_FIRST_USER_PARMTYPE (current_function_decl);
773 parm = TREE_VALUE (parm);
774 tree initlist = non_reference (parm);
776 /* Do not warn if the parameter is an lvalue reference to non-const. */
777 if (TYPE_REF_P (parm) && !TYPE_REF_IS_RVALUE (parm)
778 && !CP_TYPE_CONST_P (initlist))
779 return;
781 tree targs = CLASSTYPE_TI_ARGS (initlist);
782 tree elttype = TREE_VEC_ELT (targs, 0);
784 if (!same_type_ignoring_top_level_qualifiers_p
785 (TREE_TYPE (memtype), elttype))
786 return;
788 tree begin = find_list_begin (init);
789 if (!begin)
790 return;
792 location_t loc = cp_expr_loc_or_input_loc (init);
793 warning_at (loc, OPT_Winit_list_lifetime,
794 "initializing %qD from %qE does not extend the lifetime "
795 "of the underlying array", member, begin);
798 /* Data structure for find_uninit_fields_r, below. */
800 struct find_uninit_data {
801 /* The set tracking the yet-uninitialized members. */
802 hash_set<tree> *uninitialized;
803 /* The data member we are currently initializing. It can be either
804 a type (initializing a base class/delegating constructors), or
805 a COMPONENT_REF. */
806 tree member;
809 /* walk_tree callback that warns about using uninitialized data in
810 a member-initializer-list. */
812 static tree
813 find_uninit_fields_r (tree *tp, int *walk_subtrees, void *data)
815 find_uninit_data *d = static_cast<find_uninit_data *>(data);
816 hash_set<tree> *uninitialized = d->uninitialized;
817 tree init = *tp;
818 const tree_code code = TREE_CODE (init);
820 /* No need to look into types or unevaluated operands. */
821 if (TYPE_P (init) || unevaluated_p (code))
823 *walk_subtrees = false;
824 return NULL_TREE;
827 switch (code)
829 /* We'd need data flow info to avoid false positives. */
830 case COND_EXPR:
831 case VEC_COND_EXPR:
832 case BIND_EXPR:
833 /* We might see a MODIFY_EXPR in cases like S() : a((b = 42)), c(b) { }
834 where the initializer for 'a' surreptitiously initializes 'b'. Let's
835 not bother with these complicated scenarios in the front end. */
836 case MODIFY_EXPR:
837 /* Don't attempt to handle statement-expressions, either. */
838 case STATEMENT_LIST:
839 uninitialized->empty ();
840 gcc_fallthrough ();
841 /* If we're just taking the address of an object, it doesn't matter
842 whether it's been initialized. */
843 case ADDR_EXPR:
844 *walk_subtrees = false;
845 return NULL_TREE;
846 default:
847 break;
850 /* We'd need data flow info to avoid false positives. */
851 if (truth_value_p (code))
852 goto give_up;
853 /* Attempt to handle a simple a{b}, but no more. */
854 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
856 if (CONSTRUCTOR_NELTS (init) == 1
857 && !BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (init, 0)->value))
858 init = CONSTRUCTOR_ELT (init, 0)->value;
859 else
860 goto give_up;
862 /* Warn about uninitialized 'this'. */
863 else if (code == CALL_EXPR)
865 tree fn = get_callee_fndecl (init);
866 if (fn && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
868 tree op = CALL_EXPR_ARG (init, 0);
869 if (TREE_CODE (op) == ADDR_EXPR)
870 op = TREE_OPERAND (op, 0);
871 temp_override<tree> ovr (d->member, DECL_ARGUMENTS (fn));
872 cp_walk_tree_without_duplicates (&op, find_uninit_fields_r, data);
874 /* Functions (whether static or nonstatic member) may have side effects
875 and initialize other members; it's not the front end's job to try to
876 figure it out. But don't give up for constructors: we still want to
877 warn when initializing base classes:
879 struct D : public B {
880 int x;
881 D() : B(x) {}
884 so carry on to detect that 'x' is used uninitialized. */
885 if (!fn || !DECL_CONSTRUCTOR_P (fn))
886 goto give_up;
889 /* If we find FIELD in the uninitialized set, we warn. */
890 if (code == COMPONENT_REF)
892 tree field = TREE_OPERAND (init, 1);
893 tree type = TYPE_P (d->member) ? d->member : TREE_TYPE (d->member);
895 /* We're initializing a reference member with itself. */
896 if (TYPE_REF_P (type) && cp_tree_equal (d->member, init))
897 warning_at (EXPR_LOCATION (init), OPT_Winit_self,
898 "%qD is initialized with itself", field);
899 else if (cp_tree_equal (TREE_OPERAND (init, 0), current_class_ref)
900 && uninitialized->contains (field))
902 if (TYPE_REF_P (TREE_TYPE (field)))
903 warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
904 "reference %qD is not yet bound to a value when used "
905 "here", field);
906 else if (!INDIRECT_TYPE_P (type) || is_this_parameter (d->member))
907 warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
908 "member %qD is used uninitialized", field);
909 *walk_subtrees = false;
913 return NULL_TREE;
915 give_up:
916 *walk_subtrees = false;
917 uninitialized->empty ();
918 return integer_zero_node;
921 /* Wrapper around find_uninit_fields_r above. */
923 static void
924 find_uninit_fields (tree *t, hash_set<tree> *uninitialized, tree member)
926 if (!uninitialized->is_empty ())
928 find_uninit_data data = { uninitialized, member };
929 cp_walk_tree_without_duplicates (t, find_uninit_fields_r, &data);
933 /* Initialize MEMBER, a FIELD_DECL, with INIT, a TREE_LIST of
934 arguments. If TREE_LIST is void_type_node, an empty initializer
935 list was given; if NULL_TREE no initializer was given. UNINITIALIZED
936 is the hash set that tracks uninitialized fields. */
938 static void
939 perform_member_init (tree member, tree init, hash_set<tree> &uninitialized)
941 tree decl;
942 tree type = TREE_TYPE (member);
944 /* Use the non-static data member initializer if there was no
945 mem-initializer for this field. */
946 if (init == NULL_TREE)
947 init = get_nsdmi (member, /*ctor*/true, tf_warning_or_error);
949 if (init == error_mark_node)
950 return;
952 /* Effective C++ rule 12 requires that all data members be
953 initialized. */
954 if (warn_ecpp && init == NULL_TREE && TREE_CODE (type) != ARRAY_TYPE)
955 warning_at (DECL_SOURCE_LOCATION (current_function_decl), OPT_Weffc__,
956 "%qD should be initialized in the member initialization list",
957 member);
959 /* Get an lvalue for the data member. */
960 decl = build_class_member_access_expr (current_class_ref, member,
961 /*access_path=*/NULL_TREE,
962 /*preserve_reference=*/true,
963 tf_warning_or_error);
964 if (decl == error_mark_node)
965 return;
967 if ((warn_init_self || warn_uninitialized)
968 && init
969 && TREE_CODE (init) == TREE_LIST
970 && TREE_CHAIN (init) == NULL_TREE)
972 tree val = TREE_VALUE (init);
973 /* Handle references. */
974 if (REFERENCE_REF_P (val))
975 val = TREE_OPERAND (val, 0);
976 if (TREE_CODE (val) == COMPONENT_REF && TREE_OPERAND (val, 1) == member
977 && TREE_OPERAND (val, 0) == current_class_ref)
978 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
979 OPT_Winit_self, "%qD is initialized with itself",
980 member);
981 else
982 find_uninit_fields (&val, &uninitialized, decl);
985 if (array_of_unknown_bound_p (type))
987 maybe_reject_flexarray_init (member, init);
988 return;
991 if (init && TREE_CODE (init) == TREE_LIST)
993 /* A(): a{e} */
994 if (DIRECT_LIST_INIT_P (TREE_VALUE (init)))
995 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
996 tf_warning_or_error);
997 /* We are trying to initialize an array from a ()-list. If we
998 should attempt to do so, conjure up a CONSTRUCTOR. */
999 else if (TREE_CODE (type) == ARRAY_TYPE
1000 /* P0960 is a C++20 feature. */
1001 && cxx_dialect >= cxx20)
1002 init = do_aggregate_paren_init (init, type);
1003 else if (!CLASS_TYPE_P (type))
1004 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
1005 tf_warning_or_error);
1006 /* If we're initializing a class from a ()-list, leave the TREE_LIST
1007 alone: we might call an appropriate constructor, or (in C++20)
1008 do aggregate-initialization. */
1011 /* Assume we are initializing the member. */
1012 bool member_initialized_p = true;
1014 if (init == void_type_node)
1016 /* mem() means value-initialization. */
1017 if (TREE_CODE (type) == ARRAY_TYPE)
1019 init = build_vec_init_expr (type, init, tf_warning_or_error);
1020 init = cp_build_init_expr (decl, init);
1021 finish_expr_stmt (init);
1023 else
1025 tree value = build_value_init (type, tf_warning_or_error);
1026 if (value == error_mark_node)
1027 return;
1028 init = cp_build_init_expr (decl, value);
1029 finish_expr_stmt (init);
1032 /* Deal with this here, as we will get confused if we try to call the
1033 assignment op for an anonymous union. This can happen in a
1034 synthesized copy constructor. */
1035 else if (ANON_AGGR_TYPE_P (type))
1037 if (init)
1039 init = cp_build_init_expr (decl, TREE_VALUE (init));
1040 finish_expr_stmt (init);
1043 else if (init
1044 && (TYPE_REF_P (type)
1045 || (TREE_CODE (init) == CONSTRUCTOR
1046 && (CP_AGGREGATE_TYPE_P (type)
1047 || is_std_init_list (type)))))
1049 /* With references and list-initialization, we need to deal with
1050 extending temporary lifetimes. 12.2p5: "A temporary bound to a
1051 reference member in a constructor’s ctor-initializer (12.6.2)
1052 persists until the constructor exits." */
1053 unsigned i; tree t;
1054 releasing_vec cleanups;
1055 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
1057 if (BRACE_ENCLOSED_INITIALIZER_P (init)
1058 && CP_AGGREGATE_TYPE_P (type))
1059 init = reshape_init (type, init, tf_warning_or_error);
1060 init = digest_init (type, init, tf_warning_or_error);
1062 if (init == error_mark_node)
1063 return;
1064 if (is_empty_field (member)
1065 && !TREE_SIDE_EFFECTS (init))
1066 /* Don't add trivial initialization of an empty base/field, as they
1067 might not be ordered the way the back-end expects. */
1068 return;
1069 /* A FIELD_DECL doesn't really have a suitable lifetime, but
1070 make_temporary_var_for_ref_to_temp will treat it as automatic and
1071 set_up_extended_ref_temp wants to use the decl in a warning. */
1072 init = extend_ref_init_temps (member, init, &cleanups);
1073 if (TREE_CODE (type) == ARRAY_TYPE
1074 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (type)))
1075 init = build_vec_init_expr (type, init, tf_warning_or_error);
1076 init = cp_build_init_expr (decl, init);
1077 finish_expr_stmt (init);
1078 FOR_EACH_VEC_ELT (*cleanups, i, t)
1079 push_cleanup (NULL_TREE, t, false);
1081 else if (type_build_ctor_call (type)
1082 || (init && CLASS_TYPE_P (strip_array_types (type))))
1084 if (TREE_CODE (type) == ARRAY_TYPE)
1086 if (init == NULL_TREE
1087 || same_type_ignoring_top_level_qualifiers_p (type,
1088 TREE_TYPE (init)))
1090 if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
1092 /* Initialize the array only if it's not a flexible
1093 array member (i.e., if it has an upper bound). */
1094 init = build_vec_init_expr (type, init, tf_warning_or_error);
1095 init = cp_build_init_expr (decl, init);
1096 finish_expr_stmt (init);
1099 else
1100 error ("invalid initializer for array member %q#D", member);
1102 else
1104 int flags = LOOKUP_NORMAL;
1105 if (DECL_DEFAULTED_FN (current_function_decl))
1106 flags |= LOOKUP_DEFAULTED;
1107 if (CP_TYPE_CONST_P (type)
1108 && init == NULL_TREE
1109 && default_init_uninitialized_part (type))
1111 /* TYPE_NEEDS_CONSTRUCTING can be set just because we have a
1112 vtable; still give this diagnostic. */
1113 auto_diagnostic_group d;
1114 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1115 "uninitialized const member in %q#T", type))
1116 inform (DECL_SOURCE_LOCATION (member),
1117 "%q#D should be initialized", member );
1119 finish_expr_stmt (build_aggr_init (decl, init, flags,
1120 tf_warning_or_error));
1123 else
1125 if (init == NULL_TREE)
1127 tree core_type;
1128 /* member traversal: note it leaves init NULL */
1129 if (TYPE_REF_P (type))
1131 auto_diagnostic_group d;
1132 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1133 "uninitialized reference member in %q#T", type))
1134 inform (DECL_SOURCE_LOCATION (member),
1135 "%q#D should be initialized", member);
1137 else if (CP_TYPE_CONST_P (type))
1139 auto_diagnostic_group d;
1140 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1141 "uninitialized const member in %q#T", type))
1142 inform (DECL_SOURCE_LOCATION (member),
1143 "%q#D should be initialized", member );
1146 core_type = strip_array_types (type);
1148 if (CLASS_TYPE_P (core_type)
1149 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
1150 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
1151 diagnose_uninitialized_cst_or_ref_member (core_type,
1152 /*using_new=*/false,
1153 /*complain=*/true);
1155 /* We left the member uninitialized. */
1156 member_initialized_p = false;
1159 maybe_warn_list_ctor (member, init);
1161 if (init)
1162 finish_expr_stmt (cp_build_modify_expr (input_location, decl,
1163 INIT_EXPR, init,
1164 tf_warning_or_error));
1167 if (member_initialized_p && warn_uninitialized)
1168 /* This member is now initialized, remove it from the uninitialized
1169 set. */
1170 uninitialized.remove (member);
1172 if (type_build_dtor_call (type))
1174 tree expr;
1176 expr = build_class_member_access_expr (current_class_ref, member,
1177 /*access_path=*/NULL_TREE,
1178 /*preserve_reference=*/false,
1179 tf_warning_or_error);
1180 expr = build_delete (input_location,
1181 type, expr, sfk_complete_destructor,
1182 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0,
1183 tf_warning_or_error);
1185 if (expr != error_mark_node
1186 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1187 finish_eh_cleanup (expr);
1191 /* Returns a TREE_LIST containing (as the TREE_PURPOSE of each node) all
1192 the FIELD_DECLs on the TYPE_FIELDS list for T, in reverse order. */
1194 static tree
1195 build_field_list (tree t, tree list, int *uses_unions_or_anon_p)
1197 tree fields;
1199 /* Note whether or not T is a union. */
1200 if (TREE_CODE (t) == UNION_TYPE)
1201 *uses_unions_or_anon_p = 1;
1203 for (fields = TYPE_FIELDS (t); fields; fields = DECL_CHAIN (fields))
1205 tree fieldtype;
1207 /* Skip CONST_DECLs for enumeration constants and so forth. */
1208 if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
1209 continue;
1211 fieldtype = TREE_TYPE (fields);
1213 /* For an anonymous struct or union, we must recursively
1214 consider the fields of the anonymous type. They can be
1215 directly initialized from the constructor. */
1216 if (ANON_AGGR_TYPE_P (fieldtype))
1218 /* Add this field itself. Synthesized copy constructors
1219 initialize the entire aggregate. */
1220 list = tree_cons (fields, NULL_TREE, list);
1221 /* And now add the fields in the anonymous aggregate. */
1222 list = build_field_list (fieldtype, list, uses_unions_or_anon_p);
1223 *uses_unions_or_anon_p = 1;
1225 /* Add this field. */
1226 else if (DECL_NAME (fields))
1227 list = tree_cons (fields, NULL_TREE, list);
1230 return list;
1233 /* Return the innermost aggregate scope for FIELD, whether that is
1234 the enclosing class or an anonymous aggregate within it. */
1236 static tree
1237 innermost_aggr_scope (tree field)
1239 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1240 return TREE_TYPE (field);
1241 else
1242 return DECL_CONTEXT (field);
1245 /* The MEM_INITS are a TREE_LIST. The TREE_PURPOSE of each list gives
1246 a FIELD_DECL or BINFO in T that needs initialization. The
1247 TREE_VALUE gives the initializer, or list of initializer arguments.
1249 Return a TREE_LIST containing all of the initializations required
1250 for T, in the order in which they should be performed. The output
1251 list has the same format as the input. */
1253 static tree
1254 sort_mem_initializers (tree t, tree mem_inits)
1256 tree init;
1257 tree base, binfo, base_binfo;
1258 tree sorted_inits;
1259 tree next_subobject;
1260 vec<tree, va_gc> *vbases;
1261 int i;
1262 int uses_unions_or_anon_p = 0;
1264 /* Build up a list of initializations. The TREE_PURPOSE of entry
1265 will be the subobject (a FIELD_DECL or BINFO) to initialize. The
1266 TREE_VALUE will be the constructor arguments, or NULL if no
1267 explicit initialization was provided. */
1268 sorted_inits = NULL_TREE;
1270 /* Process the virtual bases. */
1271 for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
1272 vec_safe_iterate (vbases, i, &base); i++)
1273 sorted_inits = tree_cons (base, NULL_TREE, sorted_inits);
1275 /* Process the direct bases. */
1276 for (binfo = TYPE_BINFO (t), i = 0;
1277 BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
1278 if (!BINFO_VIRTUAL_P (base_binfo))
1279 sorted_inits = tree_cons (base_binfo, NULL_TREE, sorted_inits);
1281 /* Process the non-static data members. */
1282 sorted_inits = build_field_list (t, sorted_inits, &uses_unions_or_anon_p);
1283 /* Reverse the entire list of initializations, so that they are in
1284 the order that they will actually be performed. */
1285 sorted_inits = nreverse (sorted_inits);
1287 /* If the user presented the initializers in an order different from
1288 that in which they will actually occur, we issue a warning. Keep
1289 track of the next subobject which can be explicitly initialized
1290 without issuing a warning. */
1291 next_subobject = sorted_inits;
1293 /* Go through the explicit initializers, filling in TREE_PURPOSE in
1294 the SORTED_INITS. */
1295 for (init = mem_inits; init; init = TREE_CHAIN (init))
1297 tree subobject;
1298 tree subobject_init;
1300 subobject = TREE_PURPOSE (init);
1302 /* If the explicit initializers are in sorted order, then
1303 SUBOBJECT will be NEXT_SUBOBJECT, or something following
1304 it. */
1305 for (subobject_init = next_subobject;
1306 subobject_init;
1307 subobject_init = TREE_CHAIN (subobject_init))
1308 if (TREE_PURPOSE (subobject_init) == subobject)
1309 break;
1311 /* Issue a warning if the explicit initializer order does not
1312 match that which will actually occur.
1313 ??? Are all these on the correct lines? */
1314 if (warn_reorder && !subobject_init)
1316 if (TREE_CODE (TREE_PURPOSE (next_subobject)) == FIELD_DECL)
1317 warning_at (DECL_SOURCE_LOCATION (TREE_PURPOSE (next_subobject)),
1318 OPT_Wreorder, "%qD will be initialized after",
1319 TREE_PURPOSE (next_subobject));
1320 else
1321 warning (OPT_Wreorder, "base %qT will be initialized after",
1322 TREE_PURPOSE (next_subobject));
1323 if (TREE_CODE (subobject) == FIELD_DECL)
1324 warning_at (DECL_SOURCE_LOCATION (subobject),
1325 OPT_Wreorder, " %q#D", subobject);
1326 else
1327 warning (OPT_Wreorder, " base %qT", subobject);
1328 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1329 OPT_Wreorder, " when initialized here");
1332 /* Look again, from the beginning of the list. */
1333 if (!subobject_init)
1335 subobject_init = sorted_inits;
1336 while (TREE_PURPOSE (subobject_init) != subobject)
1337 subobject_init = TREE_CHAIN (subobject_init);
1340 /* It is invalid to initialize the same subobject more than
1341 once. */
1342 if (TREE_VALUE (subobject_init))
1344 if (TREE_CODE (subobject) == FIELD_DECL)
1345 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1346 "multiple initializations given for %qD",
1347 subobject);
1348 else
1349 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1350 "multiple initializations given for base %qT",
1351 subobject);
1354 /* Record the initialization. */
1355 TREE_VALUE (subobject_init) = TREE_VALUE (init);
1356 /* Carry over the dummy TREE_TYPE node containing the source location. */
1357 TREE_TYPE (subobject_init) = TREE_TYPE (init);
1358 next_subobject = subobject_init;
1361 /* [class.base.init]
1363 If a ctor-initializer specifies more than one mem-initializer for
1364 multiple members of the same union (including members of
1365 anonymous unions), the ctor-initializer is ill-formed.
1367 Here we also splice out uninitialized union members. */
1368 if (uses_unions_or_anon_p)
1370 tree *last_p = NULL;
1371 tree *p;
1372 for (p = &sorted_inits; *p; )
1374 tree field;
1375 tree ctx;
1377 init = *p;
1379 field = TREE_PURPOSE (init);
1381 /* Skip base classes. */
1382 if (TREE_CODE (field) != FIELD_DECL)
1383 goto next;
1385 /* If this is an anonymous aggregate with no explicit initializer,
1386 splice it out. */
1387 if (!TREE_VALUE (init) && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1388 goto splice;
1390 /* See if this field is a member of a union, or a member of a
1391 structure contained in a union, etc. */
1392 ctx = innermost_aggr_scope (field);
1394 /* If this field is not a member of a union, skip it. */
1395 if (TREE_CODE (ctx) != UNION_TYPE
1396 && !ANON_AGGR_TYPE_P (ctx))
1397 goto next;
1399 /* If this union member has no explicit initializer and no NSDMI,
1400 splice it out. */
1401 if (TREE_VALUE (init) || DECL_INITIAL (field))
1402 /* OK. */;
1403 else
1404 goto splice;
1406 /* It's only an error if we have two initializers for the same
1407 union type. */
1408 if (!last_p)
1410 last_p = p;
1411 goto next;
1414 /* See if LAST_FIELD and the field initialized by INIT are
1415 members of the same union (or the union itself). If so, there's
1416 a problem, unless they're actually members of the same structure
1417 which is itself a member of a union. For example, given:
1419 union { struct { int i; int j; }; };
1421 initializing both `i' and `j' makes sense. */
1422 ctx = common_enclosing_class
1423 (innermost_aggr_scope (field),
1424 innermost_aggr_scope (TREE_PURPOSE (*last_p)));
1426 if (ctx && (TREE_CODE (ctx) == UNION_TYPE
1427 || ctx == TREE_TYPE (TREE_PURPOSE (*last_p))))
1429 /* A mem-initializer hides an NSDMI. */
1430 if (TREE_VALUE (init) && !TREE_VALUE (*last_p))
1431 *last_p = TREE_CHAIN (*last_p);
1432 else if (TREE_VALUE (*last_p) && !TREE_VALUE (init))
1433 goto splice;
1434 else
1436 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1437 "initializations for multiple members of %qT",
1438 ctx);
1439 goto splice;
1443 last_p = p;
1445 next:
1446 p = &TREE_CHAIN (*p);
1447 continue;
1448 splice:
1449 *p = TREE_CHAIN (*p);
1453 return sorted_inits;
1456 /* Callback for cp_walk_tree to mark all PARM_DECLs in a tree as read. */
1458 static tree
1459 mark_exp_read_r (tree *tp, int *, void *)
1461 tree t = *tp;
1462 if (TREE_CODE (t) == PARM_DECL)
1463 mark_exp_read (t);
1464 return NULL_TREE;
1467 /* Initialize all bases and members of CURRENT_CLASS_TYPE. MEM_INITS
1468 is a TREE_LIST giving the explicit mem-initializer-list for the
1469 constructor. The TREE_PURPOSE of each entry is a subobject (a
1470 FIELD_DECL or a BINFO) of the CURRENT_CLASS_TYPE. The TREE_VALUE
1471 is a TREE_LIST giving the arguments to the constructor or
1472 void_type_node for an empty list of arguments. */
1474 void
1475 emit_mem_initializers (tree mem_inits)
1477 int flags = LOOKUP_NORMAL;
1479 /* We will already have issued an error message about the fact that
1480 the type is incomplete. */
1481 if (!COMPLETE_TYPE_P (current_class_type))
1482 return;
1484 /* Keep a set holding fields that are not initialized. */
1485 hash_set<tree> uninitialized;
1487 /* Initially that is all of them. */
1488 if (warn_uninitialized)
1489 for (tree f = next_aggregate_field (TYPE_FIELDS (current_class_type));
1490 f != NULL_TREE;
1491 f = next_aggregate_field (DECL_CHAIN (f)))
1492 if (!DECL_ARTIFICIAL (f)
1493 && !is_really_empty_class (TREE_TYPE (f), /*ignore_vptr*/false))
1494 uninitialized.add (f);
1496 if (mem_inits
1497 && TYPE_P (TREE_PURPOSE (mem_inits))
1498 && same_type_p (TREE_PURPOSE (mem_inits), current_class_type))
1500 /* Delegating constructor. */
1501 gcc_assert (TREE_CHAIN (mem_inits) == NULL_TREE);
1502 tree ctor = perform_target_ctor (TREE_VALUE (mem_inits));
1503 find_uninit_fields (&ctor, &uninitialized, current_class_type);
1504 return;
1507 if (DECL_DEFAULTED_FN (current_function_decl)
1508 && ! DECL_INHERITED_CTOR (current_function_decl))
1509 flags |= LOOKUP_DEFAULTED;
1511 /* Sort the mem-initializers into the order in which the
1512 initializations should be performed. */
1513 mem_inits = sort_mem_initializers (current_class_type, mem_inits);
1515 in_base_initializer = 1;
1517 /* Initialize base classes. */
1518 for (; (mem_inits
1519 && TREE_CODE (TREE_PURPOSE (mem_inits)) != FIELD_DECL);
1520 mem_inits = TREE_CHAIN (mem_inits))
1522 tree subobject = TREE_PURPOSE (mem_inits);
1523 tree arguments = TREE_VALUE (mem_inits);
1525 /* We already have issued an error message. */
1526 if (arguments == error_mark_node)
1527 continue;
1529 /* Suppress access control when calling the inherited ctor. */
1530 bool inherited_base = (DECL_INHERITED_CTOR (current_function_decl)
1531 && flag_new_inheriting_ctors
1532 && arguments);
1533 if (inherited_base)
1534 push_deferring_access_checks (dk_deferred);
1536 if (arguments == NULL_TREE)
1538 /* If these initializations are taking place in a copy constructor,
1539 the base class should probably be explicitly initialized if there
1540 is a user-defined constructor in the base class (other than the
1541 default constructor, which will be called anyway). */
1542 if (extra_warnings
1543 && DECL_COPY_CONSTRUCTOR_P (current_function_decl)
1544 && type_has_user_nondefault_constructor (BINFO_TYPE (subobject)))
1545 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1546 OPT_Wextra, "base class %q#T should be explicitly "
1547 "initialized in the copy constructor",
1548 BINFO_TYPE (subobject));
1551 /* Initialize the base. */
1552 if (!BINFO_VIRTUAL_P (subobject))
1554 tree base_addr;
1556 base_addr = build_base_path (PLUS_EXPR, current_class_ptr,
1557 subobject, 1, tf_warning_or_error);
1558 expand_aggr_init_1 (subobject, NULL_TREE,
1559 cp_build_fold_indirect_ref (base_addr),
1560 arguments,
1561 flags,
1562 tf_warning_or_error);
1563 expand_cleanup_for_base (subobject, NULL_TREE);
1564 if (STATEMENT_LIST_TAIL (cur_stmt_list))
1565 find_uninit_fields (&STATEMENT_LIST_TAIL (cur_stmt_list)->stmt,
1566 &uninitialized, BINFO_TYPE (subobject));
1568 else if (!ABSTRACT_CLASS_TYPE_P (current_class_type))
1569 /* C++14 DR1658 Means we do not have to construct vbases of
1570 abstract classes. */
1571 construct_virtual_base (subobject, arguments);
1572 else
1573 /* When not constructing vbases of abstract classes, at least mark
1574 the arguments expressions as read to avoid
1575 -Wunused-but-set-parameter false positives. */
1576 cp_walk_tree (&arguments, mark_exp_read_r, NULL, NULL);
1578 if (inherited_base)
1579 pop_deferring_access_checks ();
1581 in_base_initializer = 0;
1583 /* Initialize the vptrs. */
1584 initialize_vtbl_ptrs (current_class_ptr);
1586 /* Initialize the data members. */
1587 while (mem_inits)
1589 /* If this initializer was explicitly provided, then the dummy TREE_TYPE
1590 node contains the source location. */
1591 iloc_sentinel ils (EXPR_LOCATION (TREE_TYPE (mem_inits)));
1593 perform_member_init (TREE_PURPOSE (mem_inits),
1594 TREE_VALUE (mem_inits),
1595 uninitialized);
1597 mem_inits = TREE_CHAIN (mem_inits);
1601 /* Returns the address of the vtable (i.e., the value that should be
1602 assigned to the vptr) for BINFO. */
1604 tree
1605 build_vtbl_address (tree binfo)
1607 tree binfo_for = binfo;
1608 tree vtbl;
1610 if (BINFO_VPTR_INDEX (binfo) && BINFO_VIRTUAL_P (binfo))
1611 /* If this is a virtual primary base, then the vtable we want to store
1612 is that for the base this is being used as the primary base of. We
1613 can't simply skip the initialization, because we may be expanding the
1614 inits of a subobject constructor where the virtual base layout
1615 can be different. */
1616 while (BINFO_PRIMARY_P (binfo_for))
1617 binfo_for = BINFO_INHERITANCE_CHAIN (binfo_for);
1619 /* Figure out what vtable BINFO's vtable is based on, and mark it as
1620 used. */
1621 vtbl = get_vtbl_decl_for_binfo (binfo_for);
1622 TREE_USED (vtbl) = true;
1624 /* Now compute the address to use when initializing the vptr. */
1625 vtbl = unshare_expr (BINFO_VTABLE (binfo_for));
1626 if (VAR_P (vtbl))
1627 vtbl = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (vtbl)), vtbl);
1629 return vtbl;
1632 /* This code sets up the virtual function tables appropriate for
1633 the pointer DECL. It is a one-ply initialization.
1635 BINFO is the exact type that DECL is supposed to be. In
1636 multiple inheritance, this might mean "C's A" if C : A, B. */
1638 static void
1639 expand_virtual_init (tree binfo, tree decl)
1641 tree vtbl, vtbl_ptr;
1642 tree vtt_index;
1644 /* Compute the initializer for vptr. */
1645 vtbl = build_vtbl_address (binfo);
1647 /* We may get this vptr from a VTT, if this is a subobject
1648 constructor or subobject destructor. */
1649 vtt_index = BINFO_VPTR_INDEX (binfo);
1650 if (vtt_index)
1652 tree vtbl2;
1653 tree vtt_parm;
1655 /* Compute the value to use, when there's a VTT. */
1656 vtt_parm = current_vtt_parm;
1657 vtbl2 = fold_build_pointer_plus (vtt_parm, vtt_index);
1658 vtbl2 = cp_build_fold_indirect_ref (vtbl2);
1659 vtbl2 = convert (TREE_TYPE (vtbl), vtbl2);
1661 /* The actual initializer is the VTT value only in the subobject
1662 constructor. In maybe_clone_body we'll substitute NULL for
1663 the vtt_parm in the case of the non-subobject constructor. */
1664 vtbl = build_if_in_charge (vtbl, vtbl2);
1667 /* Compute the location of the vtpr. */
1668 vtbl_ptr = build_vfield_ref (cp_build_fold_indirect_ref (decl),
1669 TREE_TYPE (binfo));
1670 gcc_assert (vtbl_ptr != error_mark_node);
1672 /* Assign the vtable to the vptr. */
1673 vtbl = convert_force (TREE_TYPE (vtbl_ptr), vtbl, 0, tf_warning_or_error);
1674 finish_expr_stmt (cp_build_modify_expr (input_location, vtbl_ptr, NOP_EXPR,
1675 vtbl, tf_warning_or_error));
1678 /* If an exception is thrown in a constructor, those base classes already
1679 constructed must be destroyed. This function creates the cleanup
1680 for BINFO, which has just been constructed. If FLAG is non-NULL,
1681 it is a DECL which is nonzero when this base needs to be
1682 destroyed. */
1684 static void
1685 expand_cleanup_for_base (tree binfo, tree flag)
1687 tree expr;
1689 if (!type_build_dtor_call (BINFO_TYPE (binfo)))
1690 return;
1692 /* Call the destructor. */
1693 expr = build_special_member_call (current_class_ref,
1694 base_dtor_identifier,
1695 NULL,
1696 binfo,
1697 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
1698 tf_warning_or_error);
1700 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (BINFO_TYPE (binfo)))
1701 return;
1703 if (flag)
1704 expr = fold_build3_loc (input_location,
1705 COND_EXPR, void_type_node,
1706 c_common_truthvalue_conversion (input_location, flag),
1707 expr, integer_zero_node);
1709 finish_eh_cleanup (expr);
1712 /* Construct the virtual base-class VBASE passing the ARGUMENTS to its
1713 constructor. */
1715 static void
1716 construct_virtual_base (tree vbase, tree arguments)
1718 tree inner_if_stmt;
1719 tree exp;
1720 tree flag;
1722 /* If there are virtual base classes with destructors, we need to
1723 emit cleanups to destroy them if an exception is thrown during
1724 the construction process. These exception regions (i.e., the
1725 period during which the cleanups must occur) begin from the time
1726 the construction is complete to the end of the function. If we
1727 create a conditional block in which to initialize the
1728 base-classes, then the cleanup region for the virtual base begins
1729 inside a block, and ends outside of that block. This situation
1730 confuses the sjlj exception-handling code. Therefore, we do not
1731 create a single conditional block, but one for each
1732 initialization. (That way the cleanup regions always begin
1733 in the outer block.) We trust the back end to figure out
1734 that the FLAG will not change across initializations, and
1735 avoid doing multiple tests. */
1736 flag = DECL_CHAIN (DECL_ARGUMENTS (current_function_decl));
1737 inner_if_stmt = begin_if_stmt ();
1738 finish_if_stmt_cond (flag, inner_if_stmt);
1740 /* Compute the location of the virtual base. If we're
1741 constructing virtual bases, then we must be the most derived
1742 class. Therefore, we don't have to look up the virtual base;
1743 we already know where it is. */
1744 exp = convert_to_base_statically (current_class_ref, vbase);
1746 expand_aggr_init_1 (vbase, current_class_ref, exp, arguments,
1747 0, tf_warning_or_error);
1748 finish_then_clause (inner_if_stmt);
1749 finish_if_stmt (inner_if_stmt);
1751 expand_cleanup_for_base (vbase, flag);
1754 /* Find the context in which this FIELD can be initialized. */
1756 static tree
1757 initializing_context (tree field)
1759 tree t = DECL_CONTEXT (field);
1761 /* Anonymous union members can be initialized in the first enclosing
1762 non-anonymous union context. */
1763 while (t && ANON_AGGR_TYPE_P (t))
1764 t = TYPE_CONTEXT (t);
1765 return t;
1768 /* Function to give error message if member initialization specification
1769 is erroneous. FIELD is the member we decided to initialize.
1770 TYPE is the type for which the initialization is being performed.
1771 FIELD must be a member of TYPE.
1773 MEMBER_NAME is the name of the member. */
1775 static int
1776 member_init_ok_or_else (tree field, tree type, tree member_name)
1778 if (field == error_mark_node)
1779 return 0;
1780 if (!field)
1782 error ("class %qT does not have any field named %qD", type,
1783 member_name);
1784 return 0;
1786 if (VAR_P (field))
1788 error ("%q#D is a static data member; it can only be "
1789 "initialized at its definition",
1790 field);
1791 return 0;
1793 if (TREE_CODE (field) != FIELD_DECL)
1795 error ("%q#D is not a non-static data member of %qT",
1796 field, type);
1797 return 0;
1799 if (initializing_context (field) != type)
1801 error ("class %qT does not have any field named %qD", type,
1802 member_name);
1803 return 0;
1806 return 1;
1809 /* NAME is a FIELD_DECL, an IDENTIFIER_NODE which names a field, or it
1810 is a _TYPE node or TYPE_DECL which names a base for that type.
1811 Check the validity of NAME, and return either the base _TYPE, base
1812 binfo, or the FIELD_DECL of the member. If NAME is invalid, return
1813 NULL_TREE and issue a diagnostic.
1815 An old style unnamed direct single base construction is permitted,
1816 where NAME is NULL. */
1818 tree
1819 expand_member_init (tree name)
1821 tree basetype;
1822 tree field;
1824 if (!current_class_ref)
1825 return NULL_TREE;
1827 if (!name)
1829 /* This is an obsolete unnamed base class initializer. The
1830 parser will already have warned about its use. */
1831 switch (BINFO_N_BASE_BINFOS (TYPE_BINFO (current_class_type)))
1833 case 0:
1834 error ("unnamed initializer for %qT, which has no base classes",
1835 current_class_type);
1836 return NULL_TREE;
1837 case 1:
1838 basetype = BINFO_TYPE
1839 (BINFO_BASE_BINFO (TYPE_BINFO (current_class_type), 0));
1840 break;
1841 default:
1842 error ("unnamed initializer for %qT, which uses multiple inheritance",
1843 current_class_type);
1844 return NULL_TREE;
1847 else if (TYPE_P (name))
1849 basetype = TYPE_MAIN_VARIANT (name);
1850 name = TYPE_NAME (name);
1852 else if (TREE_CODE (name) == TYPE_DECL)
1853 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (name));
1854 else
1855 basetype = NULL_TREE;
1857 if (basetype)
1859 tree class_binfo;
1860 tree direct_binfo;
1861 tree virtual_binfo;
1862 int i;
1864 if (current_template_parms
1865 || same_type_p (basetype, current_class_type))
1866 return basetype;
1868 class_binfo = TYPE_BINFO (current_class_type);
1869 direct_binfo = NULL_TREE;
1870 virtual_binfo = NULL_TREE;
1872 /* Look for a direct base. */
1873 for (i = 0; BINFO_BASE_ITERATE (class_binfo, i, direct_binfo); ++i)
1874 if (SAME_BINFO_TYPE_P (BINFO_TYPE (direct_binfo), basetype))
1875 break;
1877 /* Look for a virtual base -- unless the direct base is itself
1878 virtual. */
1879 if (!direct_binfo || !BINFO_VIRTUAL_P (direct_binfo))
1880 virtual_binfo = binfo_for_vbase (basetype, current_class_type);
1882 /* [class.base.init]
1884 If a mem-initializer-id is ambiguous because it designates
1885 both a direct non-virtual base class and an inherited virtual
1886 base class, the mem-initializer is ill-formed. */
1887 if (direct_binfo && virtual_binfo)
1889 error ("%qD is both a direct base and an indirect virtual base",
1890 basetype);
1891 return NULL_TREE;
1894 if (!direct_binfo && !virtual_binfo)
1896 if (CLASSTYPE_VBASECLASSES (current_class_type))
1897 error ("type %qT is not a direct or virtual base of %qT",
1898 basetype, current_class_type);
1899 else
1900 error ("type %qT is not a direct base of %qT",
1901 basetype, current_class_type);
1902 return NULL_TREE;
1905 return direct_binfo ? direct_binfo : virtual_binfo;
1907 else
1909 if (identifier_p (name))
1910 field = lookup_field (current_class_type, name, 1, false);
1911 else
1912 field = name;
1914 if (member_init_ok_or_else (field, current_class_type, name))
1915 return field;
1918 return NULL_TREE;
1921 /* This is like `expand_member_init', only it stores one aggregate
1922 value into another.
1924 INIT comes in two flavors: it is either a value which
1925 is to be stored in EXP, or it is a parameter list
1926 to go to a constructor, which will operate on EXP.
1927 If INIT is not a parameter list for a constructor, then set
1928 LOOKUP_ONLYCONVERTING.
1929 If FLAGS is LOOKUP_ONLYCONVERTING then it is the = init form of
1930 the initializer, if FLAGS is 0, then it is the (init) form.
1931 If `init' is a CONSTRUCTOR, then we emit a warning message,
1932 explaining that such initializations are invalid.
1934 If INIT resolves to a CALL_EXPR which happens to return
1935 something of the type we are looking for, then we know
1936 that we can safely use that call to perform the
1937 initialization.
1939 The virtual function table pointer cannot be set up here, because
1940 we do not really know its type.
1942 This never calls operator=().
1944 When initializing, nothing is CONST.
1946 A default copy constructor may have to be used to perform the
1947 initialization.
1949 A constructor or a conversion operator may have to be used to
1950 perform the initialization, but not both, as it would be ambiguous. */
1952 tree
1953 build_aggr_init (tree exp, tree init, int flags, tsubst_flags_t complain)
1955 tree stmt_expr;
1956 tree compound_stmt;
1957 int destroy_temps;
1958 tree type = TREE_TYPE (exp);
1959 int was_const = TREE_READONLY (exp);
1960 int was_volatile = TREE_THIS_VOLATILE (exp);
1961 int is_global;
1963 if (init == error_mark_node)
1964 return error_mark_node;
1966 location_t init_loc = (init
1967 ? cp_expr_loc_or_input_loc (init)
1968 : location_of (exp));
1970 TREE_READONLY (exp) = 0;
1971 TREE_THIS_VOLATILE (exp) = 0;
1973 if (TREE_CODE (type) == ARRAY_TYPE)
1975 tree itype = init ? TREE_TYPE (init) : NULL_TREE;
1976 int from_array = 0;
1978 if (VAR_P (exp) && DECL_DECOMPOSITION_P (exp))
1980 from_array = 1;
1981 init = mark_rvalue_use (init);
1982 if (init
1983 && DECL_P (tree_strip_any_location_wrapper (init))
1984 && !(flags & LOOKUP_ONLYCONVERTING))
1986 /* Wrap the initializer in a CONSTRUCTOR so that build_vec_init
1987 recognizes it as direct-initialization. */
1988 init = build_constructor_single (init_list_type_node,
1989 NULL_TREE, init);
1990 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
1993 else
1995 /* Must arrange to initialize each element of EXP
1996 from elements of INIT. */
1997 if (cv_qualified_p (type))
1998 TREE_TYPE (exp) = cv_unqualified (type);
1999 if (itype && cv_qualified_p (itype))
2000 TREE_TYPE (init) = cv_unqualified (itype);
2001 from_array = (itype && same_type_p (TREE_TYPE (init),
2002 TREE_TYPE (exp)));
2004 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init)
2005 && (!from_array
2006 || (TREE_CODE (init) != CONSTRUCTOR
2007 /* Can happen, eg, handling the compound-literals
2008 extension (ext/complit12.C). */
2009 && TREE_CODE (init) != TARGET_EXPR)))
2011 if (complain & tf_error)
2012 error_at (init_loc, "array must be initialized "
2013 "with a brace-enclosed initializer");
2014 return error_mark_node;
2018 stmt_expr = build_vec_init (exp, NULL_TREE, init,
2019 /*explicit_value_init_p=*/false,
2020 from_array,
2021 complain);
2022 TREE_READONLY (exp) = was_const;
2023 TREE_THIS_VOLATILE (exp) = was_volatile;
2024 TREE_TYPE (exp) = type;
2025 /* Restore the type of init unless it was used directly. */
2026 if (init && TREE_CODE (stmt_expr) != INIT_EXPR)
2027 TREE_TYPE (init) = itype;
2028 return stmt_expr;
2031 if (is_copy_initialization (init))
2032 flags |= LOOKUP_ONLYCONVERTING;
2034 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
2035 destroy_temps = stmts_are_full_exprs_p ();
2036 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
2037 bool ok = expand_aggr_init_1 (TYPE_BINFO (type), exp, exp,
2038 init, LOOKUP_NORMAL|flags, complain);
2039 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
2040 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
2041 TREE_READONLY (exp) = was_const;
2042 TREE_THIS_VOLATILE (exp) = was_volatile;
2043 if (!ok)
2044 return error_mark_node;
2046 if ((VAR_P (exp) || TREE_CODE (exp) == PARM_DECL)
2047 && TREE_SIDE_EFFECTS (stmt_expr)
2048 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (type)))
2049 /* Just know that we've seen something for this node. */
2050 TREE_USED (exp) = 1;
2052 return stmt_expr;
2055 static bool
2056 expand_default_init (tree binfo, tree true_exp, tree exp, tree init, int flags,
2057 tsubst_flags_t complain)
2059 tree type = TREE_TYPE (exp);
2061 /* It fails because there may not be a constructor which takes
2062 its own type as the first (or only parameter), but which does
2063 take other types via a conversion. So, if the thing initializing
2064 the expression is a unit element of type X, first try X(X&),
2065 followed by initialization by X. If neither of these work
2066 out, then look hard. */
2067 tree rval;
2068 vec<tree, va_gc> *parms;
2070 /* If we have direct-initialization from an initializer list, pull
2071 it out of the TREE_LIST so the code below can see it. */
2072 if (init && TREE_CODE (init) == TREE_LIST
2073 && DIRECT_LIST_INIT_P (TREE_VALUE (init)))
2075 gcc_checking_assert ((flags & LOOKUP_ONLYCONVERTING) == 0
2076 && TREE_CHAIN (init) == NULL_TREE);
2077 init = TREE_VALUE (init);
2078 /* Only call reshape_init if it has not been called earlier
2079 by the callers. */
2080 if (BRACE_ENCLOSED_INITIALIZER_P (init) && CP_AGGREGATE_TYPE_P (type))
2081 init = reshape_init (type, init, complain);
2084 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
2085 && CP_AGGREGATE_TYPE_P (type))
2086 /* A brace-enclosed initializer for an aggregate. In C++0x this can
2087 happen for direct-initialization, too. */
2088 init = digest_init (type, init, complain);
2090 if (init == error_mark_node)
2091 return false;
2093 /* A CONSTRUCTOR of the target's type is a previously digested
2094 initializer, whether that happened just above or in
2095 cp_parser_late_parsing_nsdmi.
2097 A TARGET_EXPR with TARGET_EXPR_DIRECT_INIT_P or TARGET_EXPR_LIST_INIT_P
2098 set represents the whole initialization, so we shouldn't build up
2099 another ctor call. */
2100 if (init
2101 && (TREE_CODE (init) == CONSTRUCTOR
2102 || (TREE_CODE (init) == TARGET_EXPR
2103 && (TARGET_EXPR_DIRECT_INIT_P (init)
2104 || TARGET_EXPR_LIST_INIT_P (init))))
2105 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
2107 /* Early initialization via a TARGET_EXPR only works for
2108 complete objects. */
2109 gcc_assert (TREE_CODE (init) == CONSTRUCTOR || true_exp == exp);
2111 init = cp_build_init_expr (exp, init);
2112 TREE_SIDE_EFFECTS (init) = 1;
2113 finish_expr_stmt (init);
2114 return true;
2117 if (init && TREE_CODE (init) != TREE_LIST
2118 && (flags & LOOKUP_ONLYCONVERTING)
2119 && !unsafe_return_slot_p (exp))
2121 /* Base subobjects should only get direct-initialization. */
2122 gcc_assert (true_exp == exp);
2124 if (flags & DIRECT_BIND)
2125 /* Do nothing. We hit this in two cases: Reference initialization,
2126 where we aren't initializing a real variable, so we don't want
2127 to run a new constructor; and catching an exception, where we
2128 have already built up the constructor call so we could wrap it
2129 in an exception region. */;
2130 else
2132 init = ocp_convert (type, init, CONV_IMPLICIT|CONV_FORCE_TEMP,
2133 flags, complain | tf_no_cleanup);
2134 if (init == error_mark_node)
2135 return false;
2138 /* We need to protect the initialization of a catch parm with a
2139 call to terminate(), which shows up as a MUST_NOT_THROW_EXPR
2140 around the TARGET_EXPR for the copy constructor. See
2141 initialize_handler_parm. */
2142 tree *p = &init;
2143 while (TREE_CODE (*p) == MUST_NOT_THROW_EXPR
2144 || TREE_CODE (*p) == CLEANUP_POINT_EXPR)
2146 /* Avoid voidify_wrapper_expr making a temporary. */
2147 TREE_TYPE (*p) = void_type_node;
2148 p = &TREE_OPERAND (*p, 0);
2150 *p = cp_build_init_expr (exp, *p);
2151 finish_expr_stmt (init);
2152 return true;
2155 if (init == NULL_TREE)
2156 parms = NULL;
2157 else if (TREE_CODE (init) == TREE_LIST && !TREE_TYPE (init))
2159 parms = make_tree_vector ();
2160 for (; init != NULL_TREE; init = TREE_CHAIN (init))
2161 vec_safe_push (parms, TREE_VALUE (init));
2163 else
2164 parms = make_tree_vector_single (init);
2166 if (exp == current_class_ref && current_function_decl
2167 && DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
2169 /* Delegating constructor. */
2170 tree complete;
2171 tree base;
2172 tree elt; unsigned i;
2174 /* Unshare the arguments for the second call. */
2175 releasing_vec parms2;
2176 FOR_EACH_VEC_SAFE_ELT (parms, i, elt)
2178 elt = break_out_target_exprs (elt);
2179 vec_safe_push (parms2, elt);
2181 complete = build_special_member_call (exp, complete_ctor_identifier,
2182 &parms2, binfo, flags,
2183 complain);
2184 complete = fold_build_cleanup_point_expr (void_type_node, complete);
2186 base = build_special_member_call (exp, base_ctor_identifier,
2187 &parms, binfo, flags,
2188 complain);
2189 base = fold_build_cleanup_point_expr (void_type_node, base);
2190 if (complete == error_mark_node || base == error_mark_node)
2191 return false;
2192 rval = build_if_in_charge (complete, base);
2194 else
2196 tree ctor_name = (true_exp == exp
2197 ? complete_ctor_identifier : base_ctor_identifier);
2199 rval = build_special_member_call (exp, ctor_name, &parms, binfo, flags,
2200 complain);
2201 if (rval == error_mark_node)
2202 return false;
2205 if (parms != NULL)
2206 release_tree_vector (parms);
2208 if (exp == true_exp && TREE_CODE (rval) == CALL_EXPR)
2210 tree fn = get_callee_fndecl (rval);
2211 if (fn && DECL_DECLARED_CONSTEXPR_P (fn))
2213 tree e = maybe_constant_init (rval, exp);
2214 if (TREE_CONSTANT (e))
2215 rval = cp_build_init_expr (exp, e);
2219 /* FIXME put back convert_to_void? */
2220 if (TREE_SIDE_EFFECTS (rval))
2221 finish_expr_stmt (rval);
2223 return true;
2226 /* This function is responsible for initializing EXP with INIT
2227 (if any). Returns true on success, false on failure.
2229 BINFO is the binfo of the type for who we are performing the
2230 initialization. For example, if W is a virtual base class of A and B,
2231 and C : A, B.
2232 If we are initializing B, then W must contain B's W vtable, whereas
2233 were we initializing C, W must contain C's W vtable.
2235 TRUE_EXP is nonzero if it is the true expression being initialized.
2236 In this case, it may be EXP, or may just contain EXP. The reason we
2237 need this is because if EXP is a base element of TRUE_EXP, we
2238 don't necessarily know by looking at EXP where its virtual
2239 baseclass fields should really be pointing. But we do know
2240 from TRUE_EXP. In constructors, we don't know anything about
2241 the value being initialized.
2243 FLAGS is just passed to `build_new_method_call'. See that function
2244 for its description. */
2246 static bool
2247 expand_aggr_init_1 (tree binfo, tree true_exp, tree exp, tree init, int flags,
2248 tsubst_flags_t complain)
2250 tree type = TREE_TYPE (exp);
2252 gcc_assert (init != error_mark_node && type != error_mark_node);
2253 gcc_assert (building_stmt_list_p ());
2255 /* Use a function returning the desired type to initialize EXP for us.
2256 If the function is a constructor, and its first argument is
2257 NULL_TREE, know that it was meant for us--just slide exp on
2258 in and expand the constructor. Constructors now come
2259 as TARGET_EXPRs. */
2261 if (init && VAR_P (exp)
2262 && COMPOUND_LITERAL_P (init))
2264 vec<tree, va_gc> *cleanups = NULL;
2265 /* If store_init_value returns NULL_TREE, the INIT has been
2266 recorded as the DECL_INITIAL for EXP. That means there's
2267 nothing more we have to do. */
2268 init = store_init_value (exp, init, &cleanups, flags);
2269 if (init)
2270 finish_expr_stmt (init);
2271 gcc_assert (!cleanups);
2272 return true;
2275 /* List-initialization from {} becomes value-initialization for non-aggregate
2276 classes with default constructors. Handle this here when we're
2277 initializing a base, so protected access works. */
2278 if (exp != true_exp && init && TREE_CODE (init) == TREE_LIST)
2280 tree elt = TREE_VALUE (init);
2281 if (DIRECT_LIST_INIT_P (elt)
2282 && CONSTRUCTOR_ELTS (elt) == 0
2283 && CLASSTYPE_NON_AGGREGATE (type)
2284 && TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
2285 init = void_type_node;
2288 /* If an explicit -- but empty -- initializer list was present,
2289 that's value-initialization. */
2290 if (init == void_type_node)
2292 /* If the type has data but no user-provided default ctor, we need to zero
2293 out the object. */
2294 if (type_has_non_user_provided_default_constructor (type)
2295 && !is_really_empty_class (type, /*ignore_vptr*/true))
2297 tree field_size = NULL_TREE;
2298 if (exp != true_exp && CLASSTYPE_AS_BASE (type) != type)
2299 /* Don't clobber already initialized virtual bases. */
2300 field_size = TYPE_SIZE (CLASSTYPE_AS_BASE (type));
2301 init = build_zero_init_1 (type, NULL_TREE, /*static_storage_p=*/false,
2302 field_size);
2303 init = cp_build_init_expr (exp, init);
2304 finish_expr_stmt (init);
2307 /* If we don't need to mess with the constructor at all,
2308 then we're done. */
2309 if (! type_build_ctor_call (type))
2310 return true;
2312 /* Otherwise fall through and call the constructor. */
2313 init = NULL_TREE;
2316 /* We know that expand_default_init can handle everything we want
2317 at this point. */
2318 return expand_default_init (binfo, true_exp, exp, init, flags, complain);
2321 /* Report an error if TYPE is not a user-defined, class type. If
2322 OR_ELSE is nonzero, give an error message. */
2325 is_class_type (tree type, int or_else)
2327 if (type == error_mark_node)
2328 return 0;
2330 if (! CLASS_TYPE_P (type))
2332 if (or_else)
2333 error ("%qT is not a class type", type);
2334 return 0;
2336 return 1;
2339 /* Returns true iff the initializer INIT represents copy-initialization
2340 (and therefore we must set LOOKUP_ONLYCONVERTING when processing it). */
2342 bool
2343 is_copy_initialization (tree init)
2345 return (init && init != void_type_node
2346 && TREE_CODE (init) != TREE_LIST
2347 && !(TREE_CODE (init) == TARGET_EXPR
2348 && TARGET_EXPR_DIRECT_INIT_P (init))
2349 && !DIRECT_LIST_INIT_P (init));
2352 /* Build a reference to a member of an aggregate. This is not a C++
2353 `&', but really something which can have its address taken, and
2354 then act as a pointer to member, for example TYPE :: FIELD can have
2355 its address taken by saying & TYPE :: FIELD. ADDRESS_P is true if
2356 this expression is the operand of "&".
2358 @@ Prints out lousy diagnostics for operator <typename>
2359 @@ fields.
2361 @@ This function should be rewritten and placed in search.cc. */
2363 tree
2364 build_offset_ref (tree type, tree member, bool address_p,
2365 tsubst_flags_t complain)
2367 tree decl;
2368 tree basebinfo = NULL_TREE;
2370 /* class templates can come in as TEMPLATE_DECLs here. */
2371 if (TREE_CODE (member) == TEMPLATE_DECL)
2372 return member;
2374 if (dependent_scope_p (type) || type_dependent_expression_p (member))
2375 return build_qualified_name (NULL_TREE, type, member,
2376 /*template_p=*/false);
2378 gcc_assert (TYPE_P (type));
2379 if (! is_class_type (type, 1))
2380 return error_mark_node;
2382 gcc_assert (DECL_P (member) || BASELINK_P (member));
2383 /* Callers should call mark_used before this point, except for functions. */
2384 gcc_assert (!DECL_P (member) || TREE_USED (member)
2385 || TREE_CODE (member) == FUNCTION_DECL);
2387 type = TYPE_MAIN_VARIANT (type);
2388 if (!COMPLETE_OR_OPEN_TYPE_P (complete_type (type)))
2390 if (complain & tf_error)
2391 error ("incomplete type %qT does not have member %qD", type, member);
2392 return error_mark_node;
2395 /* Entities other than non-static members need no further
2396 processing. */
2397 if (TREE_CODE (member) == TYPE_DECL)
2398 return member;
2399 if (VAR_P (member) || TREE_CODE (member) == CONST_DECL)
2400 return convert_from_reference (member);
2402 if (TREE_CODE (member) == FIELD_DECL && DECL_C_BIT_FIELD (member))
2404 if (complain & tf_error)
2405 error ("invalid pointer to bit-field %qD", member);
2406 return error_mark_node;
2409 /* Set up BASEBINFO for member lookup. */
2410 decl = maybe_dummy_object (type, &basebinfo);
2412 /* A lot of this logic is now handled in lookup_member. */
2413 if (BASELINK_P (member))
2415 /* Go from the TREE_BASELINK to the member function info. */
2416 tree t = BASELINK_FUNCTIONS (member);
2418 if (TREE_CODE (t) != TEMPLATE_ID_EXPR && !really_overloaded_fn (t))
2420 /* Get rid of a potential OVERLOAD around it. */
2421 t = OVL_FIRST (t);
2423 /* Unique functions are handled easily. */
2425 /* For non-static member of base class, we need a special rule
2426 for access checking [class.protected]:
2428 If the access is to form a pointer to member, the
2429 nested-name-specifier shall name the derived class
2430 (or any class derived from that class). */
2431 bool ok;
2432 if (address_p && DECL_P (t)
2433 && DECL_NONSTATIC_MEMBER_P (t))
2434 ok = perform_or_defer_access_check (TYPE_BINFO (type), t, t,
2435 complain);
2436 else
2437 ok = perform_or_defer_access_check (basebinfo, t, t,
2438 complain);
2439 if (!ok)
2440 return error_mark_node;
2441 if (DECL_STATIC_FUNCTION_P (t))
2442 return member;
2443 member = t;
2445 else
2446 TREE_TYPE (member) = unknown_type_node;
2448 else if (address_p && TREE_CODE (member) == FIELD_DECL)
2450 /* We need additional test besides the one in
2451 check_accessibility_of_qualified_id in case it is
2452 a pointer to non-static member. */
2453 if (!perform_or_defer_access_check (TYPE_BINFO (type), member, member,
2454 complain))
2455 return error_mark_node;
2458 if (!address_p)
2460 /* If MEMBER is non-static, then the program has fallen afoul of
2461 [expr.prim]:
2463 An id-expression that denotes a non-static data member or
2464 non-static member function of a class can only be used:
2466 -- as part of a class member access (_expr.ref_) in which the
2467 object-expression refers to the member's class or a class
2468 derived from that class, or
2470 -- to form a pointer to member (_expr.unary.op_), or
2472 -- in the body of a non-static member function of that class or
2473 of a class derived from that class (_class.mfct.non-static_), or
2475 -- in a mem-initializer for a constructor for that class or for
2476 a class derived from that class (_class.base.init_). */
2477 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (member))
2479 /* Build a representation of the qualified name suitable
2480 for use as the operand to "&" -- even though the "&" is
2481 not actually present. */
2482 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2483 /* In Microsoft mode, treat a non-static member function as if
2484 it were a pointer-to-member. */
2485 if (flag_ms_extensions)
2487 PTRMEM_OK_P (member) = 1;
2488 return cp_build_addr_expr (member, complain);
2490 if (complain & tf_error)
2491 error ("invalid use of non-static member function %qD",
2492 TREE_OPERAND (member, 1));
2493 return error_mark_node;
2495 else if (TREE_CODE (member) == FIELD_DECL)
2497 if (complain & tf_error)
2498 error ("invalid use of non-static data member %qD", member);
2499 return error_mark_node;
2501 return member;
2504 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2505 PTRMEM_OK_P (member) = 1;
2506 return member;
2509 /* If DECL is a scalar enumeration constant or variable with a
2510 constant initializer, return the initializer (or, its initializers,
2511 recursively); otherwise, return DECL. If STRICT_P, the
2512 initializer is only returned if DECL is a
2513 constant-expression. If RETURN_AGGREGATE_CST_OK_P, it is ok to
2514 return an aggregate constant. If UNSHARE_P, return an unshared
2515 copy of the initializer. */
2517 static tree
2518 constant_value_1 (tree decl, bool strict_p, bool return_aggregate_cst_ok_p,
2519 bool unshare_p)
2521 while (TREE_CODE (decl) == CONST_DECL
2522 || decl_constant_var_p (decl)
2523 || (!strict_p && VAR_P (decl)
2524 && CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (decl))))
2526 tree init;
2527 /* If DECL is a static data member in a template
2528 specialization, we must instantiate it here. The
2529 initializer for the static data member is not processed
2530 until needed; we need it now. */
2531 mark_used (decl, tf_none);
2532 init = DECL_INITIAL (decl);
2533 if (init == error_mark_node)
2535 if (TREE_CODE (decl) == CONST_DECL
2536 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2537 /* Treat the error as a constant to avoid cascading errors on
2538 excessively recursive template instantiation (c++/9335). */
2539 return init;
2540 else
2541 return decl;
2543 /* Initializers in templates are generally expanded during
2544 instantiation, so before that for const int i(2)
2545 INIT is a TREE_LIST with the actual initializer as
2546 TREE_VALUE. */
2547 if (processing_template_decl
2548 && init
2549 && TREE_CODE (init) == TREE_LIST
2550 && TREE_CHAIN (init) == NULL_TREE)
2551 init = TREE_VALUE (init);
2552 /* Instantiate a non-dependent initializer for user variables. We
2553 mustn't do this for the temporary for an array compound literal;
2554 trying to instatiate the initializer will keep creating new
2555 temporaries until we crash. Probably it's not useful to do it for
2556 other artificial variables, either. */
2557 if (!DECL_ARTIFICIAL (decl))
2558 init = instantiate_non_dependent_or_null (init);
2559 if (!init
2560 || !TREE_TYPE (init)
2561 || !TREE_CONSTANT (init)
2562 || (!return_aggregate_cst_ok_p
2563 /* Unless RETURN_AGGREGATE_CST_OK_P is true, do not
2564 return an aggregate constant (of which string
2565 literals are a special case), as we do not want
2566 to make inadvertent copies of such entities, and
2567 we must be sure that their addresses are the
2568 same everywhere. */
2569 && (TREE_CODE (init) == CONSTRUCTOR
2570 || TREE_CODE (init) == STRING_CST)))
2571 break;
2572 /* Don't return a CONSTRUCTOR for a variable with partial run-time
2573 initialization, since it doesn't represent the entire value.
2574 Similarly for VECTOR_CSTs created by cp_folding those
2575 CONSTRUCTORs. */
2576 if ((TREE_CODE (init) == CONSTRUCTOR
2577 || TREE_CODE (init) == VECTOR_CST)
2578 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2579 break;
2580 /* If the variable has a dynamic initializer, don't use its
2581 DECL_INITIAL which doesn't reflect the real value. */
2582 if (VAR_P (decl)
2583 && TREE_STATIC (decl)
2584 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)
2585 && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2586 break;
2587 decl = init;
2589 return unshare_p ? unshare_expr (decl) : decl;
2592 /* If DECL is a CONST_DECL, or a constant VAR_DECL initialized by constant
2593 of integral or enumeration type, or a constexpr variable of scalar type,
2594 then return that value. These are those variables permitted in constant
2595 expressions by [5.19/1]. */
2597 tree
2598 scalar_constant_value (tree decl)
2600 return constant_value_1 (decl, /*strict_p=*/true,
2601 /*return_aggregate_cst_ok_p=*/false,
2602 /*unshare_p=*/true);
2605 /* Like scalar_constant_value, but can also return aggregate initializers.
2606 If UNSHARE_P, return an unshared copy of the initializer. */
2608 tree
2609 decl_really_constant_value (tree decl, bool unshare_p /*= true*/)
2611 return constant_value_1 (decl, /*strict_p=*/true,
2612 /*return_aggregate_cst_ok_p=*/true,
2613 /*unshare_p=*/unshare_p);
2616 /* A more relaxed version of decl_really_constant_value, used by the
2617 common C/C++ code. */
2619 tree
2620 decl_constant_value (tree decl, bool unshare_p)
2622 return constant_value_1 (decl, /*strict_p=*/processing_template_decl,
2623 /*return_aggregate_cst_ok_p=*/true,
2624 /*unshare_p=*/unshare_p);
2627 tree
2628 decl_constant_value (tree decl)
2630 return decl_constant_value (decl, /*unshare_p=*/true);
2633 /* Common subroutines of build_new and build_vec_delete. */
2635 /* Build and return a NEW_EXPR. If NELTS is non-NULL, TYPE[NELTS] is
2636 the type of the object being allocated; otherwise, it's just TYPE.
2637 INIT is the initializer, if any. USE_GLOBAL_NEW is true if the
2638 user explicitly wrote "::operator new". PLACEMENT, if non-NULL, is
2639 a vector of arguments to be provided as arguments to a placement
2640 new operator. This routine performs no semantic checks; it just
2641 creates and returns a NEW_EXPR. */
2643 static tree
2644 build_raw_new_expr (location_t loc, vec<tree, va_gc> *placement, tree type,
2645 tree nelts, vec<tree, va_gc> *init, int use_global_new)
2647 tree init_list;
2648 tree new_expr;
2650 /* If INIT is NULL, the we want to store NULL_TREE in the NEW_EXPR.
2651 If INIT is not NULL, then we want to store VOID_ZERO_NODE. This
2652 permits us to distinguish the case of a missing initializer "new
2653 int" from an empty initializer "new int()". */
2654 if (init == NULL)
2655 init_list = NULL_TREE;
2656 else if (init->is_empty ())
2657 init_list = void_node;
2658 else
2659 init_list = build_tree_list_vec (init);
2661 new_expr = build4_loc (loc, NEW_EXPR, build_pointer_type (type),
2662 build_tree_list_vec (placement), type, nelts,
2663 init_list);
2664 NEW_EXPR_USE_GLOBAL (new_expr) = use_global_new;
2665 TREE_SIDE_EFFECTS (new_expr) = 1;
2667 return new_expr;
2670 /* Diagnose uninitialized const members or reference members of type
2671 TYPE. USING_NEW is used to disambiguate the diagnostic between a
2672 new expression without a new-initializer and a declaration. Returns
2673 the error count. */
2675 static int
2676 diagnose_uninitialized_cst_or_ref_member_1 (tree type, tree origin,
2677 bool using_new, bool complain)
2679 tree field;
2680 int error_count = 0;
2682 if (type_has_user_provided_constructor (type))
2683 return 0;
2685 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
2687 tree field_type;
2689 if (TREE_CODE (field) != FIELD_DECL)
2690 continue;
2692 field_type = strip_array_types (TREE_TYPE (field));
2694 if (type_has_user_provided_constructor (field_type))
2695 continue;
2697 if (TYPE_REF_P (field_type))
2699 ++ error_count;
2700 if (complain)
2702 if (DECL_CONTEXT (field) == origin)
2704 if (using_new)
2705 error ("uninitialized reference member in %q#T "
2706 "using %<new%> without new-initializer", origin);
2707 else
2708 error ("uninitialized reference member in %q#T", origin);
2710 else
2712 if (using_new)
2713 error ("uninitialized reference member in base %q#T "
2714 "of %q#T using %<new%> without new-initializer",
2715 DECL_CONTEXT (field), origin);
2716 else
2717 error ("uninitialized reference member in base %q#T "
2718 "of %q#T", DECL_CONTEXT (field), origin);
2720 inform (DECL_SOURCE_LOCATION (field),
2721 "%q#D should be initialized", field);
2725 if (CP_TYPE_CONST_P (field_type))
2727 ++ error_count;
2728 if (complain)
2730 if (DECL_CONTEXT (field) == origin)
2732 if (using_new)
2733 error ("uninitialized const member in %q#T "
2734 "using %<new%> without new-initializer", origin);
2735 else
2736 error ("uninitialized const member in %q#T", origin);
2738 else
2740 if (using_new)
2741 error ("uninitialized const member in base %q#T "
2742 "of %q#T using %<new%> without new-initializer",
2743 DECL_CONTEXT (field), origin);
2744 else
2745 error ("uninitialized const member in base %q#T "
2746 "of %q#T", DECL_CONTEXT (field), origin);
2748 inform (DECL_SOURCE_LOCATION (field),
2749 "%q#D should be initialized", field);
2753 if (CLASS_TYPE_P (field_type))
2754 error_count
2755 += diagnose_uninitialized_cst_or_ref_member_1 (field_type, origin,
2756 using_new, complain);
2758 return error_count;
2762 diagnose_uninitialized_cst_or_ref_member (tree type, bool using_new, bool complain)
2764 return diagnose_uninitialized_cst_or_ref_member_1 (type, type, using_new, complain);
2767 /* Call __cxa_bad_array_new_length to indicate that the size calculation
2768 overflowed. Pretend it returns sizetype so that it plays nicely in the
2769 COND_EXPR. */
2771 tree
2772 throw_bad_array_new_length (void)
2774 if (!fn)
2776 tree name = get_identifier ("__cxa_throw_bad_array_new_length");
2778 fn = get_global_binding (name);
2779 if (!fn)
2780 fn = push_throw_library_fn
2781 (name, build_function_type_list (sizetype, NULL_TREE));
2784 return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
2787 /* Attempt to verify that the argument, OPER, of a placement new expression
2788 refers to an object sufficiently large for an object of TYPE or an array
2789 of NELTS of such objects when NELTS is non-null, and issue a warning when
2790 it does not. SIZE specifies the size needed to construct the object or
2791 array and captures the result of NELTS * sizeof (TYPE). (SIZE could be
2792 greater when the array under construction requires a cookie to store
2793 NELTS. GCC's placement new expression stores the cookie when invoking
2794 a user-defined placement new operator function but not the default one.
2795 Placement new expressions with user-defined placement new operator are
2796 not diagnosed since we don't know how they use the buffer (this could
2797 be a future extension). */
2798 static void
2799 warn_placement_new_too_small (tree type, tree nelts, tree size, tree oper)
2801 location_t loc = cp_expr_loc_or_input_loc (oper);
2803 STRIP_NOPS (oper);
2805 /* Using a function argument or a (non-array) variable as an argument
2806 to placement new is not checked since it's unknown what it might
2807 point to. */
2808 if (TREE_CODE (oper) == PARM_DECL
2809 || VAR_P (oper)
2810 || TREE_CODE (oper) == COMPONENT_REF)
2811 return;
2813 /* Evaluate any constant expressions. */
2814 size = fold_non_dependent_expr (size);
2816 access_ref ref;
2817 ref.eval = [](tree x){ return fold_non_dependent_expr (x); };
2818 ref.trail1special = warn_placement_new < 2;
2819 tree objsize = compute_objsize (oper, 1, &ref);
2820 if (!objsize)
2821 return;
2823 /* We can only draw conclusions if ref.deref == -1,
2824 i.e. oper is the address of the object. */
2825 if (ref.deref != -1)
2826 return;
2828 offset_int bytes_avail = wi::to_offset (objsize);
2829 offset_int bytes_need;
2831 if (CONSTANT_CLASS_P (size))
2832 bytes_need = wi::to_offset (size);
2833 else if (nelts && CONSTANT_CLASS_P (nelts))
2834 bytes_need = (wi::to_offset (nelts)
2835 * wi::to_offset (TYPE_SIZE_UNIT (type)));
2836 else if (tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2837 bytes_need = wi::to_offset (TYPE_SIZE_UNIT (type));
2838 else
2840 /* The type is a VLA. */
2841 return;
2844 if (bytes_avail >= bytes_need)
2845 return;
2847 /* True when the size to mention in the warning is exact as opposed
2848 to "at least N". */
2849 const bool exact_size = (ref.offrng[0] == ref.offrng[1]
2850 || ref.sizrng[1] - ref.offrng[0] == 0);
2852 tree opertype = ref.ref ? TREE_TYPE (ref.ref) : TREE_TYPE (oper);
2853 bool warned = false;
2854 if (nelts)
2855 nelts = fold_for_warn (nelts);
2856 if (nelts)
2857 if (CONSTANT_CLASS_P (nelts))
2858 warned = warning_at (loc, OPT_Wplacement_new_,
2859 (exact_size
2860 ? G_("placement new constructing an object "
2861 "of type %<%T [%wu]%> and size %qwu "
2862 "in a region of type %qT and size %qwi")
2863 : G_("placement new constructing an object "
2864 "of type %<%T [%wu]%> and size %qwu "
2865 "in a region of type %qT and size "
2866 "at most %qwu")),
2867 type, tree_to_uhwi (nelts),
2868 bytes_need.to_uhwi (),
2869 opertype, bytes_avail.to_uhwi ());
2870 else
2871 warned = warning_at (loc, OPT_Wplacement_new_,
2872 (exact_size
2873 ? G_("placement new constructing an array "
2874 "of objects of type %qT and size %qwu "
2875 "in a region of type %qT and size %qwi")
2876 : G_("placement new constructing an array "
2877 "of objects of type %qT and size %qwu "
2878 "in a region of type %qT and size "
2879 "at most %qwu")),
2880 type, bytes_need.to_uhwi (), opertype,
2881 bytes_avail.to_uhwi ());
2882 else
2883 warned = warning_at (loc, OPT_Wplacement_new_,
2884 (exact_size
2885 ? G_("placement new constructing an object "
2886 "of type %qT and size %qwu in a region "
2887 "of type %qT and size %qwi")
2888 : G_("placement new constructing an object "
2889 "of type %qT "
2890 "and size %qwu in a region of type %qT "
2891 "and size at most %qwu")),
2892 type, bytes_need.to_uhwi (), opertype,
2893 bytes_avail.to_uhwi ());
2895 if (!warned || !ref.ref)
2896 return;
2898 if (ref.offrng[0] == 0 || !ref.offset_bounded ())
2899 /* Avoid mentioning the offset when its lower bound is zero
2900 or when it's impossibly large. */
2901 inform (DECL_SOURCE_LOCATION (ref.ref),
2902 "%qD declared here", ref.ref);
2903 else if (ref.offrng[0] == ref.offrng[1])
2904 inform (DECL_SOURCE_LOCATION (ref.ref),
2905 "at offset %wi from %qD declared here",
2906 ref.offrng[0].to_shwi (), ref.ref);
2907 else
2908 inform (DECL_SOURCE_LOCATION (ref.ref),
2909 "at offset [%wi, %wi] from %qD declared here",
2910 ref.offrng[0].to_shwi (), ref.offrng[1].to_shwi (), ref.ref);
2913 /* True if alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__. */
2915 bool
2916 type_has_new_extended_alignment (tree t)
2918 return (aligned_new_threshold
2919 && TYPE_ALIGN_UNIT (t) > (unsigned)aligned_new_threshold);
2922 /* Return the alignment we expect malloc to guarantee. This should just be
2923 MALLOC_ABI_ALIGNMENT, but that macro defaults to only BITS_PER_WORD for some
2924 reason, so don't let the threshold be smaller than max_align_t_align. */
2926 unsigned
2927 malloc_alignment ()
2929 return MAX (max_align_t_align(), MALLOC_ABI_ALIGNMENT);
2932 /* Determine whether an allocation function is a namespace-scope
2933 non-replaceable placement new function. See DR 1748. */
2934 static bool
2935 std_placement_new_fn_p (tree alloc_fn)
2937 if (DECL_NAMESPACE_SCOPE_P (alloc_fn))
2939 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (alloc_fn)));
2940 if ((TREE_VALUE (first_arg) == ptr_type_node)
2941 && TREE_CHAIN (first_arg) == void_list_node)
2942 return true;
2944 return false;
2947 /* For element type ELT_TYPE, return the appropriate type of the heap object
2948 containing such element(s). COOKIE_SIZE is the size of cookie in bytes.
2949 Return
2950 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
2951 where N is nothing (flexible array member) if ITYPE2 is NULL, otherwise
2952 the array has ITYPE2 as its TYPE_DOMAIN. */
2954 tree
2955 build_new_constexpr_heap_type (tree elt_type, tree cookie_size, tree itype2)
2957 gcc_assert (tree_fits_uhwi_p (cookie_size));
2958 unsigned HOST_WIDE_INT csz = tree_to_uhwi (cookie_size);
2959 csz /= int_size_in_bytes (sizetype);
2960 tree itype1 = build_index_type (size_int (csz - 1));
2961 tree atype1 = build_cplus_array_type (sizetype, itype1);
2962 tree atype2 = build_cplus_array_type (elt_type, itype2);
2963 tree rtype = cxx_make_type (RECORD_TYPE);
2964 TYPE_NAME (rtype) = heap_identifier;
2965 tree fld1 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype1);
2966 tree fld2 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype2);
2967 DECL_FIELD_CONTEXT (fld1) = rtype;
2968 DECL_FIELD_CONTEXT (fld2) = rtype;
2969 DECL_ARTIFICIAL (fld1) = true;
2970 DECL_ARTIFICIAL (fld2) = true;
2971 TYPE_FIELDS (rtype) = fld1;
2972 DECL_CHAIN (fld1) = fld2;
2973 layout_type (rtype);
2974 return rtype;
2977 /* Help the constexpr code to find the right type for the heap variable
2978 by adding a NOP_EXPR around ALLOC_CALL if needed for cookie_size.
2979 Return ALLOC_CALL or ALLOC_CALL cast to a pointer to
2980 struct { size_t[cookie_size/sizeof(size_t)]; elt_type[]; }. */
2982 static tree
2983 maybe_wrap_new_for_constexpr (tree alloc_call, tree elt_type, tree cookie_size)
2985 if (cxx_dialect < cxx20)
2986 return alloc_call;
2988 if (current_function_decl != NULL_TREE
2989 && !DECL_DECLARED_CONSTEXPR_P (current_function_decl))
2990 return alloc_call;
2992 tree call_expr = extract_call_expr (alloc_call);
2993 if (call_expr == error_mark_node)
2994 return alloc_call;
2996 tree alloc_call_fndecl = cp_get_callee_fndecl_nofold (call_expr);
2997 if (alloc_call_fndecl == NULL_TREE
2998 || !IDENTIFIER_NEW_OP_P (DECL_NAME (alloc_call_fndecl))
2999 || CP_DECL_CONTEXT (alloc_call_fndecl) != global_namespace)
3000 return alloc_call;
3002 tree rtype = build_new_constexpr_heap_type (elt_type, cookie_size,
3003 NULL_TREE);
3004 return build_nop (build_pointer_type (rtype), alloc_call);
3007 /* Generate code for a new-expression, including calling the "operator
3008 new" function, initializing the object, and, if an exception occurs
3009 during construction, cleaning up. The arguments are as for
3010 build_raw_new_expr. This may change PLACEMENT and INIT.
3011 TYPE is the type of the object being constructed, possibly an array
3012 of NELTS elements when NELTS is non-null (in "new T[NELTS]", T may
3013 be an array of the form U[inner], with the whole expression being
3014 "new U[NELTS][inner]"). */
3016 static tree
3017 build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts,
3018 vec<tree, va_gc> **init, bool globally_qualified_p,
3019 tsubst_flags_t complain)
3021 tree size, rval;
3022 /* True iff this is a call to "operator new[]" instead of just
3023 "operator new". */
3024 bool array_p = false;
3025 /* If ARRAY_P is true, the element type of the array. This is never
3026 an ARRAY_TYPE; for something like "new int[3][4]", the
3027 ELT_TYPE is "int". If ARRAY_P is false, this is the same type as
3028 TYPE. */
3029 tree elt_type;
3030 /* The type of the new-expression. (This type is always a pointer
3031 type.) */
3032 tree pointer_type;
3033 tree non_const_pointer_type;
3034 /* The most significant array bound in int[OUTER_NELTS][inner]. */
3035 tree outer_nelts = NULL_TREE;
3036 /* For arrays with a non-constant number of elements, a bounds checks
3037 on the NELTS parameter to avoid integer overflow at runtime. */
3038 tree outer_nelts_check = NULL_TREE;
3039 bool outer_nelts_from_type = false;
3040 /* Number of the "inner" elements in "new T[OUTER_NELTS][inner]". */
3041 offset_int inner_nelts_count = 1;
3042 tree alloc_call, alloc_expr;
3043 /* Size of the inner array elements (those with constant dimensions). */
3044 offset_int inner_size;
3045 /* The address returned by the call to "operator new". This node is
3046 a VAR_DECL and is therefore reusable. */
3047 tree alloc_node;
3048 tree alloc_fn;
3049 tree cookie_expr, init_expr;
3050 int nothrow, check_new;
3051 /* If non-NULL, the number of extra bytes to allocate at the
3052 beginning of the storage allocated for an array-new expression in
3053 order to store the number of elements. */
3054 tree cookie_size = NULL_TREE;
3055 tree placement_first;
3056 tree placement_expr = NULL_TREE;
3057 /* True if the function we are calling is a placement allocation
3058 function. */
3059 bool placement_allocation_fn_p;
3060 /* True if the storage must be initialized, either by a constructor
3061 or due to an explicit new-initializer. */
3062 bool is_initialized;
3063 /* The address of the thing allocated, not including any cookie. In
3064 particular, if an array cookie is in use, DATA_ADDR is the
3065 address of the first array element. This node is a VAR_DECL, and
3066 is therefore reusable. */
3067 tree data_addr;
3068 tree orig_type = type;
3070 if (nelts)
3072 outer_nelts = nelts;
3073 array_p = true;
3075 else if (TREE_CODE (type) == ARRAY_TYPE)
3077 /* Transforms new (T[N]) to new T[N]. The former is a GNU
3078 extension for variable N. (This also covers new T where T is
3079 a VLA typedef.) */
3080 array_p = true;
3081 nelts = array_type_nelts_top (type);
3082 outer_nelts = nelts;
3083 type = TREE_TYPE (type);
3084 outer_nelts_from_type = true;
3087 /* Lots of logic below depends on whether we have a constant number of
3088 elements, so go ahead and fold it now. */
3089 const_tree cst_outer_nelts = fold_non_dependent_expr (outer_nelts, complain);
3091 /* If our base type is an array, then make sure we know how many elements
3092 it has. */
3093 for (elt_type = type;
3094 TREE_CODE (elt_type) == ARRAY_TYPE;
3095 elt_type = TREE_TYPE (elt_type))
3097 tree inner_nelts = array_type_nelts_top (elt_type);
3098 tree inner_nelts_cst = maybe_constant_value (inner_nelts);
3099 if (TREE_CODE (inner_nelts_cst) == INTEGER_CST)
3101 wi::overflow_type overflow;
3102 offset_int result = wi::mul (wi::to_offset (inner_nelts_cst),
3103 inner_nelts_count, SIGNED, &overflow);
3104 if (overflow)
3106 if (complain & tf_error)
3107 error ("integer overflow in array size");
3108 nelts = error_mark_node;
3110 inner_nelts_count = result;
3112 else
3114 if (complain & tf_error)
3116 error_at (cp_expr_loc_or_input_loc (inner_nelts),
3117 "array size in new-expression must be constant");
3118 cxx_constant_value(inner_nelts);
3120 nelts = error_mark_node;
3122 if (nelts != error_mark_node)
3123 nelts = cp_build_binary_op (input_location,
3124 MULT_EXPR, nelts,
3125 inner_nelts_cst,
3126 complain);
3129 if (!verify_type_context (input_location, TCTX_ALLOCATION, elt_type,
3130 !(complain & tf_error)))
3131 return error_mark_node;
3133 if (variably_modified_type_p (elt_type, NULL_TREE) && (complain & tf_error))
3135 error ("variably modified type not allowed in new-expression");
3136 return error_mark_node;
3139 if (nelts == error_mark_node)
3140 return error_mark_node;
3142 /* Warn if we performed the (T[N]) to T[N] transformation and N is
3143 variable. */
3144 if (outer_nelts_from_type
3145 && !TREE_CONSTANT (cst_outer_nelts))
3147 if (complain & tf_warning_or_error)
3149 pedwarn (cp_expr_loc_or_input_loc (outer_nelts), OPT_Wvla,
3150 typedef_variant_p (orig_type)
3151 ? G_("non-constant array new length must be specified "
3152 "directly, not by %<typedef%>")
3153 : G_("non-constant array new length must be specified "
3154 "without parentheses around the type-id"));
3156 else
3157 return error_mark_node;
3160 if (VOID_TYPE_P (elt_type))
3162 if (complain & tf_error)
3163 error ("invalid type %<void%> for %<new%>");
3164 return error_mark_node;
3167 if (is_std_init_list (elt_type) && !cp_unevaluated_operand)
3168 warning (OPT_Winit_list_lifetime,
3169 "%<new%> of %<initializer_list%> does not "
3170 "extend the lifetime of the underlying array");
3172 if (abstract_virtuals_error (ACU_NEW, elt_type, complain))
3173 return error_mark_node;
3175 is_initialized = (type_build_ctor_call (elt_type) || *init != NULL);
3177 if (*init == NULL && cxx_dialect < cxx11)
3179 bool maybe_uninitialized_error = false;
3180 /* A program that calls for default-initialization [...] of an
3181 entity of reference type is ill-formed. */
3182 if (CLASSTYPE_REF_FIELDS_NEED_INIT (elt_type))
3183 maybe_uninitialized_error = true;
3185 /* A new-expression that creates an object of type T initializes
3186 that object as follows:
3187 - If the new-initializer is omitted:
3188 -- If T is a (possibly cv-qualified) non-POD class type
3189 (or array thereof), the object is default-initialized (8.5).
3190 [...]
3191 -- Otherwise, the object created has indeterminate
3192 value. If T is a const-qualified type, or a (possibly
3193 cv-qualified) POD class type (or array thereof)
3194 containing (directly or indirectly) a member of
3195 const-qualified type, the program is ill-formed; */
3197 if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (elt_type))
3198 maybe_uninitialized_error = true;
3200 if (maybe_uninitialized_error
3201 && diagnose_uninitialized_cst_or_ref_member (elt_type,
3202 /*using_new=*/true,
3203 complain & tf_error))
3204 return error_mark_node;
3207 if (CP_TYPE_CONST_P (elt_type) && *init == NULL
3208 && default_init_uninitialized_part (elt_type))
3210 if (complain & tf_error)
3211 error ("uninitialized const in %<new%> of %q#T", elt_type);
3212 return error_mark_node;
3215 size = size_in_bytes (elt_type);
3216 if (array_p)
3218 /* Maximum available size in bytes. Half of the address space
3219 minus the cookie size. */
3220 offset_int max_size
3221 = wi::set_bit_in_zero <offset_int> (TYPE_PRECISION (sizetype) - 1);
3222 /* Maximum number of outer elements which can be allocated. */
3223 offset_int max_outer_nelts;
3224 tree max_outer_nelts_tree;
3226 gcc_assert (TREE_CODE (size) == INTEGER_CST);
3227 cookie_size = targetm.cxx.get_cookie_size (elt_type);
3228 gcc_assert (TREE_CODE (cookie_size) == INTEGER_CST);
3229 gcc_checking_assert (wi::ltu_p (wi::to_offset (cookie_size), max_size));
3230 /* Unconditionally subtract the cookie size. This decreases the
3231 maximum object size and is safe even if we choose not to use
3232 a cookie after all. */
3233 max_size -= wi::to_offset (cookie_size);
3234 wi::overflow_type overflow;
3235 inner_size = wi::mul (wi::to_offset (size), inner_nelts_count, SIGNED,
3236 &overflow);
3237 if (overflow || wi::gtu_p (inner_size, max_size))
3239 if (complain & tf_error)
3241 cst_size_error error;
3242 if (overflow)
3243 error = cst_size_overflow;
3244 else
3246 error = cst_size_too_big;
3247 size = size_binop (MULT_EXPR, size,
3248 wide_int_to_tree (sizetype,
3249 inner_nelts_count));
3250 size = cp_fully_fold (size);
3252 invalid_array_size_error (input_location, error, size,
3253 /*name=*/NULL_TREE);
3255 return error_mark_node;
3258 max_outer_nelts = wi::udiv_trunc (max_size, inner_size);
3259 max_outer_nelts_tree = wide_int_to_tree (sizetype, max_outer_nelts);
3261 size = size_binop (MULT_EXPR, size, fold_convert (sizetype, nelts));
3263 if (TREE_CODE (cst_outer_nelts) == INTEGER_CST)
3265 if (tree_int_cst_lt (max_outer_nelts_tree, cst_outer_nelts))
3267 /* When the array size is constant, check it at compile time
3268 to make sure it doesn't exceed the implementation-defined
3269 maximum, as required by C++ 14 (in C++ 11 this requirement
3270 isn't explicitly stated but it's enforced anyway -- see
3271 grokdeclarator in cp/decl.cc). */
3272 if (complain & tf_error)
3274 size = cp_fully_fold (size);
3275 invalid_array_size_error (input_location, cst_size_too_big,
3276 size, NULL_TREE);
3278 return error_mark_node;
3281 else
3283 /* When a runtime check is necessary because the array size
3284 isn't constant, keep only the top-most seven bits (starting
3285 with the most significant non-zero bit) of the maximum size
3286 to compare the array size against, to simplify encoding the
3287 constant maximum size in the instruction stream. */
3289 unsigned shift = (max_outer_nelts.get_precision ()) - 7
3290 - wi::clz (max_outer_nelts);
3291 max_outer_nelts = (max_outer_nelts >> shift) << shift;
3293 outer_nelts_check = fold_build2 (LE_EXPR, boolean_type_node,
3294 outer_nelts,
3295 max_outer_nelts_tree);
3299 tree align_arg = NULL_TREE;
3300 if (type_has_new_extended_alignment (elt_type))
3302 unsigned align = TYPE_ALIGN_UNIT (elt_type);
3303 /* Also consider the alignment of the cookie, if any. */
3304 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3305 align = MAX (align, TYPE_ALIGN_UNIT (size_type_node));
3306 align_arg = build_int_cst (align_type_node, align);
3309 alloc_fn = NULL_TREE;
3311 /* If PLACEMENT is a single simple pointer type not passed by
3312 reference, prepare to capture it in a temporary variable. Do
3313 this now, since PLACEMENT will change in the calls below. */
3314 placement_first = NULL_TREE;
3315 if (vec_safe_length (*placement) == 1
3316 && (TYPE_PTR_P (TREE_TYPE ((**placement)[0]))))
3317 placement_first = (**placement)[0];
3319 bool member_new_p = false;
3321 /* Allocate the object. */
3322 tree fnname;
3323 tree fns;
3325 fnname = ovl_op_identifier (false, array_p ? VEC_NEW_EXPR : NEW_EXPR);
3327 member_new_p = !globally_qualified_p
3328 && CLASS_TYPE_P (elt_type)
3329 && (array_p
3330 ? TYPE_HAS_ARRAY_NEW_OPERATOR (elt_type)
3331 : TYPE_HAS_NEW_OPERATOR (elt_type));
3333 bool member_delete_p = (!globally_qualified_p
3334 && CLASS_TYPE_P (elt_type)
3335 && (array_p
3336 ? TYPE_GETS_VEC_DELETE (elt_type)
3337 : TYPE_GETS_REG_DELETE (elt_type)));
3339 if (member_new_p)
3341 /* Use a class-specific operator new. */
3342 /* If a cookie is required, add some extra space. */
3343 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3344 size = size_binop (PLUS_EXPR, size, cookie_size);
3345 else
3347 cookie_size = NULL_TREE;
3348 /* No size arithmetic necessary, so the size check is
3349 not needed. */
3350 if (outer_nelts_check != NULL && inner_size == 1)
3351 outer_nelts_check = NULL_TREE;
3353 /* Perform the overflow check. */
3354 tree errval = TYPE_MAX_VALUE (sizetype);
3355 if (cxx_dialect >= cxx11 && flag_exceptions)
3356 errval = throw_bad_array_new_length ();
3357 if (outer_nelts_check != NULL_TREE)
3358 size = fold_build3 (COND_EXPR, sizetype, outer_nelts_check,
3359 size, errval);
3360 /* Create the argument list. */
3361 vec_safe_insert (*placement, 0, size);
3362 /* Do name-lookup to find the appropriate operator. */
3363 fns = lookup_fnfields (elt_type, fnname, /*protect=*/2, complain);
3364 if (fns == NULL_TREE)
3366 if (complain & tf_error)
3367 error ("no suitable %qD found in class %qT", fnname, elt_type);
3368 return error_mark_node;
3370 if (TREE_CODE (fns) == TREE_LIST)
3372 if (complain & tf_error)
3374 error ("request for member %qD is ambiguous", fnname);
3375 print_candidates (fns);
3377 return error_mark_node;
3379 tree dummy = build_dummy_object (elt_type);
3380 alloc_call = NULL_TREE;
3381 if (align_arg)
3383 vec<tree, va_gc> *align_args
3384 = vec_copy_and_insert (*placement, align_arg, 1);
3385 alloc_call
3386 = build_new_method_call (dummy, fns, &align_args,
3387 /*conversion_path=*/NULL_TREE,
3388 LOOKUP_NORMAL, &alloc_fn, tf_none);
3389 /* If no matching function is found and the allocated object type
3390 has new-extended alignment, the alignment argument is removed
3391 from the argument list, and overload resolution is performed
3392 again. */
3393 if (alloc_call == error_mark_node)
3394 alloc_call = NULL_TREE;
3396 if (!alloc_call)
3397 alloc_call = build_new_method_call (dummy, fns, placement,
3398 /*conversion_path=*/NULL_TREE,
3399 LOOKUP_NORMAL,
3400 &alloc_fn, complain);
3402 else
3404 /* Use a global operator new. */
3405 /* See if a cookie might be required. */
3406 if (!(array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type)))
3408 cookie_size = NULL_TREE;
3409 /* No size arithmetic necessary, so the size check is
3410 not needed. */
3411 if (outer_nelts_check != NULL && inner_size == 1)
3412 outer_nelts_check = NULL_TREE;
3415 /* If size is zero e.g. due to type having zero size, try to
3416 preserve outer_nelts for constant expression evaluation
3417 purposes. */
3418 if (integer_zerop (size) && outer_nelts)
3419 size = build2 (MULT_EXPR, TREE_TYPE (size), size, outer_nelts);
3421 alloc_call = build_operator_new_call (fnname, placement,
3422 &size, &cookie_size,
3423 align_arg, outer_nelts_check,
3424 &alloc_fn, complain);
3427 if (alloc_call == error_mark_node)
3428 return error_mark_node;
3430 gcc_assert (alloc_fn != NULL_TREE);
3432 /* Now, check to see if this function is actually a placement
3433 allocation function. This can happen even when PLACEMENT is NULL
3434 because we might have something like:
3436 struct S { void* operator new (size_t, int i = 0); };
3438 A call to `new S' will get this allocation function, even though
3439 there is no explicit placement argument. If there is more than
3440 one argument, or there are variable arguments, then this is a
3441 placement allocation function. */
3442 placement_allocation_fn_p
3443 = (type_num_arguments (TREE_TYPE (alloc_fn)) > 1
3444 || varargs_function_p (alloc_fn));
3446 if (complain & tf_warning_or_error
3447 && warn_aligned_new
3448 && !placement_allocation_fn_p
3449 && TYPE_ALIGN (elt_type) > malloc_alignment ()
3450 && (warn_aligned_new > 1
3451 || CP_DECL_CONTEXT (alloc_fn) == global_namespace)
3452 && !aligned_allocation_fn_p (alloc_fn))
3454 auto_diagnostic_group d;
3455 if (warning (OPT_Waligned_new_, "%<new%> of type %qT with extended "
3456 "alignment %d", elt_type, TYPE_ALIGN_UNIT (elt_type)))
3458 inform (input_location, "uses %qD, which does not have an alignment "
3459 "parameter", alloc_fn);
3460 if (!aligned_new_threshold)
3461 inform (input_location, "use %<-faligned-new%> to enable C++17 "
3462 "over-aligned new support");
3466 /* If we found a simple case of PLACEMENT_EXPR above, then copy it
3467 into a temporary variable. */
3468 if (!processing_template_decl
3469 && TREE_CODE (alloc_call) == CALL_EXPR
3470 && call_expr_nargs (alloc_call) == 2
3471 && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 0))) == INTEGER_TYPE
3472 && TYPE_PTR_P (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1))))
3474 tree placement = CALL_EXPR_ARG (alloc_call, 1);
3476 if (placement_first != NULL_TREE
3477 && (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))
3478 || VOID_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))))
3480 placement_expr = get_target_expr (placement_first);
3481 CALL_EXPR_ARG (alloc_call, 1)
3482 = fold_convert (TREE_TYPE (placement), placement_expr);
3485 if (!member_new_p
3486 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1)))))
3488 /* Attempt to make the warning point at the operator new argument. */
3489 if (placement_first)
3490 placement = placement_first;
3492 warn_placement_new_too_small (orig_type, nelts, size, placement);
3496 alloc_expr = alloc_call;
3497 if (cookie_size)
3498 alloc_expr = maybe_wrap_new_for_constexpr (alloc_expr, type,
3499 cookie_size);
3501 /* In the simple case, we can stop now. */
3502 pointer_type = build_pointer_type (type);
3503 if (!cookie_size && !is_initialized && !member_delete_p)
3504 return build_nop (pointer_type, alloc_expr);
3506 /* Store the result of the allocation call in a variable so that we can
3507 use it more than once. */
3508 alloc_expr = get_target_expr (alloc_expr);
3509 alloc_node = TARGET_EXPR_SLOT (alloc_expr);
3511 /* Strip any COMPOUND_EXPRs from ALLOC_CALL. */
3512 while (TREE_CODE (alloc_call) == COMPOUND_EXPR)
3513 alloc_call = TREE_OPERAND (alloc_call, 1);
3515 /* Preevaluate the placement args so that we don't reevaluate them for a
3516 placement delete. */
3517 if (placement_allocation_fn_p)
3519 tree inits;
3520 stabilize_call (alloc_call, &inits);
3521 if (inits)
3522 alloc_expr = build2 (COMPOUND_EXPR, TREE_TYPE (alloc_expr), inits,
3523 alloc_expr);
3526 /* unless an allocation function is declared with an empty excep-
3527 tion-specification (_except.spec_), throw(), it indicates failure to
3528 allocate storage by throwing a bad_alloc exception (clause _except_,
3529 _lib.bad.alloc_); it returns a non-null pointer otherwise If the allo-
3530 cation function is declared with an empty exception-specification,
3531 throw(), it returns null to indicate failure to allocate storage and a
3532 non-null pointer otherwise.
3534 So check for a null exception spec on the op new we just called. */
3536 nothrow = TYPE_NOTHROW_P (TREE_TYPE (alloc_fn));
3537 check_new
3538 = flag_check_new || (nothrow && !std_placement_new_fn_p (alloc_fn));
3540 if (cookie_size)
3542 tree cookie;
3543 tree cookie_ptr;
3544 tree size_ptr_type;
3546 /* Adjust so we're pointing to the start of the object. */
3547 data_addr = fold_build_pointer_plus (alloc_node, cookie_size);
3549 /* Store the number of bytes allocated so that we can know how
3550 many elements to destroy later. We use the last sizeof
3551 (size_t) bytes to store the number of elements. */
3552 cookie_ptr = size_binop (MINUS_EXPR, cookie_size, size_in_bytes (sizetype));
3553 cookie_ptr = fold_build_pointer_plus_loc (input_location,
3554 alloc_node, cookie_ptr);
3555 size_ptr_type = build_pointer_type (sizetype);
3556 cookie_ptr = fold_convert (size_ptr_type, cookie_ptr);
3557 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3559 cookie_expr = build2 (MODIFY_EXPR, sizetype, cookie, nelts);
3561 if (targetm.cxx.cookie_has_size ())
3563 /* Also store the element size. */
3564 cookie_ptr = fold_build_pointer_plus (cookie_ptr,
3565 fold_build1_loc (input_location,
3566 NEGATE_EXPR, sizetype,
3567 size_in_bytes (sizetype)));
3569 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3570 cookie = build2 (MODIFY_EXPR, sizetype, cookie,
3571 size_in_bytes (elt_type));
3572 cookie_expr = build2 (COMPOUND_EXPR, TREE_TYPE (cookie_expr),
3573 cookie, cookie_expr);
3576 else
3578 cookie_expr = NULL_TREE;
3579 data_addr = alloc_node;
3582 /* Now use a pointer to the type we've actually allocated. */
3584 /* But we want to operate on a non-const version to start with,
3585 since we'll be modifying the elements. */
3586 non_const_pointer_type = build_pointer_type
3587 (cp_build_qualified_type (type, cp_type_quals (type) & ~TYPE_QUAL_CONST));
3589 data_addr = fold_convert (non_const_pointer_type, data_addr);
3590 /* Any further uses of alloc_node will want this type, too. */
3591 alloc_node = fold_convert (non_const_pointer_type, alloc_node);
3593 /* Now initialize the allocated object. Note that we preevaluate the
3594 initialization expression, apart from the actual constructor call or
3595 assignment--we do this because we want to delay the allocation as long
3596 as possible in order to minimize the size of the exception region for
3597 placement delete. */
3598 if (is_initialized)
3600 bool explicit_value_init_p = false;
3602 if (*init != NULL && (*init)->is_empty ())
3604 *init = NULL;
3605 explicit_value_init_p = true;
3608 if (processing_template_decl)
3610 /* Avoid an ICE when converting to a base in build_simple_base_path.
3611 We'll throw this all away anyway, and build_new will create
3612 a NEW_EXPR. */
3613 tree t = fold_convert (build_pointer_type (elt_type), data_addr);
3614 /* build_value_init doesn't work in templates, and we don't need
3615 the initializer anyway since we're going to throw it away and
3616 rebuild it at instantiation time, so just build up a single
3617 constructor call to get any appropriate diagnostics. */
3618 init_expr = cp_build_fold_indirect_ref (t);
3619 if (type_build_ctor_call (elt_type))
3620 init_expr = build_special_member_call (init_expr,
3621 complete_ctor_identifier,
3622 init, elt_type,
3623 LOOKUP_NORMAL,
3624 complain);
3626 else if (array_p)
3628 tree vecinit = NULL_TREE;
3629 const size_t len = vec_safe_length (*init);
3630 if (len == 1 && DIRECT_LIST_INIT_P ((**init)[0]))
3632 vecinit = (**init)[0];
3633 if (CONSTRUCTOR_NELTS (vecinit) == 0)
3634 /* List-value-initialization, leave it alone. */;
3635 else
3637 tree arraytype, domain;
3638 if (TREE_CONSTANT (nelts))
3639 domain = compute_array_index_type (NULL_TREE, nelts,
3640 complain);
3641 else
3642 /* We'll check the length at runtime. */
3643 domain = NULL_TREE;
3644 arraytype = build_cplus_array_type (type, domain);
3645 /* If we have new char[4]{"foo"}, we have to reshape
3646 so that the STRING_CST isn't wrapped in { }. */
3647 vecinit = reshape_init (arraytype, vecinit, complain);
3648 /* The middle end doesn't cope with the location wrapper
3649 around a STRING_CST. */
3650 STRIP_ANY_LOCATION_WRAPPER (vecinit);
3651 vecinit = digest_init (arraytype, vecinit, complain);
3654 else if (*init)
3656 if (complain & tf_error)
3657 error ("parenthesized initializer in array new");
3658 return error_mark_node;
3660 init_expr
3661 = build_vec_init (data_addr,
3662 cp_build_binary_op (input_location,
3663 MINUS_EXPR, outer_nelts,
3664 integer_one_node,
3665 complain),
3666 vecinit,
3667 explicit_value_init_p,
3668 /*from_array=*/0,
3669 complain);
3671 else
3673 init_expr = cp_build_fold_indirect_ref (data_addr);
3675 if (type_build_ctor_call (type) && !explicit_value_init_p)
3677 init_expr = build_special_member_call (init_expr,
3678 complete_ctor_identifier,
3679 init, elt_type,
3680 LOOKUP_NORMAL,
3681 complain|tf_no_cleanup);
3683 else if (explicit_value_init_p)
3685 /* Something like `new int()'. NO_CLEANUP is needed so
3686 we don't try and build a (possibly ill-formed)
3687 destructor. */
3688 tree val = build_value_init (type, complain | tf_no_cleanup);
3689 if (val == error_mark_node)
3690 return error_mark_node;
3691 init_expr = cp_build_init_expr (init_expr, val);
3693 else
3695 tree ie;
3697 /* We are processing something like `new int (10)', which
3698 means allocate an int, and initialize it with 10.
3700 In C++20, also handle `new A(1, 2)'. */
3701 if (cxx_dialect >= cxx20
3702 && AGGREGATE_TYPE_P (type)
3703 && (*init)->length () > 1)
3705 ie = build_constructor_from_vec (init_list_type_node, *init);
3706 CONSTRUCTOR_IS_DIRECT_INIT (ie) = true;
3707 CONSTRUCTOR_IS_PAREN_INIT (ie) = true;
3708 ie = digest_init (type, ie, complain);
3710 else
3711 ie = build_x_compound_expr_from_vec (*init, "new initializer",
3712 complain);
3713 init_expr = cp_build_modify_expr (input_location, init_expr,
3714 INIT_EXPR, ie, complain);
3716 /* If the initializer uses C++14 aggregate NSDMI that refer to the
3717 object being initialized, replace them now and don't try to
3718 preevaluate. */
3719 bool had_placeholder = false;
3720 if (!processing_template_decl
3721 && TREE_CODE (init_expr) == INIT_EXPR)
3722 TREE_OPERAND (init_expr, 1)
3723 = replace_placeholders (TREE_OPERAND (init_expr, 1),
3724 TREE_OPERAND (init_expr, 0),
3725 &had_placeholder);
3728 if (init_expr == error_mark_node)
3729 return error_mark_node;
3731 else
3732 init_expr = NULL_TREE;
3734 /* If any part of the object initialization terminates by throwing an
3735 exception and a suitable deallocation function can be found, the
3736 deallocation function is called to free the memory in which the
3737 object was being constructed, after which the exception continues
3738 to propagate in the context of the new-expression. If no
3739 unambiguous matching deallocation function can be found,
3740 propagating the exception does not cause the object's memory to be
3741 freed. */
3742 if (flag_exceptions && (init_expr || member_delete_p))
3744 enum tree_code dcode = array_p ? VEC_DELETE_EXPR : DELETE_EXPR;
3745 tree cleanup;
3747 /* The Standard is unclear here, but the right thing to do
3748 is to use the same method for finding deallocation
3749 functions that we use for finding allocation functions. */
3750 cleanup = (build_op_delete_call
3751 (dcode,
3752 alloc_node,
3753 size,
3754 globally_qualified_p,
3755 placement_allocation_fn_p ? alloc_call : NULL_TREE,
3756 alloc_fn,
3757 complain));
3759 if (cleanup && init_expr && !processing_template_decl)
3760 /* Ack! First we allocate the memory. Then we set our sentry
3761 variable to true, and expand a cleanup that deletes the
3762 memory if sentry is true. Then we run the constructor, and
3763 finally clear the sentry.
3765 We need to do this because we allocate the space first, so
3766 if there are any temporaries with cleanups in the
3767 constructor args, we need this EH region to extend until
3768 end of full-expression to preserve nesting.
3770 We used to try to evaluate the args first to avoid this, but
3771 since C++17 [expr.new] says that "The invocation of the
3772 allocation function is sequenced before the evaluations of
3773 expressions in the new-initializer." */
3775 tree end, sentry, begin;
3777 begin = get_target_expr (boolean_true_node);
3778 CLEANUP_EH_ONLY (begin) = 1;
3780 sentry = TARGET_EXPR_SLOT (begin);
3782 /* CLEANUP is compiler-generated, so no diagnostics. */
3783 suppress_warning (cleanup);
3785 TARGET_EXPR_CLEANUP (begin)
3786 = build3 (COND_EXPR, void_type_node, sentry,
3787 cleanup, void_node);
3789 end = build2 (MODIFY_EXPR, TREE_TYPE (sentry),
3790 sentry, boolean_false_node);
3792 init_expr
3793 = build2 (COMPOUND_EXPR, void_type_node, begin,
3794 build2 (COMPOUND_EXPR, void_type_node, init_expr,
3795 end));
3796 /* Likewise, this is compiler-generated. */
3797 suppress_warning (init_expr);
3801 /* Now build up the return value in reverse order. */
3803 rval = data_addr;
3805 if (init_expr)
3806 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_expr, rval);
3807 if (cookie_expr)
3808 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), cookie_expr, rval);
3810 suppress_warning (rval, OPT_Wunused_value);
3812 if (rval == data_addr && TREE_CODE (alloc_expr) == TARGET_EXPR)
3813 /* If we don't have an initializer or a cookie, strip the TARGET_EXPR
3814 and return the call (which doesn't need to be adjusted). */
3815 rval = TARGET_EXPR_INITIAL (alloc_expr);
3816 else
3818 if (check_new)
3820 tree ifexp = cp_build_binary_op (input_location,
3821 NE_EXPR, alloc_node,
3822 nullptr_node,
3823 complain);
3824 rval = build_conditional_expr (input_location, ifexp, rval,
3825 alloc_node, complain);
3828 /* Perform the allocation before anything else, so that ALLOC_NODE
3829 has been initialized before we start using it. */
3830 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), alloc_expr, rval);
3833 /* A new-expression is never an lvalue. */
3834 gcc_assert (!obvalue_p (rval));
3836 return convert (pointer_type, rval);
3839 /* Generate a representation for a C++ "new" expression. *PLACEMENT
3840 is a vector of placement-new arguments (or NULL if none). If NELTS
3841 is NULL, TYPE is the type of the storage to be allocated. If NELTS
3842 is not NULL, then this is an array-new allocation; TYPE is the type
3843 of the elements in the array and NELTS is the number of elements in
3844 the array. *INIT, if non-NULL, is the initializer for the new
3845 object, or an empty vector to indicate an initializer of "()". If
3846 USE_GLOBAL_NEW is true, then the user explicitly wrote "::new"
3847 rather than just "new". This may change PLACEMENT and INIT. */
3849 tree
3850 build_new (location_t loc, vec<tree, va_gc> **placement, tree type,
3851 tree nelts, vec<tree, va_gc> **init, int use_global_new,
3852 tsubst_flags_t complain)
3854 tree rval;
3855 vec<tree, va_gc> *orig_placement = NULL;
3856 tree orig_nelts = NULL_TREE;
3857 vec<tree, va_gc> *orig_init = NULL;
3859 if (type == error_mark_node)
3860 return error_mark_node;
3862 if (nelts == NULL_TREE
3863 /* Don't do auto deduction where it might affect mangling. */
3864 && (!processing_template_decl || at_function_scope_p ()))
3866 tree auto_node = type_uses_auto (type);
3867 if (auto_node)
3869 tree d_init = NULL_TREE;
3870 const size_t len = vec_safe_length (*init);
3871 /* E.g. new auto(x) must have exactly one element, or
3872 a {} initializer will have one element. */
3873 if (len == 1)
3875 d_init = (**init)[0];
3876 d_init = resolve_nondeduced_context (d_init, complain);
3878 /* For the rest, e.g. new A(1, 2, 3), create a list. */
3879 else if (len > 1)
3881 unsigned int n;
3882 tree t;
3883 tree *pp = &d_init;
3884 FOR_EACH_VEC_ELT (**init, n, t)
3886 t = resolve_nondeduced_context (t, complain);
3887 *pp = build_tree_list (NULL_TREE, t);
3888 pp = &TREE_CHAIN (*pp);
3891 type = do_auto_deduction (type, d_init, auto_node, complain);
3895 if (processing_template_decl)
3897 if (dependent_type_p (type)
3898 || any_type_dependent_arguments_p (*placement)
3899 || (nelts && type_dependent_expression_p (nelts))
3900 || (nelts && *init)
3901 || any_type_dependent_arguments_p (*init))
3902 return build_raw_new_expr (loc, *placement, type, nelts, *init,
3903 use_global_new);
3905 orig_placement = make_tree_vector_copy (*placement);
3906 orig_nelts = nelts;
3907 if (*init)
3909 orig_init = make_tree_vector_copy (*init);
3910 /* Also copy any CONSTRUCTORs in *init, since reshape_init and
3911 digest_init clobber them in place. */
3912 for (unsigned i = 0; i < orig_init->length(); ++i)
3914 tree e = (**init)[i];
3915 if (TREE_CODE (e) == CONSTRUCTOR)
3916 (**init)[i] = copy_node (e);
3920 make_args_non_dependent (*placement);
3921 if (nelts)
3922 nelts = build_non_dependent_expr (nelts);
3923 make_args_non_dependent (*init);
3926 if (nelts)
3928 location_t nelts_loc = cp_expr_loc_or_loc (nelts, loc);
3929 if (!build_expr_type_conversion (WANT_INT | WANT_ENUM, nelts, false))
3931 if (complain & tf_error)
3932 permerror (nelts_loc,
3933 "size in array new must have integral type");
3934 else
3935 return error_mark_node;
3938 /* Try to determine the constant value only for the purposes
3939 of the diagnostic below but continue to use the original
3940 value and handle const folding later. */
3941 const_tree cst_nelts = fold_non_dependent_expr (nelts, complain);
3943 /* The expression in a noptr-new-declarator is erroneous if it's of
3944 non-class type and its value before converting to std::size_t is
3945 less than zero. ... If the expression is a constant expression,
3946 the program is ill-fomed. */
3947 if (TREE_CODE (cst_nelts) == INTEGER_CST
3948 && !valid_array_size_p (nelts_loc, cst_nelts, NULL_TREE,
3949 complain & tf_error))
3950 return error_mark_node;
3952 nelts = mark_rvalue_use (nelts);
3953 nelts = cp_save_expr (cp_convert (sizetype, nelts, complain));
3956 /* ``A reference cannot be created by the new operator. A reference
3957 is not an object (8.2.2, 8.4.3), so a pointer to it could not be
3958 returned by new.'' ARM 5.3.3 */
3959 if (TYPE_REF_P (type))
3961 if (complain & tf_error)
3962 error_at (loc, "new cannot be applied to a reference type");
3963 else
3964 return error_mark_node;
3965 type = TREE_TYPE (type);
3968 if (TREE_CODE (type) == FUNCTION_TYPE)
3970 if (complain & tf_error)
3971 error_at (loc, "new cannot be applied to a function type");
3972 return error_mark_node;
3975 /* P1009: Array size deduction in new-expressions. */
3976 const bool array_p = TREE_CODE (type) == ARRAY_TYPE;
3977 if (*init
3978 /* If ARRAY_P, we have to deduce the array bound. For C++20 paren-init,
3979 we have to process the parenthesized-list. But don't do it for (),
3980 which is value-initialization, and INIT should stay empty. */
3981 && (array_p || (cxx_dialect >= cxx20 && nelts && !(*init)->is_empty ())))
3983 /* This means we have 'new T[]()'. */
3984 if ((*init)->is_empty ())
3986 tree ctor = build_constructor (init_list_type_node, NULL);
3987 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
3988 vec_safe_push (*init, ctor);
3990 tree &elt = (**init)[0];
3991 /* The C++20 'new T[](e_0, ..., e_k)' case allowed by P0960. */
3992 if (!DIRECT_LIST_INIT_P (elt) && cxx_dialect >= cxx20)
3994 tree ctor = build_constructor_from_vec (init_list_type_node, *init);
3995 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
3996 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
3997 elt = ctor;
3998 /* We've squashed all the vector elements into the first one;
3999 truncate the rest. */
4000 (*init)->truncate (1);
4002 /* Otherwise we should have 'new T[]{e_0, ..., e_k}'. */
4003 if (array_p && !TYPE_DOMAIN (type))
4005 /* We need to reshape before deducing the bounds to handle code like
4007 struct S { int x, y; };
4008 new S[]{1, 2, 3, 4};
4010 which should deduce S[2]. But don't change ELT itself: we want to
4011 pass a list-initializer to build_new_1, even for STRING_CSTs. */
4012 tree e = elt;
4013 if (BRACE_ENCLOSED_INITIALIZER_P (e))
4014 e = reshape_init (type, e, complain);
4015 cp_complete_array_type (&type, e, /*do_default*/false);
4019 /* The type allocated must be complete. If the new-type-id was
4020 "T[N]" then we are just checking that "T" is complete here, but
4021 that is equivalent, since the value of "N" doesn't matter. */
4022 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
4023 return error_mark_node;
4025 rval = build_new_1 (placement, type, nelts, init, use_global_new, complain);
4026 if (rval == error_mark_node)
4027 return error_mark_node;
4029 if (processing_template_decl)
4031 tree ret = build_raw_new_expr (loc, orig_placement, type, orig_nelts,
4032 orig_init, use_global_new);
4033 release_tree_vector (orig_placement);
4034 release_tree_vector (orig_init);
4035 return ret;
4038 /* Wrap it in a NOP_EXPR so warn_if_unused_value doesn't complain. */
4039 rval = build1_loc (loc, NOP_EXPR, TREE_TYPE (rval), rval);
4040 suppress_warning (rval, OPT_Wunused_value);
4042 return rval;
4045 static tree
4046 build_vec_delete_1 (location_t loc, tree base, tree maxindex, tree type,
4047 special_function_kind auto_delete_vec,
4048 int use_global_delete, tsubst_flags_t complain,
4049 bool in_cleanup = false)
4051 tree virtual_size;
4052 tree ptype = build_pointer_type (type = complete_type (type));
4053 tree size_exp;
4055 /* Temporary variables used by the loop. */
4056 tree tbase, tbase_init;
4058 /* This is the body of the loop that implements the deletion of a
4059 single element, and moves temp variables to next elements. */
4060 tree body;
4062 /* This is the LOOP_EXPR that governs the deletion of the elements. */
4063 tree loop = 0;
4065 /* This is the thing that governs what to do after the loop has run. */
4066 tree deallocate_expr = 0;
4068 /* This is the BIND_EXPR which holds the outermost iterator of the
4069 loop. It is convenient to set this variable up and test it before
4070 executing any other code in the loop.
4071 This is also the containing expression returned by this function. */
4072 tree controller = NULL_TREE;
4073 tree tmp;
4075 /* We should only have 1-D arrays here. */
4076 gcc_assert (TREE_CODE (type) != ARRAY_TYPE);
4078 if (base == error_mark_node || maxindex == error_mark_node)
4079 return error_mark_node;
4081 if (!verify_type_context (loc, TCTX_DEALLOCATION, type,
4082 !(complain & tf_error)))
4083 return error_mark_node;
4085 if (!COMPLETE_TYPE_P (type))
4087 if (complain & tf_warning)
4089 auto_diagnostic_group d;
4090 if (warning_at (loc, OPT_Wdelete_incomplete,
4091 "possible problem detected in invocation of "
4092 "operator %<delete []%>"))
4094 cxx_incomplete_type_diagnostic (base, type, DK_WARNING);
4095 inform (loc, "neither the destructor nor the "
4096 "class-specific operator %<delete []%> will be called, "
4097 "even if they are declared when the class is defined");
4100 /* This size won't actually be used. */
4101 size_exp = size_one_node;
4102 goto no_destructor;
4105 size_exp = size_in_bytes (type);
4107 if (! MAYBE_CLASS_TYPE_P (type))
4108 goto no_destructor;
4109 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
4111 /* Make sure the destructor is callable. */
4112 if (type_build_dtor_call (type))
4114 tmp = build_delete (loc, ptype, base, sfk_complete_destructor,
4115 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
4116 complain);
4117 if (tmp == error_mark_node)
4118 return error_mark_node;
4120 goto no_destructor;
4123 /* The below is short by the cookie size. */
4124 virtual_size = size_binop (MULT_EXPR, size_exp,
4125 fold_convert (sizetype, maxindex));
4127 tbase = create_temporary_var (ptype);
4128 DECL_INITIAL (tbase)
4129 = fold_build_pointer_plus_loc (loc, fold_convert (ptype, base),
4130 virtual_size);
4131 tbase_init = build_stmt (loc, DECL_EXPR, tbase);
4132 controller = build3 (BIND_EXPR, void_type_node, tbase, NULL_TREE, NULL_TREE);
4133 TREE_SIDE_EFFECTS (controller) = 1;
4134 BIND_EXPR_VEC_DTOR (controller) = true;
4136 body = build1 (EXIT_EXPR, void_type_node,
4137 build2 (EQ_EXPR, boolean_type_node, tbase,
4138 fold_convert (ptype, base)));
4139 tmp = fold_build1_loc (loc, NEGATE_EXPR, sizetype, size_exp);
4140 tmp = fold_build_pointer_plus (tbase, tmp);
4141 tmp = cp_build_modify_expr (loc, tbase, NOP_EXPR, tmp, complain);
4142 if (tmp == error_mark_node)
4143 return error_mark_node;
4144 body = build_compound_expr (loc, body, tmp);
4145 tmp = build_delete (loc, ptype, tbase, sfk_complete_destructor,
4146 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
4147 complain);
4148 if (tmp == error_mark_node)
4149 return error_mark_node;
4150 body = build_compound_expr (loc, body, tmp);
4152 loop = build1 (LOOP_EXPR, void_type_node, body);
4154 /* If one destructor throws, keep trying to clean up the rest, unless we're
4155 already in a build_vec_init cleanup. */
4156 if (flag_exceptions && !in_cleanup && !expr_noexcept_p (tmp, tf_none))
4158 loop = build2 (TRY_CATCH_EXPR, void_type_node, loop,
4159 unshare_expr (loop));
4160 /* Tell honor_protect_cleanup_actions to discard this on the
4161 exceptional path. */
4162 TRY_CATCH_IS_CLEANUP (loop) = true;
4165 loop = build_compound_expr (loc, tbase_init, loop);
4167 no_destructor:
4168 /* Delete the storage if appropriate. */
4169 if (auto_delete_vec == sfk_deleting_destructor)
4171 tree base_tbd;
4173 /* The below is short by the cookie size. */
4174 virtual_size = size_binop (MULT_EXPR, size_exp,
4175 fold_convert (sizetype, maxindex));
4177 if (! TYPE_VEC_NEW_USES_COOKIE (type))
4178 /* no header */
4179 base_tbd = base;
4180 else
4182 tree cookie_size;
4184 cookie_size = targetm.cxx.get_cookie_size (type);
4185 base_tbd = cp_build_binary_op (loc,
4186 MINUS_EXPR,
4187 cp_convert (string_type_node,
4188 base, complain),
4189 cookie_size,
4190 complain);
4191 if (base_tbd == error_mark_node)
4192 return error_mark_node;
4193 base_tbd = cp_convert (ptype, base_tbd, complain);
4194 /* True size with header. */
4195 virtual_size = size_binop (PLUS_EXPR, virtual_size, cookie_size);
4198 deallocate_expr = build_op_delete_call (VEC_DELETE_EXPR,
4199 base_tbd, virtual_size,
4200 use_global_delete & 1,
4201 /*placement=*/NULL_TREE,
4202 /*alloc_fn=*/NULL_TREE,
4203 complain);
4206 body = loop;
4207 if (deallocate_expr == error_mark_node)
4208 return error_mark_node;
4209 else if (!deallocate_expr)
4211 else if (!body)
4212 body = deallocate_expr;
4213 else
4214 /* The delete operator must be called, even if a destructor
4215 throws. */
4216 body = build2 (TRY_FINALLY_EXPR, void_type_node, body, deallocate_expr);
4218 if (!body)
4219 body = integer_zero_node;
4221 /* Outermost wrapper: If pointer is null, punt. */
4222 tree cond = build2_loc (loc, NE_EXPR, boolean_type_node, base,
4223 fold_convert (TREE_TYPE (base), nullptr_node));
4224 /* This is a compiler generated comparison, don't emit
4225 e.g. -Wnonnull-compare warning for it. */
4226 suppress_warning (cond, OPT_Wnonnull_compare);
4227 body = build3_loc (loc, COND_EXPR, void_type_node,
4228 cond, body, integer_zero_node);
4229 COND_EXPR_IS_VEC_DELETE (body) = true;
4230 body = build1 (NOP_EXPR, void_type_node, body);
4232 if (controller)
4234 TREE_OPERAND (controller, 1) = body;
4235 body = controller;
4238 if (TREE_CODE (base) == SAVE_EXPR)
4239 /* Pre-evaluate the SAVE_EXPR outside of the BIND_EXPR. */
4240 body = build2 (COMPOUND_EXPR, void_type_node, base, body);
4242 return convert_to_void (body, ICV_CAST, complain);
4245 /* Create an unnamed variable of the indicated TYPE. */
4247 tree
4248 create_temporary_var (tree type)
4250 tree decl;
4252 decl = build_decl (input_location,
4253 VAR_DECL, NULL_TREE, type);
4254 TREE_USED (decl) = 1;
4255 DECL_ARTIFICIAL (decl) = 1;
4256 DECL_IGNORED_P (decl) = 1;
4257 DECL_CONTEXT (decl) = current_function_decl;
4259 return decl;
4262 /* Create a new temporary variable of the indicated TYPE, initialized
4263 to INIT.
4265 It is not entered into current_binding_level, because that breaks
4266 things when it comes time to do final cleanups (which take place
4267 "outside" the binding contour of the function). */
4269 tree
4270 get_temp_regvar (tree type, tree init)
4272 tree decl;
4274 decl = create_temporary_var (type);
4275 add_decl_expr (decl);
4277 finish_expr_stmt (cp_build_modify_expr (input_location, decl, INIT_EXPR,
4278 init, tf_warning_or_error));
4280 return decl;
4283 /* Subroutine of build_vec_init. Returns true if assigning to an array of
4284 INNER_ELT_TYPE from INIT is trivial. */
4286 static bool
4287 vec_copy_assign_is_trivial (tree inner_elt_type, tree init)
4289 tree fromtype = inner_elt_type;
4290 if (lvalue_p (init))
4291 fromtype = cp_build_reference_type (fromtype, /*rval*/false);
4292 return is_trivially_xible (MODIFY_EXPR, inner_elt_type, fromtype);
4295 /* Subroutine of build_vec_init: Check that the array has at least N
4296 elements. Other parameters are local variables in build_vec_init. */
4298 void
4299 finish_length_check (tree atype, tree iterator, tree obase, unsigned n)
4301 tree nelts = build_int_cst (ptrdiff_type_node, n - 1);
4302 if (TREE_CODE (atype) != ARRAY_TYPE)
4304 if (flag_exceptions)
4306 tree c = fold_build2 (LT_EXPR, boolean_type_node, iterator,
4307 nelts);
4308 c = build3 (COND_EXPR, void_type_node, c,
4309 throw_bad_array_new_length (), void_node);
4310 finish_expr_stmt (c);
4312 /* Don't check an array new when -fno-exceptions. */
4314 else if (sanitize_flags_p (SANITIZE_BOUNDS)
4315 && current_function_decl != NULL_TREE)
4317 /* Make sure the last element of the initializer is in bounds. */
4318 finish_expr_stmt
4319 (ubsan_instrument_bounds
4320 (input_location, obase, &nelts, /*ignore_off_by_one*/false));
4324 /* walk_tree callback to collect temporaries in an expression. */
4326 tree
4327 find_temps_r (tree *tp, int *walk_subtrees, void *data)
4329 vec<tree*> &temps = *static_cast<auto_vec<tree*> *>(data);
4330 tree t = *tp;
4331 if (TREE_CODE (t) == TARGET_EXPR
4332 && !TARGET_EXPR_ELIDING_P (t))
4333 temps.safe_push (tp);
4334 else if (TYPE_P (t))
4335 *walk_subtrees = 0;
4337 return NULL_TREE;
4340 /* walk_tree callback to collect temporaries in an expression that
4341 are allocator arguments to standard library classes. */
4343 static tree
4344 find_allocator_temps_r (tree *tp, int *walk_subtrees, void *data)
4346 vec<tree*> &temps = *static_cast<auto_vec<tree*> *>(data);
4347 tree t = *tp;
4348 if (TYPE_P (t))
4350 *walk_subtrees = 0;
4351 return NULL_TREE;
4354 /* If this is a call to a constructor for a std:: class, look for
4355 a reference-to-allocator argument. */
4356 tree fn = cp_get_callee_fndecl_nofold (t);
4357 if (fn && DECL_CONSTRUCTOR_P (fn)
4358 && decl_in_std_namespace_p (TYPE_NAME (DECL_CONTEXT (fn))))
4360 int nargs = call_expr_nargs (t);
4361 for (int i = 1; i < nargs; ++i)
4363 tree arg = get_nth_callarg (t, i);
4364 tree atype = TREE_TYPE (arg);
4365 if (TREE_CODE (atype) == REFERENCE_TYPE
4366 && is_std_allocator (TREE_TYPE (atype)))
4368 STRIP_NOPS (arg);
4369 if (TREE_CODE (arg) == ADDR_EXPR)
4371 tree *ap = &TREE_OPERAND (arg, 0);
4372 if (TREE_CODE (*ap) == TARGET_EXPR)
4373 temps.safe_push (ap);
4379 return NULL_TREE;
4382 /* If INIT initializes a standard library class, and involves a temporary
4383 std::allocator<T>, use ALLOC_OBJ for all such temporaries.
4385 Note that this can clobber the input to build_vec_init; no unsharing is
4386 done. To make this safe we use the TARGET_EXPR in all places rather than
4387 pulling out the TARGET_EXPR_SLOT.
4389 Used by build_vec_init when initializing an array of e.g. strings to reuse
4390 the same temporary allocator for all of the strings. We can do this because
4391 std::allocator has no data and the standard library doesn't care about the
4392 address of allocator objects.
4394 ??? Add an attribute to allow users to assert the same property for other
4395 classes, i.e. one object of the type is interchangeable with any other? */
4397 static void
4398 combine_allocator_temps (tree &init, tree &alloc_obj)
4400 auto_vec<tree*> temps;
4401 cp_walk_tree_without_duplicates (&init, find_allocator_temps_r, &temps);
4402 for (tree *p : temps)
4404 if (!alloc_obj)
4405 alloc_obj = *p;
4406 else
4407 *p = alloc_obj;
4411 /* `build_vec_init' returns tree structure that performs
4412 initialization of a vector of aggregate types.
4414 BASE is a reference to the vector, of ARRAY_TYPE, or a pointer
4415 to the first element, of POINTER_TYPE.
4416 MAXINDEX is the maximum index of the array (one less than the
4417 number of elements). It is only used if BASE is a pointer or
4418 TYPE_DOMAIN (TREE_TYPE (BASE)) == NULL_TREE.
4420 INIT is the (possibly NULL) initializer.
4422 If EXPLICIT_VALUE_INIT_P is true, then INIT must be NULL. All
4423 elements in the array are value-initialized.
4425 FROM_ARRAY is 0 if we should init everything with INIT
4426 (i.e., every element initialized from INIT).
4427 FROM_ARRAY is 1 if we should index into INIT in parallel
4428 with initialization of DECL.
4429 FROM_ARRAY is 2 if we should index into INIT in parallel,
4430 but use assignment instead of initialization. */
4432 tree
4433 build_vec_init (tree base, tree maxindex, tree init,
4434 bool explicit_value_init_p,
4435 int from_array,
4436 tsubst_flags_t complain,
4437 vec<tree, va_gc>** cleanup_flags /* = nullptr */)
4439 tree rval;
4440 tree base2 = NULL_TREE;
4441 tree itype = NULL_TREE;
4442 tree iterator;
4443 /* The type of BASE. */
4444 tree atype = TREE_TYPE (base);
4445 /* The type of an element in the array. */
4446 tree type = TREE_TYPE (atype);
4447 /* The element type reached after removing all outer array
4448 types. */
4449 tree inner_elt_type;
4450 /* The type of a pointer to an element in the array. */
4451 tree ptype;
4452 tree stmt_expr;
4453 tree compound_stmt;
4454 int destroy_temps;
4455 HOST_WIDE_INT num_initialized_elts = 0;
4456 bool is_global;
4457 tree obase = base;
4458 bool xvalue = false;
4459 bool errors = false;
4460 location_t loc = (init ? cp_expr_loc_or_input_loc (init)
4461 : location_of (base));
4463 if (TREE_CODE (atype) == ARRAY_TYPE && TYPE_DOMAIN (atype))
4464 maxindex = array_type_nelts (atype);
4466 if (maxindex == NULL_TREE || maxindex == error_mark_node)
4467 return error_mark_node;
4469 maxindex = maybe_constant_value (maxindex);
4470 if (explicit_value_init_p)
4471 gcc_assert (!init);
4473 inner_elt_type = strip_array_types (type);
4475 /* Look through the TARGET_EXPR around a compound literal. */
4476 if (init && TREE_CODE (init) == TARGET_EXPR
4477 && TREE_CODE (TARGET_EXPR_INITIAL (init)) == CONSTRUCTOR
4478 && from_array != 2)
4479 init = TARGET_EXPR_INITIAL (init);
4481 if (tree vi = get_vec_init_expr (init))
4482 init = VEC_INIT_EXPR_INIT (vi);
4484 bool direct_init = false;
4485 if (from_array && init && BRACE_ENCLOSED_INITIALIZER_P (init)
4486 && CONSTRUCTOR_NELTS (init) == 1)
4488 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
4489 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
4490 && TREE_CODE (elt) != VEC_INIT_EXPR)
4492 direct_init = DIRECT_LIST_INIT_P (init);
4493 init = elt;
4497 /* from_array doesn't apply to initialization from CONSTRUCTOR. */
4498 if (init && TREE_CODE (init) == CONSTRUCTOR)
4499 from_array = 0;
4501 /* If we have a braced-init-list or string constant, make sure that the array
4502 is big enough for all the initializers. */
4503 bool length_check = (init
4504 && (TREE_CODE (init) == STRING_CST
4505 || (TREE_CODE (init) == CONSTRUCTOR
4506 && CONSTRUCTOR_NELTS (init) > 0))
4507 && !TREE_CONSTANT (maxindex));
4509 if (init
4510 && TREE_CODE (atype) == ARRAY_TYPE
4511 && TREE_CONSTANT (maxindex)
4512 && !vla_type_p (type)
4513 && (from_array == 2
4514 ? vec_copy_assign_is_trivial (inner_elt_type, init)
4515 : !TYPE_NEEDS_CONSTRUCTING (type))
4516 && ((TREE_CODE (init) == CONSTRUCTOR
4517 && (BRACE_ENCLOSED_INITIALIZER_P (init)
4518 || (same_type_ignoring_top_level_qualifiers_p
4519 (atype, TREE_TYPE (init))))
4520 /* Don't do this if the CONSTRUCTOR might contain something
4521 that might throw and require us to clean up. */
4522 && (vec_safe_is_empty (CONSTRUCTOR_ELTS (init))
4523 || ! TYPE_HAS_NONTRIVIAL_DESTRUCTOR (inner_elt_type)))
4524 || from_array))
4526 /* Do non-default initialization of trivial arrays resulting from
4527 brace-enclosed initializers. In this case, digest_init and
4528 store_constructor will handle the semantics for us. */
4530 if (BRACE_ENCLOSED_INITIALIZER_P (init))
4531 init = digest_init (atype, init, complain);
4532 stmt_expr = cp_build_init_expr (base, init);
4533 return stmt_expr;
4536 maxindex = cp_convert (ptrdiff_type_node, maxindex, complain);
4537 maxindex = fold_simple (maxindex);
4539 if (TREE_CODE (atype) == ARRAY_TYPE)
4541 ptype = build_pointer_type (type);
4542 base = decay_conversion (base, complain);
4543 if (base == error_mark_node)
4544 return error_mark_node;
4545 base = cp_convert (ptype, base, complain);
4547 else
4548 ptype = atype;
4550 if (integer_all_onesp (maxindex))
4552 /* Shortcut zero element case to avoid unneeded constructor synthesis. */
4553 if (init && TREE_SIDE_EFFECTS (init))
4554 base = build2 (COMPOUND_EXPR, ptype, init, base);
4555 return base;
4558 /* The code we are generating looks like:
4560 T* t1 = (T*) base;
4561 T* rval = t1;
4562 ptrdiff_t iterator = maxindex;
4563 try {
4564 for (; iterator != -1; --iterator) {
4565 ... initialize *t1 ...
4566 ++t1;
4568 } catch (...) {
4569 ... destroy elements that were constructed ...
4571 rval;
4574 We can omit the try and catch blocks if we know that the
4575 initialization will never throw an exception, or if the array
4576 elements do not have destructors. We can omit the loop completely if
4577 the elements of the array do not have constructors.
4579 We actually wrap the entire body of the above in a STMT_EXPR, for
4580 tidiness.
4582 When copying from array to another, when the array elements have
4583 only trivial copy constructors, we should use __builtin_memcpy
4584 rather than generating a loop. That way, we could take advantage
4585 of whatever cleverness the back end has for dealing with copies
4586 of blocks of memory. */
4588 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
4589 destroy_temps = stmts_are_full_exprs_p ();
4590 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4591 rval = get_temp_regvar (ptype, base);
4592 base = get_temp_regvar (ptype, rval);
4593 tree iterator_targ = get_target_expr (maxindex);
4594 add_stmt (iterator_targ);
4595 iterator = TARGET_EXPR_SLOT (iterator_targ);
4597 /* If initializing one array from another, initialize element by
4598 element. We rely upon the below calls to do the argument
4599 checking. Evaluate the initializer before entering the try block. */
4600 if (from_array)
4602 if (lvalue_kind (init) & clk_rvalueref)
4603 xvalue = true;
4604 base2 = decay_conversion (init, complain);
4605 if (base2 == error_mark_node)
4606 return error_mark_node;
4607 itype = TREE_TYPE (base2);
4608 base2 = get_temp_regvar (itype, base2);
4609 itype = TREE_TYPE (itype);
4612 /* Protect the entire array initialization so that we can destroy
4613 the partially constructed array if an exception is thrown.
4614 But don't do this if we're assigning. */
4615 if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4616 && from_array != 2)
4618 tree e;
4619 tree m = cp_build_binary_op (input_location,
4620 MINUS_EXPR, maxindex, iterator,
4621 complain);
4623 /* Flatten multi-dimensional array since build_vec_delete only
4624 expects one-dimensional array. */
4625 if (TREE_CODE (type) == ARRAY_TYPE)
4626 m = cp_build_binary_op (input_location,
4627 MULT_EXPR, m,
4628 /* Avoid mixing signed and unsigned. */
4629 convert (TREE_TYPE (m),
4630 array_type_nelts_total (type)),
4631 complain);
4633 e = build_vec_delete_1 (input_location, rval, m,
4634 inner_elt_type, sfk_complete_destructor,
4635 /*use_global_delete=*/0, complain,
4636 /*in_cleanup*/true);
4637 if (e == error_mark_node)
4638 errors = true;
4639 TARGET_EXPR_CLEANUP (iterator_targ) = e;
4640 CLEANUP_EH_ONLY (iterator_targ) = true;
4642 /* Since we push this cleanup before doing any initialization, cleanups
4643 for any temporaries in the initialization are naturally within our
4644 cleanup region, so we don't want wrap_temporary_cleanups to do
4645 anything for arrays. But if the array is a subobject, we need to
4646 tell split_nonconstant_init how to turn off this cleanup in favor of
4647 the cleanup for the complete object. */
4648 if (cleanup_flags)
4649 vec_safe_push (*cleanup_flags, build_tree_list (iterator, maxindex));
4652 /* Should we try to create a constant initializer? */
4653 bool try_const = (TREE_CODE (atype) == ARRAY_TYPE
4654 && TREE_CONSTANT (maxindex)
4655 && (init ? TREE_CODE (init) == CONSTRUCTOR
4656 : (type_has_constexpr_default_constructor
4657 (inner_elt_type)))
4658 && (literal_type_p (inner_elt_type)
4659 || TYPE_HAS_CONSTEXPR_CTOR (inner_elt_type)));
4660 vec<constructor_elt, va_gc> *const_vec = NULL;
4661 bool saw_non_const = false;
4662 /* If we're initializing a static array, we want to do static
4663 initialization of any elements with constant initializers even if
4664 some are non-constant. */
4665 bool do_static_init = (DECL_P (obase) && TREE_STATIC (obase));
4667 bool empty_list = false;
4668 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
4669 && CONSTRUCTOR_NELTS (init) == 0)
4670 /* Skip over the handling of non-empty init lists. */
4671 empty_list = true;
4673 /* Maybe pull out constant value when from_array? */
4675 else if (init != NULL_TREE && TREE_CODE (init) == CONSTRUCTOR)
4677 /* Do non-default initialization of non-trivial arrays resulting from
4678 brace-enclosed initializers. */
4679 unsigned HOST_WIDE_INT idx;
4680 tree field, elt;
4681 /* If the constructor already has the array type, it's been through
4682 digest_init, so we shouldn't try to do anything more. */
4683 bool digested = same_type_p (atype, TREE_TYPE (init));
4684 from_array = 0;
4686 if (length_check)
4687 finish_length_check (atype, iterator, obase, CONSTRUCTOR_NELTS (init));
4689 if (try_const)
4690 vec_alloc (const_vec, CONSTRUCTOR_NELTS (init));
4692 tree alloc_obj = NULL_TREE;
4694 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
4696 tree baseref = build1 (INDIRECT_REF, type, base);
4697 tree one_init;
4699 num_initialized_elts++;
4701 /* We need to see sub-array TARGET_EXPR before cp_fold_r so we can
4702 handle cleanup flags properly. */
4703 gcc_checking_assert (!target_expr_needs_replace (elt));
4705 if (digested)
4706 one_init = cp_build_init_expr (baseref, elt);
4707 else if (tree vi = get_vec_init_expr (elt))
4708 one_init = expand_vec_init_expr (baseref, vi, complain,
4709 cleanup_flags);
4710 else if (MAYBE_CLASS_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE)
4711 one_init = build_aggr_init (baseref, elt, 0, complain);
4712 else
4713 one_init = cp_build_modify_expr (input_location, baseref,
4714 NOP_EXPR, elt, complain);
4715 if (one_init == error_mark_node)
4716 errors = true;
4717 if (try_const)
4719 if (!field)
4720 field = size_int (idx);
4721 tree e = maybe_constant_init (one_init);
4722 if (reduced_constant_expression_p (e))
4724 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4725 if (do_static_init)
4726 one_init = NULL_TREE;
4727 else
4728 one_init = cp_build_init_expr (baseref, e);
4730 else
4732 if (do_static_init)
4734 tree value = build_zero_init (TREE_TYPE (e), NULL_TREE,
4735 true);
4736 if (value)
4737 CONSTRUCTOR_APPEND_ELT (const_vec, field, value);
4739 saw_non_const = true;
4743 if (one_init)
4745 /* Only create one std::allocator temporary. */
4746 combine_allocator_temps (one_init, alloc_obj);
4747 finish_expr_stmt (one_init);
4750 one_init = cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4751 complain);
4752 if (one_init == error_mark_node)
4753 errors = true;
4754 else
4755 finish_expr_stmt (one_init);
4757 one_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4758 complain);
4759 if (one_init == error_mark_node)
4760 errors = true;
4761 else
4762 finish_expr_stmt (one_init);
4765 /* Any elements without explicit initializers get T{}. */
4766 empty_list = true;
4768 else if (init && TREE_CODE (init) == STRING_CST)
4770 /* Check that the array is at least as long as the string. */
4771 if (length_check)
4772 finish_length_check (atype, iterator, obase,
4773 TREE_STRING_LENGTH (init));
4774 tree length = build_int_cst (ptrdiff_type_node,
4775 TREE_STRING_LENGTH (init));
4777 /* Copy the string to the first part of the array. */
4778 tree alias_set = build_int_cst (build_pointer_type (type), 0);
4779 tree lhs = build2 (MEM_REF, TREE_TYPE (init), base, alias_set);
4780 tree stmt = build2 (MODIFY_EXPR, void_type_node, lhs, init);
4781 finish_expr_stmt (stmt);
4783 /* Adjust the counter and pointer. */
4784 stmt = cp_build_binary_op (loc, MINUS_EXPR, iterator, length, complain);
4785 stmt = build2 (MODIFY_EXPR, void_type_node, iterator, stmt);
4786 finish_expr_stmt (stmt);
4788 stmt = cp_build_binary_op (loc, PLUS_EXPR, base, length, complain);
4789 stmt = build2 (MODIFY_EXPR, void_type_node, base, stmt);
4790 finish_expr_stmt (stmt);
4792 /* And set the rest of the array to NUL. */
4793 from_array = 0;
4794 explicit_value_init_p = true;
4796 else if (from_array)
4798 if (init)
4799 /* OK, we set base2 above. */;
4800 else if (CLASS_TYPE_P (type)
4801 && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
4803 if (complain & tf_error)
4804 error ("initializer ends prematurely");
4805 errors = true;
4809 /* Now, default-initialize any remaining elements. We don't need to
4810 do that if a) the type does not need constructing, or b) we've
4811 already initialized all the elements.
4813 We do need to keep going if we're copying an array. */
4815 if (try_const && !init
4816 && (cxx_dialect < cxx20
4817 || !default_init_uninitialized_part (inner_elt_type)))
4818 /* With a constexpr default constructor, which we checked for when
4819 setting try_const above, default-initialization is equivalent to
4820 value-initialization, and build_value_init gives us something more
4821 friendly to maybe_constant_init. Except in C++20 and up a constexpr
4822 constructor need not initialize all the members. */
4823 explicit_value_init_p = true;
4824 if (from_array
4825 || ((type_build_ctor_call (type) || init || explicit_value_init_p)
4826 && ! (tree_fits_shwi_p (maxindex)
4827 && (num_initialized_elts
4828 == tree_to_shwi (maxindex) + 1))))
4830 /* If the ITERATOR is lesser or equal to -1, then we don't have to loop;
4831 we've already initialized all the elements. */
4832 tree for_stmt;
4833 tree elt_init;
4834 tree to;
4836 for_stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
4837 finish_init_stmt (for_stmt);
4838 finish_for_cond (build2 (GT_EXPR, boolean_type_node, iterator,
4839 build_int_cst (TREE_TYPE (iterator), -1)),
4840 for_stmt, false, 0);
4841 /* We used to pass this decrement to finish_for_expr; now we add it to
4842 elt_init below so it's part of the same full-expression as the
4843 initialization, and thus happens before any potentially throwing
4844 temporary cleanups. */
4845 tree decr = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4846 complain);
4849 to = build1 (INDIRECT_REF, type, base);
4851 /* If the initializer is {}, then all elements are initialized from T{}.
4852 But for non-classes, that's the same as value-initialization. */
4853 if (empty_list)
4855 if (cxx_dialect >= cxx11 && AGGREGATE_TYPE_P (type))
4857 init = build_constructor (init_list_type_node, NULL);
4859 else
4861 init = NULL_TREE;
4862 explicit_value_init_p = true;
4866 if (from_array)
4868 tree from;
4870 if (base2)
4872 from = build1 (INDIRECT_REF, itype, base2);
4873 if (xvalue)
4874 from = move (from);
4875 if (direct_init)
4876 from = build_tree_list (NULL_TREE, from);
4878 else
4879 from = NULL_TREE;
4881 if (TREE_CODE (type) == ARRAY_TYPE)
4882 elt_init = build_vec_init (to, NULL_TREE, from, /*val_init*/false,
4883 from_array, complain);
4884 else if (from_array == 2)
4885 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR,
4886 from, complain);
4887 else if (type_build_ctor_call (type))
4888 elt_init = build_aggr_init (to, from, 0, complain);
4889 else if (from)
4890 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR, from,
4891 complain);
4892 else
4893 gcc_unreachable ();
4895 else if (TREE_CODE (type) == ARRAY_TYPE)
4897 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init))
4899 if ((complain & tf_error))
4900 error_at (loc, "array must be initialized "
4901 "with a brace-enclosed initializer");
4902 elt_init = error_mark_node;
4904 else
4905 elt_init = build_vec_init (build1 (INDIRECT_REF, type, base),
4906 0, init,
4907 explicit_value_init_p,
4908 0, complain);
4910 else if (explicit_value_init_p)
4912 elt_init = build_value_init (type, complain);
4913 if (elt_init != error_mark_node)
4914 elt_init = cp_build_init_expr (to, elt_init);
4916 else
4918 gcc_assert (type_build_ctor_call (type) || init);
4919 if (CLASS_TYPE_P (type))
4920 elt_init = build_aggr_init (to, init, 0, complain);
4921 else
4923 if (TREE_CODE (init) == TREE_LIST)
4924 init = build_x_compound_expr_from_list (init, ELK_INIT,
4925 complain);
4926 elt_init = (init == error_mark_node
4927 ? error_mark_node
4928 : build2 (INIT_EXPR, type, to, init));
4932 if (elt_init == error_mark_node)
4933 errors = true;
4935 if (try_const)
4937 /* FIXME refs to earlier elts */
4938 tree e = maybe_constant_init (elt_init);
4939 if (reduced_constant_expression_p (e))
4941 if (initializer_zerop (e))
4942 /* Don't fill the CONSTRUCTOR with zeros. */
4943 e = NULL_TREE;
4944 if (do_static_init)
4945 elt_init = NULL_TREE;
4947 else
4949 saw_non_const = true;
4950 if (do_static_init)
4951 e = build_zero_init (TREE_TYPE (e), NULL_TREE, true);
4952 else
4953 e = NULL_TREE;
4956 if (e)
4958 HOST_WIDE_INT last = tree_to_shwi (maxindex);
4959 if (num_initialized_elts <= last)
4961 tree field = size_int (num_initialized_elts);
4962 if (num_initialized_elts != last)
4963 field = build2 (RANGE_EXPR, sizetype, field,
4964 size_int (last));
4965 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4970 /* [class.temporary]: "There are three contexts in which temporaries are
4971 destroyed at a different point than the end of the full-
4972 expression. The first context is when a default constructor is called
4973 to initialize an element of an array with no corresponding
4974 initializer. The second context is when a copy constructor is called
4975 to copy an element of an array while the entire array is copied. In
4976 either case, if the constructor has one or more default arguments, the
4977 destruction of every temporary created in a default argument is
4978 sequenced before the construction of the next array element, if any."
4980 So, for this loop, statements are full-expressions. */
4981 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
4982 if (elt_init && !errors)
4983 elt_init = build2 (COMPOUND_EXPR, void_type_node, elt_init, decr);
4984 else
4985 elt_init = decr;
4986 finish_expr_stmt (elt_init);
4987 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4989 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4990 complain));
4991 if (base2)
4992 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base2, false,
4993 complain));
4995 finish_for_stmt (for_stmt);
4998 /* The value of the array initialization is the array itself, RVAL
4999 is a pointer to the first element. */
5000 finish_stmt_expr_expr (rval, stmt_expr);
5002 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
5004 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
5006 if (errors)
5007 return error_mark_node;
5009 if (try_const)
5011 if (!saw_non_const)
5013 tree const_init = build_constructor (atype, const_vec);
5014 return build2 (INIT_EXPR, atype, obase, const_init);
5016 else if (do_static_init && !vec_safe_is_empty (const_vec))
5017 DECL_INITIAL (obase) = build_constructor (atype, const_vec);
5018 else
5019 vec_free (const_vec);
5022 /* Now make the result have the correct type. */
5023 if (TREE_CODE (atype) == ARRAY_TYPE)
5025 atype = build_reference_type (atype);
5026 stmt_expr = build1 (NOP_EXPR, atype, stmt_expr);
5027 stmt_expr = convert_from_reference (stmt_expr);
5030 return stmt_expr;
5033 /* Call the DTOR_KIND destructor for EXP. FLAGS are as for
5034 build_delete. */
5036 static tree
5037 build_dtor_call (tree exp, special_function_kind dtor_kind, int flags,
5038 tsubst_flags_t complain)
5040 tree name;
5041 switch (dtor_kind)
5043 case sfk_complete_destructor:
5044 name = complete_dtor_identifier;
5045 break;
5047 case sfk_base_destructor:
5048 name = base_dtor_identifier;
5049 break;
5051 case sfk_deleting_destructor:
5052 name = deleting_dtor_identifier;
5053 break;
5055 default:
5056 gcc_unreachable ();
5059 return build_special_member_call (exp, name,
5060 /*args=*/NULL,
5061 /*binfo=*/TREE_TYPE (exp),
5062 flags,
5063 complain);
5066 /* Generate a call to a destructor. TYPE is the type to cast ADDR to.
5067 ADDR is an expression which yields the store to be destroyed.
5068 AUTO_DELETE is the name of the destructor to call, i.e., either
5069 sfk_complete_destructor, sfk_base_destructor, or
5070 sfk_deleting_destructor.
5072 FLAGS is the logical disjunction of zero or more LOOKUP_
5073 flags. See cp-tree.h for more info. */
5075 tree
5076 build_delete (location_t loc, tree otype, tree addr,
5077 special_function_kind auto_delete,
5078 int flags, int use_global_delete, tsubst_flags_t complain)
5080 tree expr;
5082 if (addr == error_mark_node)
5083 return error_mark_node;
5085 tree type = TYPE_MAIN_VARIANT (otype);
5087 /* Can happen when CURRENT_EXCEPTION_OBJECT gets its type
5088 set to `error_mark_node' before it gets properly cleaned up. */
5089 if (type == error_mark_node)
5090 return error_mark_node;
5092 if (TYPE_PTR_P (type))
5093 type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
5095 if (TREE_CODE (type) == ARRAY_TYPE)
5097 if (TYPE_DOMAIN (type) == NULL_TREE)
5099 if (complain & tf_error)
5100 error_at (loc, "unknown array size in delete");
5101 return error_mark_node;
5103 return build_vec_delete (loc, addr, array_type_nelts (type),
5104 auto_delete, use_global_delete, complain);
5107 bool deleting = (auto_delete == sfk_deleting_destructor);
5108 gcc_assert (deleting == !(flags & LOOKUP_DESTRUCTOR));
5110 if (TYPE_PTR_P (otype))
5112 addr = mark_rvalue_use (addr);
5114 /* We don't want to warn about delete of void*, only other
5115 incomplete types. Deleting other incomplete types
5116 invokes undefined behavior, but it is not ill-formed, so
5117 compile to something that would even do The Right Thing
5118 (TM) should the type have a trivial dtor and no delete
5119 operator. */
5120 if (!VOID_TYPE_P (type))
5122 complete_type (type);
5123 if (deleting
5124 && !verify_type_context (loc, TCTX_DEALLOCATION, type,
5125 !(complain & tf_error)))
5126 return error_mark_node;
5128 if (!COMPLETE_TYPE_P (type))
5130 if (complain & tf_warning)
5132 auto_diagnostic_group d;
5133 if (warning_at (loc, OPT_Wdelete_incomplete,
5134 "possible problem detected in invocation of "
5135 "%<operator delete%>"))
5137 cxx_incomplete_type_diagnostic (addr, type, DK_WARNING);
5138 inform (loc,
5139 "neither the destructor nor the class-specific "
5140 "%<operator delete%> will be called, even if "
5141 "they are declared when the class is defined");
5145 else if (deleting && warn_delnonvdtor
5146 && MAYBE_CLASS_TYPE_P (type) && !CLASSTYPE_FINAL (type)
5147 && TYPE_POLYMORPHIC_P (type))
5149 tree dtor = CLASSTYPE_DESTRUCTOR (type);
5150 if (!dtor || !DECL_VINDEX (dtor))
5152 if (CLASSTYPE_PURE_VIRTUALS (type))
5153 warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5154 "deleting object of abstract class type %qT"
5155 " which has non-virtual destructor"
5156 " will cause undefined behavior", type);
5157 else
5158 warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5159 "deleting object of polymorphic class type %qT"
5160 " which has non-virtual destructor"
5161 " might cause undefined behavior", type);
5166 /* Throw away const and volatile on target type of addr. */
5167 addr = convert_force (build_pointer_type (type), addr, 0, complain);
5169 else
5171 /* Don't check PROTECT here; leave that decision to the
5172 destructor. If the destructor is accessible, call it,
5173 else report error. */
5174 addr = cp_build_addr_expr (addr, complain);
5175 if (addr == error_mark_node)
5176 return error_mark_node;
5178 addr = convert_force (build_pointer_type (type), addr, 0, complain);
5181 if (deleting)
5182 /* We will use ADDR multiple times so we must save it. */
5183 addr = save_expr (addr);
5185 bool virtual_p = false;
5186 if (type_build_dtor_call (type))
5188 if (CLASSTYPE_LAZY_DESTRUCTOR (type))
5189 lazily_declare_fn (sfk_destructor, type);
5190 virtual_p = DECL_VIRTUAL_P (CLASSTYPE_DESTRUCTOR (type));
5193 tree head = NULL_TREE;
5194 tree do_delete = NULL_TREE;
5195 bool destroying_delete = false;
5197 if (!deleting)
5199 /* Leave do_delete null. */
5201 /* For `::delete x', we must not use the deleting destructor
5202 since then we would not be sure to get the global `operator
5203 delete'. */
5204 else if (use_global_delete)
5206 head = get_target_expr (build_headof (addr));
5207 /* Delete the object. */
5208 do_delete = build_op_delete_call (DELETE_EXPR,
5209 head,
5210 cxx_sizeof_nowarn (type),
5211 /*global_p=*/true,
5212 /*placement=*/NULL_TREE,
5213 /*alloc_fn=*/NULL_TREE,
5214 complain);
5215 /* Otherwise, treat this like a complete object destructor
5216 call. */
5217 auto_delete = sfk_complete_destructor;
5219 /* If the destructor is non-virtual, there is no deleting
5220 variant. Instead, we must explicitly call the appropriate
5221 `operator delete' here. */
5222 else if (!virtual_p)
5224 /* Build the call. */
5225 do_delete = build_op_delete_call (DELETE_EXPR,
5226 addr,
5227 cxx_sizeof_nowarn (type),
5228 /*global_p=*/false,
5229 /*placement=*/NULL_TREE,
5230 /*alloc_fn=*/NULL_TREE,
5231 complain);
5232 /* Call the complete object destructor. */
5233 auto_delete = sfk_complete_destructor;
5234 if (do_delete != error_mark_node)
5236 tree fn = get_callee_fndecl (do_delete);
5237 destroying_delete = destroying_delete_p (fn);
5240 else if (TYPE_GETS_REG_DELETE (type))
5242 /* Make sure we have access to the member op delete, even though
5243 we'll actually be calling it from the destructor. */
5244 build_op_delete_call (DELETE_EXPR, addr, cxx_sizeof_nowarn (type),
5245 /*global_p=*/false,
5246 /*placement=*/NULL_TREE,
5247 /*alloc_fn=*/NULL_TREE,
5248 complain);
5251 if (destroying_delete)
5252 /* The operator delete will call the destructor. */
5253 expr = addr;
5254 else if (type_build_dtor_call (type))
5255 expr = build_dtor_call (cp_build_fold_indirect_ref (addr),
5256 auto_delete, flags, complain);
5257 else
5258 expr = build_trivial_dtor_call (addr);
5259 if (expr == error_mark_node)
5260 return error_mark_node;
5262 if (!deleting)
5264 protected_set_expr_location (expr, loc);
5265 return expr;
5268 if (do_delete == error_mark_node)
5269 return error_mark_node;
5271 if (do_delete && !TREE_SIDE_EFFECTS (expr))
5272 expr = do_delete;
5273 else if (do_delete)
5274 /* The delete operator must be called, regardless of whether
5275 the destructor throws.
5277 [expr.delete]/7 The deallocation function is called
5278 regardless of whether the destructor for the object or some
5279 element of the array throws an exception. */
5280 expr = build2 (TRY_FINALLY_EXPR, void_type_node, expr, do_delete);
5282 /* We need to calculate this before the dtor changes the vptr. */
5283 if (head)
5284 expr = build2 (COMPOUND_EXPR, void_type_node, head, expr);
5286 /* Handle deleting a null pointer. */
5287 warning_sentinel s (warn_address);
5288 tree ifexp = cp_build_binary_op (loc, NE_EXPR, addr,
5289 nullptr_node, complain);
5290 ifexp = cp_fully_fold (ifexp);
5292 if (ifexp == error_mark_node)
5293 return error_mark_node;
5294 /* This is a compiler generated comparison, don't emit
5295 e.g. -Wnonnull-compare warning for it. */
5296 else if (TREE_CODE (ifexp) == NE_EXPR)
5297 suppress_warning (ifexp, OPT_Wnonnull_compare);
5299 if (!integer_nonzerop (ifexp))
5300 expr = build3 (COND_EXPR, void_type_node, ifexp, expr, void_node);
5302 protected_set_expr_location (expr, loc);
5303 return expr;
5306 /* At the beginning of a destructor, push cleanups that will call the
5307 destructors for our base classes and members.
5309 Called from begin_destructor_body. */
5311 void
5312 push_base_cleanups (void)
5314 tree binfo, base_binfo;
5315 int i;
5316 tree member;
5317 tree expr;
5318 vec<tree, va_gc> *vbases;
5320 /* Run destructors for all virtual baseclasses. */
5321 if (!ABSTRACT_CLASS_TYPE_P (current_class_type)
5322 && CLASSTYPE_VBASECLASSES (current_class_type))
5324 tree cond = (condition_conversion
5325 (build2 (BIT_AND_EXPR, integer_type_node,
5326 current_in_charge_parm,
5327 integer_two_node)));
5329 /* The CLASSTYPE_VBASECLASSES vector is in initialization
5330 order, which is also the right order for pushing cleanups. */
5331 for (vbases = CLASSTYPE_VBASECLASSES (current_class_type), i = 0;
5332 vec_safe_iterate (vbases, i, &base_binfo); i++)
5334 if (type_build_dtor_call (BINFO_TYPE (base_binfo)))
5336 expr = build_special_member_call (current_class_ref,
5337 base_dtor_identifier,
5338 NULL,
5339 base_binfo,
5340 (LOOKUP_NORMAL
5341 | LOOKUP_NONVIRTUAL),
5342 tf_warning_or_error);
5343 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5345 expr = build3 (COND_EXPR, void_type_node, cond,
5346 expr, void_node);
5347 finish_decl_cleanup (NULL_TREE, expr);
5353 /* Take care of the remaining baseclasses. */
5354 for (binfo = TYPE_BINFO (current_class_type), i = 0;
5355 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5357 if (BINFO_VIRTUAL_P (base_binfo)
5358 || !type_build_dtor_call (BINFO_TYPE (base_binfo)))
5359 continue;
5361 expr = build_special_member_call (current_class_ref,
5362 base_dtor_identifier,
5363 NULL, base_binfo,
5364 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
5365 tf_warning_or_error);
5366 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5367 finish_decl_cleanup (NULL_TREE, expr);
5370 /* Don't automatically destroy union members. */
5371 if (TREE_CODE (current_class_type) == UNION_TYPE)
5372 return;
5374 for (member = TYPE_FIELDS (current_class_type); member;
5375 member = DECL_CHAIN (member))
5377 tree this_type = TREE_TYPE (member);
5378 if (this_type == error_mark_node
5379 || TREE_CODE (member) != FIELD_DECL
5380 || DECL_ARTIFICIAL (member))
5381 continue;
5382 if (ANON_AGGR_TYPE_P (this_type))
5383 continue;
5384 if (type_build_dtor_call (this_type))
5386 tree this_member = (build_class_member_access_expr
5387 (current_class_ref, member,
5388 /*access_path=*/NULL_TREE,
5389 /*preserve_reference=*/false,
5390 tf_warning_or_error));
5391 expr = build_delete (input_location, this_type, this_member,
5392 sfk_complete_destructor,
5393 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR|LOOKUP_NORMAL,
5394 0, tf_warning_or_error);
5395 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (this_type))
5396 finish_decl_cleanup (NULL_TREE, expr);
5401 /* Build a C++ vector delete expression.
5402 MAXINDEX is the number of elements to be deleted.
5403 ELT_SIZE is the nominal size of each element in the vector.
5404 BASE is the expression that should yield the store to be deleted.
5405 This function expands (or synthesizes) these calls itself.
5406 AUTO_DELETE_VEC says whether the container (vector) should be deallocated.
5408 This also calls delete for virtual baseclasses of elements of the vector.
5410 Update: MAXINDEX is no longer needed. The size can be extracted from the
5411 start of the vector for pointers, and from the type for arrays. We still
5412 use MAXINDEX for arrays because it happens to already have one of the
5413 values we'd have to extract. (We could use MAXINDEX with pointers to
5414 confirm the size, and trap if the numbers differ; not clear that it'd
5415 be worth bothering.) */
5417 tree
5418 build_vec_delete (location_t loc, tree base, tree maxindex,
5419 special_function_kind auto_delete_vec,
5420 int use_global_delete, tsubst_flags_t complain)
5422 tree type;
5423 tree rval;
5424 tree base_init = NULL_TREE;
5426 type = TREE_TYPE (base);
5428 if (TYPE_PTR_P (type))
5430 /* Step back one from start of vector, and read dimension. */
5431 tree cookie_addr;
5432 tree size_ptr_type = build_pointer_type (sizetype);
5434 base = mark_rvalue_use (base);
5435 if (TREE_SIDE_EFFECTS (base))
5437 base_init = get_target_expr (base);
5438 base = TARGET_EXPR_SLOT (base_init);
5440 type = strip_array_types (TREE_TYPE (type));
5441 cookie_addr = fold_build1_loc (loc, NEGATE_EXPR,
5442 sizetype, TYPE_SIZE_UNIT (sizetype));
5443 cookie_addr = fold_build_pointer_plus (fold_convert (size_ptr_type, base),
5444 cookie_addr);
5445 maxindex = cp_build_fold_indirect_ref (cookie_addr);
5447 else if (TREE_CODE (type) == ARRAY_TYPE)
5449 /* Get the total number of things in the array, maxindex is a
5450 bad name. */
5451 maxindex = array_type_nelts_total (type);
5452 type = strip_array_types (type);
5453 base = decay_conversion (base, complain);
5454 if (base == error_mark_node)
5455 return error_mark_node;
5456 if (TREE_SIDE_EFFECTS (base))
5458 base_init = get_target_expr (base);
5459 base = TARGET_EXPR_SLOT (base_init);
5462 else
5464 if (base != error_mark_node && !(complain & tf_error))
5465 error_at (loc,
5466 "type to vector delete is neither pointer or array type");
5467 return error_mark_node;
5470 rval = build_vec_delete_1 (loc, base, maxindex, type, auto_delete_vec,
5471 use_global_delete, complain);
5472 if (base_init && rval != error_mark_node)
5473 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), base_init, rval);
5475 protected_set_expr_location (rval, loc);
5476 return rval;
5479 #include "gt-cp-init.h"