]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/cp/init.cc
c++: DMI in template with virtual base [PR106890]
[thirdparty/gcc.git] / gcc / cp / init.cc
1 /* Handle initialization things in -*- C++ -*-
2 Copyright (C) 1987-2022 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com)
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 /* High-level class interface. */
22
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"
38
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);
52
53 static GTY(()) tree fn;
54
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. */
63
64 static bool
65 begin_init_stmts (tree *stmt_expr_p, tree *compound_stmt_p)
66 {
67 bool is_global = !building_stmt_list_p ();
68
69 *stmt_expr_p = begin_stmt_expr ();
70 *compound_stmt_p = begin_compound_stmt (BCS_NO_SCOPE);
71
72 return is_global;
73 }
74
75 /* Finish out the statement-expression begun by the previous call to
76 begin_init_stmts. Returns the statement-expression itself. */
77
78 static tree
79 finish_init_stmts (bool is_global, tree stmt_expr, tree compound_stmt)
80 {
81 finish_compound_stmt (compound_stmt);
82
83 stmt_expr = finish_stmt_expr (stmt_expr, true);
84
85 gcc_assert (!building_stmt_list_p () == is_global);
86
87 return stmt_expr;
88 }
89
90 /* Constructors */
91
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. */
95
96 static tree
97 dfs_initialize_vtbl_ptrs (tree binfo, void *data)
98 {
99 if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
100 return dfs_skip_bases;
101
102 if (!BINFO_PRIMARY_P (binfo) || BINFO_VIRTUAL_P (binfo))
103 {
104 tree base_ptr = TREE_VALUE ((tree) data);
105
106 base_ptr = build_base_path (PLUS_EXPR, base_ptr, binfo, /*nonnull=*/1,
107 tf_warning_or_error);
108
109 expand_virtual_init (binfo, base_ptr);
110 }
111
112 return NULL_TREE;
113 }
114
115 /* Initialize all the vtable pointers in the object pointed to by
116 ADDR. */
117
118 void
119 initialize_vtbl_ptrs (tree addr)
120 {
121 tree list;
122 tree type;
123
124 type = TREE_TYPE (TREE_TYPE (addr));
125 list = build_tree_list (type, addr);
126
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);
132 }
133
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. */
149
150 static tree
151 build_zero_init_1 (tree type, tree nelts, bool static_storage_p,
152 tree field_size)
153 {
154 tree init = NULL_TREE;
155
156 /* [dcl.init]
157
158 To zero-initialize an object of type T means:
159
160 -- if T is a scalar type, the storage is set to the value of zero
161 converted to T.
162
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.
165
166 -- if T is a union type, the storage for its first data member is
167 zero-initialized.
168
169 -- if T is an array type, the storage for each element is
170 zero-initialized.
171
172 -- if T is a reference type, no initialization is performed. */
173
174 gcc_assert (nelts == NULL_TREE || TREE_CODE (nelts) == INTEGER_CST);
175
176 if (type == error_mark_node)
177 ;
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. */
183 ;
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)))
191 {
192 tree field;
193 vec<constructor_elt, va_gc> *v = NULL;
194
195 /* Iterate over the fields, building initializations. */
196 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
197 {
198 if (TREE_CODE (field) != FIELD_DECL)
199 continue;
200
201 if (TREE_TYPE (field) == error_mark_node)
202 continue;
203
204 /* Don't add virtual bases for base classes if they are beyond
205 the size of the current field, that means it is present
206 somewhere else in the object. */
207 if (field_size)
208 {
209 tree bitpos = bit_position (field);
210 if (TREE_CODE (bitpos) == INTEGER_CST
211 && !tree_int_cst_lt (bitpos, field_size))
212 continue;
213 }
214
215 /* Note that for class types there will be FIELD_DECLs
216 corresponding to base classes as well. Thus, iterating
217 over TYPE_FIELDs will result in correct initialization of
218 all of the subobjects. */
219 if (!static_storage_p || !zero_init_p (TREE_TYPE (field)))
220 {
221 tree new_field_size
222 = (DECL_FIELD_IS_BASE (field)
223 && DECL_SIZE (field)
224 && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
225 ? DECL_SIZE (field) : NULL_TREE;
226 tree value = build_zero_init_1 (TREE_TYPE (field),
227 /*nelts=*/NULL_TREE,
228 static_storage_p,
229 new_field_size);
230 if (value)
231 CONSTRUCTOR_APPEND_ELT(v, field, value);
232 }
233
234 /* For unions, only the first field is initialized. */
235 if (TREE_CODE (type) == UNION_TYPE)
236 break;
237 }
238
239 /* Build a constructor to contain the initializations. */
240 init = build_constructor (type, v);
241 }
242 else if (TREE_CODE (type) == ARRAY_TYPE)
243 {
244 tree max_index;
245 vec<constructor_elt, va_gc> *v = NULL;
246
247 /* Iterate over the array elements, building initializations. */
248 if (nelts)
249 max_index = fold_build2_loc (input_location, MINUS_EXPR,
250 TREE_TYPE (nelts), nelts,
251 build_one_cst (TREE_TYPE (nelts)));
252 /* Treat flexible array members like [0] arrays. */
253 else if (TYPE_DOMAIN (type) == NULL_TREE)
254 return NULL_TREE;
255 else
256 max_index = array_type_nelts (type);
257
258 /* If we have an error_mark here, we should just return error mark
259 as we don't know the size of the array yet. */
260 if (max_index == error_mark_node)
261 return error_mark_node;
262 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
263
264 /* A zero-sized array, which is accepted as an extension, will
265 have an upper bound of -1. */
266 if (!integer_minus_onep (max_index))
267 {
268 constructor_elt ce;
269
270 /* If this is a one element array, we just use a regular init. */
271 if (integer_zerop (max_index))
272 ce.index = size_zero_node;
273 else
274 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node,
275 max_index);
276
277 ce.value = build_zero_init_1 (TREE_TYPE (type), /*nelts=*/NULL_TREE,
278 static_storage_p, NULL_TREE);
279 if (ce.value)
280 {
281 vec_alloc (v, 1);
282 v->quick_push (ce);
283 }
284 }
285
286 /* Build a constructor to contain the initializations. */
287 init = build_constructor (type, v);
288 }
289 else if (VECTOR_TYPE_P (type))
290 init = build_zero_cst (type);
291 else
292 gcc_assert (TYPE_REF_P (type));
293
294 /* In all cases, the initializer is a constant. */
295 if (init)
296 TREE_CONSTANT (init) = 1;
297
298 return init;
299 }
300
301 /* Return an expression for the zero-initialization of an object with
302 type T. This expression will either be a constant (in the case
303 that T is a scalar), or a CONSTRUCTOR (in the case that T is an
304 aggregate), or NULL (in the case that T does not require
305 initialization). In either case, the value can be used as
306 DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
307 initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
308 is the number of elements in the array. If STATIC_STORAGE_P is
309 TRUE, initializers are only generated for entities for which
310 zero-initialization does not simply mean filling the storage with
311 zero bytes. */
312
313 tree
314 build_zero_init (tree type, tree nelts, bool static_storage_p)
315 {
316 return build_zero_init_1 (type, nelts, static_storage_p, NULL_TREE);
317 }
318
319 /* Return a suitable initializer for value-initializing an object of type
320 TYPE, as described in [dcl.init]. */
321
322 tree
323 build_value_init (tree type, tsubst_flags_t complain)
324 {
325 /* [dcl.init]
326
327 To value-initialize an object of type T means:
328
329 - if T is a class type (clause 9) with either no default constructor
330 (12.1) or a default constructor that is user-provided or deleted,
331 then the object is default-initialized;
332
333 - if T is a (possibly cv-qualified) class type without a user-provided
334 or deleted default constructor, then the object is zero-initialized
335 and the semantic constraints for default-initialization are checked,
336 and if T has a non-trivial default constructor, the object is
337 default-initialized;
338
339 - if T is an array type, then each element is value-initialized;
340
341 - otherwise, the object is zero-initialized.
342
343 A program that calls for default-initialization or
344 value-initialization of an entity of reference type is ill-formed. */
345
346 if (CLASS_TYPE_P (type) && type_build_ctor_call (type))
347 {
348 tree ctor
349 = build_special_member_call (NULL_TREE, complete_ctor_identifier,
350 NULL, type, LOOKUP_NORMAL, complain);
351 if (ctor == error_mark_node || TREE_CONSTANT (ctor))
352 return ctor;
353 if (processing_template_decl)
354 /* The AGGR_INIT_EXPR tweaking below breaks in templates. */
355 return build_min (CAST_EXPR, type, NULL_TREE);
356 tree fn = NULL_TREE;
357 if (TREE_CODE (ctor) == CALL_EXPR)
358 fn = get_callee_fndecl (ctor);
359 ctor = build_aggr_init_expr (type, ctor);
360 if (fn && user_provided_p (fn))
361 return ctor;
362 else if (TYPE_HAS_COMPLEX_DFLT (type))
363 {
364 /* This is a class that needs constructing, but doesn't have
365 a user-provided constructor. So we need to zero-initialize
366 the object and then call the implicitly defined ctor.
367 This will be handled in simplify_aggr_init_expr. */
368 AGGR_INIT_ZERO_FIRST (ctor) = 1;
369 return ctor;
370 }
371 }
372
373 /* Discard any access checking during subobject initialization;
374 the checks are implied by the call to the ctor which we have
375 verified is OK (cpp0x/defaulted46.C). */
376 push_deferring_access_checks (dk_deferred);
377 tree r = build_value_init_noctor (type, complain);
378 pop_deferring_access_checks ();
379 return r;
380 }
381
382 /* Like build_value_init, but don't call the constructor for TYPE. Used
383 for base initializers. */
384
385 tree
386 build_value_init_noctor (tree type, tsubst_flags_t complain)
387 {
388 if (!COMPLETE_TYPE_P (type))
389 {
390 if (complain & tf_error)
391 error ("value-initialization of incomplete type %qT", type);
392 return error_mark_node;
393 }
394 /* FIXME the class and array cases should just use digest_init once it is
395 SFINAE-enabled. */
396 if (CLASS_TYPE_P (type))
397 {
398 gcc_assert (!TYPE_HAS_COMPLEX_DFLT (type)
399 || errorcount != 0);
400
401 if (TREE_CODE (type) != UNION_TYPE)
402 {
403 tree field;
404 vec<constructor_elt, va_gc> *v = NULL;
405
406 /* Iterate over the fields, building initializations. */
407 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
408 {
409 tree ftype, value;
410
411 if (TREE_CODE (field) != FIELD_DECL)
412 continue;
413
414 ftype = TREE_TYPE (field);
415
416 if (ftype == error_mark_node)
417 continue;
418
419 /* Ignore flexible array members for value initialization. */
420 if (TREE_CODE (ftype) == ARRAY_TYPE
421 && !COMPLETE_TYPE_P (ftype)
422 && !TYPE_DOMAIN (ftype)
423 && COMPLETE_TYPE_P (TREE_TYPE (ftype))
424 && (next_initializable_field (DECL_CHAIN (field))
425 == NULL_TREE))
426 continue;
427
428 /* Ignore unnamed zero-width bitfields. */
429 if (DECL_UNNAMED_BIT_FIELD (field)
430 && integer_zerop (DECL_SIZE (field)))
431 continue;
432
433 /* We could skip vfields and fields of types with
434 user-defined constructors, but I think that won't improve
435 performance at all; it should be simpler in general just
436 to zero out the entire object than try to only zero the
437 bits that actually need it. */
438
439 /* Note that for class types there will be FIELD_DECLs
440 corresponding to base classes as well. Thus, iterating
441 over TYPE_FIELDs will result in correct initialization of
442 all of the subobjects. */
443 value = build_value_init (ftype, complain);
444 value = maybe_constant_init (value);
445
446 if (value == error_mark_node)
447 return error_mark_node;
448
449 CONSTRUCTOR_APPEND_ELT(v, field, value);
450
451 /* We shouldn't have gotten here for anything that would need
452 non-trivial initialization, and gimplify_init_ctor_preeval
453 would need to be fixed to allow it. */
454 gcc_assert (TREE_CODE (value) != TARGET_EXPR
455 && TREE_CODE (value) != AGGR_INIT_EXPR);
456 }
457
458 /* Build a constructor to contain the zero- initializations. */
459 return build_constructor (type, v);
460 }
461 }
462 else if (TREE_CODE (type) == ARRAY_TYPE)
463 {
464 vec<constructor_elt, va_gc> *v = NULL;
465
466 /* Iterate over the array elements, building initializations. */
467 tree max_index = array_type_nelts (type);
468
469 /* If we have an error_mark here, we should just return error mark
470 as we don't know the size of the array yet. */
471 if (max_index == error_mark_node)
472 {
473 if (complain & tf_error)
474 error ("cannot value-initialize array of unknown bound %qT",
475 type);
476 return error_mark_node;
477 }
478 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
479
480 /* A zero-sized array, which is accepted as an extension, will
481 have an upper bound of -1. */
482 if (!tree_int_cst_equal (max_index, integer_minus_one_node))
483 {
484 constructor_elt ce;
485
486 /* If this is a one element array, we just use a regular init. */
487 if (tree_int_cst_equal (size_zero_node, max_index))
488 ce.index = size_zero_node;
489 else
490 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node, max_index);
491
492 ce.value = build_value_init (TREE_TYPE (type), complain);
493 ce.value = maybe_constant_init (ce.value);
494 if (ce.value == error_mark_node)
495 return error_mark_node;
496
497 vec_alloc (v, 1);
498 v->quick_push (ce);
499
500 /* We shouldn't have gotten here for anything that would need
501 non-trivial initialization, and gimplify_init_ctor_preeval
502 would need to be fixed to allow it. */
503 gcc_assert (TREE_CODE (ce.value) != TARGET_EXPR
504 && TREE_CODE (ce.value) != AGGR_INIT_EXPR);
505 }
506
507 /* Build a constructor to contain the initializations. */
508 return build_constructor (type, v);
509 }
510 else if (TREE_CODE (type) == FUNCTION_TYPE)
511 {
512 if (complain & tf_error)
513 error ("value-initialization of function type %qT", type);
514 return error_mark_node;
515 }
516 else if (TYPE_REF_P (type))
517 {
518 if (complain & tf_error)
519 error ("value-initialization of reference type %qT", type);
520 return error_mark_node;
521 }
522
523 return build_zero_init (type, NULL_TREE, /*static_storage_p=*/false);
524 }
525
526 /* Initialize current class with INIT, a TREE_LIST of arguments for
527 a target constructor. If TREE_LIST is void_type_node, an empty
528 initializer list was given. Return the target constructor. */
529
530 static tree
531 perform_target_ctor (tree init)
532 {
533 tree decl = current_class_ref;
534 tree type = current_class_type;
535
536 init = build_aggr_init (decl, init, LOOKUP_NORMAL|LOOKUP_DELEGATING_CONS,
537 tf_warning_or_error);
538 finish_expr_stmt (init);
539 if (type_build_dtor_call (type))
540 {
541 tree expr = build_delete (input_location,
542 type, decl, sfk_complete_destructor,
543 LOOKUP_NORMAL
544 |LOOKUP_NONVIRTUAL
545 |LOOKUP_DESTRUCTOR,
546 0, tf_warning_or_error);
547 if (DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
548 {
549 tree base = build_delete (input_location,
550 type, decl, sfk_base_destructor,
551 LOOKUP_NORMAL
552 |LOOKUP_NONVIRTUAL
553 |LOOKUP_DESTRUCTOR,
554 0, tf_warning_or_error);
555 expr = build_if_in_charge (expr, base);
556 }
557 if (expr != error_mark_node
558 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
559 finish_eh_cleanup (expr);
560 }
561 return init;
562 }
563
564 /* Instantiate the default member initializer of MEMBER, if needed.
565 Only get_nsdmi should use the return value of this function. */
566
567 static GTY((cache)) decl_tree_cache_map *nsdmi_inst;
568
569 tree
570 maybe_instantiate_nsdmi_init (tree member, tsubst_flags_t complain)
571 {
572 tree init = DECL_INITIAL (member);
573 if (init && DECL_LANG_SPECIFIC (member) && DECL_TEMPLATE_INFO (member))
574 {
575 init = DECL_INITIAL (DECL_TI_TEMPLATE (member));
576 location_t expr_loc
577 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (member));
578 if (TREE_CODE (init) == DEFERRED_PARSE)
579 /* Unparsed. */;
580 else if (tree *slot = hash_map_safe_get (nsdmi_inst, member))
581 init = *slot;
582 /* Check recursive instantiation. */
583 else if (DECL_INSTANTIATING_NSDMI_P (member))
584 {
585 if (complain & tf_error)
586 error_at (expr_loc, "recursive instantiation of default member "
587 "initializer for %qD", member);
588 init = error_mark_node;
589 }
590 else
591 {
592 cp_evaluated ev;
593
594 location_t sloc = input_location;
595 input_location = expr_loc;
596
597 DECL_INSTANTIATING_NSDMI_P (member) = 1;
598
599 bool pushed = false;
600 tree ctx = DECL_CONTEXT (member);
601
602 processing_template_decl_sentinel ptds (/*reset*/false);
603 if (!currently_open_class (ctx))
604 {
605 if (!LOCAL_CLASS_P (ctx))
606 push_to_top_level ();
607 else
608 /* push_to_top_level would lose the necessary function context,
609 just reset processing_template_decl. */
610 processing_template_decl = 0;
611 push_nested_class (ctx);
612 push_deferring_access_checks (dk_no_deferred);
613 pushed = true;
614 }
615
616 /* If we didn't push_to_top_level, still step out of constructor
617 scope so build_base_path doesn't try to use its __in_chrg. */
618 tree cfd = current_function_decl;
619 auto cbl = current_binding_level;
620 if (at_function_scope_p ())
621 {
622 current_function_decl
623 = decl_function_context (current_function_decl);
624 while (current_binding_level->kind != sk_class)
625 current_binding_level = current_binding_level->level_chain;
626 }
627
628 inject_this_parameter (ctx, TYPE_UNQUALIFIED);
629
630 start_lambda_scope (member);
631
632 /* Do deferred instantiation of the NSDMI. */
633 init = (tsubst_copy_and_build
634 (init, DECL_TI_ARGS (member),
635 complain, member, /*function_p=*/false,
636 /*integral_constant_expression_p=*/false));
637 init = digest_nsdmi_init (member, init, complain);
638
639 finish_lambda_scope ();
640
641 DECL_INSTANTIATING_NSDMI_P (member) = 0;
642
643 if (init != error_mark_node)
644 hash_map_safe_put<hm_ggc> (nsdmi_inst, member, init);
645
646 current_function_decl = cfd;
647 current_binding_level = cbl;
648 if (pushed)
649 {
650 pop_deferring_access_checks ();
651 pop_nested_class ();
652 if (!LOCAL_CLASS_P (ctx))
653 pop_from_top_level ();
654 }
655
656 input_location = sloc;
657 }
658 }
659
660 return init;
661 }
662
663 /* Return the non-static data initializer for FIELD_DECL MEMBER. */
664
665 tree
666 get_nsdmi (tree member, bool in_ctor, tsubst_flags_t complain)
667 {
668 tree save_ccp = current_class_ptr;
669 tree save_ccr = current_class_ref;
670
671 tree init = maybe_instantiate_nsdmi_init (member, complain);
672
673 if (init && TREE_CODE (init) == DEFERRED_PARSE)
674 {
675 if (complain & tf_error)
676 {
677 error ("default member initializer for %qD required before the end "
678 "of its enclosing class", member);
679 inform (location_of (init), "defined here");
680 DECL_INITIAL (member) = error_mark_node;
681 }
682 init = error_mark_node;
683 }
684
685 if (in_ctor)
686 {
687 current_class_ptr = save_ccp;
688 current_class_ref = save_ccr;
689 }
690 else
691 {
692 /* Use a PLACEHOLDER_EXPR when we don't have a 'this' parameter to
693 refer to; constexpr evaluation knows what to do with it. */
694 current_class_ref = build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (member));
695 current_class_ptr = build_address (current_class_ref);
696 }
697
698 /* Clear processing_template_decl for sake of break_out_target_exprs;
699 INIT is always non-templated. */
700 processing_template_decl_sentinel ptds;
701
702 /* Strip redundant TARGET_EXPR so we don't need to remap it, and
703 so the aggregate init code below will see a CONSTRUCTOR. */
704 bool simple_target = (init && SIMPLE_TARGET_EXPR_P (init));
705 if (simple_target)
706 init = TARGET_EXPR_INITIAL (init);
707 init = break_out_target_exprs (init, /*loc*/true);
708 if (init && TREE_CODE (init) == TARGET_EXPR)
709 /* In a constructor, this expresses the full initialization, prevent
710 perform_member_init from calling another constructor (58162). */
711 TARGET_EXPR_DIRECT_INIT_P (init) = in_ctor;
712 if (simple_target && TREE_CODE (init) != CONSTRUCTOR)
713 /* Now put it back so C++17 copy elision works. */
714 init = get_target_expr (init);
715
716 current_class_ptr = save_ccp;
717 current_class_ref = save_ccr;
718 return init;
719 }
720
721 /* Diagnose the flexible array MEMBER if its INITializer is non-null
722 and return true if so. Otherwise return false. */
723
724 bool
725 maybe_reject_flexarray_init (tree member, tree init)
726 {
727 tree type = TREE_TYPE (member);
728
729 if (!init
730 || TREE_CODE (type) != ARRAY_TYPE
731 || TYPE_DOMAIN (type))
732 return false;
733
734 /* Point at the flexible array member declaration if it's initialized
735 in-class, and at the ctor if it's initialized in a ctor member
736 initializer list. */
737 location_t loc;
738 if (DECL_INITIAL (member) == init
739 || !current_function_decl
740 || DECL_DEFAULTED_FN (current_function_decl))
741 loc = DECL_SOURCE_LOCATION (member);
742 else
743 loc = DECL_SOURCE_LOCATION (current_function_decl);
744
745 error_at (loc, "initializer for flexible array member %q#D", member);
746 return true;
747 }
748
749 /* If INIT's value can come from a call to std::initializer_list<T>::begin,
750 return that function. Otherwise, NULL_TREE. */
751
752 static tree
753 find_list_begin (tree init)
754 {
755 STRIP_NOPS (init);
756 while (TREE_CODE (init) == COMPOUND_EXPR)
757 init = TREE_OPERAND (init, 1);
758 STRIP_NOPS (init);
759 if (TREE_CODE (init) == COND_EXPR)
760 {
761 tree left = TREE_OPERAND (init, 1);
762 if (!left)
763 left = TREE_OPERAND (init, 0);
764 left = find_list_begin (left);
765 if (left)
766 return left;
767 return find_list_begin (TREE_OPERAND (init, 2));
768 }
769 if (TREE_CODE (init) == CALL_EXPR)
770 if (tree fn = get_callee_fndecl (init))
771 if (id_equal (DECL_NAME (fn), "begin")
772 && is_std_init_list (DECL_CONTEXT (fn)))
773 return fn;
774 return NULL_TREE;
775 }
776
777 /* If INIT initializing MEMBER is copying the address of the underlying array
778 of an initializer_list, warn. */
779
780 static void
781 maybe_warn_list_ctor (tree member, tree init)
782 {
783 tree memtype = TREE_TYPE (member);
784 if (!init || !TYPE_PTR_P (memtype)
785 || !is_list_ctor (current_function_decl))
786 return;
787
788 tree parm = FUNCTION_FIRST_USER_PARMTYPE (current_function_decl);
789 parm = TREE_VALUE (parm);
790 tree initlist = non_reference (parm);
791
792 /* Do not warn if the parameter is an lvalue reference to non-const. */
793 if (TYPE_REF_P (parm) && !TYPE_REF_IS_RVALUE (parm)
794 && !CP_TYPE_CONST_P (initlist))
795 return;
796
797 tree targs = CLASSTYPE_TI_ARGS (initlist);
798 tree elttype = TREE_VEC_ELT (targs, 0);
799
800 if (!same_type_ignoring_top_level_qualifiers_p
801 (TREE_TYPE (memtype), elttype))
802 return;
803
804 tree begin = find_list_begin (init);
805 if (!begin)
806 return;
807
808 location_t loc = cp_expr_loc_or_input_loc (init);
809 warning_at (loc, OPT_Winit_list_lifetime,
810 "initializing %qD from %qE does not extend the lifetime "
811 "of the underlying array", member, begin);
812 }
813
814 /* Data structure for find_uninit_fields_r, below. */
815
816 struct find_uninit_data {
817 /* The set tracking the yet-uninitialized members. */
818 hash_set<tree> *uninitialized;
819 /* The data member we are currently initializing. It can be either
820 a type (initializing a base class/delegating constructors), or
821 a COMPONENT_REF. */
822 tree member;
823 };
824
825 /* walk_tree callback that warns about using uninitialized data in
826 a member-initializer-list. */
827
828 static tree
829 find_uninit_fields_r (tree *tp, int *walk_subtrees, void *data)
830 {
831 find_uninit_data *d = static_cast<find_uninit_data *>(data);
832 hash_set<tree> *uninitialized = d->uninitialized;
833 tree init = *tp;
834 const tree_code code = TREE_CODE (init);
835
836 /* No need to look into types or unevaluated operands. */
837 if (TYPE_P (init) || unevaluated_p (code))
838 {
839 *walk_subtrees = false;
840 return NULL_TREE;
841 }
842
843 switch (code)
844 {
845 /* We'd need data flow info to avoid false positives. */
846 case COND_EXPR:
847 case VEC_COND_EXPR:
848 case BIND_EXPR:
849 /* We might see a MODIFY_EXPR in cases like S() : a((b = 42)), c(b) { }
850 where the initializer for 'a' surreptitiously initializes 'b'. Let's
851 not bother with these complicated scenarios in the front end. */
852 case MODIFY_EXPR:
853 /* Don't attempt to handle statement-expressions, either. */
854 case STATEMENT_LIST:
855 uninitialized->empty ();
856 gcc_fallthrough ();
857 /* If we're just taking the address of an object, it doesn't matter
858 whether it's been initialized. */
859 case ADDR_EXPR:
860 *walk_subtrees = false;
861 return NULL_TREE;
862 default:
863 break;
864 }
865
866 /* We'd need data flow info to avoid false positives. */
867 if (truth_value_p (code))
868 goto give_up;
869 /* Attempt to handle a simple a{b}, but no more. */
870 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
871 {
872 if (CONSTRUCTOR_NELTS (init) == 1
873 && !BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (init, 0)->value))
874 init = CONSTRUCTOR_ELT (init, 0)->value;
875 else
876 goto give_up;
877 }
878 /* Warn about uninitialized 'this'. */
879 else if (code == CALL_EXPR)
880 {
881 tree fn = get_callee_fndecl (init);
882 if (fn && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
883 {
884 tree op = CALL_EXPR_ARG (init, 0);
885 if (TREE_CODE (op) == ADDR_EXPR)
886 op = TREE_OPERAND (op, 0);
887 temp_override<tree> ovr (d->member, DECL_ARGUMENTS (fn));
888 cp_walk_tree_without_duplicates (&op, find_uninit_fields_r, data);
889 }
890 /* Functions (whether static or nonstatic member) may have side effects
891 and initialize other members; it's not the front end's job to try to
892 figure it out. But don't give up for constructors: we still want to
893 warn when initializing base classes:
894
895 struct D : public B {
896 int x;
897 D() : B(x) {}
898 };
899
900 so carry on to detect that 'x' is used uninitialized. */
901 if (!fn || !DECL_CONSTRUCTOR_P (fn))
902 goto give_up;
903 }
904
905 /* If we find FIELD in the uninitialized set, we warn. */
906 if (code == COMPONENT_REF)
907 {
908 tree field = TREE_OPERAND (init, 1);
909 tree type = TYPE_P (d->member) ? d->member : TREE_TYPE (d->member);
910
911 /* We're initializing a reference member with itself. */
912 if (TYPE_REF_P (type) && cp_tree_equal (d->member, init))
913 warning_at (EXPR_LOCATION (init), OPT_Winit_self,
914 "%qD is initialized with itself", field);
915 else if (cp_tree_equal (TREE_OPERAND (init, 0), current_class_ref)
916 && uninitialized->contains (field))
917 {
918 if (TYPE_REF_P (TREE_TYPE (field)))
919 warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
920 "reference %qD is not yet bound to a value when used "
921 "here", field);
922 else if (!INDIRECT_TYPE_P (type) || is_this_parameter (d->member))
923 warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
924 "member %qD is used uninitialized", field);
925 *walk_subtrees = false;
926 }
927 }
928
929 return NULL_TREE;
930
931 give_up:
932 *walk_subtrees = false;
933 uninitialized->empty ();
934 return integer_zero_node;
935 }
936
937 /* Wrapper around find_uninit_fields_r above. */
938
939 static void
940 find_uninit_fields (tree *t, hash_set<tree> *uninitialized, tree member)
941 {
942 if (!uninitialized->is_empty ())
943 {
944 find_uninit_data data = { uninitialized, member };
945 cp_walk_tree_without_duplicates (t, find_uninit_fields_r, &data);
946 }
947 }
948
949 /* Initialize MEMBER, a FIELD_DECL, with INIT, a TREE_LIST of
950 arguments. If TREE_LIST is void_type_node, an empty initializer
951 list was given; if NULL_TREE no initializer was given. UNINITIALIZED
952 is the hash set that tracks uninitialized fields. */
953
954 static void
955 perform_member_init (tree member, tree init, hash_set<tree> &uninitialized)
956 {
957 tree decl;
958 tree type = TREE_TYPE (member);
959
960 /* Use the non-static data member initializer if there was no
961 mem-initializer for this field. */
962 if (init == NULL_TREE)
963 init = get_nsdmi (member, /*ctor*/true, tf_warning_or_error);
964
965 if (init == error_mark_node)
966 return;
967
968 /* Effective C++ rule 12 requires that all data members be
969 initialized. */
970 if (warn_ecpp && init == NULL_TREE && TREE_CODE (type) != ARRAY_TYPE)
971 warning_at (DECL_SOURCE_LOCATION (current_function_decl), OPT_Weffc__,
972 "%qD should be initialized in the member initialization list",
973 member);
974
975 /* Get an lvalue for the data member. */
976 decl = build_class_member_access_expr (current_class_ref, member,
977 /*access_path=*/NULL_TREE,
978 /*preserve_reference=*/true,
979 tf_warning_or_error);
980 if (decl == error_mark_node)
981 return;
982
983 if ((warn_init_self || warn_uninitialized)
984 && init
985 && TREE_CODE (init) == TREE_LIST
986 && TREE_CHAIN (init) == NULL_TREE)
987 {
988 tree val = TREE_VALUE (init);
989 /* Handle references. */
990 if (REFERENCE_REF_P (val))
991 val = TREE_OPERAND (val, 0);
992 if (TREE_CODE (val) == COMPONENT_REF && TREE_OPERAND (val, 1) == member
993 && TREE_OPERAND (val, 0) == current_class_ref)
994 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
995 OPT_Winit_self, "%qD is initialized with itself",
996 member);
997 else
998 find_uninit_fields (&val, &uninitialized, decl);
999 }
1000
1001 if (array_of_unknown_bound_p (type))
1002 {
1003 maybe_reject_flexarray_init (member, init);
1004 return;
1005 }
1006
1007 if (init && TREE_CODE (init) == TREE_LIST)
1008 {
1009 /* A(): a{e} */
1010 if (DIRECT_LIST_INIT_P (TREE_VALUE (init)))
1011 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
1012 tf_warning_or_error);
1013 /* We are trying to initialize an array from a ()-list. If we
1014 should attempt to do so, conjure up a CONSTRUCTOR. */
1015 else if (TREE_CODE (type) == ARRAY_TYPE
1016 /* P0960 is a C++20 feature. */
1017 && cxx_dialect >= cxx20)
1018 init = do_aggregate_paren_init (init, type);
1019 else if (!CLASS_TYPE_P (type))
1020 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
1021 tf_warning_or_error);
1022 /* If we're initializing a class from a ()-list, leave the TREE_LIST
1023 alone: we might call an appropriate constructor, or (in C++20)
1024 do aggregate-initialization. */
1025 }
1026
1027 /* Assume we are initializing the member. */
1028 bool member_initialized_p = true;
1029
1030 if (init == void_type_node)
1031 {
1032 /* mem() means value-initialization. */
1033 if (TREE_CODE (type) == ARRAY_TYPE)
1034 {
1035 init = build_vec_init_expr (type, init, tf_warning_or_error);
1036 init = build2 (INIT_EXPR, type, decl, init);
1037 finish_expr_stmt (init);
1038 }
1039 else
1040 {
1041 tree value = build_value_init (type, tf_warning_or_error);
1042 if (value == error_mark_node)
1043 return;
1044 init = build2 (INIT_EXPR, type, decl, value);
1045 finish_expr_stmt (init);
1046 }
1047 }
1048 /* Deal with this here, as we will get confused if we try to call the
1049 assignment op for an anonymous union. This can happen in a
1050 synthesized copy constructor. */
1051 else if (ANON_AGGR_TYPE_P (type))
1052 {
1053 if (init)
1054 {
1055 init = build2 (INIT_EXPR, type, decl, TREE_VALUE (init));
1056 finish_expr_stmt (init);
1057 }
1058 }
1059 else if (init
1060 && (TYPE_REF_P (type)
1061 || (TREE_CODE (init) == CONSTRUCTOR
1062 && (CP_AGGREGATE_TYPE_P (type)
1063 || is_std_init_list (type)))))
1064 {
1065 /* With references and list-initialization, we need to deal with
1066 extending temporary lifetimes. 12.2p5: "A temporary bound to a
1067 reference member in a constructor’s ctor-initializer (12.6.2)
1068 persists until the constructor exits." */
1069 unsigned i; tree t;
1070 releasing_vec cleanups;
1071 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
1072 {
1073 if (BRACE_ENCLOSED_INITIALIZER_P (init)
1074 && CP_AGGREGATE_TYPE_P (type))
1075 init = reshape_init (type, init, tf_warning_or_error);
1076 init = digest_init (type, init, tf_warning_or_error);
1077 }
1078 if (init == error_mark_node)
1079 return;
1080 if (is_empty_field (member)
1081 && !TREE_SIDE_EFFECTS (init))
1082 /* Don't add trivial initialization of an empty base/field, as they
1083 might not be ordered the way the back-end expects. */
1084 return;
1085 /* A FIELD_DECL doesn't really have a suitable lifetime, but
1086 make_temporary_var_for_ref_to_temp will treat it as automatic and
1087 set_up_extended_ref_temp wants to use the decl in a warning. */
1088 init = extend_ref_init_temps (member, init, &cleanups);
1089 if (TREE_CODE (type) == ARRAY_TYPE
1090 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (type)))
1091 init = build_vec_init_expr (type, init, tf_warning_or_error);
1092 init = build2 (INIT_EXPR, type, decl, init);
1093 finish_expr_stmt (init);
1094 FOR_EACH_VEC_ELT (*cleanups, i, t)
1095 push_cleanup (NULL_TREE, t, false);
1096 }
1097 else if (type_build_ctor_call (type)
1098 || (init && CLASS_TYPE_P (strip_array_types (type))))
1099 {
1100 if (TREE_CODE (type) == ARRAY_TYPE)
1101 {
1102 if (init == NULL_TREE
1103 || same_type_ignoring_top_level_qualifiers_p (type,
1104 TREE_TYPE (init)))
1105 {
1106 if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
1107 {
1108 /* Initialize the array only if it's not a flexible
1109 array member (i.e., if it has an upper bound). */
1110 init = build_vec_init_expr (type, init, tf_warning_or_error);
1111 init = build2 (INIT_EXPR, type, decl, init);
1112 finish_expr_stmt (init);
1113 }
1114 }
1115 else
1116 error ("invalid initializer for array member %q#D", member);
1117 }
1118 else
1119 {
1120 int flags = LOOKUP_NORMAL;
1121 if (DECL_DEFAULTED_FN (current_function_decl))
1122 flags |= LOOKUP_DEFAULTED;
1123 if (CP_TYPE_CONST_P (type)
1124 && init == NULL_TREE
1125 && default_init_uninitialized_part (type))
1126 {
1127 /* TYPE_NEEDS_CONSTRUCTING can be set just because we have a
1128 vtable; still give this diagnostic. */
1129 auto_diagnostic_group d;
1130 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1131 "uninitialized const member in %q#T", type))
1132 inform (DECL_SOURCE_LOCATION (member),
1133 "%q#D should be initialized", member );
1134 }
1135 finish_expr_stmt (build_aggr_init (decl, init, flags,
1136 tf_warning_or_error));
1137 }
1138 }
1139 else
1140 {
1141 if (init == NULL_TREE)
1142 {
1143 tree core_type;
1144 /* member traversal: note it leaves init NULL */
1145 if (TYPE_REF_P (type))
1146 {
1147 auto_diagnostic_group d;
1148 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1149 "uninitialized reference member in %q#T", type))
1150 inform (DECL_SOURCE_LOCATION (member),
1151 "%q#D should be initialized", member);
1152 }
1153 else if (CP_TYPE_CONST_P (type))
1154 {
1155 auto_diagnostic_group d;
1156 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1157 "uninitialized const member in %q#T", type))
1158 inform (DECL_SOURCE_LOCATION (member),
1159 "%q#D should be initialized", member );
1160 }
1161
1162 core_type = strip_array_types (type);
1163
1164 if (CLASS_TYPE_P (core_type)
1165 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
1166 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
1167 diagnose_uninitialized_cst_or_ref_member (core_type,
1168 /*using_new=*/false,
1169 /*complain=*/true);
1170
1171 /* We left the member uninitialized. */
1172 member_initialized_p = false;
1173 }
1174
1175 maybe_warn_list_ctor (member, init);
1176
1177 if (init)
1178 finish_expr_stmt (cp_build_modify_expr (input_location, decl,
1179 INIT_EXPR, init,
1180 tf_warning_or_error));
1181 }
1182
1183 if (member_initialized_p && warn_uninitialized)
1184 /* This member is now initialized, remove it from the uninitialized
1185 set. */
1186 uninitialized.remove (member);
1187
1188 if (type_build_dtor_call (type))
1189 {
1190 tree expr;
1191
1192 expr = build_class_member_access_expr (current_class_ref, member,
1193 /*access_path=*/NULL_TREE,
1194 /*preserve_reference=*/false,
1195 tf_warning_or_error);
1196 expr = build_delete (input_location,
1197 type, expr, sfk_complete_destructor,
1198 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0,
1199 tf_warning_or_error);
1200
1201 if (expr != error_mark_node
1202 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1203 finish_eh_cleanup (expr);
1204 }
1205 }
1206
1207 /* Returns a TREE_LIST containing (as the TREE_PURPOSE of each node) all
1208 the FIELD_DECLs on the TYPE_FIELDS list for T, in reverse order. */
1209
1210 static tree
1211 build_field_list (tree t, tree list, int *uses_unions_or_anon_p)
1212 {
1213 tree fields;
1214
1215 /* Note whether or not T is a union. */
1216 if (TREE_CODE (t) == UNION_TYPE)
1217 *uses_unions_or_anon_p = 1;
1218
1219 for (fields = TYPE_FIELDS (t); fields; fields = DECL_CHAIN (fields))
1220 {
1221 tree fieldtype;
1222
1223 /* Skip CONST_DECLs for enumeration constants and so forth. */
1224 if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
1225 continue;
1226
1227 fieldtype = TREE_TYPE (fields);
1228
1229 /* For an anonymous struct or union, we must recursively
1230 consider the fields of the anonymous type. They can be
1231 directly initialized from the constructor. */
1232 if (ANON_AGGR_TYPE_P (fieldtype))
1233 {
1234 /* Add this field itself. Synthesized copy constructors
1235 initialize the entire aggregate. */
1236 list = tree_cons (fields, NULL_TREE, list);
1237 /* And now add the fields in the anonymous aggregate. */
1238 list = build_field_list (fieldtype, list, uses_unions_or_anon_p);
1239 *uses_unions_or_anon_p = 1;
1240 }
1241 /* Add this field. */
1242 else if (DECL_NAME (fields))
1243 list = tree_cons (fields, NULL_TREE, list);
1244 }
1245
1246 return list;
1247 }
1248
1249 /* Return the innermost aggregate scope for FIELD, whether that is
1250 the enclosing class or an anonymous aggregate within it. */
1251
1252 static tree
1253 innermost_aggr_scope (tree field)
1254 {
1255 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1256 return TREE_TYPE (field);
1257 else
1258 return DECL_CONTEXT (field);
1259 }
1260
1261 /* The MEM_INITS are a TREE_LIST. The TREE_PURPOSE of each list gives
1262 a FIELD_DECL or BINFO in T that needs initialization. The
1263 TREE_VALUE gives the initializer, or list of initializer arguments.
1264
1265 Return a TREE_LIST containing all of the initializations required
1266 for T, in the order in which they should be performed. The output
1267 list has the same format as the input. */
1268
1269 static tree
1270 sort_mem_initializers (tree t, tree mem_inits)
1271 {
1272 tree init;
1273 tree base, binfo, base_binfo;
1274 tree sorted_inits;
1275 tree next_subobject;
1276 vec<tree, va_gc> *vbases;
1277 int i;
1278 int uses_unions_or_anon_p = 0;
1279
1280 /* Build up a list of initializations. The TREE_PURPOSE of entry
1281 will be the subobject (a FIELD_DECL or BINFO) to initialize. The
1282 TREE_VALUE will be the constructor arguments, or NULL if no
1283 explicit initialization was provided. */
1284 sorted_inits = NULL_TREE;
1285
1286 /* Process the virtual bases. */
1287 for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
1288 vec_safe_iterate (vbases, i, &base); i++)
1289 sorted_inits = tree_cons (base, NULL_TREE, sorted_inits);
1290
1291 /* Process the direct bases. */
1292 for (binfo = TYPE_BINFO (t), i = 0;
1293 BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
1294 if (!BINFO_VIRTUAL_P (base_binfo))
1295 sorted_inits = tree_cons (base_binfo, NULL_TREE, sorted_inits);
1296
1297 /* Process the non-static data members. */
1298 sorted_inits = build_field_list (t, sorted_inits, &uses_unions_or_anon_p);
1299 /* Reverse the entire list of initializations, so that they are in
1300 the order that they will actually be performed. */
1301 sorted_inits = nreverse (sorted_inits);
1302
1303 /* If the user presented the initializers in an order different from
1304 that in which they will actually occur, we issue a warning. Keep
1305 track of the next subobject which can be explicitly initialized
1306 without issuing a warning. */
1307 next_subobject = sorted_inits;
1308
1309 /* Go through the explicit initializers, filling in TREE_PURPOSE in
1310 the SORTED_INITS. */
1311 for (init = mem_inits; init; init = TREE_CHAIN (init))
1312 {
1313 tree subobject;
1314 tree subobject_init;
1315
1316 subobject = TREE_PURPOSE (init);
1317
1318 /* If the explicit initializers are in sorted order, then
1319 SUBOBJECT will be NEXT_SUBOBJECT, or something following
1320 it. */
1321 for (subobject_init = next_subobject;
1322 subobject_init;
1323 subobject_init = TREE_CHAIN (subobject_init))
1324 if (TREE_PURPOSE (subobject_init) == subobject)
1325 break;
1326
1327 /* Issue a warning if the explicit initializer order does not
1328 match that which will actually occur.
1329 ??? Are all these on the correct lines? */
1330 if (warn_reorder && !subobject_init)
1331 {
1332 if (TREE_CODE (TREE_PURPOSE (next_subobject)) == FIELD_DECL)
1333 warning_at (DECL_SOURCE_LOCATION (TREE_PURPOSE (next_subobject)),
1334 OPT_Wreorder, "%qD will be initialized after",
1335 TREE_PURPOSE (next_subobject));
1336 else
1337 warning (OPT_Wreorder, "base %qT will be initialized after",
1338 TREE_PURPOSE (next_subobject));
1339 if (TREE_CODE (subobject) == FIELD_DECL)
1340 warning_at (DECL_SOURCE_LOCATION (subobject),
1341 OPT_Wreorder, " %q#D", subobject);
1342 else
1343 warning (OPT_Wreorder, " base %qT", subobject);
1344 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1345 OPT_Wreorder, " when initialized here");
1346 }
1347
1348 /* Look again, from the beginning of the list. */
1349 if (!subobject_init)
1350 {
1351 subobject_init = sorted_inits;
1352 while (TREE_PURPOSE (subobject_init) != subobject)
1353 subobject_init = TREE_CHAIN (subobject_init);
1354 }
1355
1356 /* It is invalid to initialize the same subobject more than
1357 once. */
1358 if (TREE_VALUE (subobject_init))
1359 {
1360 if (TREE_CODE (subobject) == FIELD_DECL)
1361 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1362 "multiple initializations given for %qD",
1363 subobject);
1364 else
1365 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1366 "multiple initializations given for base %qT",
1367 subobject);
1368 }
1369
1370 /* Record the initialization. */
1371 TREE_VALUE (subobject_init) = TREE_VALUE (init);
1372 /* Carry over the dummy TREE_TYPE node containing the source location. */
1373 TREE_TYPE (subobject_init) = TREE_TYPE (init);
1374 next_subobject = subobject_init;
1375 }
1376
1377 /* [class.base.init]
1378
1379 If a ctor-initializer specifies more than one mem-initializer for
1380 multiple members of the same union (including members of
1381 anonymous unions), the ctor-initializer is ill-formed.
1382
1383 Here we also splice out uninitialized union members. */
1384 if (uses_unions_or_anon_p)
1385 {
1386 tree *last_p = NULL;
1387 tree *p;
1388 for (p = &sorted_inits; *p; )
1389 {
1390 tree field;
1391 tree ctx;
1392
1393 init = *p;
1394
1395 field = TREE_PURPOSE (init);
1396
1397 /* Skip base classes. */
1398 if (TREE_CODE (field) != FIELD_DECL)
1399 goto next;
1400
1401 /* If this is an anonymous aggregate with no explicit initializer,
1402 splice it out. */
1403 if (!TREE_VALUE (init) && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1404 goto splice;
1405
1406 /* See if this field is a member of a union, or a member of a
1407 structure contained in a union, etc. */
1408 ctx = innermost_aggr_scope (field);
1409
1410 /* If this field is not a member of a union, skip it. */
1411 if (TREE_CODE (ctx) != UNION_TYPE
1412 && !ANON_AGGR_TYPE_P (ctx))
1413 goto next;
1414
1415 /* If this union member has no explicit initializer and no NSDMI,
1416 splice it out. */
1417 if (TREE_VALUE (init) || DECL_INITIAL (field))
1418 /* OK. */;
1419 else
1420 goto splice;
1421
1422 /* It's only an error if we have two initializers for the same
1423 union type. */
1424 if (!last_p)
1425 {
1426 last_p = p;
1427 goto next;
1428 }
1429
1430 /* See if LAST_FIELD and the field initialized by INIT are
1431 members of the same union (or the union itself). If so, there's
1432 a problem, unless they're actually members of the same structure
1433 which is itself a member of a union. For example, given:
1434
1435 union { struct { int i; int j; }; };
1436
1437 initializing both `i' and `j' makes sense. */
1438 ctx = common_enclosing_class
1439 (innermost_aggr_scope (field),
1440 innermost_aggr_scope (TREE_PURPOSE (*last_p)));
1441
1442 if (ctx && (TREE_CODE (ctx) == UNION_TYPE
1443 || ctx == TREE_TYPE (TREE_PURPOSE (*last_p))))
1444 {
1445 /* A mem-initializer hides an NSDMI. */
1446 if (TREE_VALUE (init) && !TREE_VALUE (*last_p))
1447 *last_p = TREE_CHAIN (*last_p);
1448 else if (TREE_VALUE (*last_p) && !TREE_VALUE (init))
1449 goto splice;
1450 else
1451 {
1452 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1453 "initializations for multiple members of %qT",
1454 ctx);
1455 goto splice;
1456 }
1457 }
1458
1459 last_p = p;
1460
1461 next:
1462 p = &TREE_CHAIN (*p);
1463 continue;
1464 splice:
1465 *p = TREE_CHAIN (*p);
1466 continue;
1467 }
1468 }
1469
1470 return sorted_inits;
1471 }
1472
1473 /* Callback for cp_walk_tree to mark all PARM_DECLs in a tree as read. */
1474
1475 static tree
1476 mark_exp_read_r (tree *tp, int *, void *)
1477 {
1478 tree t = *tp;
1479 if (TREE_CODE (t) == PARM_DECL)
1480 mark_exp_read (t);
1481 return NULL_TREE;
1482 }
1483
1484 /* Initialize all bases and members of CURRENT_CLASS_TYPE. MEM_INITS
1485 is a TREE_LIST giving the explicit mem-initializer-list for the
1486 constructor. The TREE_PURPOSE of each entry is a subobject (a
1487 FIELD_DECL or a BINFO) of the CURRENT_CLASS_TYPE. The TREE_VALUE
1488 is a TREE_LIST giving the arguments to the constructor or
1489 void_type_node for an empty list of arguments. */
1490
1491 void
1492 emit_mem_initializers (tree mem_inits)
1493 {
1494 int flags = LOOKUP_NORMAL;
1495
1496 /* We will already have issued an error message about the fact that
1497 the type is incomplete. */
1498 if (!COMPLETE_TYPE_P (current_class_type))
1499 return;
1500
1501 /* Keep a set holding fields that are not initialized. */
1502 hash_set<tree> uninitialized;
1503
1504 /* Initially that is all of them. */
1505 if (warn_uninitialized)
1506 for (tree f = next_initializable_field (TYPE_FIELDS (current_class_type));
1507 f != NULL_TREE;
1508 f = next_initializable_field (DECL_CHAIN (f)))
1509 if (!DECL_ARTIFICIAL (f)
1510 && !is_really_empty_class (TREE_TYPE (f), /*ignore_vptr*/false))
1511 uninitialized.add (f);
1512
1513 if (mem_inits
1514 && TYPE_P (TREE_PURPOSE (mem_inits))
1515 && same_type_p (TREE_PURPOSE (mem_inits), current_class_type))
1516 {
1517 /* Delegating constructor. */
1518 gcc_assert (TREE_CHAIN (mem_inits) == NULL_TREE);
1519 tree ctor = perform_target_ctor (TREE_VALUE (mem_inits));
1520 find_uninit_fields (&ctor, &uninitialized, current_class_type);
1521 return;
1522 }
1523
1524 if (DECL_DEFAULTED_FN (current_function_decl)
1525 && ! DECL_INHERITED_CTOR (current_function_decl))
1526 flags |= LOOKUP_DEFAULTED;
1527
1528 /* Sort the mem-initializers into the order in which the
1529 initializations should be performed. */
1530 mem_inits = sort_mem_initializers (current_class_type, mem_inits);
1531
1532 in_base_initializer = 1;
1533
1534 /* Initialize base classes. */
1535 for (; (mem_inits
1536 && TREE_CODE (TREE_PURPOSE (mem_inits)) != FIELD_DECL);
1537 mem_inits = TREE_CHAIN (mem_inits))
1538 {
1539 tree subobject = TREE_PURPOSE (mem_inits);
1540 tree arguments = TREE_VALUE (mem_inits);
1541
1542 /* We already have issued an error message. */
1543 if (arguments == error_mark_node)
1544 continue;
1545
1546 /* Suppress access control when calling the inherited ctor. */
1547 bool inherited_base = (DECL_INHERITED_CTOR (current_function_decl)
1548 && flag_new_inheriting_ctors
1549 && arguments);
1550 if (inherited_base)
1551 push_deferring_access_checks (dk_deferred);
1552
1553 if (arguments == NULL_TREE)
1554 {
1555 /* If these initializations are taking place in a copy constructor,
1556 the base class should probably be explicitly initialized if there
1557 is a user-defined constructor in the base class (other than the
1558 default constructor, which will be called anyway). */
1559 if (extra_warnings
1560 && DECL_COPY_CONSTRUCTOR_P (current_function_decl)
1561 && type_has_user_nondefault_constructor (BINFO_TYPE (subobject)))
1562 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1563 OPT_Wextra, "base class %q#T should be explicitly "
1564 "initialized in the copy constructor",
1565 BINFO_TYPE (subobject));
1566 }
1567
1568 /* Initialize the base. */
1569 if (!BINFO_VIRTUAL_P (subobject))
1570 {
1571 tree base_addr;
1572
1573 base_addr = build_base_path (PLUS_EXPR, current_class_ptr,
1574 subobject, 1, tf_warning_or_error);
1575 expand_aggr_init_1 (subobject, NULL_TREE,
1576 cp_build_fold_indirect_ref (base_addr),
1577 arguments,
1578 flags,
1579 tf_warning_or_error);
1580 expand_cleanup_for_base (subobject, NULL_TREE);
1581 if (STATEMENT_LIST_TAIL (cur_stmt_list))
1582 find_uninit_fields (&STATEMENT_LIST_TAIL (cur_stmt_list)->stmt,
1583 &uninitialized, BINFO_TYPE (subobject));
1584 }
1585 else if (!ABSTRACT_CLASS_TYPE_P (current_class_type))
1586 /* C++14 DR1658 Means we do not have to construct vbases of
1587 abstract classes. */
1588 construct_virtual_base (subobject, arguments);
1589 else
1590 /* When not constructing vbases of abstract classes, at least mark
1591 the arguments expressions as read to avoid
1592 -Wunused-but-set-parameter false positives. */
1593 cp_walk_tree (&arguments, mark_exp_read_r, NULL, NULL);
1594
1595 if (inherited_base)
1596 pop_deferring_access_checks ();
1597 }
1598 in_base_initializer = 0;
1599
1600 /* Initialize the vptrs. */
1601 initialize_vtbl_ptrs (current_class_ptr);
1602
1603 /* Initialize the data members. */
1604 while (mem_inits)
1605 {
1606 /* If this initializer was explicitly provided, then the dummy TREE_TYPE
1607 node contains the source location. */
1608 iloc_sentinel ils (EXPR_LOCATION (TREE_TYPE (mem_inits)));
1609
1610 perform_member_init (TREE_PURPOSE (mem_inits),
1611 TREE_VALUE (mem_inits),
1612 uninitialized);
1613
1614 mem_inits = TREE_CHAIN (mem_inits);
1615 }
1616 }
1617
1618 /* Returns the address of the vtable (i.e., the value that should be
1619 assigned to the vptr) for BINFO. */
1620
1621 tree
1622 build_vtbl_address (tree binfo)
1623 {
1624 tree binfo_for = binfo;
1625 tree vtbl;
1626
1627 if (BINFO_VPTR_INDEX (binfo) && BINFO_VIRTUAL_P (binfo))
1628 /* If this is a virtual primary base, then the vtable we want to store
1629 is that for the base this is being used as the primary base of. We
1630 can't simply skip the initialization, because we may be expanding the
1631 inits of a subobject constructor where the virtual base layout
1632 can be different. */
1633 while (BINFO_PRIMARY_P (binfo_for))
1634 binfo_for = BINFO_INHERITANCE_CHAIN (binfo_for);
1635
1636 /* Figure out what vtable BINFO's vtable is based on, and mark it as
1637 used. */
1638 vtbl = get_vtbl_decl_for_binfo (binfo_for);
1639 TREE_USED (vtbl) = true;
1640
1641 /* Now compute the address to use when initializing the vptr. */
1642 vtbl = unshare_expr (BINFO_VTABLE (binfo_for));
1643 if (VAR_P (vtbl))
1644 vtbl = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (vtbl)), vtbl);
1645
1646 return vtbl;
1647 }
1648
1649 /* This code sets up the virtual function tables appropriate for
1650 the pointer DECL. It is a one-ply initialization.
1651
1652 BINFO is the exact type that DECL is supposed to be. In
1653 multiple inheritance, this might mean "C's A" if C : A, B. */
1654
1655 static void
1656 expand_virtual_init (tree binfo, tree decl)
1657 {
1658 tree vtbl, vtbl_ptr;
1659 tree vtt_index;
1660
1661 /* Compute the initializer for vptr. */
1662 vtbl = build_vtbl_address (binfo);
1663
1664 /* We may get this vptr from a VTT, if this is a subobject
1665 constructor or subobject destructor. */
1666 vtt_index = BINFO_VPTR_INDEX (binfo);
1667 if (vtt_index)
1668 {
1669 tree vtbl2;
1670 tree vtt_parm;
1671
1672 /* Compute the value to use, when there's a VTT. */
1673 vtt_parm = current_vtt_parm;
1674 vtbl2 = fold_build_pointer_plus (vtt_parm, vtt_index);
1675 vtbl2 = cp_build_fold_indirect_ref (vtbl2);
1676 vtbl2 = convert (TREE_TYPE (vtbl), vtbl2);
1677
1678 /* The actual initializer is the VTT value only in the subobject
1679 constructor. In maybe_clone_body we'll substitute NULL for
1680 the vtt_parm in the case of the non-subobject constructor. */
1681 vtbl = build_if_in_charge (vtbl, vtbl2);
1682 }
1683
1684 /* Compute the location of the vtpr. */
1685 vtbl_ptr = build_vfield_ref (cp_build_fold_indirect_ref (decl),
1686 TREE_TYPE (binfo));
1687 gcc_assert (vtbl_ptr != error_mark_node);
1688
1689 /* Assign the vtable to the vptr. */
1690 vtbl = convert_force (TREE_TYPE (vtbl_ptr), vtbl, 0, tf_warning_or_error);
1691 finish_expr_stmt (cp_build_modify_expr (input_location, vtbl_ptr, NOP_EXPR,
1692 vtbl, tf_warning_or_error));
1693 }
1694
1695 /* If an exception is thrown in a constructor, those base classes already
1696 constructed must be destroyed. This function creates the cleanup
1697 for BINFO, which has just been constructed. If FLAG is non-NULL,
1698 it is a DECL which is nonzero when this base needs to be
1699 destroyed. */
1700
1701 static void
1702 expand_cleanup_for_base (tree binfo, tree flag)
1703 {
1704 tree expr;
1705
1706 if (!type_build_dtor_call (BINFO_TYPE (binfo)))
1707 return;
1708
1709 /* Call the destructor. */
1710 expr = build_special_member_call (current_class_ref,
1711 base_dtor_identifier,
1712 NULL,
1713 binfo,
1714 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
1715 tf_warning_or_error);
1716
1717 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (BINFO_TYPE (binfo)))
1718 return;
1719
1720 if (flag)
1721 expr = fold_build3_loc (input_location,
1722 COND_EXPR, void_type_node,
1723 c_common_truthvalue_conversion (input_location, flag),
1724 expr, integer_zero_node);
1725
1726 finish_eh_cleanup (expr);
1727 }
1728
1729 /* Construct the virtual base-class VBASE passing the ARGUMENTS to its
1730 constructor. */
1731
1732 static void
1733 construct_virtual_base (tree vbase, tree arguments)
1734 {
1735 tree inner_if_stmt;
1736 tree exp;
1737 tree flag;
1738
1739 /* If there are virtual base classes with destructors, we need to
1740 emit cleanups to destroy them if an exception is thrown during
1741 the construction process. These exception regions (i.e., the
1742 period during which the cleanups must occur) begin from the time
1743 the construction is complete to the end of the function. If we
1744 create a conditional block in which to initialize the
1745 base-classes, then the cleanup region for the virtual base begins
1746 inside a block, and ends outside of that block. This situation
1747 confuses the sjlj exception-handling code. Therefore, we do not
1748 create a single conditional block, but one for each
1749 initialization. (That way the cleanup regions always begin
1750 in the outer block.) We trust the back end to figure out
1751 that the FLAG will not change across initializations, and
1752 avoid doing multiple tests. */
1753 flag = DECL_CHAIN (DECL_ARGUMENTS (current_function_decl));
1754 inner_if_stmt = begin_if_stmt ();
1755 finish_if_stmt_cond (flag, inner_if_stmt);
1756
1757 /* Compute the location of the virtual base. If we're
1758 constructing virtual bases, then we must be the most derived
1759 class. Therefore, we don't have to look up the virtual base;
1760 we already know where it is. */
1761 exp = convert_to_base_statically (current_class_ref, vbase);
1762
1763 expand_aggr_init_1 (vbase, current_class_ref, exp, arguments,
1764 0, tf_warning_or_error);
1765 finish_then_clause (inner_if_stmt);
1766 finish_if_stmt (inner_if_stmt);
1767
1768 expand_cleanup_for_base (vbase, flag);
1769 }
1770
1771 /* Find the context in which this FIELD can be initialized. */
1772
1773 static tree
1774 initializing_context (tree field)
1775 {
1776 tree t = DECL_CONTEXT (field);
1777
1778 /* Anonymous union members can be initialized in the first enclosing
1779 non-anonymous union context. */
1780 while (t && ANON_AGGR_TYPE_P (t))
1781 t = TYPE_CONTEXT (t);
1782 return t;
1783 }
1784
1785 /* Function to give error message if member initialization specification
1786 is erroneous. FIELD is the member we decided to initialize.
1787 TYPE is the type for which the initialization is being performed.
1788 FIELD must be a member of TYPE.
1789
1790 MEMBER_NAME is the name of the member. */
1791
1792 static int
1793 member_init_ok_or_else (tree field, tree type, tree member_name)
1794 {
1795 if (field == error_mark_node)
1796 return 0;
1797 if (!field)
1798 {
1799 error ("class %qT does not have any field named %qD", type,
1800 member_name);
1801 return 0;
1802 }
1803 if (VAR_P (field))
1804 {
1805 error ("%q#D is a static data member; it can only be "
1806 "initialized at its definition",
1807 field);
1808 return 0;
1809 }
1810 if (TREE_CODE (field) != FIELD_DECL)
1811 {
1812 error ("%q#D is not a non-static data member of %qT",
1813 field, type);
1814 return 0;
1815 }
1816 if (initializing_context (field) != type)
1817 {
1818 error ("class %qT does not have any field named %qD", type,
1819 member_name);
1820 return 0;
1821 }
1822
1823 return 1;
1824 }
1825
1826 /* NAME is a FIELD_DECL, an IDENTIFIER_NODE which names a field, or it
1827 is a _TYPE node or TYPE_DECL which names a base for that type.
1828 Check the validity of NAME, and return either the base _TYPE, base
1829 binfo, or the FIELD_DECL of the member. If NAME is invalid, return
1830 NULL_TREE and issue a diagnostic.
1831
1832 An old style unnamed direct single base construction is permitted,
1833 where NAME is NULL. */
1834
1835 tree
1836 expand_member_init (tree name)
1837 {
1838 tree basetype;
1839 tree field;
1840
1841 if (!current_class_ref)
1842 return NULL_TREE;
1843
1844 if (!name)
1845 {
1846 /* This is an obsolete unnamed base class initializer. The
1847 parser will already have warned about its use. */
1848 switch (BINFO_N_BASE_BINFOS (TYPE_BINFO (current_class_type)))
1849 {
1850 case 0:
1851 error ("unnamed initializer for %qT, which has no base classes",
1852 current_class_type);
1853 return NULL_TREE;
1854 case 1:
1855 basetype = BINFO_TYPE
1856 (BINFO_BASE_BINFO (TYPE_BINFO (current_class_type), 0));
1857 break;
1858 default:
1859 error ("unnamed initializer for %qT, which uses multiple inheritance",
1860 current_class_type);
1861 return NULL_TREE;
1862 }
1863 }
1864 else if (TYPE_P (name))
1865 {
1866 basetype = TYPE_MAIN_VARIANT (name);
1867 name = TYPE_NAME (name);
1868 }
1869 else if (TREE_CODE (name) == TYPE_DECL)
1870 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (name));
1871 else
1872 basetype = NULL_TREE;
1873
1874 if (basetype)
1875 {
1876 tree class_binfo;
1877 tree direct_binfo;
1878 tree virtual_binfo;
1879 int i;
1880
1881 if (current_template_parms
1882 || same_type_p (basetype, current_class_type))
1883 return basetype;
1884
1885 class_binfo = TYPE_BINFO (current_class_type);
1886 direct_binfo = NULL_TREE;
1887 virtual_binfo = NULL_TREE;
1888
1889 /* Look for a direct base. */
1890 for (i = 0; BINFO_BASE_ITERATE (class_binfo, i, direct_binfo); ++i)
1891 if (SAME_BINFO_TYPE_P (BINFO_TYPE (direct_binfo), basetype))
1892 break;
1893
1894 /* Look for a virtual base -- unless the direct base is itself
1895 virtual. */
1896 if (!direct_binfo || !BINFO_VIRTUAL_P (direct_binfo))
1897 virtual_binfo = binfo_for_vbase (basetype, current_class_type);
1898
1899 /* [class.base.init]
1900
1901 If a mem-initializer-id is ambiguous because it designates
1902 both a direct non-virtual base class and an inherited virtual
1903 base class, the mem-initializer is ill-formed. */
1904 if (direct_binfo && virtual_binfo)
1905 {
1906 error ("%qD is both a direct base and an indirect virtual base",
1907 basetype);
1908 return NULL_TREE;
1909 }
1910
1911 if (!direct_binfo && !virtual_binfo)
1912 {
1913 if (CLASSTYPE_VBASECLASSES (current_class_type))
1914 error ("type %qT is not a direct or virtual base of %qT",
1915 basetype, current_class_type);
1916 else
1917 error ("type %qT is not a direct base of %qT",
1918 basetype, current_class_type);
1919 return NULL_TREE;
1920 }
1921
1922 return direct_binfo ? direct_binfo : virtual_binfo;
1923 }
1924 else
1925 {
1926 if (identifier_p (name))
1927 field = lookup_field (current_class_type, name, 1, false);
1928 else
1929 field = name;
1930
1931 if (member_init_ok_or_else (field, current_class_type, name))
1932 return field;
1933 }
1934
1935 return NULL_TREE;
1936 }
1937
1938 /* This is like `expand_member_init', only it stores one aggregate
1939 value into another.
1940
1941 INIT comes in two flavors: it is either a value which
1942 is to be stored in EXP, or it is a parameter list
1943 to go to a constructor, which will operate on EXP.
1944 If INIT is not a parameter list for a constructor, then set
1945 LOOKUP_ONLYCONVERTING.
1946 If FLAGS is LOOKUP_ONLYCONVERTING then it is the = init form of
1947 the initializer, if FLAGS is 0, then it is the (init) form.
1948 If `init' is a CONSTRUCTOR, then we emit a warning message,
1949 explaining that such initializations are invalid.
1950
1951 If INIT resolves to a CALL_EXPR which happens to return
1952 something of the type we are looking for, then we know
1953 that we can safely use that call to perform the
1954 initialization.
1955
1956 The virtual function table pointer cannot be set up here, because
1957 we do not really know its type.
1958
1959 This never calls operator=().
1960
1961 When initializing, nothing is CONST.
1962
1963 A default copy constructor may have to be used to perform the
1964 initialization.
1965
1966 A constructor or a conversion operator may have to be used to
1967 perform the initialization, but not both, as it would be ambiguous. */
1968
1969 tree
1970 build_aggr_init (tree exp, tree init, int flags, tsubst_flags_t complain)
1971 {
1972 tree stmt_expr;
1973 tree compound_stmt;
1974 int destroy_temps;
1975 tree type = TREE_TYPE (exp);
1976 int was_const = TREE_READONLY (exp);
1977 int was_volatile = TREE_THIS_VOLATILE (exp);
1978 int is_global;
1979
1980 if (init == error_mark_node)
1981 return error_mark_node;
1982
1983 location_t init_loc = (init
1984 ? cp_expr_loc_or_input_loc (init)
1985 : location_of (exp));
1986
1987 TREE_READONLY (exp) = 0;
1988 TREE_THIS_VOLATILE (exp) = 0;
1989
1990 if (TREE_CODE (type) == ARRAY_TYPE)
1991 {
1992 tree itype = init ? TREE_TYPE (init) : NULL_TREE;
1993 int from_array = 0;
1994
1995 if (VAR_P (exp) && DECL_DECOMPOSITION_P (exp))
1996 {
1997 from_array = 1;
1998 init = mark_rvalue_use (init);
1999 if (init
2000 && DECL_P (tree_strip_any_location_wrapper (init))
2001 && !(flags & LOOKUP_ONLYCONVERTING))
2002 {
2003 /* Wrap the initializer in a CONSTRUCTOR so that build_vec_init
2004 recognizes it as direct-initialization. */
2005 init = build_constructor_single (init_list_type_node,
2006 NULL_TREE, init);
2007 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
2008 }
2009 }
2010 else
2011 {
2012 /* Must arrange to initialize each element of EXP
2013 from elements of INIT. */
2014 if (cv_qualified_p (type))
2015 TREE_TYPE (exp) = cv_unqualified (type);
2016 if (itype && cv_qualified_p (itype))
2017 TREE_TYPE (init) = cv_unqualified (itype);
2018 from_array = (itype && same_type_p (TREE_TYPE (init),
2019 TREE_TYPE (exp)));
2020
2021 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init)
2022 && (!from_array
2023 || (TREE_CODE (init) != CONSTRUCTOR
2024 /* Can happen, eg, handling the compound-literals
2025 extension (ext/complit12.C). */
2026 && TREE_CODE (init) != TARGET_EXPR)))
2027 {
2028 if (complain & tf_error)
2029 error_at (init_loc, "array must be initialized "
2030 "with a brace-enclosed initializer");
2031 return error_mark_node;
2032 }
2033 }
2034
2035 stmt_expr = build_vec_init (exp, NULL_TREE, init,
2036 /*explicit_value_init_p=*/false,
2037 from_array,
2038 complain);
2039 TREE_READONLY (exp) = was_const;
2040 TREE_THIS_VOLATILE (exp) = was_volatile;
2041 TREE_TYPE (exp) = type;
2042 /* Restore the type of init unless it was used directly. */
2043 if (init && TREE_CODE (stmt_expr) != INIT_EXPR)
2044 TREE_TYPE (init) = itype;
2045 return stmt_expr;
2046 }
2047
2048 if (is_copy_initialization (init))
2049 flags |= LOOKUP_ONLYCONVERTING;
2050
2051 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
2052 destroy_temps = stmts_are_full_exprs_p ();
2053 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
2054 bool ok = expand_aggr_init_1 (TYPE_BINFO (type), exp, exp,
2055 init, LOOKUP_NORMAL|flags, complain);
2056 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
2057 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
2058 TREE_READONLY (exp) = was_const;
2059 TREE_THIS_VOLATILE (exp) = was_volatile;
2060 if (!ok)
2061 return error_mark_node;
2062
2063 if ((VAR_P (exp) || TREE_CODE (exp) == PARM_DECL)
2064 && TREE_SIDE_EFFECTS (stmt_expr)
2065 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (type)))
2066 /* Just know that we've seen something for this node. */
2067 TREE_USED (exp) = 1;
2068
2069 return stmt_expr;
2070 }
2071
2072 static bool
2073 expand_default_init (tree binfo, tree true_exp, tree exp, tree init, int flags,
2074 tsubst_flags_t complain)
2075 {
2076 tree type = TREE_TYPE (exp);
2077
2078 /* It fails because there may not be a constructor which takes
2079 its own type as the first (or only parameter), but which does
2080 take other types via a conversion. So, if the thing initializing
2081 the expression is a unit element of type X, first try X(X&),
2082 followed by initialization by X. If neither of these work
2083 out, then look hard. */
2084 tree rval;
2085 vec<tree, va_gc> *parms;
2086
2087 /* If we have direct-initialization from an initializer list, pull
2088 it out of the TREE_LIST so the code below can see it. */
2089 if (init && TREE_CODE (init) == TREE_LIST
2090 && DIRECT_LIST_INIT_P (TREE_VALUE (init)))
2091 {
2092 gcc_checking_assert ((flags & LOOKUP_ONLYCONVERTING) == 0
2093 && TREE_CHAIN (init) == NULL_TREE);
2094 init = TREE_VALUE (init);
2095 /* Only call reshape_init if it has not been called earlier
2096 by the callers. */
2097 if (BRACE_ENCLOSED_INITIALIZER_P (init) && CP_AGGREGATE_TYPE_P (type))
2098 init = reshape_init (type, init, complain);
2099 }
2100
2101 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
2102 && CP_AGGREGATE_TYPE_P (type))
2103 /* A brace-enclosed initializer for an aggregate. In C++0x this can
2104 happen for direct-initialization, too. */
2105 init = digest_init (type, init, complain);
2106
2107 if (init == error_mark_node)
2108 return false;
2109
2110 /* A CONSTRUCTOR of the target's type is a previously digested
2111 initializer, whether that happened just above or in
2112 cp_parser_late_parsing_nsdmi.
2113
2114 A TARGET_EXPR with TARGET_EXPR_DIRECT_INIT_P or TARGET_EXPR_LIST_INIT_P
2115 set represents the whole initialization, so we shouldn't build up
2116 another ctor call. */
2117 if (init
2118 && (TREE_CODE (init) == CONSTRUCTOR
2119 || (TREE_CODE (init) == TARGET_EXPR
2120 && (TARGET_EXPR_DIRECT_INIT_P (init)
2121 || TARGET_EXPR_LIST_INIT_P (init))))
2122 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
2123 {
2124 /* Early initialization via a TARGET_EXPR only works for
2125 complete objects. */
2126 gcc_assert (TREE_CODE (init) == CONSTRUCTOR || true_exp == exp);
2127
2128 init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
2129 TREE_SIDE_EFFECTS (init) = 1;
2130 finish_expr_stmt (init);
2131 return true;
2132 }
2133
2134 if (init && TREE_CODE (init) != TREE_LIST
2135 && (flags & LOOKUP_ONLYCONVERTING)
2136 && !unsafe_return_slot_p (exp))
2137 {
2138 /* Base subobjects should only get direct-initialization. */
2139 gcc_assert (true_exp == exp);
2140
2141 if (flags & DIRECT_BIND)
2142 /* Do nothing. We hit this in two cases: Reference initialization,
2143 where we aren't initializing a real variable, so we don't want
2144 to run a new constructor; and catching an exception, where we
2145 have already built up the constructor call so we could wrap it
2146 in an exception region. */;
2147 else
2148 {
2149 init = ocp_convert (type, init, CONV_IMPLICIT|CONV_FORCE_TEMP,
2150 flags, complain | tf_no_cleanup);
2151 if (init == error_mark_node)
2152 return false;
2153 }
2154
2155 if (TREE_CODE (init) == MUST_NOT_THROW_EXPR)
2156 /* We need to protect the initialization of a catch parm with a
2157 call to terminate(), which shows up as a MUST_NOT_THROW_EXPR
2158 around the TARGET_EXPR for the copy constructor. See
2159 initialize_handler_parm. */
2160 {
2161 TREE_OPERAND (init, 0) = build2 (INIT_EXPR, TREE_TYPE (exp), exp,
2162 TREE_OPERAND (init, 0));
2163 TREE_TYPE (init) = void_type_node;
2164 }
2165 else
2166 init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
2167 TREE_SIDE_EFFECTS (init) = 1;
2168 finish_expr_stmt (init);
2169 return true;
2170 }
2171
2172 if (init == NULL_TREE)
2173 parms = NULL;
2174 else if (TREE_CODE (init) == TREE_LIST && !TREE_TYPE (init))
2175 {
2176 parms = make_tree_vector ();
2177 for (; init != NULL_TREE; init = TREE_CHAIN (init))
2178 vec_safe_push (parms, TREE_VALUE (init));
2179 }
2180 else
2181 parms = make_tree_vector_single (init);
2182
2183 if (exp == current_class_ref && current_function_decl
2184 && DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
2185 {
2186 /* Delegating constructor. */
2187 tree complete;
2188 tree base;
2189 tree elt; unsigned i;
2190
2191 /* Unshare the arguments for the second call. */
2192 releasing_vec parms2;
2193 FOR_EACH_VEC_SAFE_ELT (parms, i, elt)
2194 {
2195 elt = break_out_target_exprs (elt);
2196 vec_safe_push (parms2, elt);
2197 }
2198 complete = build_special_member_call (exp, complete_ctor_identifier,
2199 &parms2, binfo, flags,
2200 complain);
2201 complete = fold_build_cleanup_point_expr (void_type_node, complete);
2202
2203 base = build_special_member_call (exp, base_ctor_identifier,
2204 &parms, binfo, flags,
2205 complain);
2206 base = fold_build_cleanup_point_expr (void_type_node, base);
2207 if (complete == error_mark_node || base == error_mark_node)
2208 return false;
2209 rval = build_if_in_charge (complete, base);
2210 }
2211 else
2212 {
2213 tree ctor_name = (true_exp == exp
2214 ? complete_ctor_identifier : base_ctor_identifier);
2215
2216 rval = build_special_member_call (exp, ctor_name, &parms, binfo, flags,
2217 complain);
2218 if (rval == error_mark_node)
2219 return false;
2220 }
2221
2222 if (parms != NULL)
2223 release_tree_vector (parms);
2224
2225 if (exp == true_exp && TREE_CODE (rval) == CALL_EXPR)
2226 {
2227 tree fn = get_callee_fndecl (rval);
2228 if (fn && DECL_DECLARED_CONSTEXPR_P (fn))
2229 {
2230 tree e = maybe_constant_init (rval, exp);
2231 if (TREE_CONSTANT (e))
2232 rval = build2 (INIT_EXPR, type, exp, e);
2233 }
2234 }
2235
2236 /* FIXME put back convert_to_void? */
2237 if (TREE_SIDE_EFFECTS (rval))
2238 finish_expr_stmt (rval);
2239
2240 return true;
2241 }
2242
2243 /* This function is responsible for initializing EXP with INIT
2244 (if any). Returns true on success, false on failure.
2245
2246 BINFO is the binfo of the type for who we are performing the
2247 initialization. For example, if W is a virtual base class of A and B,
2248 and C : A, B.
2249 If we are initializing B, then W must contain B's W vtable, whereas
2250 were we initializing C, W must contain C's W vtable.
2251
2252 TRUE_EXP is nonzero if it is the true expression being initialized.
2253 In this case, it may be EXP, or may just contain EXP. The reason we
2254 need this is because if EXP is a base element of TRUE_EXP, we
2255 don't necessarily know by looking at EXP where its virtual
2256 baseclass fields should really be pointing. But we do know
2257 from TRUE_EXP. In constructors, we don't know anything about
2258 the value being initialized.
2259
2260 FLAGS is just passed to `build_new_method_call'. See that function
2261 for its description. */
2262
2263 static bool
2264 expand_aggr_init_1 (tree binfo, tree true_exp, tree exp, tree init, int flags,
2265 tsubst_flags_t complain)
2266 {
2267 tree type = TREE_TYPE (exp);
2268
2269 gcc_assert (init != error_mark_node && type != error_mark_node);
2270 gcc_assert (building_stmt_list_p ());
2271
2272 /* Use a function returning the desired type to initialize EXP for us.
2273 If the function is a constructor, and its first argument is
2274 NULL_TREE, know that it was meant for us--just slide exp on
2275 in and expand the constructor. Constructors now come
2276 as TARGET_EXPRs. */
2277
2278 if (init && VAR_P (exp)
2279 && COMPOUND_LITERAL_P (init))
2280 {
2281 vec<tree, va_gc> *cleanups = NULL;
2282 /* If store_init_value returns NULL_TREE, the INIT has been
2283 recorded as the DECL_INITIAL for EXP. That means there's
2284 nothing more we have to do. */
2285 init = store_init_value (exp, init, &cleanups, flags);
2286 if (init)
2287 finish_expr_stmt (init);
2288 gcc_assert (!cleanups);
2289 return true;
2290 }
2291
2292 /* List-initialization from {} becomes value-initialization for non-aggregate
2293 classes with default constructors. Handle this here when we're
2294 initializing a base, so protected access works. */
2295 if (exp != true_exp && init && TREE_CODE (init) == TREE_LIST)
2296 {
2297 tree elt = TREE_VALUE (init);
2298 if (DIRECT_LIST_INIT_P (elt)
2299 && CONSTRUCTOR_ELTS (elt) == 0
2300 && CLASSTYPE_NON_AGGREGATE (type)
2301 && TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
2302 init = void_type_node;
2303 }
2304
2305 /* If an explicit -- but empty -- initializer list was present,
2306 that's value-initialization. */
2307 if (init == void_type_node)
2308 {
2309 /* If the type has data but no user-provided default ctor, we need to zero
2310 out the object. */
2311 if (type_has_non_user_provided_default_constructor (type)
2312 && !is_really_empty_class (type, /*ignore_vptr*/true))
2313 {
2314 tree field_size = NULL_TREE;
2315 if (exp != true_exp && CLASSTYPE_AS_BASE (type) != type)
2316 /* Don't clobber already initialized virtual bases. */
2317 field_size = TYPE_SIZE (CLASSTYPE_AS_BASE (type));
2318 init = build_zero_init_1 (type, NULL_TREE, /*static_storage_p=*/false,
2319 field_size);
2320 init = build2 (INIT_EXPR, type, exp, init);
2321 finish_expr_stmt (init);
2322 }
2323
2324 /* If we don't need to mess with the constructor at all,
2325 then we're done. */
2326 if (! type_build_ctor_call (type))
2327 return true;
2328
2329 /* Otherwise fall through and call the constructor. */
2330 init = NULL_TREE;
2331 }
2332
2333 /* We know that expand_default_init can handle everything we want
2334 at this point. */
2335 return expand_default_init (binfo, true_exp, exp, init, flags, complain);
2336 }
2337
2338 /* Report an error if TYPE is not a user-defined, class type. If
2339 OR_ELSE is nonzero, give an error message. */
2340
2341 int
2342 is_class_type (tree type, int or_else)
2343 {
2344 if (type == error_mark_node)
2345 return 0;
2346
2347 if (! CLASS_TYPE_P (type))
2348 {
2349 if (or_else)
2350 error ("%qT is not a class type", type);
2351 return 0;
2352 }
2353 return 1;
2354 }
2355
2356 /* Returns true iff the initializer INIT represents copy-initialization
2357 (and therefore we must set LOOKUP_ONLYCONVERTING when processing it). */
2358
2359 bool
2360 is_copy_initialization (tree init)
2361 {
2362 return (init && init != void_type_node
2363 && TREE_CODE (init) != TREE_LIST
2364 && !(TREE_CODE (init) == TARGET_EXPR
2365 && TARGET_EXPR_DIRECT_INIT_P (init))
2366 && !DIRECT_LIST_INIT_P (init));
2367 }
2368
2369 /* Build a reference to a member of an aggregate. This is not a C++
2370 `&', but really something which can have its address taken, and
2371 then act as a pointer to member, for example TYPE :: FIELD can have
2372 its address taken by saying & TYPE :: FIELD. ADDRESS_P is true if
2373 this expression is the operand of "&".
2374
2375 @@ Prints out lousy diagnostics for operator <typename>
2376 @@ fields.
2377
2378 @@ This function should be rewritten and placed in search.cc. */
2379
2380 tree
2381 build_offset_ref (tree type, tree member, bool address_p,
2382 tsubst_flags_t complain)
2383 {
2384 tree decl;
2385 tree basebinfo = NULL_TREE;
2386
2387 /* class templates can come in as TEMPLATE_DECLs here. */
2388 if (TREE_CODE (member) == TEMPLATE_DECL)
2389 return member;
2390
2391 if (dependent_scope_p (type) || type_dependent_expression_p (member))
2392 return build_qualified_name (NULL_TREE, type, member,
2393 /*template_p=*/false);
2394
2395 gcc_assert (TYPE_P (type));
2396 if (! is_class_type (type, 1))
2397 return error_mark_node;
2398
2399 gcc_assert (DECL_P (member) || BASELINK_P (member));
2400 /* Callers should call mark_used before this point, except for functions. */
2401 gcc_assert (!DECL_P (member) || TREE_USED (member)
2402 || TREE_CODE (member) == FUNCTION_DECL);
2403
2404 type = TYPE_MAIN_VARIANT (type);
2405 if (!COMPLETE_OR_OPEN_TYPE_P (complete_type (type)))
2406 {
2407 if (complain & tf_error)
2408 error ("incomplete type %qT does not have member %qD", type, member);
2409 return error_mark_node;
2410 }
2411
2412 /* Entities other than non-static members need no further
2413 processing. */
2414 if (TREE_CODE (member) == TYPE_DECL)
2415 return member;
2416 if (VAR_P (member) || TREE_CODE (member) == CONST_DECL)
2417 return convert_from_reference (member);
2418
2419 if (TREE_CODE (member) == FIELD_DECL && DECL_C_BIT_FIELD (member))
2420 {
2421 if (complain & tf_error)
2422 error ("invalid pointer to bit-field %qD", member);
2423 return error_mark_node;
2424 }
2425
2426 /* Set up BASEBINFO for member lookup. */
2427 decl = maybe_dummy_object (type, &basebinfo);
2428
2429 /* A lot of this logic is now handled in lookup_member. */
2430 if (BASELINK_P (member))
2431 {
2432 /* Go from the TREE_BASELINK to the member function info. */
2433 tree t = BASELINK_FUNCTIONS (member);
2434
2435 if (TREE_CODE (t) != TEMPLATE_ID_EXPR && !really_overloaded_fn (t))
2436 {
2437 /* Get rid of a potential OVERLOAD around it. */
2438 t = OVL_FIRST (t);
2439
2440 /* Unique functions are handled easily. */
2441
2442 /* For non-static member of base class, we need a special rule
2443 for access checking [class.protected]:
2444
2445 If the access is to form a pointer to member, the
2446 nested-name-specifier shall name the derived class
2447 (or any class derived from that class). */
2448 bool ok;
2449 if (address_p && DECL_P (t)
2450 && DECL_NONSTATIC_MEMBER_P (t))
2451 ok = perform_or_defer_access_check (TYPE_BINFO (type), t, t,
2452 complain);
2453 else
2454 ok = perform_or_defer_access_check (basebinfo, t, t,
2455 complain);
2456 if (!ok)
2457 return error_mark_node;
2458 if (DECL_STATIC_FUNCTION_P (t))
2459 return member;
2460 member = t;
2461 }
2462 else
2463 TREE_TYPE (member) = unknown_type_node;
2464 }
2465 else if (address_p && TREE_CODE (member) == FIELD_DECL)
2466 {
2467 /* We need additional test besides the one in
2468 check_accessibility_of_qualified_id in case it is
2469 a pointer to non-static member. */
2470 if (!perform_or_defer_access_check (TYPE_BINFO (type), member, member,
2471 complain))
2472 return error_mark_node;
2473 }
2474
2475 if (!address_p)
2476 {
2477 /* If MEMBER is non-static, then the program has fallen afoul of
2478 [expr.prim]:
2479
2480 An id-expression that denotes a non-static data member or
2481 non-static member function of a class can only be used:
2482
2483 -- as part of a class member access (_expr.ref_) in which the
2484 object-expression refers to the member's class or a class
2485 derived from that class, or
2486
2487 -- to form a pointer to member (_expr.unary.op_), or
2488
2489 -- in the body of a non-static member function of that class or
2490 of a class derived from that class (_class.mfct.non-static_), or
2491
2492 -- in a mem-initializer for a constructor for that class or for
2493 a class derived from that class (_class.base.init_). */
2494 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (member))
2495 {
2496 /* Build a representation of the qualified name suitable
2497 for use as the operand to "&" -- even though the "&" is
2498 not actually present. */
2499 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2500 /* In Microsoft mode, treat a non-static member function as if
2501 it were a pointer-to-member. */
2502 if (flag_ms_extensions)
2503 {
2504 PTRMEM_OK_P (member) = 1;
2505 return cp_build_addr_expr (member, complain);
2506 }
2507 if (complain & tf_error)
2508 error ("invalid use of non-static member function %qD",
2509 TREE_OPERAND (member, 1));
2510 return error_mark_node;
2511 }
2512 else if (TREE_CODE (member) == FIELD_DECL)
2513 {
2514 if (complain & tf_error)
2515 error ("invalid use of non-static data member %qD", member);
2516 return error_mark_node;
2517 }
2518 return member;
2519 }
2520
2521 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2522 PTRMEM_OK_P (member) = 1;
2523 return member;
2524 }
2525
2526 /* If DECL is a scalar enumeration constant or variable with a
2527 constant initializer, return the initializer (or, its initializers,
2528 recursively); otherwise, return DECL. If STRICT_P, the
2529 initializer is only returned if DECL is a
2530 constant-expression. If RETURN_AGGREGATE_CST_OK_P, it is ok to
2531 return an aggregate constant. If UNSHARE_P, return an unshared
2532 copy of the initializer. */
2533
2534 static tree
2535 constant_value_1 (tree decl, bool strict_p, bool return_aggregate_cst_ok_p,
2536 bool unshare_p)
2537 {
2538 while (TREE_CODE (decl) == CONST_DECL
2539 || decl_constant_var_p (decl)
2540 || (!strict_p && VAR_P (decl)
2541 && CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (decl))))
2542 {
2543 tree init;
2544 /* If DECL is a static data member in a template
2545 specialization, we must instantiate it here. The
2546 initializer for the static data member is not processed
2547 until needed; we need it now. */
2548 mark_used (decl, tf_none);
2549 init = DECL_INITIAL (decl);
2550 if (init == error_mark_node)
2551 {
2552 if (TREE_CODE (decl) == CONST_DECL
2553 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2554 /* Treat the error as a constant to avoid cascading errors on
2555 excessively recursive template instantiation (c++/9335). */
2556 return init;
2557 else
2558 return decl;
2559 }
2560 /* Initializers in templates are generally expanded during
2561 instantiation, so before that for const int i(2)
2562 INIT is a TREE_LIST with the actual initializer as
2563 TREE_VALUE. */
2564 if (processing_template_decl
2565 && init
2566 && TREE_CODE (init) == TREE_LIST
2567 && TREE_CHAIN (init) == NULL_TREE)
2568 init = TREE_VALUE (init);
2569 /* Instantiate a non-dependent initializer for user variables. We
2570 mustn't do this for the temporary for an array compound literal;
2571 trying to instatiate the initializer will keep creating new
2572 temporaries until we crash. Probably it's not useful to do it for
2573 other artificial variables, either. */
2574 if (!DECL_ARTIFICIAL (decl))
2575 init = instantiate_non_dependent_or_null (init);
2576 if (!init
2577 || !TREE_TYPE (init)
2578 || !TREE_CONSTANT (init)
2579 || (!return_aggregate_cst_ok_p
2580 /* Unless RETURN_AGGREGATE_CST_OK_P is true, do not
2581 return an aggregate constant (of which string
2582 literals are a special case), as we do not want
2583 to make inadvertent copies of such entities, and
2584 we must be sure that their addresses are the
2585 same everywhere. */
2586 && (TREE_CODE (init) == CONSTRUCTOR
2587 || TREE_CODE (init) == STRING_CST)))
2588 break;
2589 /* Don't return a CONSTRUCTOR for a variable with partial run-time
2590 initialization, since it doesn't represent the entire value.
2591 Similarly for VECTOR_CSTs created by cp_folding those
2592 CONSTRUCTORs. */
2593 if ((TREE_CODE (init) == CONSTRUCTOR
2594 || TREE_CODE (init) == VECTOR_CST)
2595 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2596 break;
2597 /* If the variable has a dynamic initializer, don't use its
2598 DECL_INITIAL which doesn't reflect the real value. */
2599 if (VAR_P (decl)
2600 && TREE_STATIC (decl)
2601 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)
2602 && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2603 break;
2604 decl = init;
2605 }
2606 return unshare_p ? unshare_expr (decl) : decl;
2607 }
2608
2609 /* If DECL is a CONST_DECL, or a constant VAR_DECL initialized by constant
2610 of integral or enumeration type, or a constexpr variable of scalar type,
2611 then return that value. These are those variables permitted in constant
2612 expressions by [5.19/1]. */
2613
2614 tree
2615 scalar_constant_value (tree decl)
2616 {
2617 return constant_value_1 (decl, /*strict_p=*/true,
2618 /*return_aggregate_cst_ok_p=*/false,
2619 /*unshare_p=*/true);
2620 }
2621
2622 /* Like scalar_constant_value, but can also return aggregate initializers.
2623 If UNSHARE_P, return an unshared copy of the initializer. */
2624
2625 tree
2626 decl_really_constant_value (tree decl, bool unshare_p /*= true*/)
2627 {
2628 return constant_value_1 (decl, /*strict_p=*/true,
2629 /*return_aggregate_cst_ok_p=*/true,
2630 /*unshare_p=*/unshare_p);
2631 }
2632
2633 /* A more relaxed version of decl_really_constant_value, used by the
2634 common C/C++ code. */
2635
2636 tree
2637 decl_constant_value (tree decl, bool unshare_p)
2638 {
2639 return constant_value_1 (decl, /*strict_p=*/processing_template_decl,
2640 /*return_aggregate_cst_ok_p=*/true,
2641 /*unshare_p=*/unshare_p);
2642 }
2643
2644 tree
2645 decl_constant_value (tree decl)
2646 {
2647 return decl_constant_value (decl, /*unshare_p=*/true);
2648 }
2649 \f
2650 /* Common subroutines of build_new and build_vec_delete. */
2651 \f
2652 /* Build and return a NEW_EXPR. If NELTS is non-NULL, TYPE[NELTS] is
2653 the type of the object being allocated; otherwise, it's just TYPE.
2654 INIT is the initializer, if any. USE_GLOBAL_NEW is true if the
2655 user explicitly wrote "::operator new". PLACEMENT, if non-NULL, is
2656 a vector of arguments to be provided as arguments to a placement
2657 new operator. This routine performs no semantic checks; it just
2658 creates and returns a NEW_EXPR. */
2659
2660 static tree
2661 build_raw_new_expr (location_t loc, vec<tree, va_gc> *placement, tree type,
2662 tree nelts, vec<tree, va_gc> *init, int use_global_new)
2663 {
2664 tree init_list;
2665 tree new_expr;
2666
2667 /* If INIT is NULL, the we want to store NULL_TREE in the NEW_EXPR.
2668 If INIT is not NULL, then we want to store VOID_ZERO_NODE. This
2669 permits us to distinguish the case of a missing initializer "new
2670 int" from an empty initializer "new int()". */
2671 if (init == NULL)
2672 init_list = NULL_TREE;
2673 else if (init->is_empty ())
2674 init_list = void_node;
2675 else
2676 init_list = build_tree_list_vec (init);
2677
2678 new_expr = build4_loc (loc, NEW_EXPR, build_pointer_type (type),
2679 build_tree_list_vec (placement), type, nelts,
2680 init_list);
2681 NEW_EXPR_USE_GLOBAL (new_expr) = use_global_new;
2682 TREE_SIDE_EFFECTS (new_expr) = 1;
2683
2684 return new_expr;
2685 }
2686
2687 /* Diagnose uninitialized const members or reference members of type
2688 TYPE. USING_NEW is used to disambiguate the diagnostic between a
2689 new expression without a new-initializer and a declaration. Returns
2690 the error count. */
2691
2692 static int
2693 diagnose_uninitialized_cst_or_ref_member_1 (tree type, tree origin,
2694 bool using_new, bool complain)
2695 {
2696 tree field;
2697 int error_count = 0;
2698
2699 if (type_has_user_provided_constructor (type))
2700 return 0;
2701
2702 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
2703 {
2704 tree field_type;
2705
2706 if (TREE_CODE (field) != FIELD_DECL)
2707 continue;
2708
2709 field_type = strip_array_types (TREE_TYPE (field));
2710
2711 if (type_has_user_provided_constructor (field_type))
2712 continue;
2713
2714 if (TYPE_REF_P (field_type))
2715 {
2716 ++ error_count;
2717 if (complain)
2718 {
2719 if (DECL_CONTEXT (field) == origin)
2720 {
2721 if (using_new)
2722 error ("uninitialized reference member in %q#T "
2723 "using %<new%> without new-initializer", origin);
2724 else
2725 error ("uninitialized reference member in %q#T", origin);
2726 }
2727 else
2728 {
2729 if (using_new)
2730 error ("uninitialized reference member in base %q#T "
2731 "of %q#T using %<new%> without new-initializer",
2732 DECL_CONTEXT (field), origin);
2733 else
2734 error ("uninitialized reference member in base %q#T "
2735 "of %q#T", DECL_CONTEXT (field), origin);
2736 }
2737 inform (DECL_SOURCE_LOCATION (field),
2738 "%q#D should be initialized", field);
2739 }
2740 }
2741
2742 if (CP_TYPE_CONST_P (field_type))
2743 {
2744 ++ error_count;
2745 if (complain)
2746 {
2747 if (DECL_CONTEXT (field) == origin)
2748 {
2749 if (using_new)
2750 error ("uninitialized const member in %q#T "
2751 "using %<new%> without new-initializer", origin);
2752 else
2753 error ("uninitialized const member in %q#T", origin);
2754 }
2755 else
2756 {
2757 if (using_new)
2758 error ("uninitialized const member in base %q#T "
2759 "of %q#T using %<new%> without new-initializer",
2760 DECL_CONTEXT (field), origin);
2761 else
2762 error ("uninitialized const member in base %q#T "
2763 "of %q#T", DECL_CONTEXT (field), origin);
2764 }
2765 inform (DECL_SOURCE_LOCATION (field),
2766 "%q#D should be initialized", field);
2767 }
2768 }
2769
2770 if (CLASS_TYPE_P (field_type))
2771 error_count
2772 += diagnose_uninitialized_cst_or_ref_member_1 (field_type, origin,
2773 using_new, complain);
2774 }
2775 return error_count;
2776 }
2777
2778 int
2779 diagnose_uninitialized_cst_or_ref_member (tree type, bool using_new, bool complain)
2780 {
2781 return diagnose_uninitialized_cst_or_ref_member_1 (type, type, using_new, complain);
2782 }
2783
2784 /* Call __cxa_bad_array_new_length to indicate that the size calculation
2785 overflowed. Pretend it returns sizetype so that it plays nicely in the
2786 COND_EXPR. */
2787
2788 tree
2789 throw_bad_array_new_length (void)
2790 {
2791 if (!fn)
2792 {
2793 tree name = get_identifier ("__cxa_throw_bad_array_new_length");
2794
2795 fn = get_global_binding (name);
2796 if (!fn)
2797 fn = push_throw_library_fn
2798 (name, build_function_type_list (sizetype, NULL_TREE));
2799 }
2800
2801 return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
2802 }
2803
2804 /* Attempt to verify that the argument, OPER, of a placement new expression
2805 refers to an object sufficiently large for an object of TYPE or an array
2806 of NELTS of such objects when NELTS is non-null, and issue a warning when
2807 it does not. SIZE specifies the size needed to construct the object or
2808 array and captures the result of NELTS * sizeof (TYPE). (SIZE could be
2809 greater when the array under construction requires a cookie to store
2810 NELTS. GCC's placement new expression stores the cookie when invoking
2811 a user-defined placement new operator function but not the default one.
2812 Placement new expressions with user-defined placement new operator are
2813 not diagnosed since we don't know how they use the buffer (this could
2814 be a future extension). */
2815 static void
2816 warn_placement_new_too_small (tree type, tree nelts, tree size, tree oper)
2817 {
2818 location_t loc = cp_expr_loc_or_input_loc (oper);
2819
2820 STRIP_NOPS (oper);
2821
2822 /* Using a function argument or a (non-array) variable as an argument
2823 to placement new is not checked since it's unknown what it might
2824 point to. */
2825 if (TREE_CODE (oper) == PARM_DECL
2826 || VAR_P (oper)
2827 || TREE_CODE (oper) == COMPONENT_REF)
2828 return;
2829
2830 /* Evaluate any constant expressions. */
2831 size = fold_non_dependent_expr (size);
2832
2833 access_ref ref;
2834 ref.eval = [](tree x){ return fold_non_dependent_expr (x); };
2835 ref.trail1special = warn_placement_new < 2;
2836 tree objsize = compute_objsize (oper, 1, &ref);
2837 if (!objsize)
2838 return;
2839
2840 /* We can only draw conclusions if ref.deref == -1,
2841 i.e. oper is the address of the object. */
2842 if (ref.deref != -1)
2843 return;
2844
2845 offset_int bytes_avail = wi::to_offset (objsize);
2846 offset_int bytes_need;
2847
2848 if (CONSTANT_CLASS_P (size))
2849 bytes_need = wi::to_offset (size);
2850 else if (nelts && CONSTANT_CLASS_P (nelts))
2851 bytes_need = (wi::to_offset (nelts)
2852 * wi::to_offset (TYPE_SIZE_UNIT (type)));
2853 else if (tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2854 bytes_need = wi::to_offset (TYPE_SIZE_UNIT (type));
2855 else
2856 {
2857 /* The type is a VLA. */
2858 return;
2859 }
2860
2861 if (bytes_avail >= bytes_need)
2862 return;
2863
2864 /* True when the size to mention in the warning is exact as opposed
2865 to "at least N". */
2866 const bool exact_size = (ref.offrng[0] == ref.offrng[1]
2867 || ref.sizrng[1] - ref.offrng[0] == 0);
2868
2869 tree opertype = ref.ref ? TREE_TYPE (ref.ref) : TREE_TYPE (oper);
2870 bool warned = false;
2871 if (nelts)
2872 nelts = fold_for_warn (nelts);
2873 if (nelts)
2874 if (CONSTANT_CLASS_P (nelts))
2875 warned = warning_at (loc, OPT_Wplacement_new_,
2876 (exact_size
2877 ? G_("placement new constructing an object "
2878 "of type %<%T [%wu]%> and size %qwu "
2879 "in a region of type %qT and size %qwi")
2880 : G_("placement new constructing an object "
2881 "of type %<%T [%wu]%> and size %qwu "
2882 "in a region of type %qT and size "
2883 "at most %qwu")),
2884 type, tree_to_uhwi (nelts),
2885 bytes_need.to_uhwi (),
2886 opertype, bytes_avail.to_uhwi ());
2887 else
2888 warned = warning_at (loc, OPT_Wplacement_new_,
2889 (exact_size
2890 ? G_("placement new constructing an array "
2891 "of objects of type %qT and size %qwu "
2892 "in a region of type %qT and size %qwi")
2893 : G_("placement new constructing an array "
2894 "of objects of type %qT and size %qwu "
2895 "in a region of type %qT and size "
2896 "at most %qwu")),
2897 type, bytes_need.to_uhwi (), opertype,
2898 bytes_avail.to_uhwi ());
2899 else
2900 warned = warning_at (loc, OPT_Wplacement_new_,
2901 (exact_size
2902 ? G_("placement new constructing an object "
2903 "of type %qT and size %qwu in a region "
2904 "of type %qT and size %qwi")
2905 : G_("placement new constructing an object "
2906 "of type %qT "
2907 "and size %qwu in a region of type %qT "
2908 "and size at most %qwu")),
2909 type, bytes_need.to_uhwi (), opertype,
2910 bytes_avail.to_uhwi ());
2911
2912 if (!warned || !ref.ref)
2913 return;
2914
2915 if (ref.offrng[0] == 0 || !ref.offset_bounded ())
2916 /* Avoid mentioning the offset when its lower bound is zero
2917 or when it's impossibly large. */
2918 inform (DECL_SOURCE_LOCATION (ref.ref),
2919 "%qD declared here", ref.ref);
2920 else if (ref.offrng[0] == ref.offrng[1])
2921 inform (DECL_SOURCE_LOCATION (ref.ref),
2922 "at offset %wi from %qD declared here",
2923 ref.offrng[0].to_shwi (), ref.ref);
2924 else
2925 inform (DECL_SOURCE_LOCATION (ref.ref),
2926 "at offset [%wi, %wi] from %qD declared here",
2927 ref.offrng[0].to_shwi (), ref.offrng[1].to_shwi (), ref.ref);
2928 }
2929
2930 /* True if alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__. */
2931
2932 bool
2933 type_has_new_extended_alignment (tree t)
2934 {
2935 return (aligned_new_threshold
2936 && TYPE_ALIGN_UNIT (t) > (unsigned)aligned_new_threshold);
2937 }
2938
2939 /* Return the alignment we expect malloc to guarantee. This should just be
2940 MALLOC_ABI_ALIGNMENT, but that macro defaults to only BITS_PER_WORD for some
2941 reason, so don't let the threshold be smaller than max_align_t_align. */
2942
2943 unsigned
2944 malloc_alignment ()
2945 {
2946 return MAX (max_align_t_align(), MALLOC_ABI_ALIGNMENT);
2947 }
2948
2949 /* Determine whether an allocation function is a namespace-scope
2950 non-replaceable placement new function. See DR 1748. */
2951 static bool
2952 std_placement_new_fn_p (tree alloc_fn)
2953 {
2954 if (DECL_NAMESPACE_SCOPE_P (alloc_fn))
2955 {
2956 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (alloc_fn)));
2957 if ((TREE_VALUE (first_arg) == ptr_type_node)
2958 && TREE_CHAIN (first_arg) == void_list_node)
2959 return true;
2960 }
2961 return false;
2962 }
2963
2964 /* For element type ELT_TYPE, return the appropriate type of the heap object
2965 containing such element(s). COOKIE_SIZE is the size of cookie in bytes.
2966 Return
2967 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
2968 where N is nothing (flexible array member) if ITYPE2 is NULL, otherwise
2969 the array has ITYPE2 as its TYPE_DOMAIN. */
2970
2971 tree
2972 build_new_constexpr_heap_type (tree elt_type, tree cookie_size, tree itype2)
2973 {
2974 gcc_assert (tree_fits_uhwi_p (cookie_size));
2975 unsigned HOST_WIDE_INT csz = tree_to_uhwi (cookie_size);
2976 csz /= int_size_in_bytes (sizetype);
2977 tree itype1 = build_index_type (size_int (csz - 1));
2978 tree atype1 = build_cplus_array_type (sizetype, itype1);
2979 tree atype2 = build_cplus_array_type (elt_type, itype2);
2980 tree rtype = cxx_make_type (RECORD_TYPE);
2981 TYPE_NAME (rtype) = heap_identifier;
2982 tree fld1 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype1);
2983 tree fld2 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype2);
2984 DECL_FIELD_CONTEXT (fld1) = rtype;
2985 DECL_FIELD_CONTEXT (fld2) = rtype;
2986 DECL_ARTIFICIAL (fld1) = true;
2987 DECL_ARTIFICIAL (fld2) = true;
2988 TYPE_FIELDS (rtype) = fld1;
2989 DECL_CHAIN (fld1) = fld2;
2990 layout_type (rtype);
2991 return rtype;
2992 }
2993
2994 /* Help the constexpr code to find the right type for the heap variable
2995 by adding a NOP_EXPR around ALLOC_CALL if needed for cookie_size.
2996 Return ALLOC_CALL or ALLOC_CALL cast to a pointer to
2997 struct { size_t[cookie_size/sizeof(size_t)]; elt_type[]; }. */
2998
2999 static tree
3000 maybe_wrap_new_for_constexpr (tree alloc_call, tree elt_type, tree cookie_size)
3001 {
3002 if (cxx_dialect < cxx20)
3003 return alloc_call;
3004
3005 if (current_function_decl != NULL_TREE
3006 && !DECL_DECLARED_CONSTEXPR_P (current_function_decl))
3007 return alloc_call;
3008
3009 tree call_expr = extract_call_expr (alloc_call);
3010 if (call_expr == error_mark_node)
3011 return alloc_call;
3012
3013 tree alloc_call_fndecl = cp_get_callee_fndecl_nofold (call_expr);
3014 if (alloc_call_fndecl == NULL_TREE
3015 || !IDENTIFIER_NEW_OP_P (DECL_NAME (alloc_call_fndecl))
3016 || CP_DECL_CONTEXT (alloc_call_fndecl) != global_namespace)
3017 return alloc_call;
3018
3019 tree rtype = build_new_constexpr_heap_type (elt_type, cookie_size,
3020 NULL_TREE);
3021 return build_nop (build_pointer_type (rtype), alloc_call);
3022 }
3023
3024 /* Generate code for a new-expression, including calling the "operator
3025 new" function, initializing the object, and, if an exception occurs
3026 during construction, cleaning up. The arguments are as for
3027 build_raw_new_expr. This may change PLACEMENT and INIT.
3028 TYPE is the type of the object being constructed, possibly an array
3029 of NELTS elements when NELTS is non-null (in "new T[NELTS]", T may
3030 be an array of the form U[inner], with the whole expression being
3031 "new U[NELTS][inner]"). */
3032
3033 static tree
3034 build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts,
3035 vec<tree, va_gc> **init, bool globally_qualified_p,
3036 tsubst_flags_t complain)
3037 {
3038 tree size, rval;
3039 /* True iff this is a call to "operator new[]" instead of just
3040 "operator new". */
3041 bool array_p = false;
3042 /* If ARRAY_P is true, the element type of the array. This is never
3043 an ARRAY_TYPE; for something like "new int[3][4]", the
3044 ELT_TYPE is "int". If ARRAY_P is false, this is the same type as
3045 TYPE. */
3046 tree elt_type;
3047 /* The type of the new-expression. (This type is always a pointer
3048 type.) */
3049 tree pointer_type;
3050 tree non_const_pointer_type;
3051 /* The most significant array bound in int[OUTER_NELTS][inner]. */
3052 tree outer_nelts = NULL_TREE;
3053 /* For arrays with a non-constant number of elements, a bounds checks
3054 on the NELTS parameter to avoid integer overflow at runtime. */
3055 tree outer_nelts_check = NULL_TREE;
3056 bool outer_nelts_from_type = false;
3057 /* Number of the "inner" elements in "new T[OUTER_NELTS][inner]". */
3058 offset_int inner_nelts_count = 1;
3059 tree alloc_call, alloc_expr;
3060 /* Size of the inner array elements (those with constant dimensions). */
3061 offset_int inner_size;
3062 /* The address returned by the call to "operator new". This node is
3063 a VAR_DECL and is therefore reusable. */
3064 tree alloc_node;
3065 tree alloc_fn;
3066 tree cookie_expr, init_expr;
3067 int nothrow, check_new;
3068 /* If non-NULL, the number of extra bytes to allocate at the
3069 beginning of the storage allocated for an array-new expression in
3070 order to store the number of elements. */
3071 tree cookie_size = NULL_TREE;
3072 tree placement_first;
3073 tree placement_expr = NULL_TREE;
3074 /* True if the function we are calling is a placement allocation
3075 function. */
3076 bool placement_allocation_fn_p;
3077 /* True if the storage must be initialized, either by a constructor
3078 or due to an explicit new-initializer. */
3079 bool is_initialized;
3080 /* The address of the thing allocated, not including any cookie. In
3081 particular, if an array cookie is in use, DATA_ADDR is the
3082 address of the first array element. This node is a VAR_DECL, and
3083 is therefore reusable. */
3084 tree data_addr;
3085 tree orig_type = type;
3086
3087 if (nelts)
3088 {
3089 outer_nelts = nelts;
3090 array_p = true;
3091 }
3092 else if (TREE_CODE (type) == ARRAY_TYPE)
3093 {
3094 /* Transforms new (T[N]) to new T[N]. The former is a GNU
3095 extension for variable N. (This also covers new T where T is
3096 a VLA typedef.) */
3097 array_p = true;
3098 nelts = array_type_nelts_top (type);
3099 outer_nelts = nelts;
3100 type = TREE_TYPE (type);
3101 outer_nelts_from_type = true;
3102 }
3103
3104 /* Lots of logic below depends on whether we have a constant number of
3105 elements, so go ahead and fold it now. */
3106 const_tree cst_outer_nelts = fold_non_dependent_expr (outer_nelts, complain);
3107
3108 /* If our base type is an array, then make sure we know how many elements
3109 it has. */
3110 for (elt_type = type;
3111 TREE_CODE (elt_type) == ARRAY_TYPE;
3112 elt_type = TREE_TYPE (elt_type))
3113 {
3114 tree inner_nelts = array_type_nelts_top (elt_type);
3115 tree inner_nelts_cst = maybe_constant_value (inner_nelts);
3116 if (TREE_CODE (inner_nelts_cst) == INTEGER_CST)
3117 {
3118 wi::overflow_type overflow;
3119 offset_int result = wi::mul (wi::to_offset (inner_nelts_cst),
3120 inner_nelts_count, SIGNED, &overflow);
3121 if (overflow)
3122 {
3123 if (complain & tf_error)
3124 error ("integer overflow in array size");
3125 nelts = error_mark_node;
3126 }
3127 inner_nelts_count = result;
3128 }
3129 else
3130 {
3131 if (complain & tf_error)
3132 {
3133 error_at (cp_expr_loc_or_input_loc (inner_nelts),
3134 "array size in new-expression must be constant");
3135 cxx_constant_value(inner_nelts);
3136 }
3137 nelts = error_mark_node;
3138 }
3139 if (nelts != error_mark_node)
3140 nelts = cp_build_binary_op (input_location,
3141 MULT_EXPR, nelts,
3142 inner_nelts_cst,
3143 complain);
3144 }
3145
3146 if (!verify_type_context (input_location, TCTX_ALLOCATION, elt_type,
3147 !(complain & tf_error)))
3148 return error_mark_node;
3149
3150 if (variably_modified_type_p (elt_type, NULL_TREE) && (complain & tf_error))
3151 {
3152 error ("variably modified type not allowed in new-expression");
3153 return error_mark_node;
3154 }
3155
3156 if (nelts == error_mark_node)
3157 return error_mark_node;
3158
3159 /* Warn if we performed the (T[N]) to T[N] transformation and N is
3160 variable. */
3161 if (outer_nelts_from_type
3162 && !TREE_CONSTANT (cst_outer_nelts))
3163 {
3164 if (complain & tf_warning_or_error)
3165 {
3166 pedwarn (cp_expr_loc_or_input_loc (outer_nelts), OPT_Wvla,
3167 typedef_variant_p (orig_type)
3168 ? G_("non-constant array new length must be specified "
3169 "directly, not by %<typedef%>")
3170 : G_("non-constant array new length must be specified "
3171 "without parentheses around the type-id"));
3172 }
3173 else
3174 return error_mark_node;
3175 }
3176
3177 if (VOID_TYPE_P (elt_type))
3178 {
3179 if (complain & tf_error)
3180 error ("invalid type %<void%> for %<new%>");
3181 return error_mark_node;
3182 }
3183
3184 if (is_std_init_list (elt_type) && !cp_unevaluated_operand)
3185 warning (OPT_Winit_list_lifetime,
3186 "%<new%> of %<initializer_list%> does not "
3187 "extend the lifetime of the underlying array");
3188
3189 if (abstract_virtuals_error_sfinae (ACU_NEW, elt_type, complain))
3190 return error_mark_node;
3191
3192 is_initialized = (type_build_ctor_call (elt_type) || *init != NULL);
3193
3194 if (*init == NULL && cxx_dialect < cxx11)
3195 {
3196 bool maybe_uninitialized_error = false;
3197 /* A program that calls for default-initialization [...] of an
3198 entity of reference type is ill-formed. */
3199 if (CLASSTYPE_REF_FIELDS_NEED_INIT (elt_type))
3200 maybe_uninitialized_error = true;
3201
3202 /* A new-expression that creates an object of type T initializes
3203 that object as follows:
3204 - If the new-initializer is omitted:
3205 -- If T is a (possibly cv-qualified) non-POD class type
3206 (or array thereof), the object is default-initialized (8.5).
3207 [...]
3208 -- Otherwise, the object created has indeterminate
3209 value. If T is a const-qualified type, or a (possibly
3210 cv-qualified) POD class type (or array thereof)
3211 containing (directly or indirectly) a member of
3212 const-qualified type, the program is ill-formed; */
3213
3214 if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (elt_type))
3215 maybe_uninitialized_error = true;
3216
3217 if (maybe_uninitialized_error
3218 && diagnose_uninitialized_cst_or_ref_member (elt_type,
3219 /*using_new=*/true,
3220 complain & tf_error))
3221 return error_mark_node;
3222 }
3223
3224 if (CP_TYPE_CONST_P (elt_type) && *init == NULL
3225 && default_init_uninitialized_part (elt_type))
3226 {
3227 if (complain & tf_error)
3228 error ("uninitialized const in %<new%> of %q#T", elt_type);
3229 return error_mark_node;
3230 }
3231
3232 size = size_in_bytes (elt_type);
3233 if (array_p)
3234 {
3235 /* Maximum available size in bytes. Half of the address space
3236 minus the cookie size. */
3237 offset_int max_size
3238 = wi::set_bit_in_zero <offset_int> (TYPE_PRECISION (sizetype) - 1);
3239 /* Maximum number of outer elements which can be allocated. */
3240 offset_int max_outer_nelts;
3241 tree max_outer_nelts_tree;
3242
3243 gcc_assert (TREE_CODE (size) == INTEGER_CST);
3244 cookie_size = targetm.cxx.get_cookie_size (elt_type);
3245 gcc_assert (TREE_CODE (cookie_size) == INTEGER_CST);
3246 gcc_checking_assert (wi::ltu_p (wi::to_offset (cookie_size), max_size));
3247 /* Unconditionally subtract the cookie size. This decreases the
3248 maximum object size and is safe even if we choose not to use
3249 a cookie after all. */
3250 max_size -= wi::to_offset (cookie_size);
3251 wi::overflow_type overflow;
3252 inner_size = wi::mul (wi::to_offset (size), inner_nelts_count, SIGNED,
3253 &overflow);
3254 if (overflow || wi::gtu_p (inner_size, max_size))
3255 {
3256 if (complain & tf_error)
3257 {
3258 cst_size_error error;
3259 if (overflow)
3260 error = cst_size_overflow;
3261 else
3262 {
3263 error = cst_size_too_big;
3264 size = size_binop (MULT_EXPR, size,
3265 wide_int_to_tree (sizetype,
3266 inner_nelts_count));
3267 size = cp_fully_fold (size);
3268 }
3269 invalid_array_size_error (input_location, error, size,
3270 /*name=*/NULL_TREE);
3271 }
3272 return error_mark_node;
3273 }
3274
3275 max_outer_nelts = wi::udiv_trunc (max_size, inner_size);
3276 max_outer_nelts_tree = wide_int_to_tree (sizetype, max_outer_nelts);
3277
3278 size = size_binop (MULT_EXPR, size, fold_convert (sizetype, nelts));
3279
3280 if (TREE_CODE (cst_outer_nelts) == INTEGER_CST)
3281 {
3282 if (tree_int_cst_lt (max_outer_nelts_tree, cst_outer_nelts))
3283 {
3284 /* When the array size is constant, check it at compile time
3285 to make sure it doesn't exceed the implementation-defined
3286 maximum, as required by C++ 14 (in C++ 11 this requirement
3287 isn't explicitly stated but it's enforced anyway -- see
3288 grokdeclarator in cp/decl.cc). */
3289 if (complain & tf_error)
3290 {
3291 size = cp_fully_fold (size);
3292 invalid_array_size_error (input_location, cst_size_too_big,
3293 size, NULL_TREE);
3294 }
3295 return error_mark_node;
3296 }
3297 }
3298 else
3299 {
3300 /* When a runtime check is necessary because the array size
3301 isn't constant, keep only the top-most seven bits (starting
3302 with the most significant non-zero bit) of the maximum size
3303 to compare the array size against, to simplify encoding the
3304 constant maximum size in the instruction stream. */
3305
3306 unsigned shift = (max_outer_nelts.get_precision ()) - 7
3307 - wi::clz (max_outer_nelts);
3308 max_outer_nelts = (max_outer_nelts >> shift) << shift;
3309
3310 outer_nelts_check = fold_build2 (LE_EXPR, boolean_type_node,
3311 outer_nelts,
3312 max_outer_nelts_tree);
3313 }
3314 }
3315
3316 tree align_arg = NULL_TREE;
3317 if (type_has_new_extended_alignment (elt_type))
3318 {
3319 unsigned align = TYPE_ALIGN_UNIT (elt_type);
3320 /* Also consider the alignment of the cookie, if any. */
3321 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3322 align = MAX (align, TYPE_ALIGN_UNIT (size_type_node));
3323 align_arg = build_int_cst (align_type_node, align);
3324 }
3325
3326 alloc_fn = NULL_TREE;
3327
3328 /* If PLACEMENT is a single simple pointer type not passed by
3329 reference, prepare to capture it in a temporary variable. Do
3330 this now, since PLACEMENT will change in the calls below. */
3331 placement_first = NULL_TREE;
3332 if (vec_safe_length (*placement) == 1
3333 && (TYPE_PTR_P (TREE_TYPE ((**placement)[0]))))
3334 placement_first = (**placement)[0];
3335
3336 bool member_new_p = false;
3337
3338 /* Allocate the object. */
3339 tree fnname;
3340 tree fns;
3341
3342 fnname = ovl_op_identifier (false, array_p ? VEC_NEW_EXPR : NEW_EXPR);
3343
3344 member_new_p = !globally_qualified_p
3345 && CLASS_TYPE_P (elt_type)
3346 && (array_p
3347 ? TYPE_HAS_ARRAY_NEW_OPERATOR (elt_type)
3348 : TYPE_HAS_NEW_OPERATOR (elt_type));
3349
3350 bool member_delete_p = (!globally_qualified_p
3351 && CLASS_TYPE_P (elt_type)
3352 && (array_p
3353 ? TYPE_GETS_VEC_DELETE (elt_type)
3354 : TYPE_GETS_REG_DELETE (elt_type)));
3355
3356 if (member_new_p)
3357 {
3358 /* Use a class-specific operator new. */
3359 /* If a cookie is required, add some extra space. */
3360 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3361 size = size_binop (PLUS_EXPR, size, cookie_size);
3362 else
3363 {
3364 cookie_size = NULL_TREE;
3365 /* No size arithmetic necessary, so the size check is
3366 not needed. */
3367 if (outer_nelts_check != NULL && inner_size == 1)
3368 outer_nelts_check = NULL_TREE;
3369 }
3370 /* Perform the overflow check. */
3371 tree errval = TYPE_MAX_VALUE (sizetype);
3372 if (cxx_dialect >= cxx11 && flag_exceptions)
3373 errval = throw_bad_array_new_length ();
3374 if (outer_nelts_check != NULL_TREE)
3375 size = fold_build3 (COND_EXPR, sizetype, outer_nelts_check,
3376 size, errval);
3377 /* Create the argument list. */
3378 vec_safe_insert (*placement, 0, size);
3379 /* Do name-lookup to find the appropriate operator. */
3380 fns = lookup_fnfields (elt_type, fnname, /*protect=*/2, complain);
3381 if (fns == NULL_TREE)
3382 {
3383 if (complain & tf_error)
3384 error ("no suitable %qD found in class %qT", fnname, elt_type);
3385 return error_mark_node;
3386 }
3387 if (TREE_CODE (fns) == TREE_LIST)
3388 {
3389 if (complain & tf_error)
3390 {
3391 error ("request for member %qD is ambiguous", fnname);
3392 print_candidates (fns);
3393 }
3394 return error_mark_node;
3395 }
3396 tree dummy = build_dummy_object (elt_type);
3397 alloc_call = NULL_TREE;
3398 if (align_arg)
3399 {
3400 vec<tree, va_gc> *align_args
3401 = vec_copy_and_insert (*placement, align_arg, 1);
3402 alloc_call
3403 = build_new_method_call (dummy, fns, &align_args,
3404 /*conversion_path=*/NULL_TREE,
3405 LOOKUP_NORMAL, &alloc_fn, tf_none);
3406 /* If no matching function is found and the allocated object type
3407 has new-extended alignment, the alignment argument is removed
3408 from the argument list, and overload resolution is performed
3409 again. */
3410 if (alloc_call == error_mark_node)
3411 alloc_call = NULL_TREE;
3412 }
3413 if (!alloc_call)
3414 alloc_call = build_new_method_call (dummy, fns, placement,
3415 /*conversion_path=*/NULL_TREE,
3416 LOOKUP_NORMAL,
3417 &alloc_fn, complain);
3418 }
3419 else
3420 {
3421 /* Use a global operator new. */
3422 /* See if a cookie might be required. */
3423 if (!(array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type)))
3424 {
3425 cookie_size = NULL_TREE;
3426 /* No size arithmetic necessary, so the size check is
3427 not needed. */
3428 if (outer_nelts_check != NULL && inner_size == 1)
3429 outer_nelts_check = NULL_TREE;
3430 }
3431
3432 /* If size is zero e.g. due to type having zero size, try to
3433 preserve outer_nelts for constant expression evaluation
3434 purposes. */
3435 if (integer_zerop (size) && outer_nelts)
3436 size = build2 (MULT_EXPR, TREE_TYPE (size), size, outer_nelts);
3437
3438 alloc_call = build_operator_new_call (fnname, placement,
3439 &size, &cookie_size,
3440 align_arg, outer_nelts_check,
3441 &alloc_fn, complain);
3442 }
3443
3444 if (alloc_call == error_mark_node)
3445 return error_mark_node;
3446
3447 gcc_assert (alloc_fn != NULL_TREE);
3448
3449 /* Now, check to see if this function is actually a placement
3450 allocation function. This can happen even when PLACEMENT is NULL
3451 because we might have something like:
3452
3453 struct S { void* operator new (size_t, int i = 0); };
3454
3455 A call to `new S' will get this allocation function, even though
3456 there is no explicit placement argument. If there is more than
3457 one argument, or there are variable arguments, then this is a
3458 placement allocation function. */
3459 placement_allocation_fn_p
3460 = (type_num_arguments (TREE_TYPE (alloc_fn)) > 1
3461 || varargs_function_p (alloc_fn));
3462
3463 if (complain & tf_warning_or_error
3464 && warn_aligned_new
3465 && !placement_allocation_fn_p
3466 && TYPE_ALIGN (elt_type) > malloc_alignment ()
3467 && (warn_aligned_new > 1
3468 || CP_DECL_CONTEXT (alloc_fn) == global_namespace)
3469 && !aligned_allocation_fn_p (alloc_fn))
3470 {
3471 auto_diagnostic_group d;
3472 if (warning (OPT_Waligned_new_, "%<new%> of type %qT with extended "
3473 "alignment %d", elt_type, TYPE_ALIGN_UNIT (elt_type)))
3474 {
3475 inform (input_location, "uses %qD, which does not have an alignment "
3476 "parameter", alloc_fn);
3477 if (!aligned_new_threshold)
3478 inform (input_location, "use %<-faligned-new%> to enable C++17 "
3479 "over-aligned new support");
3480 }
3481 }
3482
3483 /* If we found a simple case of PLACEMENT_EXPR above, then copy it
3484 into a temporary variable. */
3485 if (!processing_template_decl
3486 && TREE_CODE (alloc_call) == CALL_EXPR
3487 && call_expr_nargs (alloc_call) == 2
3488 && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 0))) == INTEGER_TYPE
3489 && TYPE_PTR_P (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1))))
3490 {
3491 tree placement = CALL_EXPR_ARG (alloc_call, 1);
3492
3493 if (placement_first != NULL_TREE
3494 && (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))
3495 || VOID_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))))
3496 {
3497 placement_expr = get_target_expr (placement_first);
3498 CALL_EXPR_ARG (alloc_call, 1)
3499 = fold_convert (TREE_TYPE (placement), placement_expr);
3500 }
3501
3502 if (!member_new_p
3503 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1)))))
3504 {
3505 /* Attempt to make the warning point at the operator new argument. */
3506 if (placement_first)
3507 placement = placement_first;
3508
3509 warn_placement_new_too_small (orig_type, nelts, size, placement);
3510 }
3511 }
3512
3513 alloc_expr = alloc_call;
3514 if (cookie_size)
3515 alloc_expr = maybe_wrap_new_for_constexpr (alloc_expr, type,
3516 cookie_size);
3517
3518 /* In the simple case, we can stop now. */
3519 pointer_type = build_pointer_type (type);
3520 if (!cookie_size && !is_initialized && !member_delete_p)
3521 return build_nop (pointer_type, alloc_expr);
3522
3523 /* Store the result of the allocation call in a variable so that we can
3524 use it more than once. */
3525 alloc_expr = get_target_expr (alloc_expr);
3526 alloc_node = TARGET_EXPR_SLOT (alloc_expr);
3527
3528 /* Strip any COMPOUND_EXPRs from ALLOC_CALL. */
3529 while (TREE_CODE (alloc_call) == COMPOUND_EXPR)
3530 alloc_call = TREE_OPERAND (alloc_call, 1);
3531
3532 /* Preevaluate the placement args so that we don't reevaluate them for a
3533 placement delete. */
3534 if (placement_allocation_fn_p)
3535 {
3536 tree inits;
3537 stabilize_call (alloc_call, &inits);
3538 if (inits)
3539 alloc_expr = build2 (COMPOUND_EXPR, TREE_TYPE (alloc_expr), inits,
3540 alloc_expr);
3541 }
3542
3543 /* unless an allocation function is declared with an empty excep-
3544 tion-specification (_except.spec_), throw(), it indicates failure to
3545 allocate storage by throwing a bad_alloc exception (clause _except_,
3546 _lib.bad.alloc_); it returns a non-null pointer otherwise If the allo-
3547 cation function is declared with an empty exception-specification,
3548 throw(), it returns null to indicate failure to allocate storage and a
3549 non-null pointer otherwise.
3550
3551 So check for a null exception spec on the op new we just called. */
3552
3553 nothrow = TYPE_NOTHROW_P (TREE_TYPE (alloc_fn));
3554 check_new
3555 = flag_check_new || (nothrow && !std_placement_new_fn_p (alloc_fn));
3556
3557 if (cookie_size)
3558 {
3559 tree cookie;
3560 tree cookie_ptr;
3561 tree size_ptr_type;
3562
3563 /* Adjust so we're pointing to the start of the object. */
3564 data_addr = fold_build_pointer_plus (alloc_node, cookie_size);
3565
3566 /* Store the number of bytes allocated so that we can know how
3567 many elements to destroy later. We use the last sizeof
3568 (size_t) bytes to store the number of elements. */
3569 cookie_ptr = size_binop (MINUS_EXPR, cookie_size, size_in_bytes (sizetype));
3570 cookie_ptr = fold_build_pointer_plus_loc (input_location,
3571 alloc_node, cookie_ptr);
3572 size_ptr_type = build_pointer_type (sizetype);
3573 cookie_ptr = fold_convert (size_ptr_type, cookie_ptr);
3574 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3575
3576 cookie_expr = build2 (MODIFY_EXPR, sizetype, cookie, nelts);
3577
3578 if (targetm.cxx.cookie_has_size ())
3579 {
3580 /* Also store the element size. */
3581 cookie_ptr = fold_build_pointer_plus (cookie_ptr,
3582 fold_build1_loc (input_location,
3583 NEGATE_EXPR, sizetype,
3584 size_in_bytes (sizetype)));
3585
3586 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3587 cookie = build2 (MODIFY_EXPR, sizetype, cookie,
3588 size_in_bytes (elt_type));
3589 cookie_expr = build2 (COMPOUND_EXPR, TREE_TYPE (cookie_expr),
3590 cookie, cookie_expr);
3591 }
3592 }
3593 else
3594 {
3595 cookie_expr = NULL_TREE;
3596 data_addr = alloc_node;
3597 }
3598
3599 /* Now use a pointer to the type we've actually allocated. */
3600
3601 /* But we want to operate on a non-const version to start with,
3602 since we'll be modifying the elements. */
3603 non_const_pointer_type = build_pointer_type
3604 (cp_build_qualified_type (type, cp_type_quals (type) & ~TYPE_QUAL_CONST));
3605
3606 data_addr = fold_convert (non_const_pointer_type, data_addr);
3607 /* Any further uses of alloc_node will want this type, too. */
3608 alloc_node = fold_convert (non_const_pointer_type, alloc_node);
3609
3610 /* Now initialize the allocated object. Note that we preevaluate the
3611 initialization expression, apart from the actual constructor call or
3612 assignment--we do this because we want to delay the allocation as long
3613 as possible in order to minimize the size of the exception region for
3614 placement delete. */
3615 if (is_initialized)
3616 {
3617 bool explicit_value_init_p = false;
3618
3619 if (*init != NULL && (*init)->is_empty ())
3620 {
3621 *init = NULL;
3622 explicit_value_init_p = true;
3623 }
3624
3625 if (processing_template_decl)
3626 {
3627 /* Avoid an ICE when converting to a base in build_simple_base_path.
3628 We'll throw this all away anyway, and build_new will create
3629 a NEW_EXPR. */
3630 tree t = fold_convert (build_pointer_type (elt_type), data_addr);
3631 /* build_value_init doesn't work in templates, and we don't need
3632 the initializer anyway since we're going to throw it away and
3633 rebuild it at instantiation time, so just build up a single
3634 constructor call to get any appropriate diagnostics. */
3635 init_expr = cp_build_fold_indirect_ref (t);
3636 if (type_build_ctor_call (elt_type))
3637 init_expr = build_special_member_call (init_expr,
3638 complete_ctor_identifier,
3639 init, elt_type,
3640 LOOKUP_NORMAL,
3641 complain);
3642 }
3643 else if (array_p)
3644 {
3645 tree vecinit = NULL_TREE;
3646 const size_t len = vec_safe_length (*init);
3647 if (len == 1 && DIRECT_LIST_INIT_P ((**init)[0]))
3648 {
3649 vecinit = (**init)[0];
3650 if (CONSTRUCTOR_NELTS (vecinit) == 0)
3651 /* List-value-initialization, leave it alone. */;
3652 else
3653 {
3654 tree arraytype, domain;
3655 if (TREE_CONSTANT (nelts))
3656 domain = compute_array_index_type (NULL_TREE, nelts,
3657 complain);
3658 else
3659 /* We'll check the length at runtime. */
3660 domain = NULL_TREE;
3661 arraytype = build_cplus_array_type (type, domain);
3662 /* If we have new char[4]{"foo"}, we have to reshape
3663 so that the STRING_CST isn't wrapped in { }. */
3664 vecinit = reshape_init (arraytype, vecinit, complain);
3665 /* The middle end doesn't cope with the location wrapper
3666 around a STRING_CST. */
3667 STRIP_ANY_LOCATION_WRAPPER (vecinit);
3668 vecinit = digest_init (arraytype, vecinit, complain);
3669 }
3670 }
3671 else if (*init)
3672 {
3673 if (complain & tf_error)
3674 error ("parenthesized initializer in array new");
3675 return error_mark_node;
3676 }
3677 init_expr
3678 = build_vec_init (data_addr,
3679 cp_build_binary_op (input_location,
3680 MINUS_EXPR, outer_nelts,
3681 integer_one_node,
3682 complain),
3683 vecinit,
3684 explicit_value_init_p,
3685 /*from_array=*/0,
3686 complain);
3687 }
3688 else
3689 {
3690 init_expr = cp_build_fold_indirect_ref (data_addr);
3691
3692 if (type_build_ctor_call (type) && !explicit_value_init_p)
3693 {
3694 init_expr = build_special_member_call (init_expr,
3695 complete_ctor_identifier,
3696 init, elt_type,
3697 LOOKUP_NORMAL,
3698 complain|tf_no_cleanup);
3699 }
3700 else if (explicit_value_init_p)
3701 {
3702 /* Something like `new int()'. NO_CLEANUP is needed so
3703 we don't try and build a (possibly ill-formed)
3704 destructor. */
3705 tree val = build_value_init (type, complain | tf_no_cleanup);
3706 if (val == error_mark_node)
3707 return error_mark_node;
3708 init_expr = build2 (INIT_EXPR, type, init_expr, val);
3709 }
3710 else
3711 {
3712 tree ie;
3713
3714 /* We are processing something like `new int (10)', which
3715 means allocate an int, and initialize it with 10.
3716
3717 In C++20, also handle `new A(1, 2)'. */
3718 if (cxx_dialect >= cxx20
3719 && AGGREGATE_TYPE_P (type)
3720 && (*init)->length () > 1)
3721 {
3722 ie = build_constructor_from_vec (init_list_type_node, *init);
3723 CONSTRUCTOR_IS_DIRECT_INIT (ie) = true;
3724 CONSTRUCTOR_IS_PAREN_INIT (ie) = true;
3725 ie = digest_init (type, ie, complain);
3726 }
3727 else
3728 ie = build_x_compound_expr_from_vec (*init, "new initializer",
3729 complain);
3730 init_expr = cp_build_modify_expr (input_location, init_expr,
3731 INIT_EXPR, ie, complain);
3732 }
3733 /* If the initializer uses C++14 aggregate NSDMI that refer to the
3734 object being initialized, replace them now and don't try to
3735 preevaluate. */
3736 bool had_placeholder = false;
3737 if (!processing_template_decl
3738 && TREE_CODE (init_expr) == INIT_EXPR)
3739 TREE_OPERAND (init_expr, 1)
3740 = replace_placeholders (TREE_OPERAND (init_expr, 1),
3741 TREE_OPERAND (init_expr, 0),
3742 &had_placeholder);
3743 }
3744
3745 if (init_expr == error_mark_node)
3746 return error_mark_node;
3747 }
3748 else
3749 init_expr = NULL_TREE;
3750
3751 /* If any part of the object initialization terminates by throwing an
3752 exception and a suitable deallocation function can be found, the
3753 deallocation function is called to free the memory in which the
3754 object was being constructed, after which the exception continues
3755 to propagate in the context of the new-expression. If no
3756 unambiguous matching deallocation function can be found,
3757 propagating the exception does not cause the object's memory to be
3758 freed. */
3759 if (flag_exceptions && (init_expr || member_delete_p))
3760 {
3761 enum tree_code dcode = array_p ? VEC_DELETE_EXPR : DELETE_EXPR;
3762 tree cleanup;
3763
3764 /* The Standard is unclear here, but the right thing to do
3765 is to use the same method for finding deallocation
3766 functions that we use for finding allocation functions. */
3767 cleanup = (build_op_delete_call
3768 (dcode,
3769 alloc_node,
3770 size,
3771 globally_qualified_p,
3772 placement_allocation_fn_p ? alloc_call : NULL_TREE,
3773 alloc_fn,
3774 complain));
3775
3776 if (cleanup && init_expr && !processing_template_decl)
3777 /* Ack! First we allocate the memory. Then we set our sentry
3778 variable to true, and expand a cleanup that deletes the
3779 memory if sentry is true. Then we run the constructor, and
3780 finally clear the sentry.
3781
3782 We need to do this because we allocate the space first, so
3783 if there are any temporaries with cleanups in the
3784 constructor args, we need this EH region to extend until
3785 end of full-expression to preserve nesting.
3786
3787 We used to try to evaluate the args first to avoid this, but
3788 since C++17 [expr.new] says that "The invocation of the
3789 allocation function is sequenced before the evaluations of
3790 expressions in the new-initializer." */
3791 {
3792 tree end, sentry, begin;
3793
3794 begin = get_target_expr (boolean_true_node);
3795 CLEANUP_EH_ONLY (begin) = 1;
3796
3797 sentry = TARGET_EXPR_SLOT (begin);
3798
3799 /* CLEANUP is compiler-generated, so no diagnostics. */
3800 suppress_warning (cleanup);
3801
3802 TARGET_EXPR_CLEANUP (begin)
3803 = build3 (COND_EXPR, void_type_node, sentry,
3804 cleanup, void_node);
3805
3806 end = build2 (MODIFY_EXPR, TREE_TYPE (sentry),
3807 sentry, boolean_false_node);
3808
3809 init_expr
3810 = build2 (COMPOUND_EXPR, void_type_node, begin,
3811 build2 (COMPOUND_EXPR, void_type_node, init_expr,
3812 end));
3813 /* Likewise, this is compiler-generated. */
3814 suppress_warning (init_expr);
3815 }
3816 }
3817
3818 /* Now build up the return value in reverse order. */
3819
3820 rval = data_addr;
3821
3822 if (init_expr)
3823 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_expr, rval);
3824 if (cookie_expr)
3825 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), cookie_expr, rval);
3826
3827 if (rval == data_addr && TREE_CODE (alloc_expr) == TARGET_EXPR)
3828 /* If we don't have an initializer or a cookie, strip the TARGET_EXPR
3829 and return the call (which doesn't need to be adjusted). */
3830 rval = TARGET_EXPR_INITIAL (alloc_expr);
3831 else
3832 {
3833 if (check_new)
3834 {
3835 tree ifexp = cp_build_binary_op (input_location,
3836 NE_EXPR, alloc_node,
3837 nullptr_node,
3838 complain);
3839 rval = build_conditional_expr (input_location, ifexp, rval,
3840 alloc_node, complain);
3841 }
3842
3843 /* Perform the allocation before anything else, so that ALLOC_NODE
3844 has been initialized before we start using it. */
3845 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), alloc_expr, rval);
3846 }
3847
3848 /* A new-expression is never an lvalue. */
3849 gcc_assert (!obvalue_p (rval));
3850
3851 return convert (pointer_type, rval);
3852 }
3853
3854 /* Generate a representation for a C++ "new" expression. *PLACEMENT
3855 is a vector of placement-new arguments (or NULL if none). If NELTS
3856 is NULL, TYPE is the type of the storage to be allocated. If NELTS
3857 is not NULL, then this is an array-new allocation; TYPE is the type
3858 of the elements in the array and NELTS is the number of elements in
3859 the array. *INIT, if non-NULL, is the initializer for the new
3860 object, or an empty vector to indicate an initializer of "()". If
3861 USE_GLOBAL_NEW is true, then the user explicitly wrote "::new"
3862 rather than just "new". This may change PLACEMENT and INIT. */
3863
3864 tree
3865 build_new (location_t loc, vec<tree, va_gc> **placement, tree type,
3866 tree nelts, vec<tree, va_gc> **init, int use_global_new,
3867 tsubst_flags_t complain)
3868 {
3869 tree rval;
3870 vec<tree, va_gc> *orig_placement = NULL;
3871 tree orig_nelts = NULL_TREE;
3872 vec<tree, va_gc> *orig_init = NULL;
3873
3874 if (type == error_mark_node)
3875 return error_mark_node;
3876
3877 if (nelts == NULL_TREE
3878 /* Don't do auto deduction where it might affect mangling. */
3879 && (!processing_template_decl || at_function_scope_p ()))
3880 {
3881 tree auto_node = type_uses_auto (type);
3882 if (auto_node)
3883 {
3884 tree d_init = NULL_TREE;
3885 const size_t len = vec_safe_length (*init);
3886 /* E.g. new auto(x) must have exactly one element, or
3887 a {} initializer will have one element. */
3888 if (len == 1)
3889 {
3890 d_init = (**init)[0];
3891 d_init = resolve_nondeduced_context (d_init, complain);
3892 }
3893 /* For the rest, e.g. new A(1, 2, 3), create a list. */
3894 else if (len > 1)
3895 {
3896 unsigned int n;
3897 tree t;
3898 tree *pp = &d_init;
3899 FOR_EACH_VEC_ELT (**init, n, t)
3900 {
3901 t = resolve_nondeduced_context (t, complain);
3902 *pp = build_tree_list (NULL_TREE, t);
3903 pp = &TREE_CHAIN (*pp);
3904 }
3905 }
3906 type = do_auto_deduction (type, d_init, auto_node, complain);
3907 }
3908 }
3909
3910 if (processing_template_decl)
3911 {
3912 if (dependent_type_p (type)
3913 || any_type_dependent_arguments_p (*placement)
3914 || (nelts && type_dependent_expression_p (nelts))
3915 || (nelts && *init)
3916 || any_type_dependent_arguments_p (*init))
3917 return build_raw_new_expr (loc, *placement, type, nelts, *init,
3918 use_global_new);
3919
3920 orig_placement = make_tree_vector_copy (*placement);
3921 orig_nelts = nelts;
3922 if (*init)
3923 {
3924 orig_init = make_tree_vector_copy (*init);
3925 /* Also copy any CONSTRUCTORs in *init, since reshape_init and
3926 digest_init clobber them in place. */
3927 for (unsigned i = 0; i < orig_init->length(); ++i)
3928 {
3929 tree e = (**init)[i];
3930 if (TREE_CODE (e) == CONSTRUCTOR)
3931 (**init)[i] = copy_node (e);
3932 }
3933 }
3934
3935 make_args_non_dependent (*placement);
3936 if (nelts)
3937 nelts = build_non_dependent_expr (nelts);
3938 make_args_non_dependent (*init);
3939 }
3940
3941 if (nelts)
3942 {
3943 location_t nelts_loc = cp_expr_loc_or_loc (nelts, loc);
3944 if (!build_expr_type_conversion (WANT_INT | WANT_ENUM, nelts, false))
3945 {
3946 if (complain & tf_error)
3947 permerror (nelts_loc,
3948 "size in array new must have integral type");
3949 else
3950 return error_mark_node;
3951 }
3952
3953 /* Try to determine the constant value only for the purposes
3954 of the diagnostic below but continue to use the original
3955 value and handle const folding later. */
3956 const_tree cst_nelts = fold_non_dependent_expr (nelts, complain);
3957
3958 /* The expression in a noptr-new-declarator is erroneous if it's of
3959 non-class type and its value before converting to std::size_t is
3960 less than zero. ... If the expression is a constant expression,
3961 the program is ill-fomed. */
3962 if (TREE_CODE (cst_nelts) == INTEGER_CST
3963 && !valid_array_size_p (nelts_loc, cst_nelts, NULL_TREE,
3964 complain & tf_error))
3965 return error_mark_node;
3966
3967 nelts = mark_rvalue_use (nelts);
3968 nelts = cp_save_expr (cp_convert (sizetype, nelts, complain));
3969 }
3970
3971 /* ``A reference cannot be created by the new operator. A reference
3972 is not an object (8.2.2, 8.4.3), so a pointer to it could not be
3973 returned by new.'' ARM 5.3.3 */
3974 if (TYPE_REF_P (type))
3975 {
3976 if (complain & tf_error)
3977 error_at (loc, "new cannot be applied to a reference type");
3978 else
3979 return error_mark_node;
3980 type = TREE_TYPE (type);
3981 }
3982
3983 if (TREE_CODE (type) == FUNCTION_TYPE)
3984 {
3985 if (complain & tf_error)
3986 error_at (loc, "new cannot be applied to a function type");
3987 return error_mark_node;
3988 }
3989
3990 /* P1009: Array size deduction in new-expressions. */
3991 const bool array_p = TREE_CODE (type) == ARRAY_TYPE;
3992 if (*init
3993 /* If ARRAY_P, we have to deduce the array bound. For C++20 paren-init,
3994 we have to process the parenthesized-list. But don't do it for (),
3995 which is value-initialization, and INIT should stay empty. */
3996 && (array_p || (cxx_dialect >= cxx20 && nelts && !(*init)->is_empty ())))
3997 {
3998 /* This means we have 'new T[]()'. */
3999 if ((*init)->is_empty ())
4000 {
4001 tree ctor = build_constructor (init_list_type_node, NULL);
4002 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
4003 vec_safe_push (*init, ctor);
4004 }
4005 tree &elt = (**init)[0];
4006 /* The C++20 'new T[](e_0, ..., e_k)' case allowed by P0960. */
4007 if (!DIRECT_LIST_INIT_P (elt) && cxx_dialect >= cxx20)
4008 {
4009 tree ctor = build_constructor_from_vec (init_list_type_node, *init);
4010 CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
4011 CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
4012 elt = ctor;
4013 /* We've squashed all the vector elements into the first one;
4014 truncate the rest. */
4015 (*init)->truncate (1);
4016 }
4017 /* Otherwise we should have 'new T[]{e_0, ..., e_k}'. */
4018 if (array_p && !TYPE_DOMAIN (type))
4019 {
4020 /* We need to reshape before deducing the bounds to handle code like
4021
4022 struct S { int x, y; };
4023 new S[]{1, 2, 3, 4};
4024
4025 which should deduce S[2]. But don't change ELT itself: we want to
4026 pass a list-initializer to build_new_1, even for STRING_CSTs. */
4027 tree e = elt;
4028 if (BRACE_ENCLOSED_INITIALIZER_P (e))
4029 e = reshape_init (type, e, complain);
4030 cp_complete_array_type (&type, e, /*do_default*/false);
4031 }
4032 }
4033
4034 /* The type allocated must be complete. If the new-type-id was
4035 "T[N]" then we are just checking that "T" is complete here, but
4036 that is equivalent, since the value of "N" doesn't matter. */
4037 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
4038 return error_mark_node;
4039
4040 rval = build_new_1 (placement, type, nelts, init, use_global_new, complain);
4041 if (rval == error_mark_node)
4042 return error_mark_node;
4043
4044 if (processing_template_decl)
4045 {
4046 tree ret = build_raw_new_expr (loc, orig_placement, type, orig_nelts,
4047 orig_init, use_global_new);
4048 release_tree_vector (orig_placement);
4049 release_tree_vector (orig_init);
4050 return ret;
4051 }
4052
4053 /* Wrap it in a NOP_EXPR so warn_if_unused_value doesn't complain. */
4054 rval = build1_loc (loc, NOP_EXPR, TREE_TYPE (rval), rval);
4055 suppress_warning (rval, OPT_Wunused_value);
4056
4057 return rval;
4058 }
4059 \f
4060 static tree
4061 build_vec_delete_1 (location_t loc, tree base, tree maxindex, tree type,
4062 special_function_kind auto_delete_vec,
4063 int use_global_delete, tsubst_flags_t complain,
4064 bool in_cleanup = false)
4065 {
4066 tree virtual_size;
4067 tree ptype = build_pointer_type (type = complete_type (type));
4068 tree size_exp;
4069
4070 /* Temporary variables used by the loop. */
4071 tree tbase, tbase_init;
4072
4073 /* This is the body of the loop that implements the deletion of a
4074 single element, and moves temp variables to next elements. */
4075 tree body;
4076
4077 /* This is the LOOP_EXPR that governs the deletion of the elements. */
4078 tree loop = 0;
4079
4080 /* This is the thing that governs what to do after the loop has run. */
4081 tree deallocate_expr = 0;
4082
4083 /* This is the BIND_EXPR which holds the outermost iterator of the
4084 loop. It is convenient to set this variable up and test it before
4085 executing any other code in the loop.
4086 This is also the containing expression returned by this function. */
4087 tree controller = NULL_TREE;
4088 tree tmp;
4089
4090 /* We should only have 1-D arrays here. */
4091 gcc_assert (TREE_CODE (type) != ARRAY_TYPE);
4092
4093 if (base == error_mark_node || maxindex == error_mark_node)
4094 return error_mark_node;
4095
4096 if (!verify_type_context (loc, TCTX_DEALLOCATION, type,
4097 !(complain & tf_error)))
4098 return error_mark_node;
4099
4100 if (!COMPLETE_TYPE_P (type))
4101 {
4102 if (complain & tf_warning)
4103 {
4104 auto_diagnostic_group d;
4105 if (warning_at (loc, OPT_Wdelete_incomplete,
4106 "possible problem detected in invocation of "
4107 "operator %<delete []%>"))
4108 {
4109 cxx_incomplete_type_diagnostic (base, type, DK_WARNING);
4110 inform (loc, "neither the destructor nor the "
4111 "class-specific operator %<delete []%> will be called, "
4112 "even if they are declared when the class is defined");
4113 }
4114 }
4115 /* This size won't actually be used. */
4116 size_exp = size_one_node;
4117 goto no_destructor;
4118 }
4119
4120 size_exp = size_in_bytes (type);
4121
4122 if (! MAYBE_CLASS_TYPE_P (type))
4123 goto no_destructor;
4124 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
4125 {
4126 /* Make sure the destructor is callable. */
4127 if (type_build_dtor_call (type))
4128 {
4129 tmp = build_delete (loc, ptype, base, sfk_complete_destructor,
4130 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
4131 complain);
4132 if (tmp == error_mark_node)
4133 return error_mark_node;
4134 }
4135 goto no_destructor;
4136 }
4137
4138 /* The below is short by the cookie size. */
4139 virtual_size = size_binop (MULT_EXPR, size_exp,
4140 fold_convert (sizetype, maxindex));
4141
4142 tbase = create_temporary_var (ptype);
4143 DECL_INITIAL (tbase)
4144 = fold_build_pointer_plus_loc (loc, fold_convert (ptype, base),
4145 virtual_size);
4146 tbase_init = build_stmt (loc, DECL_EXPR, tbase);
4147 controller = build3 (BIND_EXPR, void_type_node, tbase, NULL_TREE, NULL_TREE);
4148 TREE_SIDE_EFFECTS (controller) = 1;
4149 BIND_EXPR_VEC_DTOR (controller) = true;
4150
4151 body = build1 (EXIT_EXPR, void_type_node,
4152 build2 (EQ_EXPR, boolean_type_node, tbase,
4153 fold_convert (ptype, base)));
4154 tmp = fold_build1_loc (loc, NEGATE_EXPR, sizetype, size_exp);
4155 tmp = fold_build_pointer_plus (tbase, tmp);
4156 tmp = cp_build_modify_expr (loc, tbase, NOP_EXPR, tmp, complain);
4157 if (tmp == error_mark_node)
4158 return error_mark_node;
4159 body = build_compound_expr (loc, body, tmp);
4160 tmp = build_delete (loc, ptype, tbase, sfk_complete_destructor,
4161 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
4162 complain);
4163 if (tmp == error_mark_node)
4164 return error_mark_node;
4165 body = build_compound_expr (loc, body, tmp);
4166
4167 loop = build1 (LOOP_EXPR, void_type_node, body);
4168
4169 /* If one destructor throws, keep trying to clean up the rest, unless we're
4170 already in a build_vec_init cleanup. */
4171 if (flag_exceptions && !in_cleanup && !expr_noexcept_p (tmp, tf_none))
4172 {
4173 loop = build2 (TRY_CATCH_EXPR, void_type_node, loop,
4174 unshare_expr (loop));
4175 /* Tell honor_protect_cleanup_actions to discard this on the
4176 exceptional path. */
4177 TRY_CATCH_IS_CLEANUP (loop) = true;
4178 }
4179
4180 loop = build_compound_expr (loc, tbase_init, loop);
4181
4182 no_destructor:
4183 /* Delete the storage if appropriate. */
4184 if (auto_delete_vec == sfk_deleting_destructor)
4185 {
4186 tree base_tbd;
4187
4188 /* The below is short by the cookie size. */
4189 virtual_size = size_binop (MULT_EXPR, size_exp,
4190 fold_convert (sizetype, maxindex));
4191
4192 if (! TYPE_VEC_NEW_USES_COOKIE (type))
4193 /* no header */
4194 base_tbd = base;
4195 else
4196 {
4197 tree cookie_size;
4198
4199 cookie_size = targetm.cxx.get_cookie_size (type);
4200 base_tbd = cp_build_binary_op (loc,
4201 MINUS_EXPR,
4202 cp_convert (string_type_node,
4203 base, complain),
4204 cookie_size,
4205 complain);
4206 if (base_tbd == error_mark_node)
4207 return error_mark_node;
4208 base_tbd = cp_convert (ptype, base_tbd, complain);
4209 /* True size with header. */
4210 virtual_size = size_binop (PLUS_EXPR, virtual_size, cookie_size);
4211 }
4212
4213 deallocate_expr = build_op_delete_call (VEC_DELETE_EXPR,
4214 base_tbd, virtual_size,
4215 use_global_delete & 1,
4216 /*placement=*/NULL_TREE,
4217 /*alloc_fn=*/NULL_TREE,
4218 complain);
4219 }
4220
4221 body = loop;
4222 if (deallocate_expr == error_mark_node)
4223 return error_mark_node;
4224 else if (!deallocate_expr)
4225 ;
4226 else if (!body)
4227 body = deallocate_expr;
4228 else
4229 /* The delete operator must be called, even if a destructor
4230 throws. */
4231 body = build2 (TRY_FINALLY_EXPR, void_type_node, body, deallocate_expr);
4232
4233 if (!body)
4234 body = integer_zero_node;
4235
4236 /* Outermost wrapper: If pointer is null, punt. */
4237 tree cond = build2_loc (loc, NE_EXPR, boolean_type_node, base,
4238 fold_convert (TREE_TYPE (base), nullptr_node));
4239 /* This is a compiler generated comparison, don't emit
4240 e.g. -Wnonnull-compare warning for it. */
4241 suppress_warning (cond, OPT_Wnonnull_compare);
4242 body = build3_loc (loc, COND_EXPR, void_type_node,
4243 cond, body, integer_zero_node);
4244 COND_EXPR_IS_VEC_DELETE (body) = true;
4245 body = build1 (NOP_EXPR, void_type_node, body);
4246
4247 if (controller)
4248 {
4249 TREE_OPERAND (controller, 1) = body;
4250 body = controller;
4251 }
4252
4253 if (TREE_CODE (base) == SAVE_EXPR)
4254 /* Pre-evaluate the SAVE_EXPR outside of the BIND_EXPR. */
4255 body = build2 (COMPOUND_EXPR, void_type_node, base, body);
4256
4257 return convert_to_void (body, ICV_CAST, complain);
4258 }
4259
4260 /* Create an unnamed variable of the indicated TYPE. */
4261
4262 tree
4263 create_temporary_var (tree type)
4264 {
4265 tree decl;
4266
4267 decl = build_decl (input_location,
4268 VAR_DECL, NULL_TREE, type);
4269 TREE_USED (decl) = 1;
4270 DECL_ARTIFICIAL (decl) = 1;
4271 DECL_IGNORED_P (decl) = 1;
4272 DECL_CONTEXT (decl) = current_function_decl;
4273
4274 return decl;
4275 }
4276
4277 /* Create a new temporary variable of the indicated TYPE, initialized
4278 to INIT.
4279
4280 It is not entered into current_binding_level, because that breaks
4281 things when it comes time to do final cleanups (which take place
4282 "outside" the binding contour of the function). */
4283
4284 tree
4285 get_temp_regvar (tree type, tree init)
4286 {
4287 tree decl;
4288
4289 decl = create_temporary_var (type);
4290 add_decl_expr (decl);
4291
4292 finish_expr_stmt (cp_build_modify_expr (input_location, decl, INIT_EXPR,
4293 init, tf_warning_or_error));
4294
4295 return decl;
4296 }
4297
4298 /* Subroutine of build_vec_init. Returns true if assigning to an array of
4299 INNER_ELT_TYPE from INIT is trivial. */
4300
4301 static bool
4302 vec_copy_assign_is_trivial (tree inner_elt_type, tree init)
4303 {
4304 tree fromtype = inner_elt_type;
4305 if (lvalue_p (init))
4306 fromtype = cp_build_reference_type (fromtype, /*rval*/false);
4307 return is_trivially_xible (MODIFY_EXPR, inner_elt_type, fromtype);
4308 }
4309
4310 /* Subroutine of build_vec_init: Check that the array has at least N
4311 elements. Other parameters are local variables in build_vec_init. */
4312
4313 void
4314 finish_length_check (tree atype, tree iterator, tree obase, unsigned n)
4315 {
4316 tree nelts = build_int_cst (ptrdiff_type_node, n - 1);
4317 if (TREE_CODE (atype) != ARRAY_TYPE)
4318 {
4319 if (flag_exceptions)
4320 {
4321 tree c = fold_build2 (LT_EXPR, boolean_type_node, iterator,
4322 nelts);
4323 c = build3 (COND_EXPR, void_type_node, c,
4324 throw_bad_array_new_length (), void_node);
4325 finish_expr_stmt (c);
4326 }
4327 /* Don't check an array new when -fno-exceptions. */
4328 }
4329 else if (sanitize_flags_p (SANITIZE_BOUNDS)
4330 && current_function_decl != NULL_TREE)
4331 {
4332 /* Make sure the last element of the initializer is in bounds. */
4333 finish_expr_stmt
4334 (ubsan_instrument_bounds
4335 (input_location, obase, &nelts, /*ignore_off_by_one*/false));
4336 }
4337 }
4338
4339 /* `build_vec_init' returns tree structure that performs
4340 initialization of a vector of aggregate types.
4341
4342 BASE is a reference to the vector, of ARRAY_TYPE, or a pointer
4343 to the first element, of POINTER_TYPE.
4344 MAXINDEX is the maximum index of the array (one less than the
4345 number of elements). It is only used if BASE is a pointer or
4346 TYPE_DOMAIN (TREE_TYPE (BASE)) == NULL_TREE.
4347
4348 INIT is the (possibly NULL) initializer.
4349
4350 If EXPLICIT_VALUE_INIT_P is true, then INIT must be NULL. All
4351 elements in the array are value-initialized.
4352
4353 FROM_ARRAY is 0 if we should init everything with INIT
4354 (i.e., every element initialized from INIT).
4355 FROM_ARRAY is 1 if we should index into INIT in parallel
4356 with initialization of DECL.
4357 FROM_ARRAY is 2 if we should index into INIT in parallel,
4358 but use assignment instead of initialization. */
4359
4360 tree
4361 build_vec_init (tree base, tree maxindex, tree init,
4362 bool explicit_value_init_p,
4363 int from_array,
4364 tsubst_flags_t complain,
4365 vec<tree, va_gc>** flags /* = nullptr */)
4366 {
4367 tree rval;
4368 tree base2 = NULL_TREE;
4369 tree itype = NULL_TREE;
4370 tree iterator;
4371 /* The type of BASE. */
4372 tree atype = TREE_TYPE (base);
4373 /* The type of an element in the array. */
4374 tree type = TREE_TYPE (atype);
4375 /* The element type reached after removing all outer array
4376 types. */
4377 tree inner_elt_type;
4378 /* The type of a pointer to an element in the array. */
4379 tree ptype;
4380 tree stmt_expr;
4381 tree compound_stmt;
4382 int destroy_temps;
4383 HOST_WIDE_INT num_initialized_elts = 0;
4384 bool is_global;
4385 tree obase = base;
4386 bool xvalue = false;
4387 bool errors = false;
4388 location_t loc = (init ? cp_expr_loc_or_input_loc (init)
4389 : location_of (base));
4390
4391 if (TREE_CODE (atype) == ARRAY_TYPE && TYPE_DOMAIN (atype))
4392 maxindex = array_type_nelts (atype);
4393
4394 if (maxindex == NULL_TREE || maxindex == error_mark_node)
4395 return error_mark_node;
4396
4397 maxindex = maybe_constant_value (maxindex);
4398 if (explicit_value_init_p)
4399 gcc_assert (!init);
4400
4401 inner_elt_type = strip_array_types (type);
4402
4403 /* Look through the TARGET_EXPR around a compound literal. */
4404 if (init && TREE_CODE (init) == TARGET_EXPR
4405 && TREE_CODE (TARGET_EXPR_INITIAL (init)) == CONSTRUCTOR
4406 && from_array != 2)
4407 init = TARGET_EXPR_INITIAL (init);
4408
4409 if (tree vi = get_vec_init_expr (init))
4410 init = VEC_INIT_EXPR_INIT (vi);
4411
4412 bool direct_init = false;
4413 if (from_array && init && BRACE_ENCLOSED_INITIALIZER_P (init)
4414 && CONSTRUCTOR_NELTS (init) == 1)
4415 {
4416 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
4417 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
4418 && TREE_CODE (elt) != VEC_INIT_EXPR)
4419 {
4420 direct_init = DIRECT_LIST_INIT_P (init);
4421 init = elt;
4422 }
4423 }
4424
4425 /* If we have a braced-init-list or string constant, make sure that the array
4426 is big enough for all the initializers. */
4427 bool length_check = (init
4428 && (TREE_CODE (init) == STRING_CST
4429 || (TREE_CODE (init) == CONSTRUCTOR
4430 && CONSTRUCTOR_NELTS (init) > 0))
4431 && !TREE_CONSTANT (maxindex));
4432
4433 if (init
4434 && TREE_CODE (atype) == ARRAY_TYPE
4435 && TREE_CONSTANT (maxindex)
4436 && !vla_type_p (type)
4437 && (from_array == 2
4438 ? vec_copy_assign_is_trivial (inner_elt_type, init)
4439 : !TYPE_NEEDS_CONSTRUCTING (type))
4440 && ((TREE_CODE (init) == CONSTRUCTOR
4441 && (BRACE_ENCLOSED_INITIALIZER_P (init)
4442 || (same_type_ignoring_top_level_qualifiers_p
4443 (atype, TREE_TYPE (init))))
4444 /* Don't do this if the CONSTRUCTOR might contain something
4445 that might throw and require us to clean up. */
4446 && (vec_safe_is_empty (CONSTRUCTOR_ELTS (init))
4447 || ! TYPE_HAS_NONTRIVIAL_DESTRUCTOR (inner_elt_type)))
4448 || from_array))
4449 {
4450 /* Do non-default initialization of trivial arrays resulting from
4451 brace-enclosed initializers. In this case, digest_init and
4452 store_constructor will handle the semantics for us. */
4453
4454 if (BRACE_ENCLOSED_INITIALIZER_P (init))
4455 init = digest_init (atype, init, complain);
4456 stmt_expr = build2 (INIT_EXPR, atype, base, init);
4457 return stmt_expr;
4458 }
4459
4460 maxindex = cp_convert (ptrdiff_type_node, maxindex, complain);
4461 maxindex = fold_simple (maxindex);
4462
4463 if (TREE_CODE (atype) == ARRAY_TYPE)
4464 {
4465 ptype = build_pointer_type (type);
4466 base = decay_conversion (base, complain);
4467 if (base == error_mark_node)
4468 return error_mark_node;
4469 base = cp_convert (ptype, base, complain);
4470 }
4471 else
4472 ptype = atype;
4473
4474 if (integer_all_onesp (maxindex))
4475 {
4476 /* Shortcut zero element case to avoid unneeded constructor synthesis. */
4477 if (init && TREE_SIDE_EFFECTS (init))
4478 base = build2 (COMPOUND_EXPR, ptype, init, base);
4479 return base;
4480 }
4481
4482 /* The code we are generating looks like:
4483 ({
4484 T* t1 = (T*) base;
4485 T* rval = t1;
4486 ptrdiff_t iterator = maxindex;
4487 try {
4488 for (; iterator != -1; --iterator) {
4489 ... initialize *t1 ...
4490 ++t1;
4491 }
4492 } catch (...) {
4493 ... destroy elements that were constructed ...
4494 }
4495 rval;
4496 })
4497
4498 We can omit the try and catch blocks if we know that the
4499 initialization will never throw an exception, or if the array
4500 elements do not have destructors. We can omit the loop completely if
4501 the elements of the array do not have constructors.
4502
4503 We actually wrap the entire body of the above in a STMT_EXPR, for
4504 tidiness.
4505
4506 When copying from array to another, when the array elements have
4507 only trivial copy constructors, we should use __builtin_memcpy
4508 rather than generating a loop. That way, we could take advantage
4509 of whatever cleverness the back end has for dealing with copies
4510 of blocks of memory. */
4511
4512 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
4513 destroy_temps = stmts_are_full_exprs_p ();
4514 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4515 rval = get_temp_regvar (ptype, base);
4516 base = get_temp_regvar (ptype, rval);
4517 tree iterator_targ = get_target_expr (maxindex);
4518 add_stmt (iterator_targ);
4519 iterator = TARGET_EXPR_SLOT (iterator_targ);
4520
4521 /* If initializing one array from another, initialize element by
4522 element. We rely upon the below calls to do the argument
4523 checking. Evaluate the initializer before entering the try block. */
4524 if (from_array && init && TREE_CODE (init) != CONSTRUCTOR)
4525 {
4526 if (lvalue_kind (init) & clk_rvalueref)
4527 xvalue = true;
4528 base2 = decay_conversion (init, complain);
4529 if (base2 == error_mark_node)
4530 return error_mark_node;
4531 itype = TREE_TYPE (base2);
4532 base2 = get_temp_regvar (itype, base2);
4533 itype = TREE_TYPE (itype);
4534 }
4535
4536 /* Protect the entire array initialization so that we can destroy
4537 the partially constructed array if an exception is thrown.
4538 But don't do this if we're assigning. */
4539 if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4540 && from_array != 2)
4541 {
4542 tree e;
4543 tree m = cp_build_binary_op (input_location,
4544 MINUS_EXPR, maxindex, iterator,
4545 complain);
4546
4547 /* Flatten multi-dimensional array since build_vec_delete only
4548 expects one-dimensional array. */
4549 if (TREE_CODE (type) == ARRAY_TYPE)
4550 m = cp_build_binary_op (input_location,
4551 MULT_EXPR, m,
4552 /* Avoid mixing signed and unsigned. */
4553 convert (TREE_TYPE (m),
4554 array_type_nelts_total (type)),
4555 complain);
4556
4557 e = build_vec_delete_1 (input_location, rval, m,
4558 inner_elt_type, sfk_complete_destructor,
4559 /*use_global_delete=*/0, complain,
4560 /*in_cleanup*/true);
4561 if (e == error_mark_node)
4562 errors = true;
4563 TARGET_EXPR_CLEANUP (iterator_targ) = e;
4564 CLEANUP_EH_ONLY (iterator_targ) = true;
4565
4566 /* Since we push this cleanup before doing any initialization, cleanups
4567 for any temporaries in the initialization are naturally within our
4568 cleanup region, so we don't want wrap_temporary_cleanups to do
4569 anything for arrays. But if the array is a subobject, we need to
4570 tell split_nonconstant_init how to turn off this cleanup in favor of
4571 the cleanup for the complete object. */
4572 if (flags)
4573 vec_safe_push (*flags, build_tree_list (iterator, maxindex));
4574 }
4575
4576 /* Should we try to create a constant initializer? */
4577 bool try_const = (TREE_CODE (atype) == ARRAY_TYPE
4578 && TREE_CONSTANT (maxindex)
4579 && (init ? TREE_CODE (init) == CONSTRUCTOR
4580 : (type_has_constexpr_default_constructor
4581 (inner_elt_type)))
4582 && (literal_type_p (inner_elt_type)
4583 || TYPE_HAS_CONSTEXPR_CTOR (inner_elt_type)));
4584 vec<constructor_elt, va_gc> *const_vec = NULL;
4585 bool saw_non_const = false;
4586 /* If we're initializing a static array, we want to do static
4587 initialization of any elements with constant initializers even if
4588 some are non-constant. */
4589 bool do_static_init = (DECL_P (obase) && TREE_STATIC (obase));
4590
4591 bool empty_list = false;
4592 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
4593 && CONSTRUCTOR_NELTS (init) == 0)
4594 /* Skip over the handling of non-empty init lists. */
4595 empty_list = true;
4596
4597 /* Maybe pull out constant value when from_array? */
4598
4599 else if (init != NULL_TREE && TREE_CODE (init) == CONSTRUCTOR)
4600 {
4601 /* Do non-default initialization of non-trivial arrays resulting from
4602 brace-enclosed initializers. */
4603 unsigned HOST_WIDE_INT idx;
4604 tree field, elt;
4605 /* If the constructor already has the array type, it's been through
4606 digest_init, so we shouldn't try to do anything more. */
4607 bool digested = same_type_p (atype, TREE_TYPE (init));
4608 from_array = 0;
4609
4610 if (length_check)
4611 finish_length_check (atype, iterator, obase, CONSTRUCTOR_NELTS (init));
4612
4613 if (try_const)
4614 vec_alloc (const_vec, CONSTRUCTOR_NELTS (init));
4615
4616 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
4617 {
4618 tree baseref = build1 (INDIRECT_REF, type, base);
4619 tree one_init;
4620
4621 num_initialized_elts++;
4622
4623 /* We need to see sub-array TARGET_EXPR before cp_fold_r so we can
4624 handle cleanup flags properly. */
4625 gcc_checking_assert (!target_expr_needs_replace (elt));
4626
4627 if (digested)
4628 one_init = build2 (INIT_EXPR, type, baseref, elt);
4629 else if (tree vi = get_vec_init_expr (elt))
4630 one_init = expand_vec_init_expr (baseref, vi, complain, flags);
4631 else if (MAYBE_CLASS_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE)
4632 one_init = build_aggr_init (baseref, elt, 0, complain);
4633 else
4634 one_init = cp_build_modify_expr (input_location, baseref,
4635 NOP_EXPR, elt, complain);
4636 if (one_init == error_mark_node)
4637 errors = true;
4638 if (try_const)
4639 {
4640 if (!field)
4641 field = size_int (idx);
4642 tree e = maybe_constant_init (one_init);
4643 if (reduced_constant_expression_p (e))
4644 {
4645 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4646 if (do_static_init)
4647 one_init = NULL_TREE;
4648 else
4649 one_init = build2 (INIT_EXPR, type, baseref, e);
4650 }
4651 else
4652 {
4653 if (do_static_init)
4654 {
4655 tree value = build_zero_init (TREE_TYPE (e), NULL_TREE,
4656 true);
4657 if (value)
4658 CONSTRUCTOR_APPEND_ELT (const_vec, field, value);
4659 }
4660 saw_non_const = true;
4661 }
4662 }
4663
4664 if (one_init)
4665 finish_expr_stmt (one_init);
4666
4667 one_init = cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4668 complain);
4669 if (one_init == error_mark_node)
4670 errors = true;
4671 else
4672 finish_expr_stmt (one_init);
4673
4674 one_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4675 complain);
4676 if (one_init == error_mark_node)
4677 errors = true;
4678 else
4679 finish_expr_stmt (one_init);
4680 }
4681
4682 /* Any elements without explicit initializers get T{}. */
4683 empty_list = true;
4684 }
4685 else if (init && TREE_CODE (init) == STRING_CST)
4686 {
4687 /* Check that the array is at least as long as the string. */
4688 if (length_check)
4689 finish_length_check (atype, iterator, obase,
4690 TREE_STRING_LENGTH (init));
4691 tree length = build_int_cst (ptrdiff_type_node,
4692 TREE_STRING_LENGTH (init));
4693
4694 /* Copy the string to the first part of the array. */
4695 tree alias_set = build_int_cst (build_pointer_type (type), 0);
4696 tree lhs = build2 (MEM_REF, TREE_TYPE (init), base, alias_set);
4697 tree stmt = build2 (MODIFY_EXPR, void_type_node, lhs, init);
4698 finish_expr_stmt (stmt);
4699
4700 /* Adjust the counter and pointer. */
4701 stmt = cp_build_binary_op (loc, MINUS_EXPR, iterator, length, complain);
4702 stmt = build2 (MODIFY_EXPR, void_type_node, iterator, stmt);
4703 finish_expr_stmt (stmt);
4704
4705 stmt = cp_build_binary_op (loc, PLUS_EXPR, base, length, complain);
4706 stmt = build2 (MODIFY_EXPR, void_type_node, base, stmt);
4707 finish_expr_stmt (stmt);
4708
4709 /* And set the rest of the array to NUL. */
4710 from_array = 0;
4711 explicit_value_init_p = true;
4712 }
4713 else if (from_array)
4714 {
4715 if (init)
4716 /* OK, we set base2 above. */;
4717 else if (CLASS_TYPE_P (type)
4718 && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
4719 {
4720 if (complain & tf_error)
4721 error ("initializer ends prematurely");
4722 errors = true;
4723 }
4724 }
4725
4726 /* Now, default-initialize any remaining elements. We don't need to
4727 do that if a) the type does not need constructing, or b) we've
4728 already initialized all the elements.
4729
4730 We do need to keep going if we're copying an array. */
4731
4732 if (try_const && !init
4733 && (cxx_dialect < cxx20
4734 || !default_init_uninitialized_part (inner_elt_type)))
4735 /* With a constexpr default constructor, which we checked for when
4736 setting try_const above, default-initialization is equivalent to
4737 value-initialization, and build_value_init gives us something more
4738 friendly to maybe_constant_init. Except in C++20 and up a constexpr
4739 constructor need not initialize all the members. */
4740 explicit_value_init_p = true;
4741 if (from_array
4742 || ((type_build_ctor_call (type) || init || explicit_value_init_p)
4743 && ! (tree_fits_shwi_p (maxindex)
4744 && (num_initialized_elts
4745 == tree_to_shwi (maxindex) + 1))))
4746 {
4747 /* If the ITERATOR is lesser or equal to -1, then we don't have to loop;
4748 we've already initialized all the elements. */
4749 tree for_stmt;
4750 tree elt_init;
4751 tree to;
4752
4753 for_stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
4754 finish_init_stmt (for_stmt);
4755 finish_for_cond (build2 (GT_EXPR, boolean_type_node, iterator,
4756 build_int_cst (TREE_TYPE (iterator), -1)),
4757 for_stmt, false, 0);
4758 /* We used to pass this decrement to finish_for_expr; now we add it to
4759 elt_init below so it's part of the same full-expression as the
4760 initialization, and thus happens before any potentially throwing
4761 temporary cleanups. */
4762 tree decr = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4763 complain);
4764
4765
4766 to = build1 (INDIRECT_REF, type, base);
4767
4768 /* If the initializer is {}, then all elements are initialized from T{}.
4769 But for non-classes, that's the same as value-initialization. */
4770 if (empty_list)
4771 {
4772 if (cxx_dialect >= cxx11 && AGGREGATE_TYPE_P (type))
4773 {
4774 init = build_constructor (init_list_type_node, NULL);
4775 }
4776 else
4777 {
4778 init = NULL_TREE;
4779 explicit_value_init_p = true;
4780 }
4781 }
4782
4783 if (from_array)
4784 {
4785 tree from;
4786
4787 if (base2)
4788 {
4789 from = build1 (INDIRECT_REF, itype, base2);
4790 if (xvalue)
4791 from = move (from);
4792 if (direct_init)
4793 from = build_tree_list (NULL_TREE, from);
4794 }
4795 else
4796 from = NULL_TREE;
4797
4798 if (TREE_CODE (type) == ARRAY_TYPE)
4799 elt_init = build_vec_init (to, NULL_TREE, from, /*val_init*/false,
4800 from_array, complain);
4801 else if (from_array == 2)
4802 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR,
4803 from, complain);
4804 else if (type_build_ctor_call (type))
4805 elt_init = build_aggr_init (to, from, 0, complain);
4806 else if (from)
4807 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR, from,
4808 complain);
4809 else
4810 gcc_unreachable ();
4811 }
4812 else if (TREE_CODE (type) == ARRAY_TYPE)
4813 {
4814 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init))
4815 {
4816 if ((complain & tf_error))
4817 error_at (loc, "array must be initialized "
4818 "with a brace-enclosed initializer");
4819 elt_init = error_mark_node;
4820 }
4821 else
4822 elt_init = build_vec_init (build1 (INDIRECT_REF, type, base),
4823 0, init,
4824 explicit_value_init_p,
4825 0, complain);
4826 }
4827 else if (explicit_value_init_p)
4828 {
4829 elt_init = build_value_init (type, complain);
4830 if (elt_init != error_mark_node)
4831 elt_init = build2 (INIT_EXPR, type, to, elt_init);
4832 }
4833 else
4834 {
4835 gcc_assert (type_build_ctor_call (type) || init);
4836 if (CLASS_TYPE_P (type))
4837 elt_init = build_aggr_init (to, init, 0, complain);
4838 else
4839 {
4840 if (TREE_CODE (init) == TREE_LIST)
4841 init = build_x_compound_expr_from_list (init, ELK_INIT,
4842 complain);
4843 elt_init = (init == error_mark_node
4844 ? error_mark_node
4845 : build2 (INIT_EXPR, type, to, init));
4846 }
4847 }
4848
4849 if (elt_init == error_mark_node)
4850 errors = true;
4851
4852 if (try_const)
4853 {
4854 /* FIXME refs to earlier elts */
4855 tree e = maybe_constant_init (elt_init);
4856 if (reduced_constant_expression_p (e))
4857 {
4858 if (initializer_zerop (e))
4859 /* Don't fill the CONSTRUCTOR with zeros. */
4860 e = NULL_TREE;
4861 if (do_static_init)
4862 elt_init = NULL_TREE;
4863 }
4864 else
4865 {
4866 saw_non_const = true;
4867 if (do_static_init)
4868 e = build_zero_init (TREE_TYPE (e), NULL_TREE, true);
4869 else
4870 e = NULL_TREE;
4871 }
4872
4873 if (e)
4874 {
4875 HOST_WIDE_INT last = tree_to_shwi (maxindex);
4876 if (num_initialized_elts <= last)
4877 {
4878 tree field = size_int (num_initialized_elts);
4879 if (num_initialized_elts != last)
4880 field = build2 (RANGE_EXPR, sizetype, field,
4881 size_int (last));
4882 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4883 }
4884 }
4885 }
4886
4887 /* [class.temporary]: "There are three contexts in which temporaries are
4888 destroyed at a different point than the end of the full-
4889 expression. The first context is when a default constructor is called
4890 to initialize an element of an array with no corresponding
4891 initializer. The second context is when a copy constructor is called
4892 to copy an element of an array while the entire array is copied. In
4893 either case, if the constructor has one or more default arguments, the
4894 destruction of every temporary created in a default argument is
4895 sequenced before the construction of the next array element, if any."
4896
4897 So, for this loop, statements are full-expressions. */
4898 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
4899 if (elt_init && !errors)
4900 elt_init = build2 (COMPOUND_EXPR, void_type_node, elt_init, decr);
4901 else
4902 elt_init = decr;
4903 finish_expr_stmt (elt_init);
4904 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4905
4906 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4907 complain));
4908 if (base2)
4909 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base2, false,
4910 complain));
4911
4912 finish_for_stmt (for_stmt);
4913 }
4914
4915 /* The value of the array initialization is the array itself, RVAL
4916 is a pointer to the first element. */
4917 finish_stmt_expr_expr (rval, stmt_expr);
4918
4919 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
4920
4921 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
4922
4923 if (errors)
4924 return error_mark_node;
4925
4926 if (try_const)
4927 {
4928 if (!saw_non_const)
4929 {
4930 tree const_init = build_constructor (atype, const_vec);
4931 return build2 (INIT_EXPR, atype, obase, const_init);
4932 }
4933 else if (do_static_init && !vec_safe_is_empty (const_vec))
4934 DECL_INITIAL (obase) = build_constructor (atype, const_vec);
4935 else
4936 vec_free (const_vec);
4937 }
4938
4939 /* Now make the result have the correct type. */
4940 if (TREE_CODE (atype) == ARRAY_TYPE)
4941 {
4942 atype = build_reference_type (atype);
4943 stmt_expr = build1 (NOP_EXPR, atype, stmt_expr);
4944 stmt_expr = convert_from_reference (stmt_expr);
4945 }
4946
4947 return stmt_expr;
4948 }
4949
4950 /* Call the DTOR_KIND destructor for EXP. FLAGS are as for
4951 build_delete. */
4952
4953 static tree
4954 build_dtor_call (tree exp, special_function_kind dtor_kind, int flags,
4955 tsubst_flags_t complain)
4956 {
4957 tree name;
4958 switch (dtor_kind)
4959 {
4960 case sfk_complete_destructor:
4961 name = complete_dtor_identifier;
4962 break;
4963
4964 case sfk_base_destructor:
4965 name = base_dtor_identifier;
4966 break;
4967
4968 case sfk_deleting_destructor:
4969 name = deleting_dtor_identifier;
4970 break;
4971
4972 default:
4973 gcc_unreachable ();
4974 }
4975
4976 return build_special_member_call (exp, name,
4977 /*args=*/NULL,
4978 /*binfo=*/TREE_TYPE (exp),
4979 flags,
4980 complain);
4981 }
4982
4983 /* Generate a call to a destructor. TYPE is the type to cast ADDR to.
4984 ADDR is an expression which yields the store to be destroyed.
4985 AUTO_DELETE is the name of the destructor to call, i.e., either
4986 sfk_complete_destructor, sfk_base_destructor, or
4987 sfk_deleting_destructor.
4988
4989 FLAGS is the logical disjunction of zero or more LOOKUP_
4990 flags. See cp-tree.h for more info. */
4991
4992 tree
4993 build_delete (location_t loc, tree otype, tree addr,
4994 special_function_kind auto_delete,
4995 int flags, int use_global_delete, tsubst_flags_t complain)
4996 {
4997 tree expr;
4998
4999 if (addr == error_mark_node)
5000 return error_mark_node;
5001
5002 tree type = TYPE_MAIN_VARIANT (otype);
5003
5004 /* Can happen when CURRENT_EXCEPTION_OBJECT gets its type
5005 set to `error_mark_node' before it gets properly cleaned up. */
5006 if (type == error_mark_node)
5007 return error_mark_node;
5008
5009 if (TYPE_PTR_P (type))
5010 type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
5011
5012 if (TREE_CODE (type) == ARRAY_TYPE)
5013 {
5014 if (TYPE_DOMAIN (type) == NULL_TREE)
5015 {
5016 if (complain & tf_error)
5017 error_at (loc, "unknown array size in delete");
5018 return error_mark_node;
5019 }
5020 return build_vec_delete (loc, addr, array_type_nelts (type),
5021 auto_delete, use_global_delete, complain);
5022 }
5023
5024 bool deleting = (auto_delete == sfk_deleting_destructor);
5025 gcc_assert (deleting == !(flags & LOOKUP_DESTRUCTOR));
5026
5027 if (TYPE_PTR_P (otype))
5028 {
5029 addr = mark_rvalue_use (addr);
5030
5031 /* We don't want to warn about delete of void*, only other
5032 incomplete types. Deleting other incomplete types
5033 invokes undefined behavior, but it is not ill-formed, so
5034 compile to something that would even do The Right Thing
5035 (TM) should the type have a trivial dtor and no delete
5036 operator. */
5037 if (!VOID_TYPE_P (type))
5038 {
5039 complete_type (type);
5040 if (deleting
5041 && !verify_type_context (loc, TCTX_DEALLOCATION, type,
5042 !(complain & tf_error)))
5043 return error_mark_node;
5044
5045 if (!COMPLETE_TYPE_P (type))
5046 {
5047 if (complain & tf_warning)
5048 {
5049 auto_diagnostic_group d;
5050 if (warning_at (loc, OPT_Wdelete_incomplete,
5051 "possible problem detected in invocation of "
5052 "%<operator delete%>"))
5053 {
5054 cxx_incomplete_type_diagnostic (addr, type, DK_WARNING);
5055 inform (loc,
5056 "neither the destructor nor the class-specific "
5057 "%<operator delete%> will be called, even if "
5058 "they are declared when the class is defined");
5059 }
5060 }
5061 }
5062 else if (deleting && warn_delnonvdtor
5063 && MAYBE_CLASS_TYPE_P (type) && !CLASSTYPE_FINAL (type)
5064 && TYPE_POLYMORPHIC_P (type))
5065 {
5066 tree dtor = CLASSTYPE_DESTRUCTOR (type);
5067 if (!dtor || !DECL_VINDEX (dtor))
5068 {
5069 if (CLASSTYPE_PURE_VIRTUALS (type))
5070 warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5071 "deleting object of abstract class type %qT"
5072 " which has non-virtual destructor"
5073 " will cause undefined behavior", type);
5074 else
5075 warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5076 "deleting object of polymorphic class type %qT"
5077 " which has non-virtual destructor"
5078 " might cause undefined behavior", type);
5079 }
5080 }
5081 }
5082
5083 /* Throw away const and volatile on target type of addr. */
5084 addr = convert_force (build_pointer_type (type), addr, 0, complain);
5085 }
5086 else
5087 {
5088 /* Don't check PROTECT here; leave that decision to the
5089 destructor. If the destructor is accessible, call it,
5090 else report error. */
5091 addr = cp_build_addr_expr (addr, complain);
5092 if (addr == error_mark_node)
5093 return error_mark_node;
5094
5095 addr = convert_force (build_pointer_type (type), addr, 0, complain);
5096 }
5097
5098 if (deleting)
5099 /* We will use ADDR multiple times so we must save it. */
5100 addr = save_expr (addr);
5101
5102 bool virtual_p = false;
5103 if (type_build_dtor_call (type))
5104 {
5105 if (CLASSTYPE_LAZY_DESTRUCTOR (type))
5106 lazily_declare_fn (sfk_destructor, type);
5107 virtual_p = DECL_VIRTUAL_P (CLASSTYPE_DESTRUCTOR (type));
5108 }
5109
5110 tree head = NULL_TREE;
5111 tree do_delete = NULL_TREE;
5112 bool destroying_delete = false;
5113
5114 if (!deleting)
5115 {
5116 /* Leave do_delete null. */
5117 }
5118 /* For `::delete x', we must not use the deleting destructor
5119 since then we would not be sure to get the global `operator
5120 delete'. */
5121 else if (use_global_delete)
5122 {
5123 head = get_target_expr (build_headof (addr));
5124 /* Delete the object. */
5125 do_delete = build_op_delete_call (DELETE_EXPR,
5126 head,
5127 cxx_sizeof_nowarn (type),
5128 /*global_p=*/true,
5129 /*placement=*/NULL_TREE,
5130 /*alloc_fn=*/NULL_TREE,
5131 complain);
5132 /* Otherwise, treat this like a complete object destructor
5133 call. */
5134 auto_delete = sfk_complete_destructor;
5135 }
5136 /* If the destructor is non-virtual, there is no deleting
5137 variant. Instead, we must explicitly call the appropriate
5138 `operator delete' here. */
5139 else if (!virtual_p)
5140 {
5141 /* Build the call. */
5142 do_delete = build_op_delete_call (DELETE_EXPR,
5143 addr,
5144 cxx_sizeof_nowarn (type),
5145 /*global_p=*/false,
5146 /*placement=*/NULL_TREE,
5147 /*alloc_fn=*/NULL_TREE,
5148 complain);
5149 /* Call the complete object destructor. */
5150 auto_delete = sfk_complete_destructor;
5151 if (do_delete != error_mark_node)
5152 {
5153 tree fn = get_callee_fndecl (do_delete);
5154 destroying_delete = destroying_delete_p (fn);
5155 }
5156 }
5157 else if (TYPE_GETS_REG_DELETE (type))
5158 {
5159 /* Make sure we have access to the member op delete, even though
5160 we'll actually be calling it from the destructor. */
5161 build_op_delete_call (DELETE_EXPR, addr, cxx_sizeof_nowarn (type),
5162 /*global_p=*/false,
5163 /*placement=*/NULL_TREE,
5164 /*alloc_fn=*/NULL_TREE,
5165 complain);
5166 }
5167
5168 if (destroying_delete)
5169 /* The operator delete will call the destructor. */
5170 expr = addr;
5171 else if (type_build_dtor_call (type))
5172 expr = build_dtor_call (cp_build_fold_indirect_ref (addr),
5173 auto_delete, flags, complain);
5174 else
5175 expr = build_trivial_dtor_call (addr);
5176 if (expr == error_mark_node)
5177 return error_mark_node;
5178
5179 if (!deleting)
5180 {
5181 protected_set_expr_location (expr, loc);
5182 return expr;
5183 }
5184
5185 if (do_delete == error_mark_node)
5186 return error_mark_node;
5187
5188 if (do_delete && !TREE_SIDE_EFFECTS (expr))
5189 expr = do_delete;
5190 else if (do_delete)
5191 /* The delete operator must be called, regardless of whether
5192 the destructor throws.
5193
5194 [expr.delete]/7 The deallocation function is called
5195 regardless of whether the destructor for the object or some
5196 element of the array throws an exception. */
5197 expr = build2 (TRY_FINALLY_EXPR, void_type_node, expr, do_delete);
5198
5199 /* We need to calculate this before the dtor changes the vptr. */
5200 if (head)
5201 expr = build2 (COMPOUND_EXPR, void_type_node, head, expr);
5202
5203 /* Handle deleting a null pointer. */
5204 warning_sentinel s (warn_address);
5205 tree ifexp = cp_build_binary_op (loc, NE_EXPR, addr,
5206 nullptr_node, complain);
5207 ifexp = cp_fully_fold (ifexp);
5208
5209 if (ifexp == error_mark_node)
5210 return error_mark_node;
5211 /* This is a compiler generated comparison, don't emit
5212 e.g. -Wnonnull-compare warning for it. */
5213 else if (TREE_CODE (ifexp) == NE_EXPR)
5214 suppress_warning (ifexp, OPT_Wnonnull_compare);
5215
5216 if (!integer_nonzerop (ifexp))
5217 expr = build3 (COND_EXPR, void_type_node, ifexp, expr, void_node);
5218
5219 protected_set_expr_location (expr, loc);
5220 return expr;
5221 }
5222
5223 /* At the beginning of a destructor, push cleanups that will call the
5224 destructors for our base classes and members.
5225
5226 Called from begin_destructor_body. */
5227
5228 void
5229 push_base_cleanups (void)
5230 {
5231 tree binfo, base_binfo;
5232 int i;
5233 tree member;
5234 tree expr;
5235 vec<tree, va_gc> *vbases;
5236
5237 /* Run destructors for all virtual baseclasses. */
5238 if (!ABSTRACT_CLASS_TYPE_P (current_class_type)
5239 && CLASSTYPE_VBASECLASSES (current_class_type))
5240 {
5241 tree cond = (condition_conversion
5242 (build2 (BIT_AND_EXPR, integer_type_node,
5243 current_in_charge_parm,
5244 integer_two_node)));
5245
5246 /* The CLASSTYPE_VBASECLASSES vector is in initialization
5247 order, which is also the right order for pushing cleanups. */
5248 for (vbases = CLASSTYPE_VBASECLASSES (current_class_type), i = 0;
5249 vec_safe_iterate (vbases, i, &base_binfo); i++)
5250 {
5251 if (type_build_dtor_call (BINFO_TYPE (base_binfo)))
5252 {
5253 expr = build_special_member_call (current_class_ref,
5254 base_dtor_identifier,
5255 NULL,
5256 base_binfo,
5257 (LOOKUP_NORMAL
5258 | LOOKUP_NONVIRTUAL),
5259 tf_warning_or_error);
5260 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5261 {
5262 expr = build3 (COND_EXPR, void_type_node, cond,
5263 expr, void_node);
5264 finish_decl_cleanup (NULL_TREE, expr);
5265 }
5266 }
5267 }
5268 }
5269
5270 /* Take care of the remaining baseclasses. */
5271 for (binfo = TYPE_BINFO (current_class_type), i = 0;
5272 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5273 {
5274 if (BINFO_VIRTUAL_P (base_binfo)
5275 || !type_build_dtor_call (BINFO_TYPE (base_binfo)))
5276 continue;
5277
5278 expr = build_special_member_call (current_class_ref,
5279 base_dtor_identifier,
5280 NULL, base_binfo,
5281 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
5282 tf_warning_or_error);
5283 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5284 finish_decl_cleanup (NULL_TREE, expr);
5285 }
5286
5287 /* Don't automatically destroy union members. */
5288 if (TREE_CODE (current_class_type) == UNION_TYPE)
5289 return;
5290
5291 for (member = TYPE_FIELDS (current_class_type); member;
5292 member = DECL_CHAIN (member))
5293 {
5294 tree this_type = TREE_TYPE (member);
5295 if (this_type == error_mark_node
5296 || TREE_CODE (member) != FIELD_DECL
5297 || DECL_ARTIFICIAL (member))
5298 continue;
5299 if (ANON_AGGR_TYPE_P (this_type))
5300 continue;
5301 if (type_build_dtor_call (this_type))
5302 {
5303 tree this_member = (build_class_member_access_expr
5304 (current_class_ref, member,
5305 /*access_path=*/NULL_TREE,
5306 /*preserve_reference=*/false,
5307 tf_warning_or_error));
5308 expr = build_delete (input_location, this_type, this_member,
5309 sfk_complete_destructor,
5310 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR|LOOKUP_NORMAL,
5311 0, tf_warning_or_error);
5312 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (this_type))
5313 finish_decl_cleanup (NULL_TREE, expr);
5314 }
5315 }
5316 }
5317
5318 /* Build a C++ vector delete expression.
5319 MAXINDEX is the number of elements to be deleted.
5320 ELT_SIZE is the nominal size of each element in the vector.
5321 BASE is the expression that should yield the store to be deleted.
5322 This function expands (or synthesizes) these calls itself.
5323 AUTO_DELETE_VEC says whether the container (vector) should be deallocated.
5324
5325 This also calls delete for virtual baseclasses of elements of the vector.
5326
5327 Update: MAXINDEX is no longer needed. The size can be extracted from the
5328 start of the vector for pointers, and from the type for arrays. We still
5329 use MAXINDEX for arrays because it happens to already have one of the
5330 values we'd have to extract. (We could use MAXINDEX with pointers to
5331 confirm the size, and trap if the numbers differ; not clear that it'd
5332 be worth bothering.) */
5333
5334 tree
5335 build_vec_delete (location_t loc, tree base, tree maxindex,
5336 special_function_kind auto_delete_vec,
5337 int use_global_delete, tsubst_flags_t complain)
5338 {
5339 tree type;
5340 tree rval;
5341 tree base_init = NULL_TREE;
5342
5343 type = TREE_TYPE (base);
5344
5345 if (TYPE_PTR_P (type))
5346 {
5347 /* Step back one from start of vector, and read dimension. */
5348 tree cookie_addr;
5349 tree size_ptr_type = build_pointer_type (sizetype);
5350
5351 base = mark_rvalue_use (base);
5352 if (TREE_SIDE_EFFECTS (base))
5353 {
5354 base_init = get_target_expr (base);
5355 base = TARGET_EXPR_SLOT (base_init);
5356 }
5357 type = strip_array_types (TREE_TYPE (type));
5358 cookie_addr = fold_build1_loc (loc, NEGATE_EXPR,
5359 sizetype, TYPE_SIZE_UNIT (sizetype));
5360 cookie_addr = fold_build_pointer_plus (fold_convert (size_ptr_type, base),
5361 cookie_addr);
5362 maxindex = cp_build_fold_indirect_ref (cookie_addr);
5363 }
5364 else if (TREE_CODE (type) == ARRAY_TYPE)
5365 {
5366 /* Get the total number of things in the array, maxindex is a
5367 bad name. */
5368 maxindex = array_type_nelts_total (type);
5369 type = strip_array_types (type);
5370 base = decay_conversion (base, complain);
5371 if (base == error_mark_node)
5372 return error_mark_node;
5373 if (TREE_SIDE_EFFECTS (base))
5374 {
5375 base_init = get_target_expr (base);
5376 base = TARGET_EXPR_SLOT (base_init);
5377 }
5378 }
5379 else
5380 {
5381 if (base != error_mark_node && !(complain & tf_error))
5382 error_at (loc,
5383 "type to vector delete is neither pointer or array type");
5384 return error_mark_node;
5385 }
5386
5387 rval = build_vec_delete_1 (loc, base, maxindex, type, auto_delete_vec,
5388 use_global_delete, complain);
5389 if (base_init && rval != error_mark_node)
5390 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), base_init, rval);
5391
5392 protected_set_expr_location (rval, loc);
5393 return rval;
5394 }
5395
5396 #include "gt-cp-init.h"