1 /* Report error messages, build initializers, and perform
2    some front-end optimizations for C++ compiler.
3    Copyright (C) 1987-2022 Free Software Foundation, Inc.
4    Hacked by Michael Tiemann (tiemann@cygnus.com)
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12 
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 
23 /* This file is part of the C++ front end.
24    It contains routines to build C++ expressions given their operands,
25    including computing the types of the result, C and C++ specific error
26    checks, and some optimization.  */
27 
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "cp-tree.h"
32 #include "stor-layout.h"
33 #include "varasm.h"
34 #include "intl.h"
35 #include "gcc-rich-location.h"
36 #include "target.h"
37 
38 static tree
39 process_init_constructor (tree type, tree init, int nested, int flags,
40                                 tsubst_flags_t complain);
41 
42 
43 /* Print an error message stemming from an attempt to use
44    BASETYPE as a base class for TYPE.  */
45 
46 tree
error_not_base_type(tree basetype,tree type)47 error_not_base_type (tree basetype, tree type)
48 {
49   if (TREE_CODE (basetype) == FUNCTION_DECL)
50     basetype = DECL_CONTEXT (basetype);
51   error ("type %qT is not a base type for type %qT", basetype, type);
52   return error_mark_node;
53 }
54 
55 tree
binfo_or_else(tree base,tree type)56 binfo_or_else (tree base, tree type)
57 {
58   tree binfo = lookup_base (type, base, ba_unique,
59                                   NULL, tf_warning_or_error);
60 
61   if (binfo == error_mark_node)
62     return NULL_TREE;
63   else if (!binfo)
64     error_not_base_type (base, type);
65   return binfo;
66 }
67 
68 /* According to ARM $7.1.6, "A `const' object may be initialized, but its
69    value may not be changed thereafter.  */
70 
71 void
cxx_readonly_error(location_t loc,tree arg,enum lvalue_use errstring)72 cxx_readonly_error (location_t loc, tree arg, enum lvalue_use errstring)
73 {
74 
75 /* This macro is used to emit diagnostics to ensure that all format
76    strings are complete sentences, visible to gettext and checked at
77    compile time.  */
78 
79 #define ERROR_FOR_ASSIGNMENT(LOC, AS, ASM, IN, DE, ARG)                         \
80   do {                                                                  \
81     switch (errstring)                                                  \
82       {                                                                 \
83       case lv_assign:                                                                     \
84           error_at (LOC, AS, ARG);                                              \
85         break;                                                          \
86       case lv_asm:                                                              \
87           error_at (LOC, ASM, ARG);                                             \
88         break;                                                          \
89       case lv_increment:                                                        \
90           error_at (LOC, IN, ARG);                                              \
91         break;                                                          \
92       case lv_decrement:                                                \
93           error_at (LOC, DE, ARG);                                              \
94         break;                                                          \
95       default:                                                          \
96         gcc_unreachable ();                                             \
97       }                                                                 \
98   } while (0)
99 
100   /* Handle C++-specific things first.  */
101 
102   if (VAR_P (arg)
103       && DECL_LANG_SPECIFIC (arg)
104       && DECL_IN_AGGR_P (arg)
105       && !TREE_STATIC (arg))
106     ERROR_FOR_ASSIGNMENT (loc,
107                                 G_("assignment of constant field %qD"),
108                                 G_("constant field %qD used as %<asm%> output"),
109                                 G_("increment of constant field %qD"),
110                                 G_("decrement of constant field %qD"),
111                                 arg);
112   else if (INDIRECT_REF_P (arg)
113              && TYPE_REF_P (TREE_TYPE (TREE_OPERAND (arg, 0)))
114              && (VAR_P (TREE_OPERAND (arg, 0))
115                  || TREE_CODE (TREE_OPERAND (arg, 0)) == PARM_DECL))
116     ERROR_FOR_ASSIGNMENT (loc,
117                                 G_("assignment of read-only reference %qD"),
118                                 G_("read-only reference %qD used as %<asm%> output"),
119                                 G_("increment of read-only reference %qD"),
120                                 G_("decrement of read-only reference %qD"),
121                                 TREE_OPERAND (arg, 0));
122   else
123     readonly_error (loc, arg, errstring);
124 }
125 
126 /* If TYPE has abstract virtual functions, issue an error about trying
127    to create an object of that type.  DECL is the object declared, or
128    NULL_TREE if the declaration is unavailable, in which case USE specifies
129    the kind of invalid use.  Returns 1 if an error occurred; zero if
130    all was well.  */
131 
132 static int
abstract_virtuals_error_sfinae(tree decl,tree type,abstract_class_use use,tsubst_flags_t complain)133 abstract_virtuals_error_sfinae (tree decl, tree type, abstract_class_use use,
134                                         tsubst_flags_t complain)
135 {
136   vec<tree, va_gc> *pure;
137 
138   if (TREE_CODE (type) == ARRAY_TYPE)
139     {
140       decl = NULL_TREE;
141       use = ACU_ARRAY;
142       type = strip_array_types (type);
143     }
144 
145   /* This function applies only to classes. Any other entity can never
146      be abstract.  */
147   if (!CLASS_TYPE_P (type))
148     return 0;
149   type = TYPE_MAIN_VARIANT (type);
150 
151 #if 0
152   /* Instantiation here seems to be required by the standard,
153      but breaks e.g. boost::bind.  FIXME!  */
154   /* In SFINAE, non-N3276 context, force instantiation.  */
155   if (!(complain & (tf_error|tf_decltype)))
156     complete_type (type);
157 #endif
158 
159   if (!TYPE_SIZE (type))
160     /* TYPE is being defined, and during that time
161        CLASSTYPE_PURE_VIRTUALS holds the inline friends.  */
162     return 0;
163 
164   pure = CLASSTYPE_PURE_VIRTUALS (type);
165   if (!pure)
166     return 0;
167 
168   if (!(complain & tf_error))
169     return 1;
170 
171   auto_diagnostic_group d;
172   if (decl)
173     {
174       if (VAR_P (decl))
175           error ("cannot declare variable %q+D to be of abstract "
176                  "type %qT", decl, type);
177       else if (TREE_CODE (decl) == PARM_DECL)
178           {
179             if (DECL_NAME (decl))
180               error ("cannot declare parameter %q+D to be of abstract type %qT",
181                        decl, type);
182             else
183               error ("cannot declare parameter to be of abstract type %qT",
184                        type);
185           }
186       else if (TREE_CODE (decl) == FIELD_DECL)
187           error ("cannot declare field %q+D to be of abstract type %qT",
188                  decl, type);
189       else if (TREE_CODE (decl) == FUNCTION_DECL
190                  && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
191           error ("invalid abstract return type for member function %q+#D", decl);
192       else if (TREE_CODE (decl) == FUNCTION_DECL)
193           error ("invalid abstract return type for function %q+#D", decl);
194       else if (identifier_p (decl))
195           /* Here we do not have location information.  */
196           error ("invalid abstract type %qT for %qE", type, decl);
197       else
198           error ("invalid abstract type for %q+D", decl);
199     }
200   else switch (use)
201     {
202     case ACU_ARRAY:
203       error ("creating array of %qT, which is an abstract class type", type);
204       break;
205     case ACU_CAST:
206       error ("invalid cast to abstract class type %qT", type);
207       break;
208     case ACU_NEW:
209       error ("invalid new-expression of abstract class type %qT", type);
210       break;
211     case ACU_RETURN:
212       error ("invalid abstract return type %qT", type);
213       break;
214     case ACU_PARM:
215       error ("invalid abstract parameter type %qT", type);
216       break;
217     case ACU_THROW:
218       error ("expression of abstract class type %qT cannot "
219                "be used in throw-expression", type);
220       break;
221     case ACU_CATCH:
222       error ("cannot declare %<catch%> parameter to be of abstract "
223                "class type %qT", type);
224       break;
225     default:
226       error ("cannot allocate an object of abstract type %qT", type);
227     }
228 
229   /* Only go through this once.  */
230   if (pure->length ())
231     {
232       unsigned ix;
233       tree fn;
234 
235       inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
236                 "  because the following virtual functions are pure within %qT:",
237                 type);
238 
239       FOR_EACH_VEC_ELT (*pure, ix, fn)
240           if (! DECL_CLONED_FUNCTION_P (fn)
241               || DECL_COMPLETE_DESTRUCTOR_P (fn))
242             inform (DECL_SOURCE_LOCATION (fn), "    %#qD", fn);
243 
244       /* Now truncate the vector.  This leaves it non-null, so we know
245            there are pure virtuals, but empty so we don't list them out
246            again.  */
247       pure->truncate (0);
248     }
249 
250   return 1;
251 }
252 
253 int
abstract_virtuals_error_sfinae(tree decl,tree type,tsubst_flags_t complain)254 abstract_virtuals_error_sfinae (tree decl, tree type, tsubst_flags_t complain)
255 {
256   return abstract_virtuals_error_sfinae (decl, type, ACU_UNKNOWN, complain);
257 }
258 
259 int
abstract_virtuals_error_sfinae(abstract_class_use use,tree type,tsubst_flags_t complain)260 abstract_virtuals_error_sfinae (abstract_class_use use, tree type,
261                                         tsubst_flags_t complain)
262 {
263   return abstract_virtuals_error_sfinae (NULL_TREE, type, use, complain);
264 }
265 
266 
267 /* Wrapper for the above function in the common case of wanting errors.  */
268 
269 int
abstract_virtuals_error(tree decl,tree type)270 abstract_virtuals_error (tree decl, tree type)
271 {
272   return abstract_virtuals_error_sfinae (decl, type, tf_warning_or_error);
273 }
274 
275 int
abstract_virtuals_error(abstract_class_use use,tree type)276 abstract_virtuals_error (abstract_class_use use, tree type)
277 {
278   return abstract_virtuals_error_sfinae (use, type, tf_warning_or_error);
279 }
280 
281 /* Print an inform about the declaration of the incomplete type TYPE.  */
282 
283 void
cxx_incomplete_type_inform(const_tree type)284 cxx_incomplete_type_inform (const_tree type)
285 {
286   if (!TYPE_MAIN_DECL (type))
287     return;
288 
289   location_t loc = DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type));
290   tree ptype = strip_top_quals (CONST_CAST_TREE (type));
291 
292   if (current_class_type
293       && TYPE_BEING_DEFINED (current_class_type)
294       && same_type_p (ptype, current_class_type))
295     inform (loc, "definition of %q#T is not complete until "
296               "the closing brace", ptype);
297   else if (!TYPE_TEMPLATE_INFO (ptype))
298     inform (loc, "forward declaration of %q#T", ptype);
299   else
300     inform (loc, "declaration of %q#T", ptype);
301 }
302 
303 /* Print an error message for invalid use of an incomplete type.
304    VALUE is the expression that was used (or 0 if that isn't known)
305    and TYPE is the type that was invalid.  DIAG_KIND indicates the
306    type of diagnostic (see diagnostic.def).  */
307 
308 void
cxx_incomplete_type_diagnostic(location_t loc,const_tree value,const_tree type,diagnostic_t diag_kind)309 cxx_incomplete_type_diagnostic (location_t loc, const_tree value,
310                                         const_tree type, diagnostic_t diag_kind)
311 {
312   bool is_decl = false, complained = false;
313 
314   gcc_assert (diag_kind == DK_WARNING
315                 || diag_kind == DK_PEDWARN
316                 || diag_kind == DK_ERROR);
317 
318   /* Avoid duplicate error message.  */
319   if (TREE_CODE (type) == ERROR_MARK)
320     return;
321 
322   if (value)
323     {
324       STRIP_ANY_LOCATION_WRAPPER (value);
325 
326       if (VAR_P (value)
327             || TREE_CODE (value) == PARM_DECL
328             || TREE_CODE (value) == FIELD_DECL)
329           {
330             complained = emit_diagnostic (diag_kind, DECL_SOURCE_LOCATION (value), 0,
331                                                   "%qD has incomplete type", value);
332             is_decl = true;
333           }
334     }
335  retry:
336   /* We must print an error message.  Be clever about what it says.  */
337 
338   switch (TREE_CODE (type))
339     {
340     case RECORD_TYPE:
341     case UNION_TYPE:
342     case ENUMERAL_TYPE:
343       if (!is_decl)
344           complained = emit_diagnostic (diag_kind, loc, 0,
345                                               "invalid use of incomplete type %q#T",
346                                               type);
347       if (complained)
348           cxx_incomplete_type_inform (type);
349       break;
350 
351     case VOID_TYPE:
352       emit_diagnostic (diag_kind, loc, 0,
353                            "invalid use of %qT", type);
354       break;
355 
356     case ARRAY_TYPE:
357       if (TYPE_DOMAIN (type))
358           {
359             type = TREE_TYPE (type);
360             goto retry;
361           }
362       emit_diagnostic (diag_kind, loc, 0,
363                            "invalid use of array with unspecified bounds");
364       break;
365 
366     case OFFSET_TYPE:
367     bad_member:
368       {
369           tree member = TREE_OPERAND (value, 1);
370           if (is_overloaded_fn (member))
371             member = get_first_fn (member);
372 
373           if (DECL_FUNCTION_MEMBER_P (member)
374               && ! flag_ms_extensions)
375             {
376               gcc_rich_location richloc (loc);
377               /* If "member" has no arguments (other than "this"), then
378                  add a fix-it hint.  */
379               if (type_num_arguments (TREE_TYPE (member)) == 1)
380                 richloc.add_fixit_insert_after ("()");
381               emit_diagnostic (diag_kind, &richloc, 0,
382                                    "invalid use of member function %qD "
383                                    "(did you forget the %<()%> ?)", member);
384             }
385           else
386             emit_diagnostic (diag_kind, loc, 0,
387                                  "invalid use of member %qD "
388                                  "(did you forget the %<&%> ?)", member);
389       }
390       break;
391 
392     case TEMPLATE_TYPE_PARM:
393       if (is_auto (type))
394           {
395             if (CLASS_PLACEHOLDER_TEMPLATE (type))
396               emit_diagnostic (diag_kind, loc, 0,
397                                    "invalid use of placeholder %qT", type);
398             else
399               emit_diagnostic (diag_kind, loc, 0,
400                                    "invalid use of %qT", type);
401           }
402       else
403           emit_diagnostic (diag_kind, loc, 0,
404                                "invalid use of template type parameter %qT", type);
405       break;
406 
407     case BOUND_TEMPLATE_TEMPLATE_PARM:
408       emit_diagnostic (diag_kind, loc, 0,
409                            "invalid use of template template parameter %qT",
410                            TYPE_NAME (type));
411       break;
412 
413     case TYPE_PACK_EXPANSION:
414       emit_diagnostic (diag_kind, loc, 0,
415                            "invalid use of pack expansion %qT", type);
416       break;
417 
418     case TYPENAME_TYPE:
419     case DECLTYPE_TYPE:
420       emit_diagnostic (diag_kind, loc, 0,
421                            "invalid use of dependent type %qT", type);
422       break;
423 
424     case LANG_TYPE:
425       if (type == init_list_type_node)
426           {
427             emit_diagnostic (diag_kind, loc, 0,
428                                  "invalid use of brace-enclosed initializer list");
429             break;
430           }
431       gcc_assert (type == unknown_type_node);
432       if (value && TREE_CODE (value) == COMPONENT_REF)
433           goto bad_member;
434       else if (value && TREE_CODE (value) == ADDR_EXPR)
435           emit_diagnostic (diag_kind, loc, 0,
436                                "address of overloaded function with no contextual "
437                                "type information");
438       else if (value && TREE_CODE (value) == OVERLOAD)
439           emit_diagnostic (diag_kind, loc, 0,
440                                "overloaded function with no contextual type information");
441       else
442           emit_diagnostic (diag_kind, loc, 0,
443                                "insufficient contextual information to determine type");
444       break;
445 
446     default:
447       gcc_unreachable ();
448     }
449 }
450 
451 /* Print an error message for invalid use of an incomplete type.
452    VALUE is the expression that was used (or 0 if that isn't known)
453    and TYPE is the type that was invalid.  */
454 
455 void
cxx_incomplete_type_error(location_t loc,const_tree value,const_tree type)456 cxx_incomplete_type_error (location_t loc, const_tree value, const_tree type)
457 {
458   cxx_incomplete_type_diagnostic (loc, value, type, DK_ERROR);
459 }
460 
461 
462 /* We've just initialized subobject SUB; also insert a TARGET_EXPR with an
463    EH-only cleanup for SUB.  Because of EH region nesting issues, we need to
464    make the cleanup conditional on a flag that we will clear once the object is
465    fully initialized, so push a new flag onto FLAGS.  */
466 
467 static void
maybe_push_temp_cleanup(tree sub,vec<tree,va_gc> ** flags)468 maybe_push_temp_cleanup (tree sub, vec<tree,va_gc> **flags)
469 {
470   if (!flag_exceptions)
471     return;
472   if (tree cleanup
473       = cxx_maybe_build_cleanup (sub, tf_warning_or_error))
474     {
475       tree tx = get_target_expr (boolean_true_node);
476       tree flag = TARGET_EXPR_SLOT (tx);
477       CLEANUP_EH_ONLY (tx) = true;
478       TARGET_EXPR_CLEANUP (tx) = build3 (COND_EXPR, void_type_node,
479                                                    flag, cleanup, void_node);
480       add_stmt (tx);
481       vec_safe_push (*flags, flag);
482     }
483 }
484 
485 /* The recursive part of split_nonconstant_init.  DEST is an lvalue
486    expression to which INIT should be assigned.  INIT is a CONSTRUCTOR.
487    Return true if the whole of the value was initialized by the
488    generated statements.  */
489 
490 static bool
split_nonconstant_init_1(tree dest,tree init,bool last,vec<tree,va_gc> ** flags)491 split_nonconstant_init_1 (tree dest, tree init, bool last,
492                                 vec<tree,va_gc> **flags)
493 {
494   unsigned HOST_WIDE_INT idx, tidx = HOST_WIDE_INT_M1U;
495   tree field_index, value;
496   tree type = TREE_TYPE (dest);
497   tree inner_type = NULL;
498   bool array_type_p = false;
499   bool complete_p = true;
500   HOST_WIDE_INT num_split_elts = 0;
501   tree last_split_elt = NULL_TREE;
502 
503   switch (TREE_CODE (type))
504     {
505     case ARRAY_TYPE:
506       inner_type = TREE_TYPE (type);
507       array_type_p = true;
508       if ((TREE_SIDE_EFFECTS (init)
509              && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
510             || vla_type_p (type))
511           {
512             if (!TYPE_DOMAIN (type)
513                 && TREE_CODE (init) == CONSTRUCTOR
514                 && CONSTRUCTOR_NELTS (init))
515               {
516                 /* Flexible array.  */
517                 cp_complete_array_type (&type, init, /*default*/true);
518                 dest = build1 (VIEW_CONVERT_EXPR, type, dest);
519               }
520 
521             /* For an array, we only need/want a single cleanup region rather
522                than one per element.  build_vec_init will handle it.  */
523             tree code = build_vec_init (dest, NULL_TREE, init, false, 1,
524                                               tf_warning_or_error, flags);
525             add_stmt (code);
526             return true;
527           }
528       /* FALLTHRU */
529 
530     case RECORD_TYPE:
531     case UNION_TYPE:
532     case QUAL_UNION_TYPE:
533       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx,
534                                         field_index, value)
535           {
536             /* The current implementation of this algorithm assumes that
537                the field was set for all the elements. This is usually done
538                by process_init_constructor.  */
539             gcc_assert (field_index);
540 
541             if (!array_type_p)
542               inner_type = TREE_TYPE (field_index);
543 
544             tree sub;
545             if (array_type_p)
546               sub = build4 (ARRAY_REF, inner_type, dest, field_index,
547                                 NULL_TREE, NULL_TREE);
548             else
549               sub = build3 (COMPONENT_REF, inner_type, dest, field_index,
550                                 NULL_TREE);
551 
552             bool elt_last = last && idx == CONSTRUCTOR_NELTS (init) - 1;
553 
554             /* We need to see sub-array TARGET_EXPR before cp_fold_r so we can
555                handle cleanup flags properly.  */
556             gcc_checking_assert (!target_expr_needs_replace (value));
557 
558             if (TREE_CODE (value) == CONSTRUCTOR)
559               {
560                 if (!split_nonconstant_init_1 (sub, value, elt_last, flags)
561                           /* For flexible array member with initializer we
562                                can't remove the initializer, because only the
563                                initializer determines how many elements the
564                                flexible array member has.  */
565                       || (!array_type_p
566                           && TREE_CODE (inner_type) == ARRAY_TYPE
567                           && TYPE_DOMAIN (inner_type) == NULL
568                           && TREE_CODE (TREE_TYPE (value)) == ARRAY_TYPE
569                           && COMPLETE_TYPE_P (TREE_TYPE (value))
570                           && !integer_zerop (TYPE_SIZE (TREE_TYPE (value)))
571                           && elt_last
572                           && TYPE_HAS_TRIVIAL_DESTRUCTOR
573                                         (strip_array_types (inner_type))))
574                     complete_p = false;
575                 else
576                     {
577                       /* Mark element for removal.  */
578                       last_split_elt = field_index;
579                       CONSTRUCTOR_ELT (init, idx)->index = NULL_TREE;
580                       if (idx < tidx)
581                         tidx = idx;
582                       num_split_elts++;
583                     }
584               }
585             else if (tree vi = get_vec_init_expr (value))
586               {
587                 add_stmt (expand_vec_init_expr (sub, vi, tf_warning_or_error,
588                                                         flags));
589 
590                 /* Mark element for removal.  */
591                 last_split_elt = field_index;
592                 CONSTRUCTOR_ELT (init, idx)->index = NULL_TREE;
593                 if (idx < tidx)
594                     tidx = idx;
595                 num_split_elts++;
596               }
597             else if (!initializer_constant_valid_p (value, inner_type))
598               {
599                 tree code;
600 
601                 /* Push cleanups for any preceding members with constant
602                      initialization.  */
603                 if (CLASS_TYPE_P (type))
604                     for (tree prev = (last_split_elt ?
605                                           DECL_CHAIN (last_split_elt)
606                                           : TYPE_FIELDS (type));
607                          ; prev = DECL_CHAIN (prev))
608                       {
609                         prev = next_initializable_field (prev);
610                         if (prev == field_index)
611                           break;
612                         tree ptype = TREE_TYPE (prev);
613                         if (type_build_dtor_call (ptype))
614                           {
615                               tree pcref = build3 (COMPONENT_REF, ptype, dest, prev,
616                                                        NULL_TREE);
617                               maybe_push_temp_cleanup (pcref, flags);
618                           }
619                       }
620 
621                 /* Mark element for removal.  */
622                 CONSTRUCTOR_ELT (init, idx)->index = NULL_TREE;
623                 if (idx < tidx)
624                     tidx = idx;
625 
626                 if (TREE_CODE (field_index) == RANGE_EXPR)
627                     {
628                       /* Use build_vec_init to initialize a range.  */
629                       tree low = TREE_OPERAND (field_index, 0);
630                       tree hi = TREE_OPERAND (field_index, 1);
631                       sub = build4 (ARRAY_REF, inner_type, dest, low,
632                                         NULL_TREE, NULL_TREE);
633                       sub = cp_build_addr_expr (sub, tf_warning_or_error);
634                       tree max = size_binop (MINUS_EXPR, hi, low);
635                       code = build_vec_init (sub, max, value, false, 0,
636                                                    tf_warning_or_error);
637                       add_stmt (code);
638                       if (tree_fits_shwi_p (max))
639                         num_split_elts += tree_to_shwi (max);
640                     }
641                 else
642                     {
643                       /* We may need to add a copy constructor call if
644                          the field has [[no_unique_address]].  */
645                       if (unsafe_return_slot_p (sub))
646                         {
647                           /* But not if the initializer is an implicit ctor call
648                                we just built in digest_init.  */
649                           if (TREE_CODE (value) == TARGET_EXPR
650                                 && TARGET_EXPR_LIST_INIT_P (value)
651                                 && make_safe_copy_elision (sub, value))
652                               goto build_init;
653 
654                           tree name = (DECL_FIELD_IS_BASE (field_index)
655                                            ? base_ctor_identifier
656                                            : complete_ctor_identifier);
657                           releasing_vec args = make_tree_vector_single (value);
658                           code = build_special_member_call
659                               (sub, name, &args, inner_type,
660                                LOOKUP_NORMAL, tf_warning_or_error);
661                         }
662                       else
663                         {
664                         build_init:
665                           code = build2 (INIT_EXPR, inner_type, sub, value);
666                         }
667                       code = build_stmt (input_location, EXPR_STMT, code);
668                       add_stmt (code);
669                       if (!elt_last)
670                         maybe_push_temp_cleanup (sub, flags);
671                     }
672 
673                 last_split_elt = field_index;
674                 num_split_elts++;
675               }
676           }
677       if (num_split_elts == 1)
678           CONSTRUCTOR_ELTS (init)->ordered_remove (tidx);
679       else if (num_split_elts > 1)
680           {
681             /* Perform the delayed ordered removal of non-constant elements
682                we split out.  */
683             for (idx = tidx; idx < CONSTRUCTOR_NELTS (init); ++idx)
684               if (CONSTRUCTOR_ELT (init, idx)->index == NULL_TREE)
685                 ;
686               else
687                 {
688                     *CONSTRUCTOR_ELT (init, tidx) = *CONSTRUCTOR_ELT (init, idx);
689                     ++tidx;
690                 }
691             vec_safe_truncate (CONSTRUCTOR_ELTS (init), tidx);
692           }
693       break;
694 
695     case VECTOR_TYPE:
696       if (!initializer_constant_valid_p (init, type))
697           {
698             tree code;
699             tree cons = copy_node (init);
700             CONSTRUCTOR_ELTS (init) = NULL;
701             code = build2 (MODIFY_EXPR, type, dest, cons);
702             code = build_stmt (input_location, EXPR_STMT, code);
703             add_stmt (code);
704             num_split_elts += CONSTRUCTOR_NELTS (init);
705           }
706       break;
707 
708     default:
709       gcc_unreachable ();
710     }
711 
712   /* The rest of the initializer is now a constant. */
713   TREE_CONSTANT (init) = 1;
714   TREE_SIDE_EFFECTS (init) = 0;
715 
716   /* We didn't split out anything.  */
717   if (num_split_elts == 0)
718     return false;
719 
720   return complete_p && complete_ctor_at_level_p (TREE_TYPE (init),
721                                                              num_split_elts, inner_type);
722 }
723 
724 /* A subroutine of store_init_value.  Splits non-constant static
725    initializer INIT into a constant part and generates code to
726    perform the non-constant part of the initialization to DEST.
727    Returns the code for the runtime init.  */
728 
729 tree
split_nonconstant_init(tree dest,tree init)730 split_nonconstant_init (tree dest, tree init)
731 {
732   tree code;
733 
734   if (TREE_CODE (init) == TARGET_EXPR)
735     init = TARGET_EXPR_INITIAL (init);
736   if (TREE_CODE (init) == CONSTRUCTOR)
737     {
738       /* Subobject initializers are not full-expressions.  */
739       auto fe = (make_temp_override
740                      (current_stmt_tree ()->stmts_are_full_exprs_p, 0));
741 
742       init = cp_fully_fold_init (init);
743       code = push_stmt_list ();
744 
745       /* If the complete object is an array, build_vec_init's cleanup is
746            enough.  Otherwise, collect flags for disabling subobject
747            cleanups once the complete object is fully constructed.  */
748       vec<tree, va_gc> *flags = nullptr;
749       if (TREE_CODE (TREE_TYPE (dest)) != ARRAY_TYPE)
750           flags = make_tree_vector ();
751 
752       if (split_nonconstant_init_1 (dest, init, true, &flags))
753           init = NULL_TREE;
754 
755       for (tree f : flags)
756           {
757             /* See maybe_push_temp_cleanup.  */
758             tree d = f;
759             tree i = boolean_false_node;
760             if (TREE_CODE (f) == TREE_LIST)
761               {
762                 /* To disable a build_vec_init cleanup, set
763                      iterator = maxindex.  */
764                 d = TREE_PURPOSE (f);
765                 i = TREE_VALUE (f);
766                 ggc_free (f);
767               }
768             add_stmt (build2 (MODIFY_EXPR, TREE_TYPE (d), d, i));
769           }
770       release_tree_vector (flags);
771 
772       code = pop_stmt_list (code);
773       if (VAR_P (dest) && !is_local_temp (dest))
774           {
775             DECL_INITIAL (dest) = init;
776             TREE_READONLY (dest) = 0;
777           }
778       else if (init)
779           {
780             tree ie = build2 (INIT_EXPR, void_type_node, dest, init);
781             code = add_stmt_to_compound (ie, code);
782           }
783     }
784   else if (TREE_CODE (init) == STRING_CST
785              && array_of_runtime_bound_p (TREE_TYPE (dest)))
786     code = build_vec_init (dest, NULL_TREE, init, /*value-init*/false,
787                                  /*from array*/1, tf_warning_or_error);
788   else
789     code = build2 (INIT_EXPR, TREE_TYPE (dest), dest, init);
790 
791   return code;
792 }
793 
794 /* Perform appropriate conversions on the initial value of a variable,
795    store it in the declaration DECL,
796    and print any error messages that are appropriate.
797    If the init is invalid, store an ERROR_MARK.
798 
799    C++: Note that INIT might be a TREE_LIST, which would mean that it is
800    a base class initializer for some aggregate type, hopefully compatible
801    with DECL.  If INIT is a single element, and DECL is an aggregate
802    type, we silently convert INIT into a TREE_LIST, allowing a constructor
803    to be called.
804 
805    If INIT is a TREE_LIST and there is no constructor, turn INIT
806    into a CONSTRUCTOR and use standard initialization techniques.
807    Perhaps a warning should be generated?
808 
809    Returns code to be executed if initialization could not be performed
810    for static variable.  In that case, caller must emit the code.  */
811 
812 tree
store_init_value(tree decl,tree init,vec<tree,va_gc> ** cleanups,int flags)813 store_init_value (tree decl, tree init, vec<tree, va_gc>** cleanups, int flags)
814 {
815   tree value, type;
816 
817   /* If variable's type was invalidly declared, just ignore it.  */
818 
819   type = TREE_TYPE (decl);
820   if (TREE_CODE (type) == ERROR_MARK)
821     return NULL_TREE;
822 
823   if (MAYBE_CLASS_TYPE_P (type))
824     {
825       if (TREE_CODE (init) == TREE_LIST)
826           {
827             error ("constructor syntax used, but no constructor declared "
828                      "for type %qT", type);
829             init = build_constructor_from_list (init_list_type_node, nreverse (init));
830           }
831     }
832 
833   /* End of special C++ code.  */
834 
835   if (flags & LOOKUP_ALREADY_DIGESTED)
836     value = init;
837   else
838     {
839       if (TREE_STATIC (decl))
840           flags |= LOOKUP_ALLOW_FLEXARRAY_INIT;
841       /* Digest the specified initializer into an expression.  */
842       value = digest_init_flags (type, init, flags, tf_warning_or_error);
843     }
844 
845   /* Look for braced array initializers for character arrays and
846      recursively convert them into STRING_CSTs.  */
847   value = braced_lists_to_strings (type, value);
848 
849   current_ref_temp_count = 0;
850   value = extend_ref_init_temps (decl, value, cleanups);
851 
852   /* In C++11 constant expression is a semantic, not syntactic, property.
853      In C++98, make sure that what we thought was a constant expression at
854      template definition time is still constant and otherwise perform this
855      as optimization, e.g. to fold SIZEOF_EXPRs in the initializer.  */
856   if (decl_maybe_constant_var_p (decl) || TREE_STATIC (decl))
857     {
858       bool const_init;
859       tree oldval = value;
860       if (DECL_DECLARED_CONSTEXPR_P (decl)
861             || (DECL_IN_AGGR_P (decl)
862                 && DECL_INITIALIZED_IN_CLASS_P (decl)))
863           {
864             value = fold_non_dependent_expr (value, tf_warning_or_error,
865                                                      /*manifestly_const_eval=*/true,
866                                                      decl);
867             /* Diagnose a non-constant initializer for constexpr variable or
868                non-inline in-class-initialized static data member.  */
869             if (!require_constant_expression (value))
870               value = error_mark_node;
871             else if (processing_template_decl)
872               /* In a template we might not have done the necessary
873                  transformations to make value actually constant,
874                  e.g. extend_ref_init_temps.  */
875               value = maybe_constant_init (value, decl, true);
876             else
877               value = cxx_constant_init (value, decl);
878           }
879       else
880           value = fold_non_dependent_init (value, tf_warning_or_error,
881                                                    /*manifestly_const_eval=*/true, decl);
882       if (TREE_CODE (value) == CONSTRUCTOR && cp_has_mutable_p (type))
883           /* Poison this CONSTRUCTOR so it can't be copied to another
884              constexpr variable.  */
885           CONSTRUCTOR_MUTABLE_POISON (value) = true;
886       const_init = (reduced_constant_expression_p (value)
887                         || error_operand_p (value));
888       DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = const_init;
889       /* FIXME setting TREE_CONSTANT on refs breaks the back end.  */
890       if (!TYPE_REF_P (type))
891           TREE_CONSTANT (decl) = const_init && decl_maybe_constant_var_p (decl);
892       if (!const_init)
893           {
894             /* [dcl.constinit]/2 "If a variable declared with the constinit
895                specifier has dynamic initialization, the program is
896                ill-formed."  */
897             if (DECL_DECLARED_CONSTINIT_P (decl))
898               {
899                 error_at (location_of (decl),
900                               "%<constinit%> variable %qD does not have a constant "
901                               "initializer", decl);
902                 if (require_constant_expression (value))
903                     cxx_constant_init (value, decl);
904                 value = error_mark_node;
905               }
906             else
907               value = oldval;
908           }
909     }
910   /* Don't fold initializers of automatic variables in constexpr functions,
911      that might fold away something that needs to be diagnosed at constexpr
912      evaluation time.  */
913   if (!current_function_decl
914       || !DECL_DECLARED_CONSTEXPR_P (current_function_decl)
915       || TREE_STATIC (decl))
916     value = cp_fully_fold_init (value);
917 
918   /* Handle aggregate NSDMI in non-constant initializers, too.  */
919   value = replace_placeholders (value, decl);
920 
921   /* A COMPOUND_LITERAL_P CONSTRUCTOR is the syntactic form; by the time we get
922      here it should have been digested into an actual value for the type.  */
923   gcc_checking_assert (TREE_CODE (value) != CONSTRUCTOR
924                            || processing_template_decl
925                            || TREE_CODE (type) == VECTOR_TYPE
926                            || !TREE_HAS_CONSTRUCTOR (value));
927 
928   /* If the initializer is not a constant, fill in DECL_INITIAL with
929      the bits that are constant, and then return an expression that
930      will perform the dynamic initialization.  */
931   if (value != error_mark_node
932       && !processing_template_decl
933       && (TREE_SIDE_EFFECTS (value)
934             || vla_type_p (type)
935             || ! reduced_constant_expression_p (value)))
936     return split_nonconstant_init (decl, value);
937 
938   /* DECL may change value; purge caches.  */
939   clear_cv_and_fold_caches ();
940 
941   /* If the value is a constant, just put it in DECL_INITIAL.  If DECL
942      is an automatic variable, the middle end will turn this into a
943      dynamic initialization later.  */
944   DECL_INITIAL (decl) = value;
945   return NULL_TREE;
946 }
947 
948 
949 /* Give diagnostic about narrowing conversions within { }, or as part of
950    a converted constant expression.  If CONST_ONLY, only check
951    constants.  */
952 
953 bool
check_narrowing(tree type,tree init,tsubst_flags_t complain,bool const_only)954 check_narrowing (tree type, tree init, tsubst_flags_t complain,
955                      bool const_only/*= false*/)
956 {
957   tree ftype = unlowered_expr_type (init);
958   bool ok = true;
959   REAL_VALUE_TYPE d;
960 
961   if (((!warn_narrowing || !(complain & tf_warning))
962        && cxx_dialect == cxx98)
963       || !ARITHMETIC_TYPE_P (type)
964       /* Don't emit bogus warnings with e.g. value-dependent trees.  */
965       || instantiation_dependent_expression_p (init))
966     return ok;
967 
968   if (BRACE_ENCLOSED_INITIALIZER_P (init)
969       && TREE_CODE (type) == COMPLEX_TYPE)
970     {
971       tree elttype = TREE_TYPE (type);
972       if (CONSTRUCTOR_NELTS (init) > 0)
973         ok &= check_narrowing (elttype, CONSTRUCTOR_ELT (init, 0)->value,
974                                      complain);
975       if (CONSTRUCTOR_NELTS (init) > 1)
976           ok &= check_narrowing (elttype, CONSTRUCTOR_ELT (init, 1)->value,
977                                      complain);
978       return ok;
979     }
980 
981   /* Even non-dependent expressions can still have template
982      codes like CAST_EXPR, so use *_non_dependent_expr to cope.  */
983   init = fold_non_dependent_expr (init, complain, /*manifest*/true);
984   if (init == error_mark_node)
985     return ok;
986 
987   /* If we were asked to only check constants, return early.  */
988   if (const_only && !TREE_CONSTANT (init))
989     return ok;
990 
991   if (CP_INTEGRAL_TYPE_P (type)
992       && TREE_CODE (ftype) == REAL_TYPE)
993     ok = false;
994   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (ftype)
995              && CP_INTEGRAL_TYPE_P (type))
996     {
997       if (TREE_CODE (ftype) == ENUMERAL_TYPE)
998           /* Check for narrowing based on the values of the enumeration. */
999           ftype = ENUM_UNDERLYING_TYPE (ftype);
1000       if ((tree_int_cst_lt (TYPE_MAX_VALUE (type),
1001                                   TYPE_MAX_VALUE (ftype))
1002              || tree_int_cst_lt (TYPE_MIN_VALUE (ftype),
1003                                      TYPE_MIN_VALUE (type)))
1004             && (TREE_CODE (init) != INTEGER_CST
1005                 || !int_fits_type_p (init, type)))
1006           ok = false;
1007     }
1008   /* [dcl.init.list]#7.2: "from long double to double or float, or from
1009       double to float".  */
1010   else if (TREE_CODE (ftype) == REAL_TYPE
1011              && TREE_CODE (type) == REAL_TYPE)
1012     {
1013       if ((same_type_p (ftype, long_double_type_node)
1014              && (same_type_p (type, double_type_node)
1015                  || same_type_p (type, float_type_node)))
1016             || (same_type_p (ftype, double_type_node)
1017                 && same_type_p (type, float_type_node))
1018             || (TYPE_PRECISION (type) < TYPE_PRECISION (ftype)))
1019           {
1020             if (TREE_CODE (init) == REAL_CST)
1021               {
1022                 /* Issue 703: Loss of precision is OK as long as the value is
1023                      within the representable range of the new type.  */
1024                 REAL_VALUE_TYPE r;
1025                 d = TREE_REAL_CST (init);
1026                 real_convert (&r, TYPE_MODE (type), &d);
1027                 if (real_isinf (&r))
1028                     ok = false;
1029               }
1030             else
1031               ok = false;
1032           }
1033     }
1034   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (ftype)
1035              && TREE_CODE (type) == REAL_TYPE)
1036     {
1037       ok = false;
1038       if (TREE_CODE (init) == INTEGER_CST)
1039           {
1040             d = real_value_from_int_cst (0, init);
1041             if (exact_real_truncate (TYPE_MODE (type), &d))
1042               ok = true;
1043           }
1044     }
1045   else if (TREE_CODE (type) == BOOLEAN_TYPE
1046              && (TYPE_PTR_P (ftype) || TYPE_PTRMEM_P (ftype)))
1047     /* C++20 P1957R2: converting from a pointer type or a pointer-to-member
1048        type to bool should be considered narrowing.  This is a DR so is not
1049        limited to C++20 only.  */
1050     ok = false;
1051 
1052   bool almost_ok = ok;
1053   if (!ok && !CONSTANT_CLASS_P (init) && (complain & tf_warning_or_error))
1054     {
1055       tree folded = cp_fully_fold (init);
1056       if (TREE_CONSTANT (folded) && check_narrowing (type, folded, tf_none))
1057           almost_ok = true;
1058     }
1059 
1060   if (!ok)
1061     {
1062       location_t loc = cp_expr_loc_or_input_loc (init);
1063       if (cxx_dialect == cxx98)
1064           {
1065             if (complain & tf_warning)
1066               warning_at (loc, OPT_Wnarrowing, "narrowing conversion of %qE "
1067                               "from %qH to %qI is ill-formed in C++11",
1068                               init, ftype, type);
1069             ok = true;
1070           }
1071       else if (!CONSTANT_CLASS_P (init))
1072           {
1073             if (complain & tf_warning_or_error)
1074               {
1075                 auto_diagnostic_group d;
1076                 if ((!almost_ok || pedantic)
1077                       && pedwarn (loc, OPT_Wnarrowing,
1078                                     "narrowing conversion of %qE from %qH to %qI",
1079                                     init, ftype, type)
1080                       && almost_ok)
1081                     inform (loc, " the expression has a constant value but is not "
1082                               "a C++ constant-expression");
1083                 ok = true;
1084               }
1085           }
1086       else if (complain & tf_error)
1087           {
1088             int savederrorcount = errorcount;
1089             global_dc->pedantic_errors = 1;
1090             auto s = make_temp_override (global_dc->dc_warn_system_headers, true);
1091             pedwarn (loc, OPT_Wnarrowing,
1092                        "narrowing conversion of %qE from %qH to %qI",
1093                        init, ftype, type);
1094             if (errorcount == savederrorcount)
1095               ok = true;
1096             global_dc->pedantic_errors = flag_pedantic_errors;
1097           }
1098     }
1099 
1100   return ok;
1101 }
1102 
1103 /* True iff TYPE is a C++20 "ordinary" character type.  */
1104 
1105 bool
ordinary_char_type_p(tree type)1106 ordinary_char_type_p (tree type)
1107 {
1108   type = TYPE_MAIN_VARIANT (type);
1109   return (type == char_type_node
1110             || type == signed_char_type_node
1111             || type == unsigned_char_type_node);
1112 }
1113 
1114 /* True iff the string literal INIT has a type suitable for initializing array
1115    TYPE.  */
1116 
1117 bool
array_string_literal_compatible_p(tree type,tree init)1118 array_string_literal_compatible_p (tree type, tree init)
1119 {
1120   tree to_char_type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
1121   tree from_char_type = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (init)));
1122 
1123   if (to_char_type == from_char_type)
1124     return true;
1125   /* The array element type does not match the initializing string
1126      literal element type; this is only allowed when both types are
1127      ordinary character type.  There are no string literals of
1128      signed or unsigned char type in the language, but we can get
1129      them internally from converting braced-init-lists to
1130      STRING_CST.  */
1131   if (ordinary_char_type_p (to_char_type)
1132       && ordinary_char_type_p (from_char_type))
1133     return true;
1134   return false;
1135 }
1136 
1137 /* Process the initializer INIT for a variable of type TYPE, emitting
1138    diagnostics for invalid initializers and converting the initializer as
1139    appropriate.
1140 
1141    For aggregate types, it assumes that reshape_init has already run, thus the
1142    initializer will have the right shape (brace elision has been undone).
1143 
1144    NESTED is non-zero iff we are being called for an element of a CONSTRUCTOR,
1145    2 iff the element of a CONSTRUCTOR is inside another CONSTRUCTOR.  */
1146 
1147 static tree
digest_init_r(tree type,tree init,int nested,int flags,tsubst_flags_t complain)1148 digest_init_r (tree type, tree init, int nested, int flags,
1149                  tsubst_flags_t complain)
1150 {
1151   enum tree_code code = TREE_CODE (type);
1152 
1153   if (error_operand_p (init))
1154     return error_mark_node;
1155 
1156   gcc_assert (init);
1157 
1158   /* We must strip the outermost array type when completing the type,
1159      because the its bounds might be incomplete at the moment.  */
1160   if (!complete_type_or_maybe_complain (code == ARRAY_TYPE
1161                                                   ? TREE_TYPE (type) : type, NULL_TREE,
1162                                                   complain))
1163     return error_mark_node;
1164 
1165   location_t loc = cp_expr_loc_or_input_loc (init);
1166 
1167   tree stripped_init = init;
1168 
1169   if (BRACE_ENCLOSED_INITIALIZER_P (init)
1170       && CONSTRUCTOR_IS_PAREN_INIT (init))
1171     flags |= LOOKUP_AGGREGATE_PAREN_INIT;
1172 
1173   /* Strip NON_LVALUE_EXPRs since we aren't using as an lvalue
1174      (g++.old-deja/g++.law/casts2.C).  */
1175   if (TREE_CODE (init) == NON_LVALUE_EXPR)
1176     stripped_init = TREE_OPERAND (init, 0);
1177 
1178   stripped_init = tree_strip_any_location_wrapper (stripped_init);
1179 
1180   /* Initialization of an array of chars from a string constant. The initializer
1181      can be optionally enclosed in braces, but reshape_init has already removed
1182      them if they were present.  */
1183   if (code == ARRAY_TYPE)
1184     {
1185       if (nested && !TYPE_DOMAIN (type))
1186           /* C++ flexible array members have a null domain.  */
1187           {
1188             if (flags & LOOKUP_ALLOW_FLEXARRAY_INIT)
1189               pedwarn (loc, OPT_Wpedantic,
1190                          "initialization of a flexible array member");
1191             else
1192               {
1193                 if (complain & tf_error)
1194                     error_at (loc, "non-static initialization of"
1195                                      " a flexible array member");
1196                 return error_mark_node;
1197               }
1198           }
1199 
1200       tree typ1 = TYPE_MAIN_VARIANT (TREE_TYPE (type));
1201       if (char_type_p (typ1)
1202             && TREE_CODE (stripped_init) == STRING_CST)
1203           {
1204             if (!array_string_literal_compatible_p (type, init))
1205               {
1206                 if (complain & tf_error)
1207                     error_at (loc, "cannot initialize array of %qT from "
1208                                 "a string literal with type array of %qT",
1209                                 typ1,
1210                                 TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (init))));
1211                 return error_mark_node;
1212               }
1213 
1214             if (nested == 2 && !TYPE_DOMAIN (type))
1215               {
1216                 if (complain & tf_error)
1217                     error_at (loc, "initialization of flexible array member "
1218                                      "in a nested context");
1219                 return error_mark_node;
1220               }
1221 
1222             if (type != TREE_TYPE (init)
1223                 && !variably_modified_type_p (type, NULL_TREE))
1224               {
1225                 init = copy_node (init);
1226                 TREE_TYPE (init) = type;
1227                 /* If we have a location wrapper, then also copy the wrapped
1228                      node, and update the copy's type.  */
1229                 if (location_wrapper_p (init))
1230                     {
1231                       stripped_init = copy_node (stripped_init);
1232                       TREE_OPERAND (init, 0) = stripped_init;
1233                       TREE_TYPE (stripped_init) = type;
1234                     }
1235               }
1236             if (TYPE_DOMAIN (type) && TREE_CONSTANT (TYPE_SIZE (type)))
1237               {
1238                 /* Not a flexible array member.  */
1239                 int size = TREE_INT_CST_LOW (TYPE_SIZE (type));
1240                 size = (size + BITS_PER_UNIT - 1) / BITS_PER_UNIT;
1241                 /* In C it is ok to subtract 1 from the length of the string
1242                      because it's ok to ignore the terminating null char that is
1243                      counted in the length of the constant, but in C++ this would
1244                      be invalid.  */
1245                 if (size < TREE_STRING_LENGTH (stripped_init))
1246                     {
1247                       permerror (loc, "initializer-string for %qT is too long",
1248                                    type);
1249 
1250                       init = build_string (size,
1251                                                TREE_STRING_POINTER (stripped_init));
1252                       TREE_TYPE (init) = type;
1253                     }
1254               }
1255             return init;
1256           }
1257     }
1258 
1259   /* Handle scalar types (including conversions) and references.  */
1260   if ((code != COMPLEX_TYPE || BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
1261       && (SCALAR_TYPE_P (type) || code == REFERENCE_TYPE))
1262     {
1263       /* Narrowing is OK when initializing an aggregate from
1264            a parenthesized list.  */
1265       if (nested && !(flags & LOOKUP_AGGREGATE_PAREN_INIT))
1266           flags |= LOOKUP_NO_NARROWING;
1267       init = convert_for_initialization (0, type, init, flags,
1268                                                    ICR_INIT, NULL_TREE, 0,
1269                                                    complain);
1270 
1271       return init;
1272     }
1273 
1274   /* Come here only for aggregates: records, arrays, unions, complex numbers
1275      and vectors.  */
1276   gcc_assert (code == ARRAY_TYPE
1277                 || VECTOR_TYPE_P (type)
1278                 || code == RECORD_TYPE
1279                 || code == UNION_TYPE
1280                 || code == OPAQUE_TYPE
1281                 || code == COMPLEX_TYPE);
1282 
1283   /* "If T is a class type and the initializer list has a single
1284      element of type cv U, where U is T or a class derived from T,
1285      the object is initialized from that element."  */
1286   if (cxx_dialect >= cxx11
1287       && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)
1288       && !CONSTRUCTOR_IS_DESIGNATED_INIT (stripped_init)
1289       && CONSTRUCTOR_NELTS (stripped_init) == 1
1290       && ((CLASS_TYPE_P (type) && !CLASSTYPE_NON_AGGREGATE (type))
1291             || VECTOR_TYPE_P (type)))
1292     {
1293       tree elt = CONSTRUCTOR_ELT (stripped_init, 0)->value;
1294       if (reference_related_p (type, TREE_TYPE (elt)))
1295           {
1296             /* In C++17, aggregates can have bases, thus participate in
1297                aggregate initialization.  In the following case:
1298 
1299                  struct B { int c; };
1300                  struct D : B { };
1301                  D d{{D{{42}}}};
1302 
1303               there's an extra set of braces, so the D temporary initializes
1304               the first element of d, which is the B base subobject.  The base
1305               of type B is copy-initialized from the D temporary, causing
1306               object slicing.  */
1307             tree field = next_initializable_field (TYPE_FIELDS (type));
1308             if (field && DECL_FIELD_IS_BASE (field))
1309               {
1310                 if (warning_at (loc, 0, "initializing a base class of type %qT "
1311                                     "results in object slicing", TREE_TYPE (field)))
1312                     inform (loc, "remove %<{ }%> around initializer");
1313               }
1314             else if (flag_checking)
1315               /* We should have fixed this in reshape_init.  */
1316               gcc_unreachable ();
1317           }
1318     }
1319 
1320   if (SIMPLE_TARGET_EXPR_P (stripped_init))
1321     stripped_init = TARGET_EXPR_INITIAL (stripped_init);
1322 
1323   if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init)
1324       && !TYPE_NON_AGGREGATE_CLASS (type))
1325     return process_init_constructor (type, stripped_init, nested, flags,
1326                                              complain);
1327   else
1328     {
1329       if (COMPOUND_LITERAL_P (stripped_init) && code == ARRAY_TYPE)
1330           {
1331             if (complain & tf_error)
1332               error_at (loc, "cannot initialize aggregate of type %qT with "
1333                           "a compound literal", type);
1334 
1335             return error_mark_node;
1336           }
1337 
1338       if (code == ARRAY_TYPE
1339             && !BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
1340           {
1341             /* Allow the result of build_array_copy and of
1342                build_value_init_noctor.  */
1343             if ((TREE_CODE (stripped_init) == VEC_INIT_EXPR
1344                  || TREE_CODE (stripped_init) == CONSTRUCTOR)
1345                 && (same_type_ignoring_top_level_qualifiers_p
1346                       (type, TREE_TYPE (init))))
1347               return init;
1348 
1349             if (complain & tf_error)
1350               error_at (loc, "array must be initialized with a brace-enclosed"
1351                           " initializer");
1352             return error_mark_node;
1353           }
1354 
1355       return convert_for_initialization (NULL_TREE, type, init,
1356                                                    flags,
1357                                                    ICR_INIT, NULL_TREE, 0,
1358                                          complain);
1359     }
1360 }
1361 
1362 tree
digest_init(tree type,tree init,tsubst_flags_t complain)1363 digest_init (tree type, tree init, tsubst_flags_t complain)
1364 {
1365   return digest_init_r (type, init, 0, LOOKUP_IMPLICIT, complain);
1366 }
1367 
1368 tree
digest_init_flags(tree type,tree init,int flags,tsubst_flags_t complain)1369 digest_init_flags (tree type, tree init, int flags, tsubst_flags_t complain)
1370 {
1371   return digest_init_r (type, init, 0, flags, complain);
1372 }
1373 
1374 /* Process the initializer INIT for an NSDMI DECL (a FIELD_DECL).  */
1375 tree
digest_nsdmi_init(tree decl,tree init,tsubst_flags_t complain)1376 digest_nsdmi_init (tree decl, tree init, tsubst_flags_t complain)
1377 {
1378   gcc_assert (TREE_CODE (decl) == FIELD_DECL);
1379 
1380   tree type = TREE_TYPE (decl);
1381   if (DECL_BIT_FIELD_TYPE (decl))
1382     type = DECL_BIT_FIELD_TYPE (decl);
1383   int flags = LOOKUP_IMPLICIT;
1384   if (DIRECT_LIST_INIT_P (init))
1385     {
1386       flags = LOOKUP_NORMAL;
1387       complain |= tf_no_cleanup;
1388     }
1389   if (BRACE_ENCLOSED_INITIALIZER_P (init)
1390       && CP_AGGREGATE_TYPE_P (type))
1391     init = reshape_init (type, init, complain);
1392   init = digest_init_flags (type, init, flags, complain);
1393   return init;
1394 }
1395 
1396 /* Set of flags used within process_init_constructor to describe the
1397    initializers.  */
1398 #define PICFLAG_ERRONEOUS 1
1399 #define PICFLAG_NOT_ALL_CONSTANT 2
1400 #define PICFLAG_NOT_ALL_SIMPLE 4
1401 #define PICFLAG_SIDE_EFFECTS 8
1402 #define PICFLAG_VEC_INIT 16
1403 
1404 /* Given an initializer INIT, return the flag (PICFLAG_*) which better
1405    describe it.  */
1406 
1407 static int
picflag_from_initializer(tree init)1408 picflag_from_initializer (tree init)
1409 {
1410   if (init == error_mark_node)
1411     return PICFLAG_ERRONEOUS;
1412   else if (!TREE_CONSTANT (init))
1413     {
1414       if (TREE_SIDE_EFFECTS (init))
1415           return PICFLAG_SIDE_EFFECTS;
1416       else
1417           return PICFLAG_NOT_ALL_CONSTANT;
1418     }
1419   else if (!initializer_constant_valid_p (init, TREE_TYPE (init)))
1420     return PICFLAG_NOT_ALL_SIMPLE;
1421   return 0;
1422 }
1423 
1424 /* Adjust INIT for going into a CONSTRUCTOR.  */
1425 
1426 static tree
massage_init_elt(tree type,tree init,int nested,int flags,tsubst_flags_t complain)1427 massage_init_elt (tree type, tree init, int nested, int flags,
1428                       tsubst_flags_t complain)
1429 {
1430   int new_flags = LOOKUP_IMPLICIT;
1431   if (flags & LOOKUP_ALLOW_FLEXARRAY_INIT)
1432     new_flags |= LOOKUP_ALLOW_FLEXARRAY_INIT;
1433   if (flags & LOOKUP_AGGREGATE_PAREN_INIT)
1434     new_flags |= LOOKUP_AGGREGATE_PAREN_INIT;
1435   init = digest_init_r (type, init, nested ? 2 : 1, new_flags, complain);
1436   /* When we defer constant folding within a statement, we may want to
1437      defer this folding as well.  Don't call this on CONSTRUCTORs because
1438      their elements have already been folded, and we must avoid folding
1439      the result of get_nsdmi.  */
1440   if (TREE_CODE (init) != CONSTRUCTOR)
1441     {
1442       tree t = fold_non_dependent_init (init, complain);
1443       if (TREE_CONSTANT (t))
1444           init = t;
1445     }
1446   return init;
1447 }
1448 
1449 /* Subroutine of process_init_constructor, which will process an initializer
1450    INIT for an array or vector of type TYPE. Returns the flags (PICFLAG_*)
1451    which describe the initializers.  */
1452 
1453 static int
process_init_constructor_array(tree type,tree init,int nested,int flags,tsubst_flags_t complain)1454 process_init_constructor_array (tree type, tree init, int nested, int flags,
1455                                         tsubst_flags_t complain)
1456 {
1457   unsigned HOST_WIDE_INT i, len = 0;
1458   int picflags = 0;
1459   bool unbounded = false;
1460   constructor_elt *ce;
1461   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (init);
1462 
1463   gcc_assert (TREE_CODE (type) == ARRAY_TYPE
1464                 || VECTOR_TYPE_P (type));
1465 
1466   if (TREE_CODE (type) == ARRAY_TYPE)
1467     {
1468       /* C++ flexible array members have a null domain.  */
1469       tree domain = TYPE_DOMAIN (type);
1470       if (domain && TREE_CONSTANT (TYPE_MAX_VALUE (domain)))
1471           len = wi::ext (wi::to_offset (TYPE_MAX_VALUE (domain))
1472                        - wi::to_offset (TYPE_MIN_VALUE (domain)) + 1,
1473                            TYPE_PRECISION (TREE_TYPE (domain)),
1474                            TYPE_SIGN (TREE_TYPE (domain))).to_uhwi ();
1475       else
1476           unbounded = true;  /* Take as many as there are.  */
1477 
1478       if (nested == 2 && !domain && !vec_safe_is_empty (v))
1479           {
1480             if (complain & tf_error)
1481               error_at (cp_expr_loc_or_input_loc (init),
1482                           "initialization of flexible array member "
1483                           "in a nested context");
1484             return PICFLAG_ERRONEOUS;
1485           }
1486     }
1487   else
1488     /* Vectors are like simple fixed-size arrays.  */
1489     unbounded = !TYPE_VECTOR_SUBPARTS (type).is_constant (&len);
1490 
1491   /* There must not be more initializers than needed.  */
1492   if (!unbounded && vec_safe_length (v) > len)
1493     {
1494       if (complain & tf_error)
1495           error ("too many initializers for %qT", type);
1496       else
1497           return PICFLAG_ERRONEOUS;
1498     }
1499 
1500   FOR_EACH_VEC_SAFE_ELT (v, i, ce)
1501     {
1502       if (!ce->index)
1503           ce->index = size_int (i);
1504       else if (!check_array_designated_initializer (ce, i))
1505           ce->index = error_mark_node;
1506       gcc_assert (ce->value);
1507       ce->value
1508           = massage_init_elt (TREE_TYPE (type), ce->value, nested, flags,
1509                                   complain);
1510 
1511       gcc_checking_assert
1512           (ce->value == error_mark_node
1513            || (same_type_ignoring_top_level_qualifiers_p
1514                (strip_array_types (TREE_TYPE (type)),
1515                 strip_array_types (TREE_TYPE (ce->value)))));
1516 
1517       picflags |= picflag_from_initializer (ce->value);
1518       /* Propagate CONSTRUCTOR_PLACEHOLDER_BOUNDARY to outer
1519            CONSTRUCTOR.  */
1520       if (TREE_CODE (ce->value) == CONSTRUCTOR
1521             && CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ce->value))
1522           {
1523             CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init) = 1;
1524             CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ce->value) = 0;
1525           }
1526     }
1527 
1528   /* No more initializers. If the array is unbounded, we are done. Otherwise,
1529      we must add initializers ourselves.  */
1530   if (!unbounded)
1531     for (; i < len; ++i)
1532       {
1533           tree next;
1534 
1535           if (type_build_ctor_call (TREE_TYPE (type)))
1536             {
1537               /* If this type needs constructors run for default-initialization,
1538                  we can't rely on the back end to do it for us, so make the
1539                  initialization explicit by list-initializing from T{}.  */
1540               next = build_constructor (init_list_type_node, NULL);
1541               next = massage_init_elt (TREE_TYPE (type), next, nested, flags,
1542                                              complain);
1543               if (initializer_zerop (next))
1544                 /* The default zero-initialization is fine for us; don't
1545                      add anything to the CONSTRUCTOR.  */
1546                 next = NULL_TREE;
1547             }
1548           else if (!zero_init_p (TREE_TYPE (type)))
1549             next = build_zero_init (TREE_TYPE (type),
1550                                           /*nelts=*/NULL_TREE,
1551                                           /*static_storage_p=*/false);
1552           else
1553             /* The default zero-initialization is fine for us; don't
1554                add anything to the CONSTRUCTOR.  */
1555             next = NULL_TREE;
1556 
1557           if (next)
1558             {
1559               if (next != error_mark_node
1560                     && ! seen_error () // Improves error-recovery on anew5.C.
1561                     && (initializer_constant_valid_p (next, TREE_TYPE (next))
1562                         != null_pointer_node))
1563                 {
1564                     /* Use VEC_INIT_EXPR for non-constant initialization of
1565                        trailing elements with no explicit initializers.  */
1566                     picflags |= PICFLAG_VEC_INIT;
1567                     break;
1568                 }
1569 
1570               picflags |= picflag_from_initializer (next);
1571               /* Propagate CONSTRUCTOR_PLACEHOLDER_BOUNDARY to outer
1572                  CONSTRUCTOR.  */
1573               if (TREE_CODE (next) == CONSTRUCTOR
1574                     && CONSTRUCTOR_PLACEHOLDER_BOUNDARY (next))
1575                 {
1576                     CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init) = 1;
1577                     CONSTRUCTOR_PLACEHOLDER_BOUNDARY (next) = 0;
1578                 }
1579               if (len > i+1)
1580                 {
1581                     tree range = build2 (RANGE_EXPR, size_type_node,
1582                                              build_int_cst (size_type_node, i),
1583                                              build_int_cst (size_type_node, len - 1));
1584                     CONSTRUCTOR_APPEND_ELT (v, range, next);
1585                     break;
1586                 }
1587               else
1588                 CONSTRUCTOR_APPEND_ELT (v, size_int (i), next);
1589             }
1590           else
1591             /* Don't bother checking all the other elements.  */
1592             break;
1593       }
1594 
1595   CONSTRUCTOR_ELTS (init) = v;
1596   return picflags;
1597 }
1598 
1599 /* Subroutine of process_init_constructor, which will process an initializer
1600    INIT for a class of type TYPE. Returns the flags (PICFLAG_*) which describe
1601    the initializers.  */
1602 
1603 static int
process_init_constructor_record(tree type,tree init,int nested,int flags,tsubst_flags_t complain)1604 process_init_constructor_record (tree type, tree init, int nested, int flags,
1605                                          tsubst_flags_t complain)
1606 {
1607   vec<constructor_elt, va_gc> *v = NULL;
1608   tree field;
1609   int skipped = 0;
1610 
1611   gcc_assert (TREE_CODE (type) == RECORD_TYPE);
1612   gcc_assert (!CLASSTYPE_VBASECLASSES (type));
1613   gcc_assert (!TYPE_BINFO (type)
1614                 || cxx_dialect >= cxx17
1615                 || !BINFO_N_BASE_BINFOS (TYPE_BINFO (type)));
1616   gcc_assert (!TYPE_POLYMORPHIC_P (type));
1617 
1618  restart:
1619   int picflags = 0;
1620   unsigned HOST_WIDE_INT idx = 0;
1621   int designator_skip = -1;
1622   /* Generally, we will always have an index for each initializer (which is
1623      a FIELD_DECL, put by reshape_init), but compound literals don't go trough
1624      reshape_init. So we need to handle both cases.  */
1625   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1626     {
1627       tree next;
1628 
1629       if (TREE_CODE (field) != FIELD_DECL
1630             || (DECL_ARTIFICIAL (field)
1631                 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field))))
1632           continue;
1633 
1634       if (DECL_UNNAMED_BIT_FIELD (field))
1635           continue;
1636 
1637       /* If this is a bitfield, first convert to the declared type.  */
1638       tree fldtype = TREE_TYPE (field);
1639       if (DECL_BIT_FIELD_TYPE (field))
1640           fldtype = DECL_BIT_FIELD_TYPE (field);
1641       if (fldtype == error_mark_node)
1642           return PICFLAG_ERRONEOUS;
1643 
1644       next = NULL_TREE;
1645       if (idx < CONSTRUCTOR_NELTS (init))
1646           {
1647             constructor_elt *ce = &(*CONSTRUCTOR_ELTS (init))[idx];
1648             if (ce->index)
1649               {
1650                 /* We can have either a FIELD_DECL or an IDENTIFIER_NODE. The
1651                      latter case can happen in templates where lookup has to be
1652                      deferred.  */
1653                 gcc_assert (TREE_CODE (ce->index) == FIELD_DECL
1654                                 || identifier_p (ce->index));
1655                 if (ce->index == field || ce->index == DECL_NAME (field))
1656                     next = ce->value;
1657                 else
1658                     {
1659                       ce = NULL;
1660                       if (designator_skip == -1)
1661                         designator_skip = 1;
1662                     }
1663               }
1664             else
1665               {
1666                 designator_skip = 0;
1667                 next = ce->value;
1668               }
1669 
1670             if (ce)
1671               {
1672                 gcc_assert (ce->value);
1673                 next = massage_init_elt (fldtype, next, nested, flags, complain);
1674                 ++idx;
1675               }
1676           }
1677       if (next == error_mark_node)
1678           /* We skip initializers for empty bases/fields, so skipping an invalid
1679              one could make us accept invalid code.  */
1680           return PICFLAG_ERRONEOUS;
1681       else if (next)
1682           /* Already handled above.  */;
1683       else if (DECL_INITIAL (field))
1684           {
1685             if (skipped > 0)
1686               {
1687                 /* We're using an NSDMI past a field with implicit
1688                    zero-init.  Go back and make it explicit.  */
1689                 skipped = -1;
1690                 vec_safe_truncate (v, 0);
1691                 goto restart;
1692               }
1693             /* C++14 aggregate NSDMI.  */
1694             next = get_nsdmi (field, /*ctor*/false, complain);
1695             if (!CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init)
1696                 && find_placeholders (next))
1697               CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init) = 1;
1698           }
1699       else if (type_build_ctor_call (fldtype))
1700           {
1701             /* If this type needs constructors run for
1702                default-initialization, we can't rely on the back end to do it
1703                for us, so build up TARGET_EXPRs.  If the type in question is
1704                a class, just build one up; if it's an array, recurse.  */
1705             next = build_constructor (init_list_type_node, NULL);
1706             next = massage_init_elt (fldtype, next, nested, flags, complain);
1707 
1708             /* Warn when some struct elements are implicitly initialized.  */
1709             if ((complain & tf_warning)
1710                 && !cp_unevaluated_operand
1711                 && !EMPTY_CONSTRUCTOR_P (init))
1712               warning (OPT_Wmissing_field_initializers,
1713                          "missing initializer for member %qD", field);
1714           }
1715       else
1716           {
1717             if (TYPE_REF_P (fldtype))
1718               {
1719                 if (complain & tf_error)
1720                     error ("member %qD is uninitialized reference", field);
1721                 else
1722                     return PICFLAG_ERRONEOUS;
1723               }
1724             else if (CLASSTYPE_REF_FIELDS_NEED_INIT (fldtype))
1725               {
1726                 if (complain & tf_error)
1727                     error ("member %qD with uninitialized reference fields", field);
1728                 else
1729                     return PICFLAG_ERRONEOUS;
1730               }
1731             /* Do nothing for flexible array members since they need not have any
1732                elements.  Don't worry about 'skipped' because a flexarray has to
1733                be the last field.  */
1734             else if (TREE_CODE (fldtype) == ARRAY_TYPE && !TYPE_DOMAIN (fldtype))
1735               continue;
1736 
1737             /* Warn when some struct elements are implicitly initialized
1738                to zero.  */
1739             if ((complain & tf_warning)
1740                 && !cp_unevaluated_operand
1741                 && !EMPTY_CONSTRUCTOR_P (init))
1742               warning (OPT_Wmissing_field_initializers,
1743                          "missing initializer for member %qD", field);
1744 
1745             if (!zero_init_p (fldtype) || skipped < 0)
1746               {
1747                 if (TYPE_REF_P (fldtype))
1748                     next = build_zero_cst (fldtype);
1749                 else
1750                     next = build_zero_init (fldtype, /*nelts=*/NULL_TREE,
1751                                                   /*static_storage_p=*/false);
1752               }
1753             else
1754               {
1755                 /* The default zero-initialization is fine for us; don't
1756                      add anything to the CONSTRUCTOR.  */
1757                 skipped = 1;
1758                 continue;
1759               }
1760           }
1761 
1762       if (is_empty_field (field)
1763             && !TREE_SIDE_EFFECTS (next))
1764           /* Don't add trivial initialization of an empty base/field to the
1765              constructor, as they might not be ordered the way the back-end
1766              expects.  */
1767           continue;
1768 
1769       /* If this is a bitfield, now convert to the lowered type.  */
1770       if (fldtype != TREE_TYPE (field))
1771           next = cp_convert_and_check (TREE_TYPE (field), next, complain);
1772       picflags |= picflag_from_initializer (next);
1773       /* Propagate CONSTRUCTOR_PLACEHOLDER_BOUNDARY to outer CONSTRUCTOR.  */
1774       if (TREE_CODE (next) == CONSTRUCTOR
1775             && CONSTRUCTOR_PLACEHOLDER_BOUNDARY (next))
1776           {
1777             CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init) = 1;
1778             CONSTRUCTOR_PLACEHOLDER_BOUNDARY (next) = 0;
1779           }
1780       CONSTRUCTOR_APPEND_ELT (v, field, next);
1781     }
1782 
1783   if (idx < CONSTRUCTOR_NELTS (init))
1784     {
1785       if (complain & tf_error)
1786           {
1787             constructor_elt *ce = &(*CONSTRUCTOR_ELTS (init))[idx];
1788             /* For better diagnostics, try to find out if it is really
1789                the case of too many initializers or if designators are
1790                in incorrect order.  */
1791             if (designator_skip == 1 && ce->index)
1792               {
1793                 gcc_assert (TREE_CODE (ce->index) == FIELD_DECL
1794                                 || identifier_p (ce->index));
1795                 for (field = TYPE_FIELDS (type);
1796                        field; field = DECL_CHAIN (field))
1797                     {
1798                       if (TREE_CODE (field) != FIELD_DECL
1799                           || (DECL_ARTIFICIAL (field)
1800                                 && !(cxx_dialect >= cxx17
1801                                      && DECL_FIELD_IS_BASE (field))))
1802                         continue;
1803 
1804                       if (DECL_UNNAMED_BIT_FIELD (field))
1805                         continue;
1806 
1807                       if (ce->index == field || ce->index == DECL_NAME (field))
1808                         break;
1809                     }
1810               }
1811             if (field)
1812               error ("designator order for field %qD does not match declaration "
1813                        "order in %qT", field, type);
1814             else
1815               error ("too many initializers for %qT", type);
1816           }
1817       else
1818           return PICFLAG_ERRONEOUS;
1819     }
1820 
1821   CONSTRUCTOR_ELTS (init) = v;
1822   return picflags;
1823 }
1824 
1825 /* Subroutine of process_init_constructor, which will process a single
1826    initializer INIT for a union of type TYPE. Returns the flags (PICFLAG_*)
1827    which describe the initializer.  */
1828 
1829 static int
process_init_constructor_union(tree type,tree init,int nested,int flags,tsubst_flags_t complain)1830 process_init_constructor_union (tree type, tree init, int nested, int flags,
1831                                         tsubst_flags_t complain)
1832 {
1833   constructor_elt *ce;
1834   int len;
1835 
1836   /* If the initializer was empty, use the union's NSDMI if it has one.
1837      Otherwise use default zero initialization.  */
1838   if (vec_safe_is_empty (CONSTRUCTOR_ELTS (init)))
1839     {
1840       for (tree field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1841           {
1842             if (TREE_CODE (field) == FIELD_DECL
1843                 && DECL_INITIAL (field) != NULL_TREE)
1844               {
1845                 tree val = get_nsdmi (field, /*in_ctor=*/false, complain);
1846                 if (!CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init)
1847                       && find_placeholders (val))
1848                     CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init) = 1;
1849                 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (init), field, val);
1850                 break;
1851               }
1852           }
1853 
1854       if (vec_safe_is_empty (CONSTRUCTOR_ELTS (init)))
1855           return 0;
1856     }
1857 
1858   len = CONSTRUCTOR_ELTS (init)->length ();
1859   if (len > 1)
1860     {
1861       if (!(complain & tf_error))
1862           return PICFLAG_ERRONEOUS;
1863       error ("too many initializers for %qT", type);
1864       CONSTRUCTOR_ELTS (init)->block_remove (1, len-1);
1865     }
1866 
1867   ce = &(*CONSTRUCTOR_ELTS (init))[0];
1868 
1869   /* If this element specifies a field, initialize via that field.  */
1870   if (ce->index)
1871     {
1872       if (TREE_CODE (ce->index) == FIELD_DECL)
1873           ;
1874       else if (identifier_p (ce->index))
1875           {
1876             /* This can happen within a cast, see g++.dg/opt/cse2.C.  */
1877             tree name = ce->index;
1878             tree field;
1879             for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1880               if (DECL_NAME (field) == name)
1881                 break;
1882             if (!field)
1883               {
1884                 if (complain & tf_error)
1885                     error ("no field %qD found in union being initialized",
1886                            field);
1887                 ce->value = error_mark_node;
1888               }
1889             ce->index = field;
1890           }
1891       else
1892           {
1893             gcc_assert (TREE_CODE (ce->index) == INTEGER_CST
1894                           || TREE_CODE (ce->index) == RANGE_EXPR);
1895             if (complain & tf_error)
1896               error ("index value instead of field name in union initializer");
1897             ce->value = error_mark_node;
1898           }
1899     }
1900   else
1901     {
1902       /* Find the first named field.  ANSI decided in September 1990
1903            that only named fields count here.  */
1904       tree field = TYPE_FIELDS (type);
1905       while (field && (!DECL_NAME (field) || TREE_CODE (field) != FIELD_DECL))
1906           field = TREE_CHAIN (field);
1907       if (field == NULL_TREE)
1908           {
1909             if (complain & tf_error)
1910               error ("too many initializers for %qT", type);
1911             ce->value = error_mark_node;
1912           }
1913       ce->index = field;
1914     }
1915 
1916   if (ce->value && ce->value != error_mark_node)
1917     ce->value = massage_init_elt (TREE_TYPE (ce->index), ce->value, nested,
1918                                           flags, complain);
1919 
1920   /* Propagate CONSTRUCTOR_PLACEHOLDER_BOUNDARY to outer CONSTRUCTOR.  */
1921   if (ce->value
1922       && TREE_CODE (ce->value) == CONSTRUCTOR
1923       && CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ce->value))
1924     {
1925       CONSTRUCTOR_PLACEHOLDER_BOUNDARY (init) = 1;
1926       CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ce->value) = 0;
1927     }
1928   return picflag_from_initializer (ce->value);
1929 }
1930 
1931 /* Process INIT, a constructor for a variable of aggregate type TYPE. The
1932    constructor is a brace-enclosed initializer, and will be modified in-place.
1933 
1934    Each element is converted to the right type through digest_init, and
1935    missing initializers are added following the language rules (zero-padding,
1936    etc.).
1937 
1938    After the execution, the initializer will have TREE_CONSTANT if all elts are
1939    constant, and TREE_STATIC set if, in addition, all elts are simple enough
1940    constants that the assembler and linker can compute them.
1941 
1942    The function returns the initializer itself, or error_mark_node in case
1943    of error.  */
1944 
1945 static tree
process_init_constructor(tree type,tree init,int nested,int flags,tsubst_flags_t complain)1946 process_init_constructor (tree type, tree init, int nested, int flags,
1947                                 tsubst_flags_t complain)
1948 {
1949   int picflags;
1950 
1951   gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
1952 
1953   if (TREE_CODE (type) == ARRAY_TYPE || VECTOR_TYPE_P (type))
1954     picflags = process_init_constructor_array (type, init, nested, flags,
1955                                                          complain);
1956   else if (TREE_CODE (type) == RECORD_TYPE)
1957     picflags = process_init_constructor_record (type, init, nested, flags,
1958                                                             complain);
1959   else if (TREE_CODE (type) == UNION_TYPE)
1960     picflags = process_init_constructor_union (type, init, nested, flags,
1961                                                          complain);
1962   else
1963     gcc_unreachable ();
1964 
1965   if (picflags & PICFLAG_ERRONEOUS)
1966     return error_mark_node;
1967 
1968   TREE_TYPE (init) = type;
1969   if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type) == NULL_TREE)
1970     cp_complete_array_type (&TREE_TYPE (init), init, /*do_default=*/0);
1971   if (picflags & PICFLAG_SIDE_EFFECTS)
1972     {
1973       TREE_CONSTANT (init) = false;
1974       TREE_SIDE_EFFECTS (init) = true;
1975     }
1976   else if (picflags & PICFLAG_NOT_ALL_CONSTANT)
1977     {
1978       /* Make sure TREE_CONSTANT isn't set from build_constructor.  */
1979       TREE_CONSTANT (init) = false;
1980       TREE_SIDE_EFFECTS (init) = false;
1981     }
1982   else
1983     {
1984       TREE_CONSTANT (init) = 1;
1985       TREE_SIDE_EFFECTS (init) = false;
1986       if (!(picflags & PICFLAG_NOT_ALL_SIMPLE))
1987           TREE_STATIC (init) = 1;
1988     }
1989   if (picflags & PICFLAG_VEC_INIT)
1990     {
1991       /* Defer default-initialization of array elements with no corresponding
1992            initializer-clause until later so we can use a loop.  */
1993       TREE_TYPE (init) = init_list_type_node;
1994       init = build_vec_init_expr (type, init, complain);
1995       init = get_target_expr (init);
1996     }
1997   return init;
1998 }
1999 
2000 /* Given a structure or union value DATUM, construct and return
2001    the structure or union component which results from narrowing
2002    that value to the base specified in BASETYPE.  For example, given the
2003    hierarchy
2004 
2005    class L { int ii; };
2006    class A : L { ... };
2007    class B : L { ... };
2008    class C : A, B { ... };
2009 
2010    and the declaration
2011 
2012    C x;
2013 
2014    then the expression
2015 
2016    x.A::ii refers to the ii member of the L part of
2017    the A part of the C object named by X.  In this case,
2018    DATUM would be x, and BASETYPE would be A.
2019 
2020    I used to think that this was nonconformant, that the standard specified
2021    that first we look up ii in A, then convert x to an L& and pull out the
2022    ii part.  But in fact, it does say that we convert x to an A&; A here
2023    is known as the "naming class".  (jason 2000-12-19)
2024 
2025    BINFO_P points to a variable initialized either to NULL_TREE or to the
2026    binfo for the specific base subobject we want to convert to.  */
2027 
2028 tree
build_scoped_ref(tree datum,tree basetype,tree * binfo_p)2029 build_scoped_ref (tree datum, tree basetype, tree* binfo_p)
2030 {
2031   tree binfo;
2032 
2033   if (datum == error_mark_node)
2034     return error_mark_node;
2035   if (*binfo_p)
2036     binfo = *binfo_p;
2037   else
2038     binfo = lookup_base (TREE_TYPE (datum), basetype, ba_check,
2039                                NULL, tf_warning_or_error);
2040 
2041   if (!binfo || binfo == error_mark_node)
2042     {
2043       *binfo_p = NULL_TREE;
2044       if (!binfo)
2045           error_not_base_type (basetype, TREE_TYPE (datum));
2046       return error_mark_node;
2047     }
2048 
2049   *binfo_p = binfo;
2050   return build_base_path (PLUS_EXPR, datum, binfo, 1,
2051                                 tf_warning_or_error);
2052 }
2053 
2054 /* Build a reference to an object specified by the C++ `->' operator.
2055    Usually this just involves dereferencing the object, but if the
2056    `->' operator is overloaded, then such overloads must be
2057    performed until an object which does not have the `->' operator
2058    overloaded is found.  An error is reported when circular pointer
2059    delegation is detected.  */
2060 
2061 tree
build_x_arrow(location_t loc,tree expr,tsubst_flags_t complain)2062 build_x_arrow (location_t loc, tree expr, tsubst_flags_t complain)
2063 {
2064   tree orig_expr = expr;
2065   tree type = TREE_TYPE (expr);
2066   tree last_rval = NULL_TREE;
2067   vec<tree, va_gc> *types_memoized = NULL;
2068 
2069   if (type == error_mark_node)
2070     return error_mark_node;
2071 
2072   if (processing_template_decl)
2073     {
2074       tree ttype = NULL_TREE;
2075       if (type && TYPE_PTR_P (type))
2076           ttype = TREE_TYPE (type);
2077       if (ttype && !dependent_scope_p (ttype))
2078           /* Pointer to current instantiation, don't treat as dependent.  */;
2079       else if (type_dependent_expression_p (expr))
2080           {
2081             expr = build_min_nt_loc (loc, ARROW_EXPR, expr);
2082             TREE_TYPE (expr) = ttype;
2083             return expr;
2084           }
2085       expr = build_non_dependent_expr (expr);
2086     }
2087 
2088   if (MAYBE_CLASS_TYPE_P (type))
2089     {
2090       struct tinst_level *actual_inst = current_instantiation ();
2091       tree fn = NULL;
2092 
2093       while ((expr = build_new_op (loc, COMPONENT_REF,
2094                                            LOOKUP_NORMAL, expr, NULL_TREE, NULL_TREE,
2095                                            NULL_TREE, &fn, complain)))
2096           {
2097             if (expr == error_mark_node)
2098               return error_mark_node;
2099 
2100             /* This provides a better instantiation backtrace in case of
2101                error.  */
2102             if (fn && DECL_USE_TEMPLATE (fn))
2103               push_tinst_level_loc (fn,
2104                                           (current_instantiation () != actual_inst)
2105                                           ? DECL_SOURCE_LOCATION (fn)
2106                                           : input_location);
2107             fn = NULL;
2108 
2109             if (vec_member (TREE_TYPE (expr), types_memoized))
2110               {
2111                 if (complain & tf_error)
2112                     error ("circular pointer delegation detected");
2113                 return error_mark_node;
2114               }
2115 
2116             vec_safe_push (types_memoized, TREE_TYPE (expr));
2117             last_rval = expr;
2118           }
2119 
2120       while (current_instantiation () != actual_inst)
2121           pop_tinst_level ();
2122 
2123       if (last_rval == NULL_TREE)
2124           {
2125             if (complain & tf_error)
2126               error ("base operand of %<->%> has non-pointer type %qT", type);
2127             return error_mark_node;
2128           }
2129 
2130       if (TYPE_REF_P (TREE_TYPE (last_rval)))
2131           last_rval = convert_from_reference (last_rval);
2132     }
2133   else
2134     {
2135       last_rval = decay_conversion (expr, complain);
2136       if (last_rval == error_mark_node)
2137           return error_mark_node;
2138     }
2139 
2140   if (TYPE_PTR_P (TREE_TYPE (last_rval)))
2141     {
2142       if (processing_template_decl)
2143           {
2144             expr = build_min (ARROW_EXPR, TREE_TYPE (TREE_TYPE (last_rval)),
2145                                   orig_expr);
2146             TREE_SIDE_EFFECTS (expr) = TREE_SIDE_EFFECTS (last_rval);
2147             return expr;
2148           }
2149 
2150       return cp_build_indirect_ref (loc, last_rval, RO_ARROW, complain);
2151     }
2152 
2153   if (complain & tf_error)
2154     {
2155       if (types_memoized)
2156           error ("result of %<operator->()%> yields non-pointer result");
2157       else
2158           error ("base operand of %<->%> is not a pointer");
2159     }
2160   return error_mark_node;
2161 }
2162 
2163 /* Return an expression for "DATUM .* COMPONENT".  DATUM has not
2164    already been checked out to be of aggregate type.  */
2165 
2166 tree
build_m_component_ref(tree datum,tree component,tsubst_flags_t complain)2167 build_m_component_ref (tree datum, tree component, tsubst_flags_t complain)
2168 {
2169   tree ptrmem_type;
2170   tree objtype;
2171   tree type;
2172   tree binfo;
2173   tree ctype;
2174 
2175   datum = mark_lvalue_use (datum);
2176   component = mark_rvalue_use (component);
2177 
2178   if (error_operand_p (datum) || error_operand_p (component))
2179     return error_mark_node;
2180 
2181   ptrmem_type = TREE_TYPE (component);
2182   if (!TYPE_PTRMEM_P (ptrmem_type))
2183     {
2184       if (complain & tf_error)
2185           error ("%qE cannot be used as a member pointer, since it is of "
2186                  "type %qT", component, ptrmem_type);
2187       return error_mark_node;
2188     }
2189 
2190   objtype = TYPE_MAIN_VARIANT (TREE_TYPE (datum));
2191   if (! MAYBE_CLASS_TYPE_P (objtype))
2192     {
2193       if (complain & tf_error)
2194           error ("cannot apply member pointer %qE to %qE, which is of "
2195                  "non-class type %qT", component, datum, objtype);
2196       return error_mark_node;
2197     }
2198 
2199   type = TYPE_PTRMEM_POINTED_TO_TYPE (ptrmem_type);
2200   ctype = complete_type (TYPE_PTRMEM_CLASS_TYPE (ptrmem_type));
2201 
2202   if (!COMPLETE_TYPE_P (ctype))
2203     {
2204       if (!same_type_p (ctype, objtype))
2205           goto mismatch;
2206       binfo = NULL;
2207     }
2208   else
2209     {
2210       binfo = lookup_base (objtype, ctype, ba_check, NULL, complain);
2211 
2212       if (!binfo)
2213           {
2214           mismatch:
2215             if (complain & tf_error)
2216               error ("pointer to member type %qT incompatible with object "
2217                        "type %qT", type, objtype);
2218             return error_mark_node;
2219           }
2220       else if (binfo == error_mark_node)
2221           return error_mark_node;
2222     }
2223 
2224   if (TYPE_PTRDATAMEM_P (ptrmem_type))
2225     {
2226       bool is_lval = real_lvalue_p (datum);
2227       tree ptype;
2228 
2229       /* Compute the type of the field, as described in [expr.ref].
2230            There's no such thing as a mutable pointer-to-member, so
2231            things are not as complex as they are for references to
2232            non-static data members.  */
2233       type = cp_build_qualified_type (type,
2234                                               (cp_type_quals (type)
2235                                                | cp_type_quals (TREE_TYPE (datum))));
2236 
2237       datum = build_address (datum);
2238 
2239       /* Convert object to the correct base.  */
2240       if (binfo)
2241           {
2242             datum = build_base_path (PLUS_EXPR, datum, binfo, 1, complain);
2243             if (datum == error_mark_node)
2244               return error_mark_node;
2245           }
2246 
2247       /* Build an expression for "object + offset" where offset is the
2248            value stored in the pointer-to-data-member.  */
2249       ptype = build_pointer_type (type);
2250       datum = fold_build_pointer_plus (fold_convert (ptype, datum), component);
2251       datum = cp_build_fold_indirect_ref (datum);
2252       if (datum == error_mark_node)
2253           return error_mark_node;
2254 
2255       /* If the object expression was an rvalue, return an rvalue.  */
2256       if (!is_lval)
2257           datum = move (datum);
2258       return datum;
2259     }
2260   else
2261     {
2262       /* 5.5/6: In a .* expression whose object expression is an rvalue, the
2263            program is ill-formed if the second operand is a pointer to member
2264            function with ref-qualifier & (for C++20: unless its cv-qualifier-seq
2265            is const). In a .* expression whose object expression is an lvalue,
2266            the program is ill-formed if the second operand is a pointer to member
2267            function with ref-qualifier &&.  */
2268       if (FUNCTION_REF_QUALIFIED (type))
2269           {
2270             bool lval = lvalue_p (datum);
2271             if (lval && FUNCTION_RVALUE_QUALIFIED (type))
2272               {
2273                 if (complain & tf_error)
2274                     error ("pointer-to-member-function type %qT requires an rvalue",
2275                            ptrmem_type);
2276                 return error_mark_node;
2277               }
2278             else if (!lval && !FUNCTION_RVALUE_QUALIFIED (type))
2279               {
2280                 if ((type_memfn_quals (type)
2281                        & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE))
2282                       != TYPE_QUAL_CONST)
2283                     {
2284                       if (complain & tf_error)
2285                         error ("pointer-to-member-function type %qT requires "
2286                                  "an lvalue", ptrmem_type);
2287                       return error_mark_node;
2288                     }
2289                 else if (cxx_dialect < cxx20)
2290                     {
2291                       if (complain & tf_warning_or_error)
2292                         pedwarn (input_location, OPT_Wpedantic,
2293                                    "pointer-to-member-function type %qT requires "
2294                                    "an lvalue before C++20", ptrmem_type);
2295                       else
2296                         return error_mark_node;
2297                     }
2298               }
2299           }
2300       return build2 (OFFSET_REF, type, datum, component);
2301     }
2302 }
2303 
2304 /* Return a tree node for the expression TYPENAME '(' PARMS ')'.  */
2305 
2306 static tree
build_functional_cast_1(location_t loc,tree exp,tree parms,tsubst_flags_t complain)2307 build_functional_cast_1 (location_t loc, tree exp, tree parms,
2308                                tsubst_flags_t complain)
2309 {
2310   /* This is either a call to a constructor,
2311      or a C cast in C++'s `functional' notation.  */
2312 
2313   /* The type to which we are casting.  */
2314   tree type;
2315 
2316   if (error_operand_p (exp) || parms == error_mark_node)
2317     return error_mark_node;
2318 
2319   if (TREE_CODE (exp) == TYPE_DECL)
2320     {
2321       type = TREE_TYPE (exp);
2322 
2323       if (DECL_ARTIFICIAL (exp))
2324           cp_handle_deprecated_or_unavailable (type);
2325     }
2326   else
2327     type = exp;
2328 
2329   /* We need to check this explicitly, since value-initialization of
2330      arrays is allowed in other situations.  */
2331   if (TREE_CODE (type) == ARRAY_TYPE)
2332     {
2333       if (complain & tf_error)
2334           error_at (loc, "functional cast to array type %qT", type);
2335       return error_mark_node;
2336     }
2337 
2338   if (tree anode = type_uses_auto (type))
2339     {
2340       tree init;
2341       if (CLASS_PLACEHOLDER_TEMPLATE (anode))
2342           init = parms;
2343       /* C++23 auto(x).  */
2344       else if (!AUTO_IS_DECLTYPE (anode)
2345                  && list_length (parms) == 1)
2346           {
2347             init = TREE_VALUE (parms);
2348             if (is_constrained_auto (anode))
2349               {
2350                 if (complain & tf_error)
2351                     error_at (loc, "%<auto(x)%> cannot be constrained");
2352                 return error_mark_node;
2353               }
2354             else if (cxx_dialect < cxx23)
2355               pedwarn (loc, OPT_Wc__23_extensions,
2356                          "%<auto(x)%> only available with "
2357                          "%<-std=c++2b%> or %<-std=gnu++2b%>");
2358           }
2359       else
2360           {
2361             if (complain & tf_error)
2362               error_at (loc, "invalid use of %qT", anode);
2363             return error_mark_node;
2364           }
2365       type = do_auto_deduction (type, init, anode, complain,
2366                                         adc_variable_type);
2367       if (type == error_mark_node)
2368           return error_mark_node;
2369     }
2370 
2371   if (processing_template_decl)
2372     {
2373       tree t;
2374 
2375       /* Diagnose this even in a template.  We could also try harder
2376            to give all the usual errors when the type and args are
2377            non-dependent...  */
2378       if (TYPE_REF_P (type) && !parms)
2379           {
2380             if (complain & tf_error)
2381               error_at (loc, "invalid value-initialization of reference type");
2382             return error_mark_node;
2383           }
2384 
2385       t = build_min (CAST_EXPR, type, parms);
2386       /* We don't know if it will or will not have side effects.  */
2387       TREE_SIDE_EFFECTS (t) = 1;
2388       return t;
2389     }
2390 
2391   if (! MAYBE_CLASS_TYPE_P (type))
2392     {
2393       if (parms == NULL_TREE)
2394           {
2395             if (VOID_TYPE_P (type))
2396               return void_node;
2397             return build_value_init (cv_unqualified (type), complain);
2398           }
2399 
2400       /* This must build a C cast.  */
2401       parms = build_x_compound_expr_from_list (parms, ELK_FUNC_CAST, complain);
2402       return cp_build_c_cast (loc, type, parms, complain);
2403     }
2404 
2405   /* Prepare to evaluate as a call to a constructor.  If this expression
2406      is actually used, for example,
2407 
2408      return X (arg1, arg2, ...);
2409 
2410      then the slot being initialized will be filled in.  */
2411 
2412   if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
2413     return error_mark_node;
2414   if (abstract_virtuals_error_sfinae (ACU_CAST, type, complain))
2415     return error_mark_node;
2416 
2417   /* [expr.type.conv]
2418 
2419      If the expression list is a single-expression, the type
2420      conversion is equivalent (in definedness, and if defined in
2421      meaning) to the corresponding cast expression.  */
2422   if (parms && TREE_CHAIN (parms) == NULL_TREE)
2423     return cp_build_c_cast (loc, type, TREE_VALUE (parms), complain);
2424 
2425   /* [expr.type.conv]
2426 
2427      The expression T(), where T is a simple-type-specifier for a
2428      non-array complete object type or the (possibly cv-qualified)
2429      void type, creates an rvalue of the specified type, which is
2430      value-initialized.  */
2431 
2432   if (parms == NULL_TREE)
2433     {
2434       exp = build_value_init (type, complain);
2435       exp = get_target_expr_sfinae (exp, complain);
2436       return exp;
2437     }
2438 
2439   /* Call the constructor.  */
2440   releasing_vec parmvec;
2441   for (; parms != NULL_TREE; parms = TREE_CHAIN (parms))
2442     vec_safe_push (parmvec, TREE_VALUE (parms));
2443   exp = build_special_member_call (NULL_TREE, complete_ctor_identifier,
2444                                            &parmvec, type, LOOKUP_NORMAL, complain);
2445 
2446   if (exp == error_mark_node)
2447     return error_mark_node;
2448 
2449   return build_cplus_new (type, exp, complain);
2450 }
2451 
2452 tree
build_functional_cast(location_t loc,tree exp,tree parms,tsubst_flags_t complain)2453 build_functional_cast (location_t loc, tree exp, tree parms,
2454                            tsubst_flags_t complain)
2455 {
2456   tree result = build_functional_cast_1 (loc, exp, parms, complain);
2457   protected_set_expr_location (result, loc);
2458   return result;
2459 }
2460 
2461 
2462 /* Add new exception specifier SPEC, to the LIST we currently have.
2463    If it's already in LIST then do nothing.
2464    Moan if it's bad and we're allowed to. COMPLAIN < 0 means we
2465    know what we're doing.  */
2466 
2467 tree
add_exception_specifier(tree list,tree spec,tsubst_flags_t complain)2468 add_exception_specifier (tree list, tree spec, tsubst_flags_t complain)
2469 {
2470   bool ok;
2471   tree core = spec;
2472   bool is_ptr;
2473   diagnostic_t diag_type = DK_UNSPECIFIED; /* none */
2474 
2475   if (spec == error_mark_node)
2476     return list;
2477 
2478   gcc_assert (spec && (!list || TREE_VALUE (list)));
2479 
2480   /* [except.spec] 1, type in an exception specifier shall not be
2481      incomplete, or pointer or ref to incomplete other than pointer
2482      to cv void.  */
2483   is_ptr = TYPE_PTR_P (core);
2484   if (is_ptr || TYPE_REF_P (core))
2485     core = TREE_TYPE (core);
2486   if (complain < 0)
2487     ok = true;
2488   else if (VOID_TYPE_P (core))
2489     ok = is_ptr;
2490   else if (TREE_CODE (core) == TEMPLATE_TYPE_PARM)
2491     ok = true;
2492   else if (processing_template_decl)
2493     ok = true;
2494   else if (!verify_type_context (input_location, TCTX_EXCEPTIONS, core,
2495                                          !(complain & tf_error)))
2496     return error_mark_node;
2497   else
2498     {
2499       ok = true;
2500       /* 15.4/1 says that types in an exception specifier must be complete,
2501            but it seems more reasonable to only require this on definitions
2502            and calls.  So just give a pedwarn at this point; we will give an
2503            error later if we hit one of those two cases.  */
2504       if (!COMPLETE_TYPE_P (complete_type (core)))
2505           diag_type = DK_PEDWARN; /* pedwarn */
2506     }
2507 
2508   if (ok)
2509     {
2510       tree probe;
2511 
2512       for (probe = list; probe; probe = TREE_CHAIN (probe))
2513           if (same_type_p (TREE_VALUE (probe), spec))
2514             break;
2515       if (!probe)
2516           list = tree_cons (NULL_TREE, spec, list);
2517     }
2518   else
2519     diag_type = DK_ERROR; /* error */
2520 
2521   if (diag_type != DK_UNSPECIFIED
2522       && (complain & tf_warning_or_error))
2523     cxx_incomplete_type_diagnostic (NULL_TREE, core, diag_type);
2524 
2525   return list;
2526 }
2527 
2528 /* Like nothrow_spec_p, but don't abort on deferred noexcept.  */
2529 
2530 static bool
nothrow_spec_p_uninst(const_tree spec)2531 nothrow_spec_p_uninst (const_tree spec)
2532 {
2533   if (DEFERRED_NOEXCEPT_SPEC_P (spec))
2534     return false;
2535   return nothrow_spec_p (spec);
2536 }
2537 
2538 /* Combine the two exceptions specifier lists LIST and ADD, and return
2539    their union.  */
2540 
2541 tree
merge_exception_specifiers(tree list,tree add)2542 merge_exception_specifiers (tree list, tree add)
2543 {
2544   tree noex, orig_list;
2545 
2546   if (list == error_mark_node || add == error_mark_node)
2547     return error_mark_node;
2548 
2549   /* No exception-specifier or noexcept(false) are less strict than
2550      anything else.  Prefer the newer variant (LIST).  */
2551   if (!list || list == noexcept_false_spec)
2552     return list;
2553   else if (!add || add == noexcept_false_spec)
2554     return add;
2555 
2556   /* noexcept(true) and throw() are stricter than anything else.
2557      As above, prefer the more recent one (LIST).  */
2558   if (nothrow_spec_p_uninst (add))
2559     return list;
2560 
2561   /* Two implicit noexcept specs (e.g. on a destructor) are equivalent.  */
2562   if (UNEVALUATED_NOEXCEPT_SPEC_P (add)
2563       && UNEVALUATED_NOEXCEPT_SPEC_P (list))
2564     return list;
2565   /* We should have instantiated other deferred noexcept specs by now.  */
2566   gcc_assert (!DEFERRED_NOEXCEPT_SPEC_P (add));
2567 
2568   if (nothrow_spec_p_uninst (list))
2569     return add;
2570   noex = TREE_PURPOSE (list);
2571   gcc_checking_assert (!TREE_PURPOSE (add)
2572                            || errorcount || !flag_exceptions
2573                            || cp_tree_equal (noex, TREE_PURPOSE (add)));
2574 
2575   /* Combine the dynamic-exception-specifiers, if any.  */
2576   orig_list = list;
2577   for (; add && TREE_VALUE (add); add = TREE_CHAIN (add))
2578     {
2579       tree spec = TREE_VALUE (add);
2580       tree probe;
2581 
2582       for (probe = orig_list; probe && TREE_VALUE (probe);
2583              probe = TREE_CHAIN (probe))
2584           if (same_type_p (TREE_VALUE (probe), spec))
2585             break;
2586       if (!probe)
2587           {
2588             spec = build_tree_list (NULL_TREE, spec);
2589             TREE_CHAIN (spec) = list;
2590             list = spec;
2591           }
2592     }
2593 
2594   /* Keep the noexcept-specifier at the beginning of the list.  */
2595   if (noex != TREE_PURPOSE (list))
2596     list = tree_cons (noex, TREE_VALUE (list), TREE_CHAIN (list));
2597 
2598   return list;
2599 }
2600 
2601 /* Subroutine of build_call.  Ensure that each of the types in the
2602    exception specification is complete.  Technically, 15.4/1 says that
2603    they need to be complete when we see a declaration of the function,
2604    but we should be able to get away with only requiring this when the
2605    function is defined or called.  See also add_exception_specifier.  */
2606 
2607 void
require_complete_eh_spec_types(tree fntype,tree decl)2608 require_complete_eh_spec_types (tree fntype, tree decl)
2609 {
2610   tree raises;
2611   /* Don't complain about calls to op new.  */
2612   if (decl && DECL_ARTIFICIAL (decl))
2613     return;
2614   for (raises = TYPE_RAISES_EXCEPTIONS (fntype); raises;
2615        raises = TREE_CHAIN (raises))
2616     {
2617       tree type = TREE_VALUE (raises);
2618       if (type && !COMPLETE_TYPE_P (type))
2619           {
2620             if (decl)
2621               error
2622                 ("call to function %qD which throws incomplete type %q#T",
2623                  decl, type);
2624             else
2625               error ("call to function which throws incomplete type %q#T",
2626                        decl);
2627           }
2628     }
2629 }
2630