Use HOST_SIZE_T_PRINT_* and HOST_WIDE_INT_T_PRINT_* some more
[official-gcc.git] / gcc / cp / pt.cc
blob475f2181cc4909efcc107f4e14c55eaa445d8885
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2024 Free Software Foundation, Inc.
3 Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4 Rewritten by Jason Merrill (jason@cygnus.com).
6 This file is part of GCC.
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.
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.
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/>. */
22 /* Known bugs or deficiencies include:
24 all methods must be provided in header files; can't use a source
25 file that contains only the method templates and "just win".
27 Fixed by: C++20 modules. */
29 #include "config.h"
30 #define INCLUDE_ALGORITHM // for std::equal
31 #include "system.h"
32 #include "coretypes.h"
33 #include "cp-tree.h"
34 #include "timevar.h"
35 #include "stringpool.h"
36 #include "varasm.h"
37 #include "attribs.h"
38 #include "stor-layout.h"
39 #include "intl.h"
40 #include "c-family/c-objc.h"
41 #include "cp-objcp-common.h"
42 #include "toplev.h"
43 #include "tree-iterator.h"
44 #include "type-utils.h"
45 #include "gimplify.h"
46 #include "gcc-rich-location.h"
47 #include "selftest.h"
48 #include "target.h"
49 #include "builtins.h"
50 #include "omp-general.h"
52 /* The type of functions taking a tree, and some additional data, and
53 returning an int. */
54 typedef int (*tree_fn_t) (tree, void*);
56 /* The PENDING_TEMPLATES is a list of templates whose instantiations
57 have been deferred, either because their definitions were not yet
58 available, or because we were putting off doing the work. */
59 struct GTY ((chain_next ("%h.next"))) pending_template
61 struct pending_template *next;
62 struct tinst_level *tinst;
65 static GTY(()) struct pending_template *pending_templates;
66 static GTY(()) struct pending_template *last_pending_template;
68 int processing_template_parmlist;
69 static int template_header_count;
71 static vec<int> inline_parm_levels;
73 static GTY(()) struct tinst_level *current_tinst_level;
75 static GTY(()) vec<tree, va_gc> *saved_access_scope;
77 /* Live only within one (recursive) call to tsubst_expr. We use
78 this to pass the statement expression node from the STMT_EXPR
79 to the EXPR_STMT that is its result. */
80 static tree cur_stmt_expr;
82 // -------------------------------------------------------------------------- //
83 // Local Specialization Stack
85 // Implementation of the RAII helper for creating new local
86 // specializations.
87 local_specialization_stack::local_specialization_stack (lss_policy policy)
88 : saved (local_specializations)
90 if (policy == lss_nop)
92 else if (policy == lss_blank || !saved)
93 local_specializations = new hash_map<tree, tree>;
94 else
95 local_specializations = new hash_map<tree, tree>(*saved);
98 local_specialization_stack::~local_specialization_stack ()
100 if (local_specializations != saved)
102 delete local_specializations;
103 local_specializations = saved;
107 /* True if we've recursed into fn_type_unification too many times. */
108 static bool excessive_deduction_depth;
110 struct spec_hasher : ggc_ptr_hash<spec_entry>
112 static hashval_t hash (tree, tree);
113 static hashval_t hash (spec_entry *);
114 static bool equal (spec_entry *, spec_entry *);
117 /* The general template is not in these tables. */
118 typedef hash_table<spec_hasher> spec_hash_table;
119 static GTY (()) spec_hash_table *decl_specializations;
120 static GTY (()) spec_hash_table *type_specializations;
122 /* Contains canonical template parameter types. The vector is indexed by
123 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
124 TREE_LIST, whose TREE_VALUEs contain the canonical template
125 parameters of various types and levels. */
126 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
128 #define UNIFY_ALLOW_NONE 0
129 #define UNIFY_ALLOW_MORE_CV_QUAL 1
130 #define UNIFY_ALLOW_LESS_CV_QUAL 2
131 #define UNIFY_ALLOW_DERIVED 4
132 #define UNIFY_ALLOW_INTEGER 8
133 #define UNIFY_ALLOW_OUTER_LEVEL 16
134 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
135 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
137 enum template_base_result {
138 tbr_incomplete_type,
139 tbr_ambiguous_baseclass,
140 tbr_success
143 static bool resolve_overloaded_unification (tree, tree, tree, tree,
144 unification_kind_t, int,
145 bool);
146 static int try_one_overload (tree, tree, tree, tree, tree,
147 unification_kind_t, int, bool, bool);
148 static int unify (tree, tree, tree, tree, int, bool);
149 static void add_pending_template (tree);
150 static tree reopen_tinst_level (struct tinst_level *);
151 static tree tsubst_initializer_list (tree, tree);
152 static tree get_partial_spec_bindings (tree, tree, tree);
153 static void tsubst_enum (tree, tree, tree);
154 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
155 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
156 struct conversion **, bool, bool);
157 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
158 tree*, tree*, tree);
159 static int type_unification_real (tree, tree, tree, const tree *,
160 unsigned int, int, unification_kind_t,
161 vec<deferred_access_check, va_gc> **,
162 bool);
163 static void note_template_header (int);
164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166 static tree convert_template_argument (tree, tree, tree,
167 tsubst_flags_t, int, tree);
168 static tree for_each_template_parm (tree, tree_fn_t, void*,
169 hash_set<tree> *, bool, tree_fn_t = NULL);
170 static tree expand_template_argument_pack (tree);
171 static tree build_template_parm_index (int, int, int, tree, tree);
172 static bool inline_needs_template_parms (tree, bool);
173 static void push_inline_template_parms_recursive (tree, int);
174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175 static int mark_template_parm (tree, void *);
176 static int template_parm_this_level_p (tree, void *);
177 static tree tsubst_friend_function (tree, tree);
178 static tree tsubst_friend_class (tree, tree);
179 static int can_complete_type_without_circularity (tree);
180 static tree get_bindings (tree, tree, tree, bool);
181 static int template_decl_level (tree);
182 static int check_cv_quals_for_unify (int, tree, tree);
183 static int unify_pack_expansion (tree, tree, tree,
184 tree, unification_kind_t, bool, bool);
185 static tree copy_template_args (tree);
186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
190 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
191 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
192 static bool check_specialization_scope (void);
193 static tree process_partial_specialization (tree);
194 static enum template_base_result get_template_base (tree, tree, tree, tree,
195 bool , tree *);
196 static tree try_class_unification (tree, tree, tree, tree, bool);
197 static bool class_nttp_const_wrapper_p (tree t);
198 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
199 tree, tree);
200 static bool template_template_parm_bindings_ok_p (tree, tree);
201 static void tsubst_default_arguments (tree, tsubst_flags_t);
202 static tree for_each_template_parm_r (tree *, int *, void *);
203 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
204 static void copy_default_args_to_explicit_spec (tree);
205 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
206 static bool dependent_template_arg_p (tree);
207 static bool dependent_type_p_r (tree);
208 static tree tsubst_stmt (tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_decl (tree, tree, tsubst_flags_t, bool = true);
210 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
211 static tree tsubst_name (tree, tree, tsubst_flags_t, tree);
212 static void perform_instantiation_time_access_checks (tree, tree);
213 static tree listify (tree);
214 static tree listify_autos (tree, tree);
215 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
216 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
217 static tree get_underlying_template (tree);
218 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
219 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
220 static tree make_argument_pack (tree);
221 static tree enclosing_instantiation_of (tree tctx);
222 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
223 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
224 static void mark_template_arguments_used (tree, tree);
225 static bool uses_outer_template_parms (tree);
226 static tree alias_ctad_tweaks (tree, tree);
227 static tree inherited_ctad_tweaks (tree, tree, tsubst_flags_t);
228 static tree deduction_guides_for (tree, bool&, tsubst_flags_t);
230 /* Make the current scope suitable for access checking when we are
231 processing T. T can be FUNCTION_DECL for instantiated function
232 template, VAR_DECL for static member variable, or TYPE_DECL for
233 for a class or alias template (needed by instantiate_decl). */
235 void
236 push_access_scope (tree t)
238 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
239 || TREE_CODE (t) == TYPE_DECL);
241 if (DECL_FRIEND_CONTEXT (t))
242 push_nested_class (DECL_FRIEND_CONTEXT (t));
243 else if (DECL_IMPLICIT_TYPEDEF_P (t)
244 && CLASS_TYPE_P (TREE_TYPE (t)))
245 push_nested_class (TREE_TYPE (t));
246 else if (DECL_CLASS_SCOPE_P (t))
247 push_nested_class (DECL_CONTEXT (t));
248 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
249 /* An artificial deduction guide should have the same access as
250 the constructor. */
251 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
252 else
253 push_to_top_level ();
255 if (TREE_CODE (t) == FUNCTION_DECL)
257 vec_safe_push (saved_access_scope, current_function_decl);
258 current_function_decl = t;
262 /* Restore the scope set up by push_access_scope. T is the node we
263 are processing. */
265 void
266 pop_access_scope (tree t)
268 if (TREE_CODE (t) == FUNCTION_DECL)
269 current_function_decl = saved_access_scope->pop();
271 if (DECL_FRIEND_CONTEXT (t)
272 || (DECL_IMPLICIT_TYPEDEF_P (t)
273 && CLASS_TYPE_P (TREE_TYPE (t)))
274 || DECL_CLASS_SCOPE_P (t)
275 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
276 pop_nested_class ();
277 else
278 pop_from_top_level ();
281 /* Do any processing required when DECL (a member template
282 declaration) is finished. Returns the TEMPLATE_DECL corresponding
283 to DECL, unless it is a specialization, in which case the DECL
284 itself is returned. */
286 tree
287 finish_member_template_decl (tree decl)
289 if (decl == error_mark_node)
290 return error_mark_node;
292 gcc_assert (DECL_P (decl));
294 if (TREE_CODE (decl) == TYPE_DECL)
296 tree type;
298 type = TREE_TYPE (decl);
299 if (type == error_mark_node)
300 return error_mark_node;
301 if (MAYBE_CLASS_TYPE_P (type)
302 && CLASSTYPE_TEMPLATE_INFO (type)
303 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
305 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
306 check_member_template (tmpl);
307 return tmpl;
309 return NULL_TREE;
311 else if (TREE_CODE (decl) == FIELD_DECL)
312 error_at (DECL_SOURCE_LOCATION (decl),
313 "data member %qD cannot be a member template", decl);
314 else if (DECL_TEMPLATE_INFO (decl))
316 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
318 check_member_template (DECL_TI_TEMPLATE (decl));
319 return DECL_TI_TEMPLATE (decl);
321 else
322 return NULL_TREE;
324 else
325 error_at (DECL_SOURCE_LOCATION (decl),
326 "invalid member template declaration %qD", decl);
328 return error_mark_node;
331 /* Create a template info node. */
333 tree
334 build_template_info (tree template_decl, tree template_args)
336 tree result = make_node (TEMPLATE_INFO);
337 TI_TEMPLATE (result) = template_decl;
338 TI_ARGS (result) = template_args;
339 return result;
342 /* DECL_TEMPLATE_INFO, if applicable, or NULL_TREE. */
344 static tree
345 decl_template_info (const_tree decl)
347 /* This needs to match template_info_decl_check. */
348 if (DECL_LANG_SPECIFIC (decl))
349 switch (TREE_CODE (decl))
351 case FUNCTION_DECL:
352 if (DECL_THUNK_P (decl))
353 break;
354 gcc_fallthrough ();
355 case VAR_DECL:
356 case FIELD_DECL:
357 case TYPE_DECL:
358 case CONCEPT_DECL:
359 case TEMPLATE_DECL:
360 return DECL_TEMPLATE_INFO (decl);
362 default:
363 break;
365 return NULL_TREE;
368 /* Return the template info node corresponding to T, whatever T is. */
370 tree
371 get_template_info (const_tree t)
373 tree tinfo = NULL_TREE;
375 if (!t || t == error_mark_node)
376 return NULL;
378 if (TREE_CODE (t) == NAMESPACE_DECL
379 || TREE_CODE (t) == PARM_DECL)
380 return NULL;
382 if (DECL_P (t))
383 tinfo = decl_template_info (t);
385 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
386 t = TREE_TYPE (t);
388 if (OVERLOAD_TYPE_P (t))
389 tinfo = TYPE_TEMPLATE_INFO (t);
390 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
391 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
393 return tinfo;
396 /* Returns the template nesting level of the indicated class TYPE.
398 For example, in:
399 template <class T>
400 struct A
402 template <class U>
403 struct B {};
406 A<T>::B<U> has depth two, while A<T> has depth one.
407 Both A<T>::B<int> and A<int>::B<U> have depth one, if
408 they are instantiations, not specializations.
410 This function is guaranteed to return 0 if passed NULL_TREE so
411 that, for example, `template_class_depth (current_class_type)' is
412 always safe. */
415 template_class_depth (tree type)
417 int depth;
419 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
421 tree tinfo = get_template_info (type);
423 if (tinfo
424 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
425 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
426 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
427 ++depth;
429 if (DECL_P (type))
431 if (tree fctx = DECL_FRIEND_CONTEXT (type))
432 type = fctx;
433 else
434 type = CP_DECL_CONTEXT (type);
436 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
437 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
438 else
439 type = CP_TYPE_CONTEXT (type);
442 return depth;
445 /* Return TRUE if NODE instantiates a template that has arguments of
446 its own, be it directly a primary template or indirectly through a
447 partial specializations. */
448 static bool
449 instantiates_primary_template_p (tree node)
451 tree tinfo = get_template_info (node);
452 if (!tinfo)
453 return false;
455 tree tmpl = TI_TEMPLATE (tinfo);
456 if (PRIMARY_TEMPLATE_P (tmpl))
457 return true;
459 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
460 return false;
462 /* So now we know we have a specialization, but it could be a full
463 or a partial specialization. To tell which, compare the depth of
464 its template arguments with those of its context. */
466 tree ctxt = DECL_CONTEXT (tmpl);
467 tree ctinfo = get_template_info (ctxt);
468 if (!ctinfo)
469 return true;
471 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
472 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
475 /* Subroutine of maybe_begin_member_template_processing.
476 Returns true if processing DECL needs us to push template parms. */
478 static bool
479 inline_needs_template_parms (tree decl, bool nsdmi)
481 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
482 return false;
484 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
485 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
488 /* Subroutine of maybe_begin_member_template_processing.
489 Push the template parms in PARMS, starting from LEVELS steps into the
490 chain, and ending at the beginning, since template parms are listed
491 innermost first. */
493 static void
494 push_inline_template_parms_recursive (tree parmlist, int levels)
496 tree parms = TREE_VALUE (parmlist);
497 int i;
499 if (levels > 1)
500 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
502 ++processing_template_decl;
503 current_template_parms
504 = tree_cons (size_int (current_template_depth + 1),
505 parms, current_template_parms);
506 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
507 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
508 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
510 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
511 NULL);
512 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
514 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
516 if (error_operand_p (parm))
517 continue;
519 gcc_assert (DECL_P (parm));
521 switch (TREE_CODE (parm))
523 case TYPE_DECL:
524 case TEMPLATE_DECL:
525 pushdecl (parm);
526 break;
528 case PARM_DECL:
529 /* Push the CONST_DECL. */
530 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
531 break;
533 default:
534 gcc_unreachable ();
539 /* Restore the template parameter context for a member template, a
540 friend template defined in a class definition, or a non-template
541 member of template class. */
543 void
544 maybe_begin_member_template_processing (tree decl)
546 tree parms;
547 int levels = 0;
548 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
550 if (nsdmi)
552 tree ctx = DECL_CONTEXT (decl);
553 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
554 /* Disregard full specializations (c++/60999). */
555 && uses_template_parms (ctx)
556 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
559 if (inline_needs_template_parms (decl, nsdmi))
561 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
562 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
564 if (DECL_TEMPLATE_SPECIALIZATION (decl))
566 --levels;
567 parms = TREE_CHAIN (parms);
570 push_inline_template_parms_recursive (parms, levels);
573 /* Remember how many levels of template parameters we pushed so that
574 we can pop them later. */
575 inline_parm_levels.safe_push (levels);
578 /* Undo the effects of maybe_begin_member_template_processing. */
580 void
581 maybe_end_member_template_processing (void)
583 int i;
584 int last;
586 if (inline_parm_levels.length () == 0)
587 return;
589 last = inline_parm_levels.pop ();
590 for (i = 0; i < last; ++i)
592 --processing_template_decl;
593 current_template_parms = TREE_CHAIN (current_template_parms);
594 poplevel (0, 0, 0);
598 /* Return a new template argument vector which contains all of ARGS,
599 but has as its innermost set of arguments the EXTRA_ARGS. */
601 tree
602 add_to_template_args (tree args, tree extra_args)
604 tree new_args;
605 int extra_depth;
606 int i;
607 int j;
609 if (args == NULL_TREE || extra_args == error_mark_node)
610 return extra_args;
612 extra_depth = TMPL_ARGS_DEPTH (extra_args);
613 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
615 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
616 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
618 for (j = 1; j <= extra_depth; ++j, ++i)
619 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
621 return new_args;
624 /* Like add_to_template_args, but only the outermost ARGS are added to
625 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
626 (EXTRA_ARGS) levels are added. This function is used to combine
627 the template arguments from a partial instantiation with the
628 template arguments used to attain the full instantiation from the
629 partial instantiation.
631 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
633 tree
634 add_outermost_template_args (tree args, tree extra_args)
636 tree new_args;
638 if (!args)
639 return extra_args;
640 if (TREE_CODE (args) == TEMPLATE_DECL)
642 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
643 args = TI_ARGS (ti);
646 /* If there are more levels of EXTRA_ARGS than there are ARGS,
647 something very fishy is going on. */
648 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
650 /* If *all* the new arguments will be the EXTRA_ARGS, just return
651 them. */
652 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
653 return extra_args;
655 /* For the moment, we make ARGS look like it contains fewer levels. */
656 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
658 new_args = add_to_template_args (args, extra_args);
660 /* Now, we restore ARGS to its full dimensions. */
661 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
663 return new_args;
666 /* Return the N levels of innermost template arguments from the ARGS. */
668 tree
669 get_innermost_template_args (tree args, int n)
671 tree new_args;
672 int extra_levels;
673 int i;
675 gcc_assert (n >= 0);
677 /* If N is 1, just return the innermost set of template arguments. */
678 if (n == 1)
679 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
681 /* If we're not removing anything, just return the arguments we were
682 given. */
683 extra_levels = TMPL_ARGS_DEPTH (args) - n;
684 gcc_assert (extra_levels >= 0);
685 if (extra_levels == 0)
686 return args;
688 /* Make a new set of arguments, not containing the outer arguments. */
689 new_args = make_tree_vec (n);
690 for (i = 1; i <= n; ++i)
691 SET_TMPL_ARGS_LEVEL (new_args, i,
692 TMPL_ARGS_LEVEL (args, i + extra_levels));
694 return new_args;
697 /* The inverse of get_innermost_template_args: Return all but the innermost
698 EXTRA_LEVELS levels of template arguments from the ARGS. */
700 static tree
701 strip_innermost_template_args (tree args, int extra_levels)
703 tree new_args;
704 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
705 int i;
707 gcc_assert (n >= 0);
709 /* If N is 1, just return the outermost set of template arguments. */
710 if (n == 1)
711 return TMPL_ARGS_LEVEL (args, 1);
713 /* If we're not removing anything, just return the arguments we were
714 given. */
715 gcc_assert (extra_levels >= 0);
716 if (extra_levels == 0)
717 return args;
719 /* Make a new set of arguments, not containing the inner arguments. */
720 new_args = make_tree_vec (n);
721 for (i = 1; i <= n; ++i)
722 SET_TMPL_ARGS_LEVEL (new_args, i,
723 TMPL_ARGS_LEVEL (args, i));
725 return new_args;
728 /* We've got a template header coming up; push to a new level for storing
729 the parms. */
731 void
732 begin_template_parm_list (void)
734 /* We use a non-tag-transparent scope here, which causes pushtag to
735 put tags in this scope, rather than in the enclosing class or
736 namespace scope. This is the right thing, since we want
737 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
738 global template class, push_template_decl handles putting the
739 TEMPLATE_DECL into top-level scope. For a nested template class,
740 e.g.:
742 template <class T> struct S1 {
743 template <class T> struct S2 {};
746 pushtag contains special code to insert the TEMPLATE_DECL for S2
747 at the right scope. */
748 begin_scope (sk_template_parms, NULL);
749 ++processing_template_decl;
750 ++processing_template_parmlist;
751 note_template_header (0);
753 /* Add a dummy parameter level while we process the parameter list. */
754 current_template_parms
755 = tree_cons (size_int (current_template_depth + 1),
756 make_tree_vec (0),
757 current_template_parms);
760 /* This routine is called when a specialization is declared. If it is
761 invalid to declare a specialization here, an error is reported and
762 false is returned, otherwise this routine will return true. */
764 static bool
765 check_specialization_scope (void)
767 tree scope = current_scope ();
769 /* [temp.expl.spec]
771 An explicit specialization shall be declared in the namespace of
772 which the template is a member, or, for member templates, in the
773 namespace of which the enclosing class or enclosing class
774 template is a member. An explicit specialization of a member
775 function, member class or static data member of a class template
776 shall be declared in the namespace of which the class template
777 is a member. */
778 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
780 error ("explicit specialization in non-namespace scope %qD", scope);
781 return false;
784 /* [temp.expl.spec]
786 In an explicit specialization declaration for a member of a class
787 template or a member template that appears in namespace scope,
788 the member template and some of its enclosing class templates may
789 remain unspecialized, except that the declaration shall not
790 explicitly specialize a class member template if its enclosing
791 class templates are not explicitly specialized as well. */
792 if (current_template_parms)
794 error ("enclosing class templates are not explicitly specialized");
795 return false;
798 return true;
801 /* We've just seen template <>. */
803 bool
804 begin_specialization (void)
806 begin_scope (sk_template_spec, NULL);
807 note_template_header (1);
808 return check_specialization_scope ();
811 /* Called at then end of processing a declaration preceded by
812 template<>. */
814 void
815 end_specialization (void)
817 finish_scope ();
818 reset_specialization ();
821 /* Any template <>'s that we have seen thus far are not referring to a
822 function specialization. */
824 void
825 reset_specialization (void)
827 processing_specialization = 0;
828 template_header_count = 0;
831 /* We've just seen a template header. If SPECIALIZATION is nonzero,
832 it was of the form template <>. */
834 static void
835 note_template_header (int specialization)
837 processing_specialization = specialization;
838 template_header_count++;
841 /* We're beginning an explicit instantiation. */
843 void
844 begin_explicit_instantiation (void)
846 gcc_assert (!processing_explicit_instantiation);
847 processing_explicit_instantiation = true;
851 void
852 end_explicit_instantiation (void)
854 gcc_assert (processing_explicit_instantiation);
855 processing_explicit_instantiation = false;
858 /* An explicit specialization or partial specialization of TMPL is being
859 declared. Check that the namespace in which the specialization is
860 occurring is permissible. Returns false iff it is invalid to
861 specialize TMPL in the current namespace. */
863 static bool
864 check_specialization_namespace (tree tmpl)
866 tree tpl_ns = decl_namespace_context (tmpl);
868 /* [tmpl.expl.spec]
870 An explicit specialization shall be declared in a namespace enclosing the
871 specialized template. An explicit specialization whose declarator-id is
872 not qualified shall be declared in the nearest enclosing namespace of the
873 template, or, if the namespace is inline (7.3.1), any namespace from its
874 enclosing namespace set. */
875 if (current_scope() != DECL_CONTEXT (tmpl)
876 && !at_namespace_scope_p ())
878 error ("specialization of %qD must appear at namespace scope", tmpl);
879 return false;
882 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
883 /* Same or enclosing namespace. */
884 return true;
885 else
887 auto_diagnostic_group d;
888 if (permerror (input_location,
889 "specialization of %qD in different namespace", tmpl))
890 inform (DECL_SOURCE_LOCATION (tmpl),
891 " from definition of %q#D", tmpl);
892 return false;
896 /* SPEC is an explicit instantiation. Check that it is valid to
897 perform this explicit instantiation in the current namespace. */
899 static void
900 check_explicit_instantiation_namespace (tree spec)
902 tree ns;
904 /* DR 275: An explicit instantiation shall appear in an enclosing
905 namespace of its template. */
906 ns = decl_namespace_context (spec);
907 if (!is_nested_namespace (current_namespace, ns))
908 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
909 "(which does not enclose namespace %qD)",
910 spec, current_namespace, ns);
913 /* Returns true if TYPE is a new partial specialization that needs to be
914 set up. This may also modify TYPE to point to the correct (new or
915 existing) constrained partial specialization. */
917 static bool
918 maybe_new_partial_specialization (tree& type)
920 /* An implicit instantiation of an incomplete type implies
921 the definition of a new class template.
923 template<typename T>
924 struct S;
926 template<typename T>
927 struct S<T*>;
929 Here, S<T*> is an implicit instantiation of S whose type
930 is incomplete. */
931 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
932 return true;
934 /* It can also be the case that TYPE is a completed specialization.
935 Continuing the previous example, suppose we also declare:
937 template<typename T>
938 requires Integral<T>
939 struct S<T*>;
941 Here, S<T*> refers to the specialization S<T*> defined
942 above. However, we need to differentiate definitions because
943 we intend to define a new partial specialization. In this case,
944 we rely on the fact that the constraints are different for
945 this declaration than that above.
947 Note that we also get here for injected class names and
948 late-parsed template definitions. We must ensure that we
949 do not create new type declarations for those cases. */
950 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
952 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
953 tree args = CLASSTYPE_TI_ARGS (type);
955 /* If there are no template parameters, this cannot be a new
956 partial template specialization? */
957 if (!current_template_parms)
958 return false;
960 /* The injected-class-name is not a new partial specialization. */
961 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
962 return false;
964 /* If the constraints are not the same as those of the primary
965 then, we can probably create a new specialization. */
966 tree type_constr = current_template_constraints ();
968 if (type == TREE_TYPE (tmpl))
970 tree main_constr = get_constraints (tmpl);
971 if (equivalent_constraints (type_constr, main_constr))
972 return false;
975 /* Also, if there's a pre-existing specialization with matching
976 constraints, then this also isn't new. */
977 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
978 while (specs)
980 tree spec_tmpl = TREE_VALUE (specs);
981 tree spec_args = TREE_PURPOSE (specs);
982 tree spec_constr = get_constraints (spec_tmpl);
983 if (comp_template_args (args, spec_args)
984 && equivalent_constraints (type_constr, spec_constr))
986 type = TREE_TYPE (spec_tmpl);
987 return false;
989 specs = TREE_CHAIN (specs);
992 /* Create a new type node (and corresponding type decl)
993 for the newly declared specialization. */
994 tree t = make_class_type (TREE_CODE (type));
995 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
996 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
998 /* We only need a separate type node for storing the definition of this
999 partial specialization; uses of S<T*> are unconstrained, so all are
1000 equivalent. So keep TYPE_CANONICAL the same. */
1001 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
1003 /* Build the corresponding type decl. */
1004 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
1005 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
1006 DECL_SOURCE_LOCATION (d) = input_location;
1007 TREE_PUBLIC (d) = TREE_PUBLIC (DECL_TEMPLATE_RESULT (tmpl));
1009 set_instantiating_module (d);
1010 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
1012 type = t;
1013 return true;
1016 return false;
1019 /* The TYPE is being declared. If it is a template type, that means it
1020 is a partial specialization. Do appropriate error-checking. */
1022 tree
1023 maybe_process_partial_specialization (tree type)
1025 tree context;
1027 if (type == error_mark_node)
1028 return error_mark_node;
1030 /* A lambda that appears in specialization context is not itself a
1031 specialization. */
1032 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1033 return type;
1035 /* An injected-class-name is not a specialization. */
1036 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1037 return type;
1039 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1041 error ("name of class shadows template template parameter %qD",
1042 TYPE_NAME (type));
1043 return error_mark_node;
1046 context = TYPE_CONTEXT (type);
1048 if (TYPE_ALIAS_P (type))
1050 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1052 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1053 error ("specialization of alias template %qD",
1054 TI_TEMPLATE (tinfo));
1055 else
1056 error ("explicit specialization of non-template %qT", type);
1057 return error_mark_node;
1059 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1061 /* This is for ordinary explicit specialization and partial
1062 specialization of a template class such as:
1064 template <> class C<int>;
1068 template <class T> class C<T*>;
1070 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1072 if (maybe_new_partial_specialization (type))
1074 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1075 && !at_namespace_scope_p ())
1076 return error_mark_node;
1077 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1078 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1079 if (processing_template_decl)
1081 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1082 if (decl == error_mark_node)
1083 return error_mark_node;
1084 return TREE_TYPE (decl);
1087 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1088 error ("specialization of %qT after instantiation", type);
1089 else if (errorcount && !processing_specialization
1090 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1091 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1092 /* Trying to define a specialization either without a template<> header
1093 or in an inappropriate place. We've already given an error, so just
1094 bail now so we don't actually define the specialization. */
1095 return error_mark_node;
1097 else if (CLASS_TYPE_P (type)
1098 && !CLASSTYPE_USE_TEMPLATE (type)
1099 && CLASSTYPE_TEMPLATE_INFO (type)
1100 && context && CLASS_TYPE_P (context)
1101 && CLASSTYPE_TEMPLATE_INFO (context))
1103 /* This is for an explicit specialization of member class
1104 template according to [temp.expl.spec/18]:
1106 template <> template <class U> class C<int>::D;
1108 The context `C<int>' must be an implicit instantiation.
1109 Otherwise this is just a member class template declared
1110 earlier like:
1112 template <> class C<int> { template <class U> class D; };
1113 template <> template <class U> class C<int>::D;
1115 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1116 while in the second case, `C<int>::D' is a primary template
1117 and `C<T>::D' may not exist. */
1119 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1120 && !COMPLETE_TYPE_P (type))
1122 tree t;
1123 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1125 if (current_namespace
1126 != decl_namespace_context (tmpl))
1128 if (permerror (input_location,
1129 "specialization of %qD in different namespace",
1130 type))
1131 inform (DECL_SOURCE_LOCATION (tmpl),
1132 "from definition of %q#D", tmpl);
1135 /* Check for invalid specialization after instantiation:
1137 template <> template <> class C<int>::D<int>;
1138 template <> template <class U> class C<int>::D; */
1140 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1141 t; t = TREE_CHAIN (t))
1143 tree inst = TREE_VALUE (t);
1144 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1145 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1147 /* We already have a full specialization of this partial
1148 instantiation, or a full specialization has been
1149 looked up but not instantiated. Reassign it to the
1150 new member specialization template. */
1151 spec_entry elt;
1152 spec_entry *entry;
1154 elt.tmpl = most_general_template (tmpl);
1155 elt.args = CLASSTYPE_TI_ARGS (inst);
1156 elt.spec = inst;
1158 type_specializations->remove_elt (&elt);
1160 elt.tmpl = tmpl;
1161 CLASSTYPE_TI_ARGS (inst)
1162 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1164 spec_entry **slot
1165 = type_specializations->find_slot (&elt, INSERT);
1166 entry = ggc_alloc<spec_entry> ();
1167 *entry = elt;
1168 *slot = entry;
1170 else
1171 /* But if we've had an implicit instantiation, that's a
1172 problem ([temp.expl.spec]/6). */
1173 error ("specialization %qT after instantiation %qT",
1174 type, inst);
1177 /* Mark TYPE as a specialization. And as a result, we only
1178 have one level of template argument for the innermost
1179 class template. */
1180 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1181 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1182 CLASSTYPE_TI_ARGS (type)
1183 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1186 else if (processing_specialization)
1188 /* Someday C++0x may allow for enum template specialization. */
1189 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1190 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1191 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1192 "of %qD not allowed by ISO C++", type);
1193 else
1195 error ("explicit specialization of non-template %qT", type);
1196 return error_mark_node;
1200 return type;
1203 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1204 gone through coerce_template_parms by now. */
1206 static void
1207 verify_unstripped_args_1 (tree inner)
1209 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1211 tree arg = TREE_VEC_ELT (inner, i);
1212 if (TREE_CODE (arg) == TEMPLATE_DECL)
1213 /* OK */;
1214 else if (TYPE_P (arg))
1215 gcc_assert (strip_typedefs (arg, NULL) == arg);
1216 else if (ARGUMENT_PACK_P (arg))
1217 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1218 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1219 /* Allow typedefs on the type of a non-type argument, since a
1220 parameter can have them. */;
1221 else
1222 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1226 static void
1227 verify_unstripped_args (tree args)
1229 ++processing_template_decl;
1230 if (!any_dependent_template_arguments_p (args))
1231 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1232 --processing_template_decl;
1235 /* Retrieve the specialization (in the sense of [temp.spec] - a
1236 specialization is either an instantiation or an explicit
1237 specialization) of TMPL for the given template ARGS. If there is
1238 no such specialization, return NULL_TREE. The ARGS are a vector of
1239 arguments, or a vector of vectors of arguments, in the case of
1240 templates with more than one level of parameters.
1242 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1243 then we search for a partial specialization matching ARGS. This
1244 parameter is ignored if TMPL is not a class template.
1246 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1247 result is a NONTYPE_ARGUMENT_PACK. */
1249 static tree
1250 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1252 if (tmpl == NULL_TREE)
1253 return NULL_TREE;
1255 if (args == error_mark_node)
1256 return NULL_TREE;
1258 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1259 || TREE_CODE (tmpl) == FIELD_DECL);
1261 /* There should be as many levels of arguments as there are
1262 levels of parameters. */
1263 gcc_assert (TMPL_ARGS_DEPTH (args)
1264 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1265 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1266 : template_class_depth (DECL_CONTEXT (tmpl))));
1268 if (flag_checking)
1269 verify_unstripped_args (args);
1271 /* Lambda functions in templates aren't instantiated normally, but through
1272 tsubst_lambda_expr. */
1273 if (lambda_fn_in_template_p (tmpl))
1274 return NULL_TREE;
1276 spec_entry elt;
1277 elt.tmpl = tmpl;
1278 elt.args = args;
1279 elt.spec = NULL_TREE;
1281 spec_hash_table *specializations;
1282 if (DECL_CLASS_TEMPLATE_P (tmpl))
1283 specializations = type_specializations;
1284 else
1285 specializations = decl_specializations;
1287 if (hash == 0)
1288 hash = spec_hasher::hash (&elt);
1289 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1290 return found->spec;
1292 return NULL_TREE;
1295 /* Like retrieve_specialization, but for local declarations. */
1297 tree
1298 retrieve_local_specialization (tree tmpl)
1300 if (local_specializations == NULL)
1301 return NULL_TREE;
1303 tree *slot = local_specializations->get (tmpl);
1304 return slot ? *slot : NULL_TREE;
1307 /* Returns nonzero iff DECL is a specialization of TMPL. */
1310 is_specialization_of (tree decl, tree tmpl)
1312 tree t;
1314 if (TREE_CODE (decl) == FUNCTION_DECL)
1316 for (t = decl;
1317 t != NULL_TREE;
1318 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1319 if (t == tmpl)
1320 return 1;
1322 else
1324 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1326 for (t = TREE_TYPE (decl);
1327 t != NULL_TREE;
1328 t = CLASSTYPE_USE_TEMPLATE (t)
1329 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1330 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1331 return 1;
1334 return 0;
1337 /* Returns nonzero iff DECL is a specialization of friend declaration
1338 FRIEND_DECL according to [temp.friend]. */
1340 bool
1341 is_specialization_of_friend (tree decl, tree friend_decl)
1343 bool need_template = true;
1344 int template_depth;
1346 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1347 || TREE_CODE (decl) == TYPE_DECL);
1349 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1350 of a template class, we want to check if DECL is a specialization
1351 if this. */
1352 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1353 && DECL_CLASS_SCOPE_P (friend_decl)
1354 && DECL_TEMPLATE_INFO (friend_decl)
1355 && !DECL_USE_TEMPLATE (friend_decl))
1357 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1358 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1359 need_template = false;
1361 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1362 && !PRIMARY_TEMPLATE_P (friend_decl))
1363 need_template = false;
1365 /* There is nothing to do if this is not a template friend. */
1366 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1367 return false;
1369 if (is_specialization_of (decl, friend_decl))
1370 return true;
1372 /* [temp.friend/6]
1373 A member of a class template may be declared to be a friend of a
1374 non-template class. In this case, the corresponding member of
1375 every specialization of the class template is a friend of the
1376 class granting friendship.
1378 For example, given a template friend declaration
1380 template <class T> friend void A<T>::f();
1382 the member function below is considered a friend
1384 template <> struct A<int> {
1385 void f();
1388 For this type of template friend, TEMPLATE_DEPTH below will be
1389 nonzero. To determine if DECL is a friend of FRIEND, we first
1390 check if the enclosing class is a specialization of another. */
1392 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1393 if (template_depth
1394 && DECL_CLASS_SCOPE_P (decl)
1395 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1396 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1398 /* Next, we check the members themselves. In order to handle
1399 a few tricky cases, such as when FRIEND_DECL's are
1401 template <class T> friend void A<T>::g(T t);
1402 template <class T> template <T t> friend void A<T>::h();
1404 and DECL's are
1406 void A<int>::g(int);
1407 template <int> void A<int>::h();
1409 we need to figure out ARGS, the template arguments from
1410 the context of DECL. This is required for template substitution
1411 of `T' in the function parameter of `g' and template parameter
1412 of `h' in the above examples. Here ARGS corresponds to `int'. */
1414 tree context = DECL_CONTEXT (decl);
1415 tree args = NULL_TREE;
1416 int current_depth = 0;
1418 while (current_depth < template_depth)
1420 if (CLASSTYPE_TEMPLATE_INFO (context))
1422 if (current_depth == 0)
1423 args = TYPE_TI_ARGS (context);
1424 else
1425 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1426 current_depth++;
1428 context = TYPE_CONTEXT (context);
1431 if (TREE_CODE (decl) == FUNCTION_DECL)
1433 bool is_template;
1434 tree friend_type;
1435 tree decl_type;
1436 tree friend_args_type;
1437 tree decl_args_type;
1439 /* Make sure that both DECL and FRIEND_DECL are templates or
1440 non-templates. */
1441 is_template = DECL_TEMPLATE_INFO (decl)
1442 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1443 if (need_template ^ is_template)
1444 return false;
1445 else if (is_template)
1447 /* If both are templates, check template parameter list. */
1448 tree friend_parms
1449 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1450 args, tf_none);
1451 if (!comp_template_parms
1452 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1453 friend_parms))
1454 return false;
1456 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1458 else
1459 decl_type = TREE_TYPE (decl);
1461 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1462 tf_none, NULL_TREE);
1463 if (friend_type == error_mark_node)
1464 return false;
1466 /* Check if return types match. */
1467 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1468 return false;
1470 /* Check if function parameter types match, ignoring the
1471 `this' parameter. */
1472 friend_args_type = TYPE_ARG_TYPES (friend_type);
1473 decl_args_type = TYPE_ARG_TYPES (decl_type);
1474 if (DECL_IOBJ_MEMBER_FUNCTION_P (friend_decl))
1475 friend_args_type = TREE_CHAIN (friend_args_type);
1476 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
1477 decl_args_type = TREE_CHAIN (decl_args_type);
1479 return compparms (decl_args_type, friend_args_type);
1481 else
1483 /* DECL is a TYPE_DECL */
1484 bool is_template;
1485 tree decl_type = TREE_TYPE (decl);
1487 /* Make sure that both DECL and FRIEND_DECL are templates or
1488 non-templates. */
1489 is_template
1490 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1491 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1493 if (need_template ^ is_template)
1494 return false;
1495 else if (is_template)
1497 tree friend_parms;
1498 /* If both are templates, check the name of the two
1499 TEMPLATE_DECL's first because is_friend didn't. */
1500 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1501 != DECL_NAME (friend_decl))
1502 return false;
1504 /* Now check template parameter list. */
1505 friend_parms
1506 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1507 args, tf_none);
1508 return comp_template_parms
1509 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1510 friend_parms);
1512 else
1513 return (DECL_NAME (decl)
1514 == DECL_NAME (friend_decl));
1517 return false;
1520 /* Register the specialization SPEC as a specialization of TMPL with
1521 the indicated ARGS. IS_FRIEND indicates whether the specialization
1522 is actually just a friend declaration. ATTRLIST is the list of
1523 attributes that the specialization is declared with or NULL when
1524 it isn't. Returns SPEC, or an equivalent prior declaration, if
1525 available.
1527 We also store instantiations of field packs in the hash table, even
1528 though they are not themselves templates, to make lookup easier. */
1530 static tree
1531 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1532 hashval_t hash)
1534 tree fn;
1536 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1537 || (TREE_CODE (tmpl) == FIELD_DECL
1538 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1540 spec_entry elt;
1541 elt.tmpl = tmpl;
1542 elt.args = args;
1543 elt.spec = spec;
1545 if (hash == 0)
1546 hash = spec_hasher::hash (&elt);
1548 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1549 if (*slot)
1550 fn = (*slot)->spec;
1551 else
1552 fn = NULL_TREE;
1554 /* We can sometimes try to re-register a specialization that we've
1555 already got. In particular, regenerate_decl_from_template calls
1556 duplicate_decls which will update the specialization list. But,
1557 we'll still get called again here anyhow. It's more convenient
1558 to simply allow this than to try to prevent it. */
1559 if (fn == spec)
1560 return spec;
1561 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1563 if (DECL_TEMPLATE_INSTANTIATION (fn))
1565 if (DECL_ODR_USED (fn)
1566 || DECL_EXPLICIT_INSTANTIATION (fn))
1568 error ("specialization of %qD after instantiation",
1569 fn);
1570 return error_mark_node;
1572 else
1574 tree clone;
1575 /* This situation should occur only if the first
1576 specialization is an implicit instantiation, the
1577 second is an explicit specialization, and the
1578 implicit instantiation has not yet been used. That
1579 situation can occur if we have implicitly
1580 instantiated a member function and then specialized
1581 it later.
1583 We can also wind up here if a friend declaration that
1584 looked like an instantiation turns out to be a
1585 specialization:
1587 template <class T> void foo(T);
1588 class S { friend void foo<>(int) };
1589 template <> void foo(int);
1591 We transform the existing DECL in place so that any
1592 pointers to it become pointers to the updated
1593 declaration.
1595 If there was a definition for the template, but not
1596 for the specialization, we want this to look as if
1597 there were no definition, and vice versa. */
1598 DECL_INITIAL (fn) = NULL_TREE;
1599 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1601 /* The call to duplicate_decls will have applied
1602 [temp.expl.spec]:
1604 An explicit specialization of a function template
1605 is inline only if it is explicitly declared to be,
1606 and independently of whether its function template
1609 to the primary function; now copy the inline bits to
1610 the various clones. */
1611 FOR_EACH_CLONE (clone, fn)
1613 DECL_DECLARED_INLINE_P (clone)
1614 = DECL_DECLARED_INLINE_P (fn);
1615 DECL_SOURCE_LOCATION (clone)
1616 = DECL_SOURCE_LOCATION (fn);
1617 DECL_DELETED_FN (clone)
1618 = DECL_DELETED_FN (fn);
1620 check_specialization_namespace (tmpl);
1622 return fn;
1625 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1627 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1628 if (dd == error_mark_node)
1629 /* We've already complained in duplicate_decls. */
1630 return error_mark_node;
1632 if (dd == NULL_TREE && DECL_INITIAL (spec))
1633 /* Dup decl failed, but this is a new definition. Set the
1634 line number so any errors match this new
1635 definition. */
1636 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1638 return fn;
1641 else if (fn)
1642 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1644 /* A specialization must be declared in the same namespace as the
1645 template it is specializing. */
1646 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1647 && !check_specialization_namespace (tmpl))
1648 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1650 spec_entry *entry = ggc_alloc<spec_entry> ();
1651 gcc_assert (tmpl && args && spec);
1652 *entry = elt;
1653 *slot = entry;
1654 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1655 && PRIMARY_TEMPLATE_P (tmpl)
1656 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1657 || variable_template_p (tmpl))
1658 /* If TMPL is a forward declaration of a template function, keep a list
1659 of all specializations in case we need to reassign them to a friend
1660 template later in tsubst_friend_function.
1662 Also keep a list of all variable template instantiations so that
1663 process_partial_specialization can check whether a later partial
1664 specialization would have used it. */
1665 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1666 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1668 return spec;
1671 /* Restricts tree and type comparisons. */
1672 int comparing_specializations;
1673 int comparing_dependent_aliases;
1675 /* Whether we are comparing template arguments during partial ordering
1676 (and therefore want the comparison to look through dependent alias
1677 template specializations). */
1679 static int comparing_for_partial_ordering;
1681 /* Returns true iff two spec_entry nodes are equivalent. */
1683 bool
1684 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1686 int equal;
1688 ++comparing_specializations;
1689 ++comparing_dependent_aliases;
1690 ++processing_template_decl;
1691 equal = (e1->tmpl == e2->tmpl
1692 && comp_template_args (e1->args, e2->args));
1693 if (equal && flag_concepts
1694 /* tmpl could be a FIELD_DECL for a capture pack. */
1695 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1696 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1697 && uses_template_parms (e1->args))
1699 /* Partial specializations of a variable template can be distinguished by
1700 constraints. */
1701 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1702 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1703 equal = equivalent_constraints (c1, c2);
1705 --processing_template_decl;
1706 --comparing_dependent_aliases;
1707 --comparing_specializations;
1709 return equal;
1712 /* Returns a hash for a template TMPL and template arguments ARGS. */
1714 static hashval_t
1715 hash_tmpl_and_args (tree tmpl, tree args)
1717 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1718 return iterative_hash_template_arg (args, val);
1721 hashval_t
1722 spec_hasher::hash (tree tmpl, tree args)
1724 ++comparing_specializations;
1725 hashval_t val = hash_tmpl_and_args (tmpl, args);
1726 --comparing_specializations;
1727 return val;
1730 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1731 ignoring SPEC. */
1733 hashval_t
1734 spec_hasher::hash (spec_entry *e)
1736 return spec_hasher::hash (e->tmpl, e->args);
1739 /* Recursively calculate a hash value for a template argument ARG, for use
1740 in the hash tables of template specializations. We must be
1741 careful to (at least) skip the same entities template_args_equal
1742 does. */
1744 hashval_t
1745 iterative_hash_template_arg (tree arg, hashval_t val)
1747 if (arg == NULL_TREE)
1748 return iterative_hash_object (arg, val);
1750 if (!TYPE_P (arg))
1751 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1752 while (CONVERT_EXPR_P (arg)
1753 || TREE_CODE (arg) == NON_LVALUE_EXPR
1754 || class_nttp_const_wrapper_p (arg))
1755 arg = TREE_OPERAND (arg, 0);
1757 enum tree_code code = TREE_CODE (arg);
1759 val = iterative_hash_object (code, val);
1761 switch (code)
1763 case ARGUMENT_PACK_SELECT:
1764 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1765 preserving it in a hash table, which is bad because it will change
1766 meaning when gen_elem_of_pack_expansion_instantiation changes the
1767 ARGUMENT_PACK_SELECT_INDEX. */
1768 gcc_unreachable ();
1770 case ERROR_MARK:
1771 return val;
1773 case IDENTIFIER_NODE:
1774 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1776 case TREE_VEC:
1777 for (tree elt : tree_vec_range (arg))
1778 val = iterative_hash_template_arg (elt, val);
1779 return val;
1781 case TYPE_PACK_EXPANSION:
1782 case EXPR_PACK_EXPANSION:
1783 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1784 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1786 case TYPE_ARGUMENT_PACK:
1787 case NONTYPE_ARGUMENT_PACK:
1788 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1790 case TREE_LIST:
1791 for (; arg; arg = TREE_CHAIN (arg))
1792 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1793 return val;
1795 case OVERLOAD:
1796 for (lkp_iterator iter (arg); iter; ++iter)
1797 val = iterative_hash_template_arg (*iter, val);
1798 return val;
1800 case CONSTRUCTOR:
1802 iterative_hash_template_arg (TREE_TYPE (arg), val);
1803 for (auto &e: CONSTRUCTOR_ELTS (arg))
1805 val = iterative_hash_template_arg (e.index, val);
1806 val = iterative_hash_template_arg (e.value, val);
1808 return val;
1811 case PARM_DECL:
1812 if (!DECL_ARTIFICIAL (arg))
1814 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1815 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1817 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1819 case TEMPLATE_DECL:
1820 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
1821 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1822 break;
1824 case TARGET_EXPR:
1825 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1827 case PTRMEM_CST:
1828 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1829 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1831 case TEMPLATE_PARM_INDEX:
1832 val = iterative_hash_template_arg
1833 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1834 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1835 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1837 case TRAIT_EXPR:
1838 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1839 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1840 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1842 case BASELINK:
1843 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1844 val);
1845 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1846 val);
1848 case MODOP_EXPR:
1849 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1850 code = TREE_CODE (TREE_OPERAND (arg, 1));
1851 val = iterative_hash_object (code, val);
1852 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1854 case LAMBDA_EXPR:
1855 /* [temp.over.link] Two lambda-expressions are never considered
1856 equivalent.
1858 So just hash the closure type. */
1859 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1861 case CAST_EXPR:
1862 case IMPLICIT_CONV_EXPR:
1863 case STATIC_CAST_EXPR:
1864 case REINTERPRET_CAST_EXPR:
1865 case CONST_CAST_EXPR:
1866 case DYNAMIC_CAST_EXPR:
1867 case NEW_EXPR:
1868 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1869 /* Now hash operands as usual. */
1870 break;
1872 case CALL_EXPR:
1874 tree fn = CALL_EXPR_FN (arg);
1875 if (tree name = call_expr_dependent_name (arg))
1877 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1878 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1879 fn = name;
1881 val = iterative_hash_template_arg (fn, val);
1882 call_expr_arg_iterator ai;
1883 for (tree x = first_call_expr_arg (arg, &ai); x;
1884 x = next_call_expr_arg (&ai))
1885 val = iterative_hash_template_arg (x, val);
1886 return val;
1889 default:
1890 break;
1893 char tclass = TREE_CODE_CLASS (code);
1894 switch (tclass)
1896 case tcc_type:
1897 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1899 // We want an alias specialization that survived strip_typedefs
1900 // to hash differently from its TYPE_CANONICAL, to avoid hash
1901 // collisions that compare as different in template_args_equal.
1902 // These could be dependent specializations that strip_typedefs
1903 // left alone, or untouched specializations because
1904 // coerce_template_parms returns the unconverted template
1905 // arguments if it sees incomplete argument packs.
1906 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1907 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1910 switch (code)
1912 case DECLTYPE_TYPE:
1913 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1914 break;
1916 case TYPENAME_TYPE:
1917 if (comparing_specializations)
1919 /* Hash the components that are relevant to TYPENAME_TYPE
1920 equivalence as determined by structural_comptypes. We
1921 can only coherently do this when comparing_specializations
1922 is set, because otherwise structural_comptypes tries
1923 resolving TYPENAME_TYPE via the current instantiation. */
1924 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1925 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1926 val = iterative_hash_template_arg (context, val);
1927 val = iterative_hash_template_arg (fullname, val);
1929 break;
1931 default:
1932 if (tree canonical = TYPE_CANONICAL (arg))
1933 val = iterative_hash_object (TYPE_HASH (canonical), val);
1934 else if (tree ti = TYPE_TEMPLATE_INFO (arg))
1936 val = iterative_hash_template_arg (TI_TEMPLATE (ti), val);
1937 val = iterative_hash_template_arg (TI_ARGS (ti), val);
1939 break;
1942 return val;
1944 case tcc_declaration:
1945 case tcc_constant:
1946 return iterative_hash_expr (arg, val);
1948 default:
1949 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1950 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1951 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1952 return val;
1956 /* Unregister the specialization SPEC as a specialization of TMPL.
1957 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1958 if the SPEC was listed as a specialization of TMPL.
1960 Note that SPEC has been ggc_freed, so we can't look inside it. */
1962 bool
1963 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1965 spec_entry *entry;
1966 spec_entry elt;
1968 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1969 elt.args = TI_ARGS (tinfo);
1970 elt.spec = NULL_TREE;
1972 entry = decl_specializations->find (&elt);
1973 if (entry != NULL)
1975 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1976 gcc_assert (new_spec != NULL_TREE);
1977 entry->spec = new_spec;
1978 return 1;
1981 return 0;
1984 /* Like register_specialization, but for local declarations. We are
1985 registering SPEC, an instantiation of TMPL. */
1987 void
1988 register_local_specialization (tree spec, tree tmpl)
1990 gcc_assert (tmpl != spec);
1991 local_specializations->put (tmpl, spec);
1994 /* Registers T as a specialization of itself. This is used to preserve
1995 the references to already-parsed parameters when instantiating
1996 postconditions. */
1998 void
1999 register_local_identity (tree t)
2001 local_specializations->put (t, t);
2004 /* TYPE is a class type. Returns true if TYPE is an explicitly
2005 specialized class. */
2007 bool
2008 explicit_class_specialization_p (tree type)
2010 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2011 return false;
2012 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2015 /* Print the list of functions at FNS, going through all the overloads
2016 for each element of the list. Alternatively, FNS cannot be a
2017 TREE_LIST, in which case it will be printed together with all the
2018 overloads.
2020 MORE and *STR should respectively be FALSE and NULL when the function
2021 is called from the outside. They are used internally on recursive
2022 calls. print_candidates manages the two parameters and leaves NULL
2023 in *STR when it ends. */
2025 static void
2026 print_candidates_1 (tree fns, char **str, bool more = false)
2028 if (TREE_CODE (fns) == TREE_LIST)
2029 for (; fns; fns = TREE_CHAIN (fns))
2030 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2031 else
2032 for (lkp_iterator iter (fns); iter;)
2034 tree cand = *iter;
2035 ++iter;
2037 const char *pfx = *str;
2038 if (!pfx)
2040 if (more || iter)
2041 pfx = _("candidates are:");
2042 else
2043 pfx = _("candidate is:");
2044 *str = get_spaces (pfx);
2046 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2050 /* Print the list of candidate FNS in an error message. FNS can also
2051 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2053 void
2054 print_candidates (tree fns)
2056 char *str = NULL;
2057 print_candidates_1 (fns, &str);
2058 free (str);
2061 /* Get a (possibly) constrained template declaration for the
2062 purpose of ordering candidates. */
2063 static tree
2064 get_template_for_ordering (tree list)
2066 gcc_assert (TREE_CODE (list) == TREE_LIST);
2067 tree f = TREE_VALUE (list);
2068 if (tree ti = DECL_TEMPLATE_INFO (f))
2069 return TI_TEMPLATE (ti);
2070 return f;
2073 /* Among candidates having the same signature, return the
2074 most constrained or NULL_TREE if there is no best candidate.
2075 If the signatures of candidates vary (e.g., template
2076 specialization vs. member function), then there can be no
2077 most constrained.
2079 Note that we don't compare constraints on the functions
2080 themselves, but rather those of their templates. */
2081 static tree
2082 most_constrained_function (tree candidates)
2084 // Try to find the best candidate in a first pass.
2085 tree champ = candidates;
2086 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2088 int winner = more_constrained (get_template_for_ordering (champ),
2089 get_template_for_ordering (c));
2090 if (winner == -1)
2091 champ = c; // The candidate is more constrained
2092 else if (winner == 0)
2093 return NULL_TREE; // Neither is more constrained
2096 // Verify that the champ is better than previous candidates.
2097 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2098 if (!more_constrained (get_template_for_ordering (champ),
2099 get_template_for_ordering (c)))
2100 return NULL_TREE;
2103 return champ;
2107 /* Returns the template (one of the functions given by TEMPLATE_ID)
2108 which can be specialized to match the indicated DECL with the
2109 explicit template args given in TEMPLATE_ID. The DECL may be
2110 NULL_TREE if none is available. In that case, the functions in
2111 TEMPLATE_ID are non-members.
2113 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2114 specialization of a member template.
2116 The TEMPLATE_COUNT is the number of references to qualifying
2117 template classes that appeared in the name of the function. See
2118 check_explicit_specialization for a more accurate description.
2120 TSK indicates what kind of template declaration (if any) is being
2121 declared. TSK_TEMPLATE indicates that the declaration given by
2122 DECL, though a FUNCTION_DECL, has template parameters, and is
2123 therefore a template function.
2125 The template args (those explicitly specified and those deduced)
2126 are output in a newly created vector *TARGS_OUT.
2128 If it is impossible to determine the result, an error message is
2129 issued. The error_mark_node is returned to indicate failure. */
2131 static tree
2132 determine_specialization (tree template_id,
2133 tree decl,
2134 tree* targs_out,
2135 int need_member_template,
2136 int template_count,
2137 tmpl_spec_kind tsk)
2139 tree fns;
2140 tree targs;
2141 tree explicit_targs;
2142 tree candidates = NULL_TREE;
2144 /* A TREE_LIST of templates of which DECL may be a specialization.
2145 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2146 corresponding TREE_PURPOSE is the set of template arguments that,
2147 when used to instantiate the template, would produce a function
2148 with the signature of DECL. */
2149 tree templates = NULL_TREE;
2150 int header_count;
2151 cp_binding_level *b;
2153 *targs_out = NULL_TREE;
2155 if (template_id == error_mark_node || decl == error_mark_node)
2156 return error_mark_node;
2158 /* We shouldn't be specializing a member template of an
2159 unspecialized class template; we already gave an error in
2160 check_specialization_scope, now avoid crashing. */
2161 if (!VAR_P (decl)
2162 && template_count && DECL_CLASS_SCOPE_P (decl)
2163 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2165 gcc_assert (errorcount);
2166 return error_mark_node;
2169 fns = TREE_OPERAND (template_id, 0);
2170 explicit_targs = TREE_OPERAND (template_id, 1);
2172 if (fns == error_mark_node)
2173 return error_mark_node;
2175 /* Check for baselinks. */
2176 if (BASELINK_P (fns))
2177 fns = BASELINK_FUNCTIONS (fns);
2179 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2181 error_at (DECL_SOURCE_LOCATION (decl),
2182 "%qD is not a function template", fns);
2183 return error_mark_node;
2185 else if (VAR_P (decl) && !variable_template_p (fns))
2187 error ("%qD is not a variable template", fns);
2188 return error_mark_node;
2191 /* Count the number of template headers specified for this
2192 specialization. */
2193 header_count = 0;
2194 for (b = current_binding_level;
2195 b->kind == sk_template_parms;
2196 b = b->level_chain)
2197 ++header_count;
2199 tree orig_fns = fns;
2200 bool header_mismatch = false;
2202 if (variable_template_p (fns))
2204 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2205 targs = coerce_template_parms (parms, explicit_targs, fns,
2206 tf_warning_or_error);
2207 if (targs != error_mark_node
2208 && constraints_satisfied_p (fns, targs))
2209 templates = tree_cons (targs, fns, templates);
2211 else for (lkp_iterator iter (fns); iter; ++iter)
2213 tree fn = *iter;
2215 if (TREE_CODE (fn) == TEMPLATE_DECL)
2217 tree decl_arg_types;
2218 tree fn_arg_types;
2220 /* In case of explicit specialization, we need to check if
2221 the number of template headers appearing in the specialization
2222 is correct. This is usually done in check_explicit_specialization,
2223 but the check done there cannot be exhaustive when specializing
2224 member functions. Consider the following code:
2226 template <> void A<int>::f(int);
2227 template <> template <> void A<int>::f(int);
2229 Assuming that A<int> is not itself an explicit specialization
2230 already, the first line specializes "f" which is a non-template
2231 member function, whilst the second line specializes "f" which
2232 is a template member function. So both lines are syntactically
2233 correct, and check_explicit_specialization does not reject
2234 them.
2236 Here, we can do better, as we are matching the specialization
2237 against the declarations. We count the number of template
2238 headers, and we check if they match TEMPLATE_COUNT + 1
2239 (TEMPLATE_COUNT is the number of qualifying template classes,
2240 plus there must be another header for the member template
2241 itself).
2243 Notice that if header_count is zero, this is not a
2244 specialization but rather a template instantiation, so there
2245 is no check we can perform here. */
2246 if (header_count && header_count != template_count + 1)
2248 header_mismatch = true;
2249 continue;
2252 /* Check that the number of template arguments at the
2253 innermost level for DECL is the same as for FN. */
2254 if (current_binding_level->kind == sk_template_parms
2255 && !current_binding_level->explicit_spec_p
2256 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2257 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2258 (current_template_parms))))
2259 continue;
2261 /* DECL might be a specialization of FN. */
2262 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2263 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2265 /* For a non-static member function, we need to make sure
2266 that the const qualification is the same. Since
2267 get_bindings does not try to merge the "this" parameter,
2268 we must do the comparison explicitly. */
2269 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
2271 if (!same_type_p (TREE_VALUE (fn_arg_types),
2272 TREE_VALUE (decl_arg_types)))
2273 continue;
2275 /* And the ref-qualification. */
2276 if (type_memfn_rqual (TREE_TYPE (decl))
2277 != type_memfn_rqual (TREE_TYPE (fn)))
2278 continue;
2281 /* Skip the "this" parameter and, for constructors of
2282 classes with virtual bases, the VTT parameter. A
2283 full specialization of a constructor will have a VTT
2284 parameter, but a template never will. */
2285 decl_arg_types
2286 = skip_artificial_parms_for (decl, decl_arg_types);
2287 fn_arg_types
2288 = skip_artificial_parms_for (fn, fn_arg_types);
2290 /* Function templates cannot be specializations; there are
2291 no partial specializations of functions. Therefore, if
2292 the type of DECL does not match FN, there is no
2293 match.
2295 Note that it should never be the case that we have both
2296 candidates added here, and for regular member functions
2297 below. */
2298 if (tsk == tsk_template)
2300 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2301 current_template_parms))
2302 continue;
2303 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2304 TREE_TYPE (TREE_TYPE (fn))))
2305 continue;
2306 if (!compparms (fn_arg_types, decl_arg_types))
2307 continue;
2309 tree freq = get_constraints (fn);
2310 tree dreq = get_constraints (decl);
2311 if (!freq != !dreq)
2312 continue;
2313 if (freq)
2315 /* C++20 CA104: Substitute directly into the
2316 constraint-expression. */
2317 tree fargs = DECL_TI_ARGS (fn);
2318 tsubst_flags_t complain = tf_none;
2319 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2320 if (!cp_tree_equal (freq, dreq))
2321 continue;
2324 candidates = tree_cons (NULL_TREE, fn, candidates);
2325 continue;
2328 /* See whether this function might be a specialization of this
2329 template. Suppress access control because we might be trying
2330 to make this specialization a friend, and we have already done
2331 access control for the declaration of the specialization. */
2332 push_deferring_access_checks (dk_no_check);
2333 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2334 pop_deferring_access_checks ();
2336 if (!targs)
2337 /* We cannot deduce template arguments that when used to
2338 specialize TMPL will produce DECL. */
2339 continue;
2341 if (uses_template_parms (targs))
2342 /* We deduced something involving 'auto', which isn't a valid
2343 template argument. */
2344 continue;
2346 /* Save this template, and the arguments deduced. */
2347 templates = tree_cons (targs, fn, templates);
2349 else if (need_member_template)
2350 /* FN is an ordinary member function, and we need a
2351 specialization of a member template. */
2353 else if (TREE_CODE (fn) != FUNCTION_DECL)
2354 /* We can get IDENTIFIER_NODEs here in certain erroneous
2355 cases. */
2357 else if (!DECL_FUNCTION_MEMBER_P (fn))
2358 /* This is just an ordinary non-member function. Nothing can
2359 be a specialization of that. */
2361 else if (DECL_ARTIFICIAL (fn))
2362 /* Cannot specialize functions that are created implicitly. */
2364 else
2366 tree decl_arg_types;
2368 /* This is an ordinary member function. However, since
2369 we're here, we can assume its enclosing class is a
2370 template class. For example,
2372 template <typename T> struct S { void f(); };
2373 template <> void S<int>::f() {}
2375 Here, S<int>::f is a non-template, but S<int> is a
2376 template class. If FN has the same type as DECL, we
2377 might be in business. */
2379 if (!DECL_TEMPLATE_INFO (fn))
2380 /* Its enclosing class is an explicit specialization
2381 of a template class. This is not a candidate. */
2382 continue;
2384 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2385 TREE_TYPE (TREE_TYPE (fn))))
2386 /* The return types differ. */
2387 continue;
2389 /* Adjust the type of DECL in case FN is a static member. */
2390 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2391 if (DECL_STATIC_FUNCTION_P (fn)
2392 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2393 decl_arg_types = TREE_CHAIN (decl_arg_types);
2395 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2396 decl_arg_types))
2397 continue;
2399 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
2400 && (type_memfn_rqual (TREE_TYPE (decl))
2401 != type_memfn_rqual (TREE_TYPE (fn))))
2402 continue;
2404 // If the deduced arguments do not satisfy the constraints,
2405 // this is not a candidate.
2406 if (flag_concepts && !constraints_satisfied_p (fn))
2407 continue;
2409 // Add the candidate.
2410 candidates = tree_cons (NULL_TREE, fn, candidates);
2414 if (templates && TREE_CHAIN (templates))
2416 /* We have:
2418 [temp.expl.spec]
2420 It is possible for a specialization with a given function
2421 signature to be instantiated from more than one function
2422 template. In such cases, explicit specification of the
2423 template arguments must be used to uniquely identify the
2424 function template specialization being specialized.
2426 Note that here, there's no suggestion that we're supposed to
2427 determine which of the candidate templates is most
2428 specialized. However, we, also have:
2430 [temp.func.order]
2432 Partial ordering of overloaded function template
2433 declarations is used in the following contexts to select
2434 the function template to which a function template
2435 specialization refers:
2437 -- when an explicit specialization refers to a function
2438 template.
2440 So, we do use the partial ordering rules, at least for now.
2441 This extension can only serve to make invalid programs valid,
2442 so it's safe. And, there is strong anecdotal evidence that
2443 the committee intended the partial ordering rules to apply;
2444 the EDG front end has that behavior, and John Spicer claims
2445 that the committee simply forgot to delete the wording in
2446 [temp.expl.spec]. */
2447 tree tmpl = most_specialized_instantiation (templates);
2448 if (tmpl != error_mark_node)
2450 templates = tmpl;
2451 TREE_CHAIN (templates) = NULL_TREE;
2455 // Concepts allows multiple declarations of member functions
2456 // with the same signature. Like above, we need to rely on
2457 // on the partial ordering of those candidates to determine which
2458 // is the best.
2459 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2461 if (tree cand = most_constrained_function (candidates))
2463 candidates = cand;
2464 TREE_CHAIN (cand) = NULL_TREE;
2468 if (templates == NULL_TREE && candidates == NULL_TREE)
2470 error ("template-id %qD for %q+D does not match any template "
2471 "declaration", template_id, decl);
2472 if (header_mismatch)
2473 inform (DECL_SOURCE_LOCATION (decl),
2474 "saw %d %<template<>%>, need %d for "
2475 "specializing a member function template",
2476 header_count, template_count + 1);
2477 print_candidates (orig_fns);
2478 return error_mark_node;
2480 else if ((templates && TREE_CHAIN (templates))
2481 || (candidates && TREE_CHAIN (candidates))
2482 || (templates && candidates))
2484 error ("ambiguous template specialization %qD for %q+D",
2485 template_id, decl);
2486 candidates = chainon (candidates, templates);
2487 print_candidates (candidates);
2488 return error_mark_node;
2491 /* We have one, and exactly one, match. */
2492 if (candidates)
2494 tree fn = TREE_VALUE (candidates);
2495 *targs_out = copy_node (DECL_TI_ARGS (fn));
2497 /* Propagate the candidate's constraints to the declaration. */
2498 if (tsk != tsk_template)
2499 set_constraints (decl, get_constraints (fn));
2501 /* DECL is a re-declaration or partial instantiation of a template
2502 function. */
2503 if (TREE_CODE (fn) == TEMPLATE_DECL)
2504 return fn;
2505 /* It was a specialization of an ordinary member function in a
2506 template class. */
2507 return DECL_TI_TEMPLATE (fn);
2510 /* It was a specialization of a template. */
2511 tree tmpl = TREE_VALUE (templates);
2512 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2514 /* Propagate the template's constraints to the declaration. */
2515 if (tsk != tsk_template)
2516 set_constraints (decl, get_constraints (tmpl));
2518 return tmpl;
2521 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2522 but with the default argument values filled in from those in the
2523 TMPL_TYPES. */
2525 static tree
2526 copy_default_args_to_explicit_spec_1 (tree spec_types,
2527 tree tmpl_types)
2529 tree new_spec_types;
2531 if (!spec_types)
2532 return NULL_TREE;
2534 if (spec_types == void_list_node)
2535 return void_list_node;
2537 /* Substitute into the rest of the list. */
2538 new_spec_types =
2539 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2540 TREE_CHAIN (tmpl_types));
2542 /* Add the default argument for this parameter. */
2543 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2544 TREE_VALUE (spec_types),
2545 new_spec_types);
2548 /* DECL is an explicit specialization. Replicate default arguments
2549 from the template it specializes. (That way, code like:
2551 template <class T> void f(T = 3);
2552 template <> void f(double);
2553 void g () { f (); }
2555 works, as required.) An alternative approach would be to look up
2556 the correct default arguments at the call-site, but this approach
2557 is consistent with how implicit instantiations are handled. */
2559 static void
2560 copy_default_args_to_explicit_spec (tree decl)
2562 tree tmpl;
2563 tree spec_types;
2564 tree tmpl_types;
2565 tree new_spec_types;
2566 tree old_type;
2567 tree new_type;
2568 tree t;
2569 tree object_type = NULL_TREE;
2570 tree in_charge = NULL_TREE;
2571 tree vtt = NULL_TREE;
2573 /* See if there's anything we need to do. */
2574 tmpl = DECL_TI_TEMPLATE (decl);
2575 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2576 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2577 if (TREE_PURPOSE (t))
2578 break;
2579 if (!t)
2580 return;
2582 old_type = TREE_TYPE (decl);
2583 spec_types = TYPE_ARG_TYPES (old_type);
2585 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
2587 /* Remove the this pointer, but remember the object's type for
2588 CV quals. */
2589 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2590 spec_types = TREE_CHAIN (spec_types);
2591 tmpl_types = TREE_CHAIN (tmpl_types);
2593 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2595 /* DECL may contain more parameters than TMPL due to the extra
2596 in-charge parameter in constructors and destructors. */
2597 in_charge = spec_types;
2598 spec_types = TREE_CHAIN (spec_types);
2600 if (DECL_HAS_VTT_PARM_P (decl))
2602 vtt = spec_types;
2603 spec_types = TREE_CHAIN (spec_types);
2607 /* Compute the merged default arguments. */
2608 new_spec_types =
2609 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2611 /* Compute the new FUNCTION_TYPE. */
2612 if (object_type)
2614 if (vtt)
2615 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2616 TREE_VALUE (vtt),
2617 new_spec_types);
2619 if (in_charge)
2620 /* Put the in-charge parameter back. */
2621 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2622 TREE_VALUE (in_charge),
2623 new_spec_types);
2625 new_type = build_method_type_directly (object_type,
2626 TREE_TYPE (old_type),
2627 new_spec_types);
2629 else
2630 new_type = build_function_type (TREE_TYPE (old_type),
2631 new_spec_types);
2632 new_type = cp_build_type_attribute_variant (new_type,
2633 TYPE_ATTRIBUTES (old_type));
2634 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2636 TREE_TYPE (decl) = new_type;
2639 /* Return the number of template headers we expect to see for a definition
2640 or specialization of CTYPE or one of its non-template members. */
2643 num_template_headers_for_class (tree ctype)
2645 int num_templates = 0;
2647 while (ctype && CLASS_TYPE_P (ctype))
2649 /* You're supposed to have one `template <...>' for every
2650 template class, but you don't need one for a full
2651 specialization. For example:
2653 template <class T> struct S{};
2654 template <> struct S<int> { void f(); };
2655 void S<int>::f () {}
2657 is correct; there shouldn't be a `template <>' for the
2658 definition of `S<int>::f'. */
2659 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2660 /* If CTYPE does not have template information of any
2661 kind, then it is not a template, nor is it nested
2662 within a template. */
2663 break;
2664 if (explicit_class_specialization_p (ctype))
2665 break;
2666 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2667 ++num_templates;
2669 ctype = TYPE_CONTEXT (ctype);
2672 return num_templates;
2675 /* Do a simple sanity check on the template headers that precede the
2676 variable declaration DECL. */
2678 void
2679 check_template_variable (tree decl)
2681 tree ctx = CP_DECL_CONTEXT (decl);
2682 int wanted = num_template_headers_for_class (ctx);
2683 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2684 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2686 if (cxx_dialect < cxx14)
2687 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2688 "variable templates only available with "
2689 "%<-std=c++14%> or %<-std=gnu++14%>");
2691 // Namespace-scope variable templates should have a template header.
2692 ++wanted;
2694 if (template_header_count > wanted)
2696 auto_diagnostic_group d;
2697 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2698 "too many template headers for %qD "
2699 "(should be %d)",
2700 decl, wanted);
2701 if (warned && CLASS_TYPE_P (ctx)
2702 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2703 inform (DECL_SOURCE_LOCATION (decl),
2704 "members of an explicitly specialized class are defined "
2705 "without a template header");
2709 /* An explicit specialization whose declarator-id or class-head-name is not
2710 qualified shall be declared in the nearest enclosing namespace of the
2711 template, or, if the namespace is inline (7.3.1), any namespace from its
2712 enclosing namespace set.
2714 If the name declared in the explicit instantiation is an unqualified name,
2715 the explicit instantiation shall appear in the namespace where its template
2716 is declared or, if that namespace is inline (7.3.1), any namespace from its
2717 enclosing namespace set. */
2719 void
2720 check_unqualified_spec_or_inst (tree t, location_t loc)
2722 tree tmpl = most_general_template (t);
2723 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2724 && !is_nested_namespace (current_namespace,
2725 CP_DECL_CONTEXT (tmpl), true))
2727 if (processing_specialization)
2728 permerror (loc, "explicit specialization of %qD outside its "
2729 "namespace must use a nested-name-specifier", tmpl);
2730 else if (processing_explicit_instantiation
2731 && cxx_dialect >= cxx11)
2732 /* This was allowed in C++98, so only pedwarn. */
2733 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2734 "outside its namespace must use a nested-name-"
2735 "specifier", tmpl);
2739 /* Warn for a template specialization SPEC that is missing some of a set
2740 of function or type attributes that the template TEMPL is declared with.
2741 ATTRLIST is a list of additional attributes that SPEC should be taken
2742 to ultimately be declared with. */
2744 static void
2745 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2747 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2748 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2750 /* Avoid warning if the difference between the primary and
2751 the specialization is not in one of the attributes below. */
2752 const char* const blacklist[] = {
2753 "alloc_align", "alloc_size", "assume_aligned", "format",
2754 "format_arg", "malloc", "nonnull", NULL
2757 /* Put together a list of the black listed attributes that the primary
2758 template is declared with that the specialization is not, in case
2759 it's not apparent from the most recent declaration of the primary. */
2760 pretty_printer str;
2761 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2762 blacklist, &str);
2764 if (!nattrs)
2765 return;
2767 auto_diagnostic_group d;
2768 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2769 "explicit specialization %q#D may be missing attributes",
2770 spec))
2771 inform (DECL_SOURCE_LOCATION (tmpl),
2772 nattrs > 1
2773 ? G_("missing primary template attributes %s")
2774 : G_("missing primary template attribute %s"),
2775 pp_formatted_text (&str));
2778 /* Check to see if the function just declared, as indicated in
2779 DECLARATOR, and in DECL, is a specialization of a function
2780 template. We may also discover that the declaration is an explicit
2781 instantiation at this point.
2783 Returns DECL, or an equivalent declaration that should be used
2784 instead if all goes well. Issues an error message if something is
2785 amiss. Returns error_mark_node if the error is not easily
2786 recoverable.
2788 FLAGS is a bitmask consisting of the following flags:
2790 2: The function has a definition.
2791 4: The function is a friend.
2793 The TEMPLATE_COUNT is the number of references to qualifying
2794 template classes that appeared in the name of the function. For
2795 example, in
2797 template <class T> struct S { void f(); };
2798 void S<int>::f();
2800 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2801 classes are not counted in the TEMPLATE_COUNT, so that in
2803 template <class T> struct S {};
2804 template <> struct S<int> { void f(); }
2805 template <> void S<int>::f();
2807 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2808 invalid; there should be no template <>.)
2810 If the function is a specialization, it is marked as such via
2811 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2812 is set up correctly, and it is added to the list of specializations
2813 for that template. */
2815 tree
2816 check_explicit_specialization (tree declarator,
2817 tree decl,
2818 int template_count,
2819 int flags,
2820 tree attrlist)
2822 int have_def = flags & 2;
2823 int is_friend = flags & 4;
2824 bool is_concept = flags & 8;
2825 int specialization = 0;
2826 int explicit_instantiation = 0;
2827 int member_specialization = 0;
2828 tree ctype = DECL_CLASS_CONTEXT (decl);
2829 tree dname = DECL_NAME (decl);
2830 tmpl_spec_kind tsk;
2832 if (is_friend)
2834 if (!processing_specialization)
2835 tsk = tsk_none;
2836 else
2837 tsk = tsk_excessive_parms;
2839 else
2840 tsk = current_tmpl_spec_kind (template_count);
2842 switch (tsk)
2844 case tsk_none:
2845 if (processing_specialization && !VAR_P (decl))
2847 specialization = 1;
2848 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2850 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2851 || (DECL_LANG_SPECIFIC (decl)
2852 && DECL_IMPLICIT_INSTANTIATION (decl)))
2854 if (is_friend)
2855 /* This could be something like:
2857 template <class T> void f(T);
2858 class S { friend void f<>(int); } */
2859 specialization = 1;
2860 else
2862 /* This case handles bogus declarations like template <>
2863 template <class T> void f<int>(); */
2865 error_at (cp_expr_loc_or_input_loc (declarator),
2866 "template-id %qE in declaration of primary template",
2867 declarator);
2868 return decl;
2871 break;
2873 case tsk_invalid_member_spec:
2874 /* The error has already been reported in
2875 check_specialization_scope. */
2876 return error_mark_node;
2878 case tsk_invalid_expl_inst:
2879 error ("template parameter list used in explicit instantiation");
2881 /* Fall through. */
2883 case tsk_expl_inst:
2884 if (have_def)
2885 error ("definition provided for explicit instantiation");
2887 explicit_instantiation = 1;
2888 break;
2890 case tsk_excessive_parms:
2891 case tsk_insufficient_parms:
2892 if (tsk == tsk_excessive_parms)
2893 error ("too many template parameter lists in declaration of %qD",
2894 decl);
2895 else if (template_header_count)
2896 error("too few template parameter lists in declaration of %qD", decl);
2897 else
2898 error("explicit specialization of %qD must be introduced by "
2899 "%<template <>%>", decl);
2901 /* Fall through. */
2902 case tsk_expl_spec:
2903 if (is_concept)
2904 error ("explicit specialization declared %<concept%>");
2906 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2907 /* In cases like template<> constexpr bool v = true;
2908 We'll give an error in check_template_variable. */
2909 break;
2911 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2912 if (ctype)
2913 member_specialization = 1;
2914 else
2915 specialization = 1;
2916 break;
2918 case tsk_template:
2919 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2921 /* This case handles bogus declarations like template <>
2922 template <class T> void f<int>(); */
2924 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2925 error_at (cp_expr_loc_or_input_loc (declarator),
2926 "template-id %qE in declaration of primary template",
2927 declarator);
2928 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2930 /* Partial specialization of variable template. */
2931 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2932 specialization = 1;
2933 goto ok;
2935 else if (cxx_dialect < cxx14)
2936 error_at (cp_expr_loc_or_input_loc (declarator),
2937 "non-type partial specialization %qE "
2938 "is not allowed", declarator);
2939 else
2940 error_at (cp_expr_loc_or_input_loc (declarator),
2941 "non-class, non-variable partial specialization %qE "
2942 "is not allowed", declarator);
2943 return decl;
2944 ok:;
2947 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2948 /* This is a specialization of a member template, without
2949 specialization the containing class. Something like:
2951 template <class T> struct S {
2952 template <class U> void f (U);
2954 template <> template <class U> void S<int>::f(U) {}
2956 That's a specialization -- but of the entire template. */
2957 specialization = 1;
2958 break;
2960 default:
2961 gcc_unreachable ();
2964 if ((specialization || member_specialization)
2965 /* This doesn't apply to variable templates. */
2966 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2968 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2969 for (; t; t = TREE_CHAIN (t))
2970 if (TREE_PURPOSE (t))
2972 permerror (input_location,
2973 "default argument specified in explicit specialization");
2974 break;
2978 if (specialization || member_specialization || explicit_instantiation)
2980 tree tmpl = NULL_TREE;
2981 tree targs = NULL_TREE;
2982 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2983 bool found_hidden = false;
2985 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2986 if (!was_template_id)
2988 tree fns;
2990 gcc_assert (identifier_p (declarator));
2991 if (ctype)
2992 fns = dname;
2993 else
2995 /* If there is no class context, the explicit instantiation
2996 must be at namespace scope. */
2997 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2999 /* Find the namespace binding, using the declaration
3000 context. */
3001 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3002 LOOK_want::NORMAL, true);
3003 if (fns == error_mark_node)
3005 /* If lookup fails, look for a friend declaration so we can
3006 give a better diagnostic. */
3007 fns = (lookup_qualified_name
3008 (CP_DECL_CONTEXT (decl), dname,
3009 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3010 /*complain*/true));
3011 found_hidden = true;
3014 if (fns == error_mark_node || !is_overloaded_fn (fns))
3016 error ("%qD is not a template function", dname);
3017 fns = error_mark_node;
3021 declarator = lookup_template_function (fns, NULL_TREE);
3024 if (declarator == error_mark_node)
3025 return error_mark_node;
3027 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3029 if (!explicit_instantiation)
3030 /* A specialization in class scope. This is invalid,
3031 but the error will already have been flagged by
3032 check_specialization_scope. */
3033 return error_mark_node;
3034 else
3036 /* It's not valid to write an explicit instantiation in
3037 class scope, e.g.:
3039 class C { template void f(); }
3041 This case is caught by the parser. However, on
3042 something like:
3044 template class C { void f(); };
3046 (which is invalid) we can get here. The error will be
3047 issued later. */
3051 return decl;
3053 else if (ctype != NULL_TREE
3054 && (identifier_p (TREE_OPERAND (declarator, 0))))
3056 // We'll match variable templates in start_decl.
3057 if (VAR_P (decl))
3058 return decl;
3060 /* Find the list of functions in ctype that have the same
3061 name as the declared function. */
3062 tree name = TREE_OPERAND (declarator, 0);
3064 if (constructor_name_p (name, ctype))
3066 if (DECL_CONSTRUCTOR_P (decl)
3067 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3068 : !CLASSTYPE_DESTRUCTOR (ctype))
3070 /* From [temp.expl.spec]:
3072 If such an explicit specialization for the member
3073 of a class template names an implicitly-declared
3074 special member function (clause _special_), the
3075 program is ill-formed.
3077 Similar language is found in [temp.explicit]. */
3078 error ("specialization of implicitly-declared special member function");
3079 return error_mark_node;
3082 name = DECL_NAME (decl);
3085 /* For a type-conversion operator, We might be looking for
3086 `operator int' which will be a specialization of
3087 `operator T'. Grab all the conversion operators, and
3088 then select from them. */
3089 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3090 ? conv_op_identifier : name);
3092 if (fns == NULL_TREE)
3094 error ("no member function %qD declared in %qT", name, ctype);
3095 return error_mark_node;
3097 else
3098 TREE_OPERAND (declarator, 0) = fns;
3101 /* Figure out what exactly is being specialized at this point.
3102 Note that for an explicit instantiation, even one for a
3103 member function, we cannot tell a priori whether the
3104 instantiation is for a member template, or just a member
3105 function of a template class. Even if a member template is
3106 being instantiated, the member template arguments may be
3107 elided if they can be deduced from the rest of the
3108 declaration. */
3109 tmpl = determine_specialization (declarator, decl,
3110 &targs,
3111 member_specialization,
3112 template_count,
3113 tsk);
3115 if (!tmpl || tmpl == error_mark_node)
3116 /* We couldn't figure out what this declaration was
3117 specializing. */
3118 return error_mark_node;
3119 else
3121 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3123 auto_diagnostic_group d;
3124 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3125 "friend declaration %qD is not visible to "
3126 "explicit specialization", tmpl))
3127 inform (DECL_SOURCE_LOCATION (tmpl),
3128 "friend declaration here");
3131 if (!ctype && !is_friend
3132 && CP_DECL_CONTEXT (decl) == current_namespace)
3133 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3135 tree gen_tmpl = most_general_template (tmpl);
3137 if (explicit_instantiation)
3139 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3140 is done by do_decl_instantiation later. */
3142 int arg_depth = TMPL_ARGS_DEPTH (targs);
3143 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3145 if (arg_depth > parm_depth)
3147 /* If TMPL is not the most general template (for
3148 example, if TMPL is a friend template that is
3149 injected into namespace scope), then there will
3150 be too many levels of TARGS. Remove some of them
3151 here. */
3152 int i;
3153 tree new_targs;
3155 new_targs = make_tree_vec (parm_depth);
3156 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3157 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3158 = TREE_VEC_ELT (targs, i);
3159 targs = new_targs;
3162 return instantiate_template (tmpl, targs, tf_error);
3165 /* If we thought that the DECL was a member function, but it
3166 turns out to be specializing a static member function,
3167 make DECL a static member function as well. */
3168 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3169 && DECL_STATIC_FUNCTION_P (tmpl)
3170 && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
3171 revert_static_member_fn (decl);
3173 /* If this is a specialization of a member template of a
3174 template class, we want to return the TEMPLATE_DECL, not
3175 the specialization of it. */
3176 if (tsk == tsk_template && !was_template_id)
3178 tree result = DECL_TEMPLATE_RESULT (tmpl);
3179 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3180 DECL_INITIAL (result) = NULL_TREE;
3181 if (have_def)
3183 tree parm;
3184 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3185 DECL_SOURCE_LOCATION (result)
3186 = DECL_SOURCE_LOCATION (decl);
3187 /* We want to use the argument list specified in the
3188 definition, not in the original declaration. */
3189 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3190 for (parm = DECL_ARGUMENTS (result); parm;
3191 parm = DECL_CHAIN (parm))
3192 DECL_CONTEXT (parm) = result;
3194 decl = register_specialization (tmpl, gen_tmpl, targs,
3195 is_friend, 0);
3196 remove_contract_attributes (result);
3197 return decl;
3200 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3201 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3203 if (was_template_id)
3204 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3206 /* Inherit default function arguments from the template
3207 DECL is specializing. */
3208 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3209 copy_default_args_to_explicit_spec (decl);
3211 /* This specialization has the same protection as the
3212 template it specializes. */
3213 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3214 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3216 /* 7.1.1-1 [dcl.stc]
3218 A storage-class-specifier shall not be specified in an
3219 explicit specialization...
3221 The parser rejects these, so unless action is taken here,
3222 explicit function specializations will always appear with
3223 global linkage.
3225 The action recommended by the C++ CWG in response to C++
3226 defect report 605 is to make the storage class and linkage
3227 of the explicit specialization match the templated function:
3229 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3231 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3233 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3234 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3236 /* A concept cannot be specialized. */
3237 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3239 error ("explicit specialization of function concept %qD",
3240 gen_tmpl);
3241 return error_mark_node;
3244 /* This specialization has the same linkage and visibility as
3245 the function template it specializes. */
3246 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3247 if (! TREE_PUBLIC (decl))
3249 DECL_INTERFACE_KNOWN (decl) = 1;
3250 DECL_NOT_REALLY_EXTERN (decl) = 1;
3252 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3253 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3255 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3256 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3260 /* If DECL is a friend declaration, declared using an
3261 unqualified name, the namespace associated with DECL may
3262 have been set incorrectly. For example, in:
3264 template <typename T> void f(T);
3265 namespace N {
3266 struct S { friend void f<int>(int); }
3269 we will have set the DECL_CONTEXT for the friend
3270 declaration to N, rather than to the global namespace. */
3271 if (DECL_NAMESPACE_SCOPE_P (decl))
3272 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3274 if (is_friend && !have_def)
3275 /* This is not really a declaration of a specialization.
3276 It's just the name of an instantiation. But, it's not
3277 a request for an instantiation, either. */
3278 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3279 else if (TREE_CODE (decl) == FUNCTION_DECL)
3280 /* A specialization is not necessarily COMDAT. */
3281 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3282 && DECL_DECLARED_INLINE_P (decl));
3283 else if (VAR_P (decl))
3284 DECL_COMDAT (decl) = false;
3286 /* If this is a full specialization, register it so that we can find
3287 it again. Partial specializations will be registered in
3288 process_partial_specialization. */
3289 if (!processing_template_decl)
3291 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3293 decl = register_specialization (decl, gen_tmpl, targs,
3294 is_friend, 0);
3297 /* If this is a specialization, splice any contracts that may have
3298 been inherited from the template, removing them. */
3299 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3300 remove_contract_attributes (decl);
3302 /* A 'structor should already have clones. */
3303 gcc_assert (decl == error_mark_node
3304 || variable_template_p (tmpl)
3305 || !(DECL_CONSTRUCTOR_P (decl)
3306 || DECL_DESTRUCTOR_P (decl))
3307 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3311 return decl;
3314 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3315 parameters. These are represented in the same format used for
3316 DECL_TEMPLATE_PARMS. */
3319 comp_template_parms (const_tree parms1, const_tree parms2)
3321 if (parms1 == parms2)
3322 return 1;
3324 tree t1 = TREE_VALUE (parms1);
3325 tree t2 = TREE_VALUE (parms2);
3326 int i;
3328 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3329 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3331 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3332 return 0;
3334 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3336 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3337 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3339 /* If either of the template parameters are invalid, assume
3340 they match for the sake of error recovery. */
3341 if (error_operand_p (parm1) || error_operand_p (parm2))
3342 return 1;
3344 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3345 return 0;
3347 if (TREE_CODE (parm1) == TYPE_DECL
3348 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm1))
3349 == TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm2))))
3350 continue;
3351 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3352 return 0;
3355 return 1;
3358 /* Returns true if two template parameters are declared with
3359 equivalent constraints. */
3361 static bool
3362 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3364 tree req1 = TREE_TYPE (parm1);
3365 tree req2 = TREE_TYPE (parm2);
3366 if (!req1 != !req2)
3367 return false;
3368 if (req1)
3369 return cp_tree_equal (req1, req2);
3370 return true;
3373 /* Returns true when two template parameters are equivalent. */
3375 static bool
3376 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3378 tree decl1 = TREE_VALUE (parm1);
3379 tree decl2 = TREE_VALUE (parm2);
3381 /* If either of the template parameters are invalid, assume
3382 they match for the sake of error recovery. */
3383 if (error_operand_p (decl1) || error_operand_p (decl2))
3384 return true;
3386 /* ... they declare parameters of the same kind. */
3387 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3388 return false;
3390 /* ... one parameter was introduced by a parameter declaration, then
3391 both are. This case arises as a result of eagerly rewriting declarations
3392 during parsing. */
3393 if (DECL_IMPLICIT_TEMPLATE_PARM_P (decl1)
3394 != DECL_IMPLICIT_TEMPLATE_PARM_P (decl2))
3395 return false;
3397 /* ... if either declares a pack, they both do. */
3398 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3399 return false;
3401 if (TREE_CODE (decl1) == PARM_DECL)
3403 /* ... if they declare non-type parameters, the types are equivalent. */
3404 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3405 return false;
3407 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3409 /* ... if they declare template template parameters, their template
3410 parameter lists are equivalent. */
3411 if (!template_heads_equivalent_p (decl1, decl2))
3412 return false;
3415 /* ... if they are declared with a qualified-concept name, they both
3416 are, and those names are equivalent. */
3417 return template_parameter_constraints_equivalent_p (parm1, parm2);
3420 /* Returns true if two template parameters lists are equivalent.
3421 Two template parameter lists are equivalent if they have the
3422 same length and their corresponding parameters are equivalent.
3424 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3425 data structure returned by DECL_TEMPLATE_PARMS.
3427 This is generally the same implementation as comp_template_parms
3428 except that it also the concept names and arguments used to
3429 introduce parameters. */
3431 static bool
3432 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3434 if (parms1 == parms2)
3435 return true;
3437 tree list1 = TREE_VALUE (parms1);
3438 tree list2 = TREE_VALUE (parms2);
3440 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3441 return 0;
3443 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3445 tree parm1 = TREE_VEC_ELT (list1, i);
3446 tree parm2 = TREE_VEC_ELT (list2, i);
3447 if (!template_parameters_equivalent_p (parm1, parm2))
3448 return false;
3451 return true;
3454 /* Return true if the requires-clause of the template parameter lists are
3455 equivalent and false otherwise. */
3456 static bool
3457 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3459 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3460 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3461 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3462 return false;
3463 if (!cp_tree_equal (req1, req2))
3464 return false;
3465 return true;
3468 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3469 Two template heads are equivalent if their template parameter
3470 lists are equivalent and their requires clauses are equivalent.
3472 In pre-C++20, this is equivalent to calling comp_template_parms
3473 for the template parameters of TMPL1 and TMPL2. */
3475 bool
3476 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3478 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3479 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3481 /* Don't change the matching rules for pre-C++20. */
3482 if (cxx_dialect < cxx20)
3483 return comp_template_parms (parms1, parms2);
3485 /* ... have the same number of template parameters, and their
3486 corresponding parameters are equivalent. */
3487 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3488 return false;
3490 /* ... if either has a requires-clause, they both do and their
3491 corresponding constraint-expressions are equivalent. */
3492 return template_requirements_equivalent_p (parms1, parms2);
3495 /* Determine whether PARM is a parameter pack. */
3497 bool
3498 template_parameter_pack_p (const_tree parm)
3500 /* Determine if we have a non-type template parameter pack. */
3501 if (TREE_CODE (parm) == PARM_DECL)
3502 return (DECL_TEMPLATE_PARM_P (parm)
3503 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3504 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3505 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3507 /* If this is a list of template parameters, we could get a
3508 TYPE_DECL or a TEMPLATE_DECL. */
3509 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3510 parm = TREE_TYPE (parm);
3512 /* Otherwise it must be a type template parameter. */
3513 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3514 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3515 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3518 /* Determine if T is a function parameter pack. */
3520 bool
3521 function_parameter_pack_p (const_tree t)
3523 if (t && TREE_CODE (t) == PARM_DECL)
3524 return DECL_PACK_P (t);
3525 return false;
3528 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3529 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3531 tree
3532 get_function_template_decl (const_tree primary_func_tmpl_inst)
3534 if (! primary_func_tmpl_inst
3535 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3536 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3537 return NULL;
3539 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3542 /* Return true iff the function parameter PARAM_DECL was expanded
3543 from the function parameter pack PACK. */
3545 bool
3546 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3548 if (DECL_ARTIFICIAL (param_decl)
3549 || !function_parameter_pack_p (pack))
3550 return false;
3552 /* The parameter pack and its pack arguments have the same
3553 DECL_PARM_INDEX. */
3554 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3557 /* Determine whether ARGS describes a variadic template args list,
3558 i.e., one that is terminated by a template argument pack. */
3560 static bool
3561 template_args_variadic_p (tree args)
3563 int nargs;
3564 tree last_parm;
3566 if (args == NULL_TREE)
3567 return false;
3569 args = INNERMOST_TEMPLATE_ARGS (args);
3570 nargs = TREE_VEC_LENGTH (args);
3572 if (nargs == 0)
3573 return false;
3575 last_parm = TREE_VEC_ELT (args, nargs - 1);
3577 return ARGUMENT_PACK_P (last_parm);
3580 /* Generate a new name for the parameter pack name NAME (an
3581 IDENTIFIER_NODE) that incorporates its */
3583 static tree
3584 make_ith_pack_parameter_name (tree name, int i)
3586 /* Munge the name to include the parameter index. */
3587 #define NUMBUF_LEN 128
3588 char numbuf[NUMBUF_LEN];
3589 char* newname;
3590 int newname_len;
3592 if (name == NULL_TREE)
3593 return name;
3594 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3595 newname_len = IDENTIFIER_LENGTH (name)
3596 + strlen (numbuf) + 2;
3597 newname = (char*)alloca (newname_len);
3598 snprintf (newname, newname_len,
3599 "%s#%i", IDENTIFIER_POINTER (name), i);
3600 return get_identifier (newname);
3603 /* Return true if T is a primary function, class or alias template
3604 specialization, not including the template pattern. */
3606 bool
3607 primary_template_specialization_p (const_tree t)
3609 if (!t)
3610 return false;
3612 if (VAR_OR_FUNCTION_DECL_P (t))
3613 return (DECL_LANG_SPECIFIC (t)
3614 && DECL_USE_TEMPLATE (t)
3615 && DECL_TEMPLATE_INFO (t)
3616 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3617 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3618 return (CLASSTYPE_TEMPLATE_INFO (t)
3619 && CLASSTYPE_USE_TEMPLATE (t)
3620 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3621 else if (alias_template_specialization_p (t, nt_transparent))
3622 return true;
3623 return false;
3626 /* Return true if PARM is a template template parameter. */
3628 bool
3629 template_template_parameter_p (const_tree parm)
3631 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3634 /* Return true iff PARM is a DECL representing a type template
3635 parameter. */
3637 bool
3638 template_type_parameter_p (const_tree parm)
3640 return (parm
3641 && (TREE_CODE (parm) == TYPE_DECL
3642 || TREE_CODE (parm) == TEMPLATE_DECL)
3643 && DECL_TEMPLATE_PARM_P (parm));
3646 /* Return the template parameters of T if T is a
3647 primary template instantiation, NULL otherwise. */
3649 tree
3650 get_primary_template_innermost_parameters (const_tree t)
3652 tree parms = NULL, template_info = NULL;
3654 if ((template_info = get_template_info (t))
3655 && primary_template_specialization_p (t))
3656 parms = INNERMOST_TEMPLATE_PARMS
3657 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3659 return parms;
3662 /* Returns the template arguments of T if T is a template instantiation,
3663 NULL otherwise. */
3665 tree
3666 get_template_innermost_arguments (const_tree t)
3668 tree args = NULL, template_info = NULL;
3670 if ((template_info = get_template_info (t))
3671 && TI_ARGS (template_info))
3672 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3674 return args;
3677 /* Return the argument pack elements of T if T is a template argument pack,
3678 NULL otherwise. */
3680 tree
3681 get_template_argument_pack_elems (const_tree t)
3683 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3684 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3685 return NULL;
3687 return ARGUMENT_PACK_ARGS (t);
3690 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3691 ARGUMENT_PACK_SELECT represents. */
3693 static tree
3694 argument_pack_select_arg (tree t)
3696 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3697 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3699 /* If the selected argument is an expansion E, that most likely means we were
3700 called from gen_elem_of_pack_expansion_instantiation during the
3701 substituting of an argument pack (of which the Ith element is a pack
3702 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3703 In this case, the Ith element resulting from this substituting is going to
3704 be a pack expansion, which pattern is the pattern of E. Let's return the
3705 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3706 resulting pack expansion from it. */
3707 if (PACK_EXPANSION_P (arg))
3709 /* Make sure we aren't throwing away arg info. */
3710 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3711 arg = PACK_EXPANSION_PATTERN (arg);
3714 return arg;
3717 /* Return a modification of ARGS that's suitable for preserving inside a hash
3718 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3719 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3721 static tree
3722 preserve_args (tree args, bool cow_p = true)
3724 if (!args)
3725 return NULL_TREE;
3727 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3729 tree t = TREE_VEC_ELT (args, i);
3730 tree r;
3731 if (!t)
3732 r = NULL_TREE;
3733 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3734 r = argument_pack_select_arg (t);
3735 else if (TREE_CODE (t) == TREE_VEC)
3736 r = preserve_args (t, cow_p);
3737 else
3738 r = t;
3739 if (r != t)
3741 if (cow_p)
3743 args = copy_template_args (args);
3744 cow_p = false;
3746 TREE_VEC_ELT (args, i) = r;
3750 return args;
3753 /* True iff FN is a function representing a built-in variadic parameter
3754 pack. */
3756 bool
3757 builtin_pack_fn_p (tree fn)
3759 if (!fn
3760 || TREE_CODE (fn) != FUNCTION_DECL
3761 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3762 return false;
3764 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3765 return true;
3767 return false;
3770 /* True iff CALL is a call to a function representing a built-in variadic
3771 parameter pack. */
3773 static bool
3774 builtin_pack_call_p (tree call)
3776 if (TREE_CODE (call) != CALL_EXPR)
3777 return false;
3778 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3781 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3783 static tree
3784 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3785 tree in_decl)
3787 tree ohi = CALL_EXPR_ARG (call, 0);
3788 tree hi = tsubst_expr (ohi, args, complain, in_decl);
3790 if (instantiation_dependent_expression_p (hi))
3792 if (hi != ohi)
3794 call = copy_node (call);
3795 CALL_EXPR_ARG (call, 0) = hi;
3797 tree ex = make_pack_expansion (call, complain);
3798 tree vec = make_tree_vec (1);
3799 TREE_VEC_ELT (vec, 0) = ex;
3800 return vec;
3802 else
3804 hi = instantiate_non_dependent_expr (hi, complain);
3805 hi = cxx_constant_value (hi, complain);
3806 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3808 /* Calculate the largest value of len that won't make the size of the vec
3809 overflow an int. The compiler will exceed resource limits long before
3810 this, but it seems a decent place to diagnose. */
3811 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3813 if (len < 0 || len > max)
3815 if ((complain & tf_error)
3816 && hi != error_mark_node)
3817 error ("argument to %<__integer_pack%> must be between 0 and %d",
3818 max);
3819 return error_mark_node;
3822 tree vec = make_tree_vec (len);
3824 for (int i = 0; i < len; ++i)
3825 TREE_VEC_ELT (vec, i) = size_int (i);
3827 return vec;
3831 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3832 CALL. */
3834 static tree
3835 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3836 tree in_decl)
3838 if (!builtin_pack_call_p (call))
3839 return NULL_TREE;
3841 tree fn = CALL_EXPR_FN (call);
3843 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3844 return expand_integer_pack (call, args, complain, in_decl);
3846 return NULL_TREE;
3849 /* Return true if the tree T has the extra args mechanism for
3850 avoiding partial instantiation. */
3852 static bool
3853 has_extra_args_mechanism_p (const_tree t)
3855 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3856 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3857 || (TREE_CODE (t) == IF_STMT
3858 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3861 /* Structure used to track the progress of find_parameter_packs_r. */
3862 struct find_parameter_pack_data
3864 /* TREE_LIST that will contain all of the parameter packs found by
3865 the traversal. */
3866 tree* parameter_packs;
3868 /* Set of AST nodes that have been visited by the traversal. */
3869 hash_set<tree> *visited;
3871 /* True iff we're making a type pack expansion. */
3872 bool type_pack_expansion_p;
3874 /* True iff we found a subtree that has the extra args mechanism. */
3875 bool found_extra_args_tree_p = false;
3878 /* Identifies all of the argument packs that occur in a template
3879 argument and appends them to the TREE_LIST inside DATA, which is a
3880 find_parameter_pack_data structure. This is a subroutine of
3881 make_pack_expansion and uses_parameter_packs. */
3882 static tree
3883 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3885 tree t = *tp;
3886 struct find_parameter_pack_data* ppd =
3887 (struct find_parameter_pack_data*)data;
3888 bool parameter_pack_p = false;
3890 #define WALK_SUBTREE(NODE) \
3891 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3892 ppd, ppd->visited) \
3894 /* Don't look through typedefs; we are interested in whether a
3895 parameter pack is actually written in the expression/type we're
3896 looking at, not the target type. */
3897 if (TYPE_P (t) && typedef_variant_p (t))
3899 /* But do look at arguments for an alias template. */
3900 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3901 cp_walk_tree (&TI_ARGS (tinfo),
3902 &find_parameter_packs_r,
3903 ppd, ppd->visited);
3904 *walk_subtrees = 0;
3905 return NULL_TREE;
3908 /* Identify whether this is a parameter pack or not. */
3909 switch (TREE_CODE (t))
3911 case TEMPLATE_PARM_INDEX:
3912 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3913 parameter_pack_p = true;
3914 break;
3916 case TEMPLATE_TYPE_PARM:
3917 t = TYPE_MAIN_VARIANT (t);
3918 /* FALLTHRU */
3919 case TEMPLATE_TEMPLATE_PARM:
3920 /* If the placeholder appears in the decl-specifier-seq of a function
3921 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3922 is a pack expansion, the invented template parameter is a template
3923 parameter pack. */
3924 if (ppd->type_pack_expansion_p && is_auto (t))
3925 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3926 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3927 parameter_pack_p = true;
3928 break;
3930 case FIELD_DECL:
3931 case PARM_DECL:
3932 if (DECL_PACK_P (t))
3934 /* We don't want to walk into the type of a PARM_DECL,
3935 because we don't want to see the type parameter pack. */
3936 *walk_subtrees = 0;
3937 parameter_pack_p = true;
3939 break;
3941 case VAR_DECL:
3942 if (DECL_PACK_P (t))
3944 /* We don't want to walk into the type of a variadic capture proxy,
3945 because we don't want to see the type parameter pack. */
3946 *walk_subtrees = 0;
3947 parameter_pack_p = true;
3949 else if (variable_template_specialization_p (t))
3951 cp_walk_tree (&DECL_TI_ARGS (t),
3952 find_parameter_packs_r,
3953 ppd, ppd->visited);
3954 *walk_subtrees = 0;
3956 break;
3958 case CALL_EXPR:
3959 if (builtin_pack_call_p (t))
3960 parameter_pack_p = true;
3961 break;
3963 case BASES:
3964 parameter_pack_p = true;
3965 break;
3966 default:
3967 /* Not a parameter pack. */
3968 break;
3971 if (parameter_pack_p)
3973 /* Add this parameter pack to the list. */
3974 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3977 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3978 ppd->found_extra_args_tree_p = true;
3980 if (TYPE_P (t))
3981 cp_walk_tree (&TYPE_CONTEXT (t),
3982 &find_parameter_packs_r, ppd, ppd->visited);
3984 /* This switch statement will return immediately if we don't find a
3985 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3986 switch (TREE_CODE (t))
3988 case BOUND_TEMPLATE_TEMPLATE_PARM:
3989 /* Check the template itself. */
3990 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3991 &find_parameter_packs_r, ppd, ppd->visited);
3992 return NULL_TREE;
3994 case DECL_EXPR:
3996 tree decl = DECL_EXPR_DECL (t);
3997 /* Ignore the declaration of a capture proxy for a parameter pack. */
3998 if (is_capture_proxy (decl))
3999 *walk_subtrees = 0;
4000 if (is_typedef_decl (decl))
4001 /* Since we stop at typedefs above, we need to look through them at
4002 the point of the DECL_EXPR. */
4003 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4004 &find_parameter_packs_r, ppd, ppd->visited);
4005 return NULL_TREE;
4008 case TEMPLATE_DECL:
4009 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4010 return NULL_TREE;
4011 cp_walk_tree (&TREE_TYPE (t),
4012 &find_parameter_packs_r, ppd, ppd->visited);
4013 return NULL_TREE;
4015 case TYPE_PACK_EXPANSION:
4016 case EXPR_PACK_EXPANSION:
4017 *walk_subtrees = 0;
4018 return NULL_TREE;
4020 case INTEGER_TYPE:
4021 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4022 ppd, ppd->visited);
4023 *walk_subtrees = 0;
4024 return NULL_TREE;
4026 case IDENTIFIER_NODE:
4027 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4028 ppd->visited);
4029 *walk_subtrees = 0;
4030 return NULL_TREE;
4032 case LAMBDA_EXPR:
4034 /* Since we defer implicit capture, look in the parms and body. */
4035 tree fn = lambda_function (t);
4036 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4037 ppd->visited);
4038 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4039 ppd->visited);
4040 return NULL_TREE;
4043 case DECLTYPE_TYPE:
4045 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4046 type_pack_expansion_p to false so that any placeholders
4047 within the expression don't get marked as parameter packs. */
4048 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4049 ppd->type_pack_expansion_p = false;
4050 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4051 ppd, ppd->visited);
4052 ppd->type_pack_expansion_p = type_pack_expansion_p;
4053 *walk_subtrees = 0;
4054 return NULL_TREE;
4057 case IF_STMT:
4058 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4059 ppd, ppd->visited);
4060 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4061 ppd, ppd->visited);
4062 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4063 ppd, ppd->visited);
4064 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4065 *walk_subtrees = 0;
4066 return NULL_TREE;
4068 case TAG_DEFN:
4069 t = TREE_TYPE (t);
4070 if (CLASS_TYPE_P (t))
4072 /* Local class, need to look through the whole definition.
4073 TYPE_BINFO might be unset for a partial instantiation. */
4074 if (TYPE_BINFO (t))
4075 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4076 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4077 ppd, ppd->visited);
4079 else
4080 /* Enum, look at the values. */
4081 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4082 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4083 &find_parameter_packs_r,
4084 ppd, ppd->visited);
4085 return NULL_TREE;
4087 case FUNCTION_TYPE:
4088 case METHOD_TYPE:
4089 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4090 break;
4092 default:
4093 return NULL_TREE;
4096 #undef WALK_SUBTREE
4098 return NULL_TREE;
4101 /* Determines if the expression or type T uses any parameter packs. */
4102 tree
4103 uses_parameter_packs (tree t)
4105 tree parameter_packs = NULL_TREE;
4106 struct find_parameter_pack_data ppd;
4107 ppd.parameter_packs = &parameter_packs;
4108 ppd.visited = new hash_set<tree>;
4109 ppd.type_pack_expansion_p = false;
4110 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4111 delete ppd.visited;
4112 return parameter_packs;
4115 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4116 representation a base-class initializer into a parameter pack
4117 expansion. If all goes well, the resulting node will be an
4118 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4119 respectively. */
4120 tree
4121 make_pack_expansion (tree arg, tsubst_flags_t complain)
4123 tree result;
4124 tree parameter_packs = NULL_TREE;
4125 bool for_types = false;
4126 struct find_parameter_pack_data ppd;
4128 if (!arg || arg == error_mark_node)
4129 return arg;
4131 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4133 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4134 class initializer. In this case, the TREE_PURPOSE will be a
4135 _TYPE node (representing the base class expansion we're
4136 initializing) and the TREE_VALUE will be a TREE_LIST
4137 containing the initialization arguments.
4139 The resulting expansion looks somewhat different from most
4140 expansions. Rather than returning just one _EXPANSION, we
4141 return a TREE_LIST whose TREE_PURPOSE is a
4142 TYPE_PACK_EXPANSION containing the bases that will be
4143 initialized. The TREE_VALUE will be identical to the
4144 original TREE_VALUE, which is a list of arguments that will
4145 be passed to each base. We do not introduce any new pack
4146 expansion nodes into the TREE_VALUE (although it is possible
4147 that some already exist), because the TREE_PURPOSE and
4148 TREE_VALUE all need to be expanded together with the same
4149 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4150 resulting TREE_PURPOSE will mention the parameter packs in
4151 both the bases and the arguments to the bases. */
4152 tree purpose;
4153 tree value;
4154 tree parameter_packs = NULL_TREE;
4156 /* Determine which parameter packs will be used by the base
4157 class expansion. */
4158 ppd.visited = new hash_set<tree>;
4159 ppd.parameter_packs = &parameter_packs;
4160 ppd.type_pack_expansion_p = false;
4161 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4162 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4163 &ppd, ppd.visited);
4165 if (parameter_packs == NULL_TREE)
4167 if (complain & tf_error)
4168 error ("base initializer expansion %qT contains no parameter packs",
4169 arg);
4170 delete ppd.visited;
4171 return error_mark_node;
4174 if (TREE_VALUE (arg) != void_type_node)
4176 /* Collect the sets of parameter packs used in each of the
4177 initialization arguments. */
4178 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4180 /* Determine which parameter packs will be expanded in this
4181 argument. */
4182 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4183 &ppd, ppd.visited);
4187 delete ppd.visited;
4189 /* Create the pack expansion type for the base type. */
4190 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4191 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4192 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4193 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4195 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4196 they will rarely be compared to anything. */
4197 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4199 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4202 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4203 for_types = true;
4205 /* Build the PACK_EXPANSION_* node. */
4206 result = for_types
4207 ? cxx_make_type (TYPE_PACK_EXPANSION)
4208 : make_node (EXPR_PACK_EXPANSION);
4209 PACK_EXPANSION_PATTERN (result) = arg;
4210 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4212 /* Propagate type and const-expression information. */
4213 TREE_TYPE (result) = TREE_TYPE (arg);
4214 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4215 /* Mark this read now, since the expansion might be length 0. */
4216 mark_exp_read (arg);
4218 else
4219 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4220 they will rarely be compared to anything. */
4221 SET_TYPE_STRUCTURAL_EQUALITY (result);
4223 /* Determine which parameter packs will be expanded. */
4224 ppd.parameter_packs = &parameter_packs;
4225 ppd.visited = new hash_set<tree>;
4226 ppd.type_pack_expansion_p = TYPE_P (arg);
4227 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4228 delete ppd.visited;
4230 /* Make sure we found some parameter packs. */
4231 if (parameter_packs == NULL_TREE)
4233 if (complain & tf_error)
4235 if (TYPE_P (arg))
4236 error ("expansion pattern %qT contains no parameter packs", arg);
4237 else
4238 error ("expansion pattern %qE contains no parameter packs", arg);
4240 return error_mark_node;
4242 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4244 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4245 if (ppd.found_extra_args_tree_p)
4246 /* If the pattern of this pack expansion contains a subtree that has
4247 the extra args mechanism for avoiding partial instantiation, then
4248 force this pack expansion to also use extra args. Otherwise
4249 partial instantiation of this pack expansion may not lower the
4250 level of some parameter packs within the pattern, which would
4251 confuse tsubst_pack_expansion later (PR101764). */
4252 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4254 return result;
4257 /* Checks T for any "bare" parameter packs, which have not yet been
4258 expanded, and issues an error if any are found. This operation can
4259 only be done on full expressions or types (e.g., an expression
4260 statement, "if" condition, etc.), because we could have expressions like:
4262 foo(f(g(h(args)))...)
4264 where "args" is a parameter pack. check_for_bare_parameter_packs
4265 should not be called for the subexpressions args, h(args),
4266 g(h(args)), or f(g(h(args))), because we would produce erroneous
4267 error messages.
4269 Returns TRUE and emits an error if there were bare parameter packs,
4270 returns FALSE otherwise. */
4271 bool
4272 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4274 tree parameter_packs = NULL_TREE;
4275 struct find_parameter_pack_data ppd;
4277 if (!processing_template_decl || !t || t == error_mark_node)
4278 return false;
4280 if (TREE_CODE (t) == TYPE_DECL)
4281 t = TREE_TYPE (t);
4283 ppd.parameter_packs = &parameter_packs;
4284 ppd.visited = new hash_set<tree>;
4285 ppd.type_pack_expansion_p = false;
4286 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4287 delete ppd.visited;
4289 if (!parameter_packs)
4290 return false;
4292 if (loc == UNKNOWN_LOCATION)
4293 loc = cp_expr_loc_or_input_loc (t);
4295 /* It's OK for a lambda to have an unexpanded parameter pack from the
4296 containing context, but do complain about unexpanded capture packs. */
4297 tree lam = current_lambda_expr ();
4298 if (lam)
4299 lam = TREE_TYPE (lam);
4301 if (lam && lam != current_class_type)
4303 /* We're in a lambda, but it isn't the innermost class.
4304 This should work, but currently doesn't. */
4305 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4306 return true;
4309 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4310 for (; parameter_packs;
4311 parameter_packs = TREE_CHAIN (parameter_packs))
4313 tree pack = TREE_VALUE (parameter_packs);
4314 if (is_capture_proxy (pack)
4315 || (TREE_CODE (pack) == PARM_DECL
4316 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4317 break;
4320 if (parameter_packs)
4322 error_at (loc, "parameter packs not expanded with %<...%>:");
4323 while (parameter_packs)
4325 tree pack = TREE_VALUE (parameter_packs);
4326 tree name = NULL_TREE;
4328 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4329 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4330 name = TYPE_NAME (pack);
4331 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4332 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4333 else if (TREE_CODE (pack) == CALL_EXPR)
4334 name = DECL_NAME (CALL_EXPR_FN (pack));
4335 else
4336 name = DECL_NAME (pack);
4338 if (name)
4339 inform (loc, " %qD", name);
4340 else
4341 inform (loc, " %s", "<anonymous>");
4343 parameter_packs = TREE_CHAIN (parameter_packs);
4346 return true;
4349 return false;
4352 /* Expand any parameter packs that occur in the template arguments in
4353 ARGS. */
4354 tree
4355 expand_template_argument_pack (tree args)
4357 if (args == error_mark_node)
4358 return error_mark_node;
4360 tree result_args = NULL_TREE;
4361 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4362 int num_result_args = -1;
4363 int non_default_args_count = -1;
4365 /* First, determine if we need to expand anything, and the number of
4366 slots we'll need. */
4367 for (in_arg = 0; in_arg < nargs; ++in_arg)
4369 tree arg = TREE_VEC_ELT (args, in_arg);
4370 if (arg == NULL_TREE)
4371 return args;
4372 if (ARGUMENT_PACK_P (arg))
4374 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4375 if (num_result_args < 0)
4376 num_result_args = in_arg + num_packed;
4377 else
4378 num_result_args += num_packed;
4380 else
4382 if (num_result_args >= 0)
4383 num_result_args++;
4387 /* If no expansion is necessary, we're done. */
4388 if (num_result_args < 0)
4389 return args;
4391 /* Expand arguments. */
4392 result_args = make_tree_vec (num_result_args);
4393 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4394 non_default_args_count =
4395 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4396 for (in_arg = 0; in_arg < nargs; ++in_arg)
4398 tree arg = TREE_VEC_ELT (args, in_arg);
4399 if (ARGUMENT_PACK_P (arg))
4401 tree packed = ARGUMENT_PACK_ARGS (arg);
4402 int i, num_packed = TREE_VEC_LENGTH (packed);
4403 for (i = 0; i < num_packed; ++i, ++out_arg)
4404 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4405 if (non_default_args_count > 0)
4406 non_default_args_count += num_packed - 1;
4408 else
4410 TREE_VEC_ELT (result_args, out_arg) = arg;
4411 ++out_arg;
4414 if (non_default_args_count >= 0)
4415 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4416 return result_args;
4419 /* Checks if DECL shadows a template parameter.
4421 [temp.local]: A template-parameter shall not be redeclared within its
4422 scope (including nested scopes).
4424 Emits an error and returns TRUE if the DECL shadows a parameter,
4425 returns FALSE otherwise. */
4427 bool
4428 check_template_shadow (tree decl)
4430 tree olddecl;
4432 /* If we're not in a template, we can't possibly shadow a template
4433 parameter. */
4434 if (!current_template_parms)
4435 return true;
4437 /* Figure out what we're shadowing. */
4438 decl = OVL_FIRST (decl);
4439 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4441 /* If there's no previous binding for this name, we're not shadowing
4442 anything, let alone a template parameter. */
4443 if (!olddecl)
4444 return true;
4446 /* If we're not shadowing a template parameter, we're done. Note
4447 that OLDDECL might be an OVERLOAD (or perhaps even an
4448 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4449 node. */
4450 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4451 return true;
4453 /* We check for decl != olddecl to avoid bogus errors for using a
4454 name inside a class. We check TPFI to avoid duplicate errors for
4455 inline member templates. */
4456 if (decl == olddecl
4457 || (DECL_TEMPLATE_PARM_P (decl)
4458 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4459 return true;
4461 /* Don't complain about the injected class name, as we've already
4462 complained about the class itself. */
4463 if (DECL_SELF_REFERENCE_P (decl))
4464 return false;
4466 if (DECL_TEMPLATE_PARM_P (decl))
4467 error ("declaration of template parameter %q+D shadows "
4468 "template parameter", decl);
4469 else
4470 error ("declaration of %q+#D shadows template parameter", decl);
4471 inform (DECL_SOURCE_LOCATION (olddecl),
4472 "template parameter %qD declared here", olddecl);
4473 return false;
4476 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4477 ORIG_LEVEL, DECL, and TYPE. */
4479 static tree
4480 build_template_parm_index (int index,
4481 int level,
4482 int orig_level,
4483 tree decl,
4484 tree type)
4486 tree t = make_node (TEMPLATE_PARM_INDEX);
4487 TEMPLATE_PARM_IDX (t) = index;
4488 TEMPLATE_PARM_LEVEL (t) = level;
4489 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4490 TEMPLATE_PARM_DECL (t) = decl;
4491 TREE_TYPE (t) = type;
4492 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4493 TREE_READONLY (t) = TREE_READONLY (decl);
4495 return t;
4498 struct ctp_hasher : ggc_ptr_hash<tree_node>
4500 static hashval_t hash (tree t)
4502 ++comparing_specializations;
4503 tree_code code = TREE_CODE (t);
4504 hashval_t val = iterative_hash_object (code, 0);
4505 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4506 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4507 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
4508 val = iterative_hash_template_arg (CLASS_PLACEHOLDER_TEMPLATE (t), val);
4509 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4510 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4511 --comparing_specializations;
4512 return val;
4515 static bool equal (tree t, tree u)
4517 ++comparing_specializations;
4518 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4519 --comparing_specializations;
4520 return eq;
4524 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4526 /* Find the canonical type parameter for the given template type
4527 parameter. Returns the canonical type parameter, which may be TYPE
4528 if no such parameter existed. */
4530 tree
4531 canonical_type_parameter (tree type)
4533 if (ctp_table == NULL)
4534 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4536 tree& slot = *ctp_table->find_slot (type, INSERT);
4537 if (slot == NULL_TREE)
4538 slot = type;
4539 return slot;
4542 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4543 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4544 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4545 new one is created. */
4547 static tree
4548 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4549 tsubst_flags_t complain)
4551 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4552 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4553 != TEMPLATE_PARM_LEVEL (index) - levels)
4554 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4556 tree orig_decl = TEMPLATE_PARM_DECL (index);
4558 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4559 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4560 type);
4561 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4562 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4563 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4564 DECL_ARTIFICIAL (decl) = 1;
4565 SET_DECL_TEMPLATE_PARM_P (decl);
4567 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4568 TEMPLATE_PARM_LEVEL (index) - levels,
4569 TEMPLATE_PARM_ORIG_LEVEL (index),
4570 decl, type);
4571 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4572 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4573 = TEMPLATE_PARM_PARAMETER_PACK (index);
4575 /* Template template parameters need this. */
4576 tree inner = decl;
4577 if (TREE_CODE (decl) == TEMPLATE_DECL)
4579 inner = build_lang_decl_loc (DECL_SOURCE_LOCATION (decl),
4580 TYPE_DECL, DECL_NAME (decl), type);
4581 DECL_TEMPLATE_RESULT (decl) = inner;
4582 DECL_ARTIFICIAL (inner) = true;
4583 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (orig_decl),
4584 args, complain);
4585 DECL_TEMPLATE_PARMS (decl) = parms;
4586 tree orig_inner = DECL_TEMPLATE_RESULT (orig_decl);
4587 DECL_TEMPLATE_INFO (inner)
4588 = build_template_info (DECL_TI_TEMPLATE (orig_inner),
4589 template_parms_to_args (parms));
4592 /* Attach the TPI to the decl. */
4593 if (TREE_CODE (inner) == TYPE_DECL)
4594 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4595 else
4596 DECL_INITIAL (decl) = tpi;
4599 return TEMPLATE_PARM_DESCENDANTS (index);
4602 /* Process information from new template parameter PARM and append it
4603 to the LIST being built. This new parameter is a non-type
4604 parameter iff IS_NON_TYPE is true. This new parameter is a
4605 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4606 is in PARM_LOC. */
4608 tree
4609 process_template_parm (tree list, location_t parm_loc, tree parm,
4610 bool is_non_type, bool is_parameter_pack)
4612 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4613 tree prev = NULL_TREE;
4614 int idx = 0;
4616 if (list)
4618 prev = tree_last (list);
4620 tree p = TREE_VALUE (prev);
4621 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4622 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4623 else if (TREE_CODE (p) == PARM_DECL)
4624 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4626 ++idx;
4629 tree decl = NULL_TREE;
4630 tree defval = TREE_PURPOSE (parm);
4631 tree constr = TREE_TYPE (parm);
4633 if (is_non_type)
4635 parm = TREE_VALUE (parm);
4637 SET_DECL_TEMPLATE_PARM_P (parm);
4639 if (TREE_TYPE (parm) != error_mark_node)
4641 /* [temp.param]
4643 The top-level cv-qualifiers on the template-parameter are
4644 ignored when determining its type. */
4645 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4646 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4647 TREE_TYPE (parm) = error_mark_node;
4648 else if (uses_parameter_packs (TREE_TYPE (parm))
4649 && !is_parameter_pack
4650 /* If we're in a nested template parameter list, the template
4651 template parameter could be a parameter pack. */
4652 && processing_template_parmlist == 1)
4654 /* This template parameter is not a parameter pack, but it
4655 should be. Complain about "bare" parameter packs. */
4656 check_for_bare_parameter_packs (TREE_TYPE (parm));
4658 /* Recover by calling this a parameter pack. */
4659 is_parameter_pack = true;
4663 /* A template parameter is not modifiable. */
4664 TREE_CONSTANT (parm) = 1;
4665 TREE_READONLY (parm) = 1;
4666 decl = build_decl (parm_loc,
4667 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4668 TREE_CONSTANT (decl) = 1;
4669 TREE_READONLY (decl) = 1;
4670 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4671 = build_template_parm_index (idx, current_template_depth,
4672 current_template_depth,
4673 decl, TREE_TYPE (parm));
4675 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4676 = is_parameter_pack;
4678 else
4680 tree t;
4681 parm = TREE_VALUE (TREE_VALUE (parm));
4683 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4685 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4686 /* This is for distinguishing between real templates and template
4687 template parameters */
4688 TREE_TYPE (parm) = t;
4690 /* any_template_parm_r expects to be able to get the targs of a
4691 DECL_TEMPLATE_RESULT. */
4692 tree result = DECL_TEMPLATE_RESULT (parm);
4693 TREE_TYPE (result) = t;
4694 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4695 tree tinfo = build_template_info (parm, args);
4696 retrofit_lang_decl (result);
4697 DECL_TEMPLATE_INFO (result) = tinfo;
4699 decl = parm;
4701 else
4703 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4704 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4705 decl = build_decl (parm_loc,
4706 TYPE_DECL, parm, t);
4709 TYPE_NAME (t) = decl;
4710 TYPE_STUB_DECL (t) = decl;
4711 parm = decl;
4712 TEMPLATE_TYPE_PARM_INDEX (t)
4713 = build_template_parm_index (idx, current_template_depth,
4714 current_template_depth,
4715 decl, TREE_TYPE (parm));
4716 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4717 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4719 DECL_ARTIFICIAL (decl) = 1;
4720 SET_DECL_TEMPLATE_PARM_P (decl);
4722 if (TREE_CODE (parm) == TEMPLATE_DECL
4723 && !uses_outer_template_parms (parm))
4724 TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
4726 /* Build requirements for the type/template parameter.
4727 This must be done after SET_DECL_TEMPLATE_PARM_P or
4728 process_template_parm could fail. */
4729 tree reqs = finish_shorthand_constraint (parm, constr);
4731 decl = pushdecl (decl);
4732 if (!is_non_type)
4733 parm = decl;
4735 /* Build the parameter node linking the parameter declaration,
4736 its default argument (if any), and its constraints (if any). */
4737 parm = build_tree_list (defval, parm);
4738 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4740 if (prev)
4741 TREE_CHAIN (prev) = parm;
4742 else
4743 list = parm;
4745 return list;
4748 /* The end of a template parameter list has been reached. Process the
4749 tree list into a parameter vector, converting each parameter into a more
4750 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4751 as PARM_DECLs. */
4753 tree
4754 end_template_parm_list (tree parms)
4756 tree saved_parmlist = make_tree_vec (list_length (parms));
4758 /* Pop the dummy parameter level and add the real one. We do not
4759 morph the dummy parameter in place, as it might have been
4760 captured by a (nested) template-template-parm. */
4761 current_template_parms = TREE_CHAIN (current_template_parms);
4763 current_template_parms
4764 = tree_cons (size_int (current_template_depth + 1),
4765 saved_parmlist, current_template_parms);
4767 for (unsigned ix = 0; parms; ix++)
4769 tree parm = parms;
4770 parms = TREE_CHAIN (parms);
4771 TREE_CHAIN (parm) = NULL_TREE;
4773 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4776 --processing_template_parmlist;
4778 return saved_parmlist;
4781 // Explicitly indicate the end of the template parameter list. We assume
4782 // that the current template parameters have been constructed and/or
4783 // managed explicitly, as when creating new template template parameters
4784 // from a shorthand constraint.
4785 void
4786 end_template_parm_list ()
4788 --processing_template_parmlist;
4791 /* end_template_decl is called after a template declaration is seen. */
4793 void
4794 end_template_decl (void)
4796 reset_specialization ();
4798 if (! processing_template_decl)
4799 return;
4801 /* This matches the pushlevel in begin_template_parm_list. */
4802 finish_scope ();
4804 --processing_template_decl;
4805 current_template_parms = TREE_CHAIN (current_template_parms);
4808 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4809 thereof, and converts it into an argument suitable to be passed to
4810 the type substitution functions. Note that if the TREE_LIST contains
4811 an error_mark node, the returned argument is error_mark_node. */
4813 tree
4814 template_parm_to_arg (tree t)
4816 if (!t)
4817 return NULL_TREE;
4819 if (TREE_CODE (t) == TREE_LIST)
4820 t = TREE_VALUE (t);
4822 if (error_operand_p (t))
4823 return error_mark_node;
4825 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4827 if (TREE_CODE (t) == TYPE_DECL
4828 || TREE_CODE (t) == TEMPLATE_DECL)
4829 t = TREE_TYPE (t);
4830 else
4831 t = DECL_INITIAL (t);
4834 gcc_assert (TEMPLATE_PARM_P (t));
4836 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4837 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4839 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4841 /* Turn this argument into a TYPE_ARGUMENT_PACK
4842 with a single element, which expands T. */
4843 tree vec = make_tree_vec (1);
4844 if (CHECKING_P)
4845 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4847 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4849 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4850 ARGUMENT_PACK_ARGS (t) = vec;
4853 else
4855 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4857 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4858 with a single element, which expands T. */
4859 tree vec = make_tree_vec (1);
4860 if (CHECKING_P)
4861 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4863 t = convert_from_reference (t);
4864 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4866 t = make_node (NONTYPE_ARGUMENT_PACK);
4867 ARGUMENT_PACK_ARGS (t) = vec;
4869 else
4870 t = convert_from_reference (t);
4872 return t;
4875 /* If T looks like a generic template argument produced by template_parm_to_arg,
4876 return the corresponding template parameter, otherwise return NULL_TREE. */
4878 static tree
4879 template_arg_to_parm (tree t)
4881 if (t == NULL_TREE)
4882 return NULL_TREE;
4884 if (ARGUMENT_PACK_P (t))
4886 tree args = ARGUMENT_PACK_ARGS (t);
4887 if (TREE_VEC_LENGTH (args) == 1
4888 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4889 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4892 if (REFERENCE_REF_P (t))
4893 t = TREE_OPERAND (t, 0);
4895 if (TEMPLATE_PARM_P (t))
4896 return t;
4897 else
4898 return NULL_TREE;
4901 /* Given a single level of template parameters (a TREE_VEC), return it
4902 as a set of template arguments. */
4904 tree
4905 template_parms_level_to_args (tree parms)
4907 parms = copy_node (parms);
4908 TREE_TYPE (parms) = NULL_TREE;
4909 for (tree& parm : tree_vec_range (parms))
4910 parm = template_parm_to_arg (parm);
4912 if (CHECKING_P)
4913 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4915 return parms;
4918 /* Given a set of template parameters, return them as a set of template
4919 arguments. The template parameters are represented as a TREE_VEC, in
4920 the form documented in cp-tree.h for template arguments. */
4922 tree
4923 template_parms_to_args (tree parms)
4925 tree header;
4926 tree args = NULL_TREE;
4927 int length = TMPL_PARMS_DEPTH (parms);
4928 int l = length;
4930 /* If there is only one level of template parameters, we do not
4931 create a TREE_VEC of TREE_VECs. Instead, we return a single
4932 TREE_VEC containing the arguments. */
4933 if (length > 1)
4934 args = make_tree_vec (length);
4936 for (header = parms; header; header = TREE_CHAIN (header))
4938 tree a = template_parms_level_to_args (TREE_VALUE (header));
4940 if (length > 1)
4941 TREE_VEC_ELT (args, --l) = a;
4942 else
4943 args = a;
4946 return args;
4949 /* Within the declaration of a template, return the currently active
4950 template parameters as an argument TREE_VEC. */
4952 static tree
4953 current_template_args (void)
4955 return template_parms_to_args (current_template_parms);
4958 /* Return the fully generic arguments for of TMPL, i.e. what
4959 current_template_args would be while parsing it. */
4961 tree
4962 generic_targs_for (tree tmpl)
4964 if (tmpl == NULL_TREE)
4965 return NULL_TREE;
4966 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4967 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4968 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4969 template parameter, it has no TEMPLATE_INFO; for a partial
4970 specialization, it has the arguments for the primary template, and we
4971 want the arguments for the partial specialization. */;
4972 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4973 if (tree ti = get_template_info (result))
4974 return TI_ARGS (ti);
4975 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4978 /* Return the template arguments corresponding to the template parameters of
4979 DECL's enclosing scope. When DECL is a member of a partial specialization,
4980 this returns the arguments for the partial specialization as opposed to those
4981 for the primary template, which is the main difference between this function
4982 and simply using e.g. the TYPE_TI_ARGS of DECL's DECL_CONTEXT. */
4984 tree
4985 outer_template_args (const_tree decl)
4987 if (TREE_CODE (decl) == TEMPLATE_DECL)
4988 decl = DECL_TEMPLATE_RESULT (decl);
4989 tree ti = get_template_info (decl);
4990 if (!ti)
4991 return NULL_TREE;
4992 tree args = TI_ARGS (ti);
4993 if (!PRIMARY_TEMPLATE_P (TI_TEMPLATE (ti)))
4994 return args;
4995 if (TMPL_ARGS_DEPTH (args) == 1)
4996 return NULL_TREE;
4997 return strip_innermost_template_args (args, 1);
5000 /* Update the declared TYPE by doing any lookups which were thought to be
5001 dependent, but are not now that we know the SCOPE of the declarator. */
5003 tree
5004 maybe_update_decl_type (tree orig_type, tree scope)
5006 tree type = orig_type;
5008 if (type == NULL_TREE)
5009 return type;
5011 if (TREE_CODE (orig_type) == TYPE_DECL)
5012 type = TREE_TYPE (type);
5014 if (scope && TYPE_P (scope) && dependent_type_p (scope)
5015 && dependent_type_p (type)
5016 /* Don't bother building up the args in this case. */
5017 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5019 /* tsubst in the args corresponding to the template parameters,
5020 including auto if present. Most things will be unchanged, but
5021 make_typename_type and tsubst_qualified_id will resolve
5022 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5023 tree args = current_template_args ();
5024 tree auto_node = type_uses_auto (type);
5025 tree pushed;
5026 if (auto_node)
5028 tree auto_vec = make_tree_vec (1);
5029 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5030 args = add_to_template_args (args, auto_vec);
5032 pushed = push_scope (scope);
5033 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5034 if (pushed)
5035 pop_scope (scope);
5038 if (type == error_mark_node)
5039 return orig_type;
5041 if (TREE_CODE (orig_type) == TYPE_DECL)
5043 if (same_type_p (type, TREE_TYPE (orig_type)))
5044 type = orig_type;
5045 else
5046 type = TYPE_NAME (type);
5048 return type;
5051 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5052 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5053 the new template is a member template. */
5055 static tree
5056 build_template_decl (tree decl, tree parms, bool member_template_p)
5058 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5060 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5061 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5062 DECL_TEMPLATE_PARMS (tmpl) = parms;
5063 DECL_TEMPLATE_RESULT (tmpl) = decl;
5064 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5065 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5066 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5067 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5069 /* Propagate module information from the decl. */
5070 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5072 return tmpl;
5075 struct template_parm_data
5077 /* The level of the template parameters we are currently
5078 processing. */
5079 int level;
5081 /* The index of the specialization argument we are currently
5082 processing. */
5083 int current_arg;
5085 /* An array whose size is the number of template parameters. The
5086 elements are nonzero if the parameter has been used in any one
5087 of the arguments processed so far. */
5088 int* parms;
5090 /* An array whose size is the number of template arguments. The
5091 elements are nonzero if the argument makes use of template
5092 parameters of this level. */
5093 int* arg_uses_template_parms;
5096 /* Subroutine of push_template_decl used to see if each template
5097 parameter in a partial specialization is used in the explicit
5098 argument list. If T is of the LEVEL given in DATA (which is
5099 treated as a template_parm_data*), then DATA->PARMS is marked
5100 appropriately. */
5102 static int
5103 mark_template_parm (tree t, void* data)
5105 int level;
5106 int idx;
5107 struct template_parm_data* tpd = (struct template_parm_data*) data;
5109 template_parm_level_and_index (t, &level, &idx);
5111 if (level == tpd->level)
5113 tpd->parms[idx] = 1;
5114 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5117 /* In C++17 the type of a non-type argument is a deduced context. */
5118 if (cxx_dialect >= cxx17
5119 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5120 for_each_template_parm (TREE_TYPE (t),
5121 &mark_template_parm,
5122 data,
5123 NULL,
5124 /*include_nondeduced_p=*/false);
5126 /* Return zero so that for_each_template_parm will continue the
5127 traversal of the tree; we want to mark *every* template parm. */
5128 return 0;
5131 /* Process the partial specialization DECL. */
5133 static tree
5134 process_partial_specialization (tree decl)
5136 tree type = TREE_TYPE (decl);
5137 tree tinfo = get_template_info (decl);
5138 tree maintmpl = TI_TEMPLATE (tinfo);
5139 tree specargs = TI_ARGS (tinfo);
5140 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5141 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5142 tree inner_parms;
5143 tree inst;
5144 int nargs = TREE_VEC_LENGTH (inner_args);
5145 int ntparms;
5146 int i;
5147 bool did_error_intro = false;
5148 struct template_parm_data tpd;
5149 struct template_parm_data tpd2;
5151 gcc_assert (current_template_parms);
5153 /* A concept cannot be specialized. */
5154 if (flag_concepts && variable_concept_p (maintmpl))
5156 error ("specialization of variable concept %q#D", maintmpl);
5157 return error_mark_node;
5160 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5161 ntparms = TREE_VEC_LENGTH (inner_parms);
5163 /* We check that each of the template parameters given in the
5164 partial specialization is used in the argument list to the
5165 specialization. For example:
5167 template <class T> struct S;
5168 template <class T> struct S<T*>;
5170 The second declaration is OK because `T*' uses the template
5171 parameter T, whereas
5173 template <class T> struct S<int>;
5175 is no good. Even trickier is:
5177 template <class T>
5178 struct S1
5180 template <class U>
5181 struct S2;
5182 template <class U>
5183 struct S2<T>;
5186 The S2<T> declaration is actually invalid; it is a
5187 full-specialization. Of course,
5189 template <class U>
5190 struct S2<T (*)(U)>;
5192 or some such would have been OK. */
5193 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5194 tpd.parms = XALLOCAVEC (int, ntparms);
5195 memset (tpd.parms, 0, sizeof (int) * ntparms);
5197 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5198 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5199 for (i = 0; i < nargs; ++i)
5201 tpd.current_arg = i;
5202 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5203 &mark_template_parm,
5204 &tpd,
5205 NULL,
5206 /*include_nondeduced_p=*/false);
5208 for (i = 0; i < ntparms; ++i)
5209 if (tpd.parms[i] == 0)
5211 /* One of the template parms was not used in a deduced context in the
5212 specialization. */
5213 if (!did_error_intro)
5215 error ("template parameters not deducible in "
5216 "partial specialization:");
5217 did_error_intro = true;
5220 inform (input_location, " %qD",
5221 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5224 if (did_error_intro)
5225 return error_mark_node;
5227 /* [temp.class.spec]
5229 The argument list of the specialization shall not be identical to
5230 the implicit argument list of the primary template. */
5231 tree main_args
5232 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5233 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5234 && (!flag_concepts
5235 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5237 if (!flag_concepts)
5238 error ("partial specialization %q+D does not specialize "
5239 "any template arguments; to define the primary template, "
5240 "remove the template argument list", decl);
5241 else
5242 error ("partial specialization %q+D does not specialize any "
5243 "template arguments and is not more constrained than "
5244 "the primary template; to define the primary template, "
5245 "remove the template argument list", decl);
5246 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5249 /* A partial specialization that replaces multiple parameters of the
5250 primary template with a pack expansion is less specialized for those
5251 parameters. */
5252 if (nargs < DECL_NTPARMS (maintmpl))
5254 error ("partial specialization is not more specialized than the "
5255 "primary template because it replaces multiple parameters "
5256 "with a pack expansion");
5257 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5258 /* Avoid crash in process_partial_specialization. */
5259 return decl;
5262 else if (nargs > DECL_NTPARMS (maintmpl))
5264 error ("too many arguments for partial specialization %qT", type);
5265 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5266 /* Avoid crash below. */
5267 return decl;
5270 /* If we aren't in a dependent class, we can actually try deduction. */
5271 else if (tpd.level == 1
5272 /* FIXME we should be able to handle a partial specialization of a
5273 partial instantiation, but currently we can't (c++/41727). */
5274 && TMPL_ARGS_DEPTH (specargs) == 1
5275 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5277 auto_diagnostic_group d;
5278 if (pedwarn (input_location, 0,
5279 "partial specialization %qD is not more specialized than",
5280 decl))
5281 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5282 maintmpl);
5285 /* [temp.spec.partial]
5287 The type of a template parameter corresponding to a specialized
5288 non-type argument shall not be dependent on a parameter of the
5289 specialization.
5291 Also, we verify that pack expansions only occur at the
5292 end of the argument list. */
5293 tpd2.parms = 0;
5294 for (i = 0; i < nargs; ++i)
5296 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5297 tree arg = TREE_VEC_ELT (inner_args, i);
5298 tree packed_args = NULL_TREE;
5299 int j, len = 1;
5301 if (ARGUMENT_PACK_P (arg))
5303 /* Extract the arguments from the argument pack. We'll be
5304 iterating over these in the following loop. */
5305 packed_args = ARGUMENT_PACK_ARGS (arg);
5306 len = TREE_VEC_LENGTH (packed_args);
5309 for (j = 0; j < len; j++)
5311 if (packed_args)
5312 /* Get the Jth argument in the parameter pack. */
5313 arg = TREE_VEC_ELT (packed_args, j);
5315 if (PACK_EXPANSION_P (arg))
5317 /* Pack expansions must come at the end of the
5318 argument list. */
5319 if ((packed_args && j < len - 1)
5320 || (!packed_args && i < nargs - 1))
5322 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5323 error ("parameter pack argument %qE must be at the "
5324 "end of the template argument list", arg);
5325 else
5326 error ("parameter pack argument %qT must be at the "
5327 "end of the template argument list", arg);
5331 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5332 /* We only care about the pattern. */
5333 arg = PACK_EXPANSION_PATTERN (arg);
5335 if (/* These first two lines are the `non-type' bit. */
5336 !TYPE_P (arg)
5337 && TREE_CODE (arg) != TEMPLATE_DECL
5338 /* This next two lines are the `argument expression is not just a
5339 simple identifier' condition and also the `specialized
5340 non-type argument' bit. */
5341 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5342 && !((REFERENCE_REF_P (arg)
5343 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5344 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5346 /* Look at the corresponding template parameter,
5347 marking which template parameters its type depends
5348 upon. */
5349 tree type = TREE_TYPE (parm);
5351 if (!tpd2.parms)
5353 /* We haven't yet initialized TPD2. Do so now. */
5354 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5355 /* The number of parameters here is the number in the
5356 main template, which, as checked in the assertion
5357 above, is NARGS. */
5358 tpd2.parms = XALLOCAVEC (int, nargs);
5359 tpd2.level =
5360 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5363 /* Mark the template parameters. But this time, we're
5364 looking for the template parameters of the main
5365 template, not in the specialization. */
5366 tpd2.current_arg = i;
5367 tpd2.arg_uses_template_parms[i] = 0;
5368 memset (tpd2.parms, 0, sizeof (int) * nargs);
5369 for_each_template_parm (type,
5370 &mark_template_parm,
5371 &tpd2,
5372 NULL,
5373 /*include_nondeduced_p=*/false);
5375 if (tpd2.arg_uses_template_parms [i])
5377 /* The type depended on some template parameters.
5378 If they are fully specialized in the
5379 specialization, that's OK. */
5380 int j;
5381 int count = 0;
5382 for (j = 0; j < nargs; ++j)
5383 if (tpd2.parms[j] != 0
5384 && tpd.arg_uses_template_parms [j])
5385 ++count;
5386 if (count != 0)
5387 error_n (input_location, count,
5388 "type %qT of template argument %qE depends "
5389 "on a template parameter",
5390 "type %qT of template argument %qE depends "
5391 "on template parameters",
5392 type,
5393 arg);
5399 /* We should only get here once. */
5400 if (TREE_CODE (decl) == TYPE_DECL)
5401 gcc_assert (!COMPLETE_TYPE_P (type));
5403 // Build the template decl.
5404 tree tmpl = build_template_decl (decl, current_template_parms,
5405 DECL_MEMBER_TEMPLATE_P (maintmpl));
5406 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5407 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5408 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5410 /* Give template template parms a DECL_CONTEXT of the template
5411 for which they are a parameter. */
5412 for (i = 0; i < ntparms; ++i)
5414 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5415 if (TREE_CODE (parm) == TEMPLATE_DECL)
5416 DECL_CONTEXT (parm) = tmpl;
5419 if (VAR_P (decl))
5420 /* We didn't register this in check_explicit_specialization so we could
5421 wait until the constraints were set. */
5422 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5423 else
5424 associate_classtype_constraints (type);
5426 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5427 = tree_cons (specargs, tmpl,
5428 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5429 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5430 /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL. */
5431 gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
5432 TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
5434 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5435 inst = TREE_CHAIN (inst))
5437 tree instance = TREE_VALUE (inst);
5438 if (TYPE_P (instance)
5439 ? (COMPLETE_TYPE_P (instance)
5440 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5441 : DECL_TEMPLATE_INSTANTIATION (instance))
5443 tree partial_ti = most_specialized_partial_spec (instance, tf_none,
5444 /*rechecking=*/true);
5445 tree inst_decl = (DECL_P (instance)
5446 ? instance : TYPE_NAME (instance));
5447 if (!partial_ti)
5448 /* OK */;
5449 else if (partial_ti == error_mark_node)
5450 permerror (input_location,
5451 "declaration of %qD ambiguates earlier template "
5452 "instantiation for %qD", decl, inst_decl);
5453 else if (TI_TEMPLATE (partial_ti) == tmpl)
5454 permerror (input_location,
5455 "partial specialization of %qD after instantiation "
5456 "of %qD", decl, inst_decl);
5460 return decl;
5463 /* PARM is a template parameter of some form; return the corresponding
5464 TEMPLATE_PARM_INDEX. */
5466 static tree
5467 get_template_parm_index (tree parm)
5469 if (TREE_CODE (parm) == PARM_DECL
5470 || TREE_CODE (parm) == CONST_DECL)
5471 parm = DECL_INITIAL (parm);
5472 else if (TREE_CODE (parm) == TYPE_DECL
5473 || TREE_CODE (parm) == TEMPLATE_DECL)
5474 parm = TREE_TYPE (parm);
5475 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5476 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5477 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5478 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5479 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5480 return parm;
5483 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5484 parameter packs used by the template parameter PARM. */
5486 static void
5487 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5489 /* A type parm can't refer to another parm. */
5490 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5491 return;
5492 else if (TREE_CODE (parm) == PARM_DECL)
5494 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5495 ppd, ppd->visited);
5496 return;
5499 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5501 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5502 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5504 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5505 if (template_parameter_pack_p (p))
5506 /* Any packs in the type are expanded by this parameter. */;
5507 else
5508 fixed_parameter_pack_p_1 (p, ppd);
5512 /* PARM is a template parameter pack. Return any parameter packs used in
5513 its type or the type of any of its template parameters. If there are
5514 any such packs, it will be instantiated into a fixed template parameter
5515 list by partial instantiation rather than be fully deduced. */
5517 tree
5518 fixed_parameter_pack_p (tree parm)
5520 /* This can only be true in a member template. */
5521 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5522 return NULL_TREE;
5523 /* This can only be true for a parameter pack. */
5524 if (!template_parameter_pack_p (parm))
5525 return NULL_TREE;
5526 /* A type parm can't refer to another parm. */
5527 if (TREE_CODE (parm) == TYPE_DECL)
5528 return NULL_TREE;
5530 tree parameter_packs = NULL_TREE;
5531 struct find_parameter_pack_data ppd;
5532 ppd.parameter_packs = &parameter_packs;
5533 ppd.visited = new hash_set<tree>;
5534 ppd.type_pack_expansion_p = false;
5536 fixed_parameter_pack_p_1 (parm, &ppd);
5538 delete ppd.visited;
5539 return parameter_packs;
5542 /* Check that a template declaration's use of default arguments and
5543 parameter packs is not invalid. Here, PARMS are the template
5544 parameters. IS_PRIMARY is true if DECL is the thing declared by
5545 a primary template. IS_PARTIAL is true if DECL is a partial
5546 specialization.
5548 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5549 function template declaration or a friend class template
5550 declaration. In the function case, 1 indicates a declaration, 2
5551 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5552 emitted for extraneous default arguments.
5554 Returns TRUE if there were no errors found, FALSE otherwise. */
5556 bool
5557 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5558 bool is_partial, int is_friend_decl)
5560 const char *msg;
5561 int last_level_to_check;
5562 tree parm_level;
5563 bool no_errors = true;
5565 /* [temp.param]
5567 A default template-argument shall not be specified in a
5568 function template declaration or a function template definition, nor
5569 in the template-parameter-list of the definition of a member of a
5570 class template. */
5572 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5573 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5574 /* You can't have a function template declaration in a local
5575 scope, nor you can you define a member of a class template in a
5576 local scope. */
5577 return true;
5579 if ((TREE_CODE (decl) == TYPE_DECL
5580 && TREE_TYPE (decl)
5581 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5582 || (TREE_CODE (decl) == FUNCTION_DECL
5583 && LAMBDA_FUNCTION_P (decl)))
5584 /* A lambda doesn't have an explicit declaration; don't complain
5585 about the parms of the enclosing class. */
5586 return true;
5588 if (current_class_type
5589 && !TYPE_BEING_DEFINED (current_class_type)
5590 && DECL_LANG_SPECIFIC (decl)
5591 && DECL_DECLARES_FUNCTION_P (decl)
5592 /* If this is either a friend defined in the scope of the class
5593 or a member function. */
5594 && (DECL_FUNCTION_MEMBER_P (decl)
5595 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5596 : DECL_FRIEND_CONTEXT (decl)
5597 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5598 : false)
5599 /* And, if it was a member function, it really was defined in
5600 the scope of the class. */
5601 && (!DECL_FUNCTION_MEMBER_P (decl)
5602 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5603 /* We already checked these parameters when the template was
5604 declared, so there's no need to do it again now. This function
5605 was defined in class scope, but we're processing its body now
5606 that the class is complete. */
5607 return true;
5609 /* Core issue 226 (C++0x only): the following only applies to class
5610 templates. */
5611 if (is_primary
5612 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5614 /* [temp.param]
5616 If a template-parameter has a default template-argument, all
5617 subsequent template-parameters shall have a default
5618 template-argument supplied. */
5619 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5621 tree inner_parms = TREE_VALUE (parm_level);
5622 int ntparms = TREE_VEC_LENGTH (inner_parms);
5623 int seen_def_arg_p = 0;
5624 int i;
5626 for (i = 0; i < ntparms; ++i)
5628 tree parm = TREE_VEC_ELT (inner_parms, i);
5630 if (parm == error_mark_node)
5631 continue;
5633 if (TREE_PURPOSE (parm))
5634 seen_def_arg_p = 1;
5635 else if (seen_def_arg_p
5636 && !template_parameter_pack_p (TREE_VALUE (parm)))
5638 error ("no default argument for %qD", TREE_VALUE (parm));
5639 /* For better subsequent error-recovery, we indicate that
5640 there should have been a default argument. */
5641 TREE_PURPOSE (parm) = error_mark_node;
5642 no_errors = false;
5644 else if (!is_partial
5645 && !is_friend_decl
5646 /* Don't complain about an enclosing partial
5647 specialization. */
5648 && parm_level == parms
5649 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5650 && i < ntparms - 1
5651 && template_parameter_pack_p (TREE_VALUE (parm))
5652 /* A fixed parameter pack will be partially
5653 instantiated into a fixed length list. */
5654 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5656 /* A primary class template, primary variable template
5657 (DR 2032), or alias template can only have one
5658 parameter pack, at the end of the template
5659 parameter list. */
5661 error ("parameter pack %q+D must be at the end of the"
5662 " template parameter list", TREE_VALUE (parm));
5664 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5665 = error_mark_node;
5666 no_errors = false;
5672 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5673 || is_partial
5674 || !is_primary
5675 || is_friend_decl)
5676 /* For an ordinary class template, default template arguments are
5677 allowed at the innermost level, e.g.:
5678 template <class T = int>
5679 struct S {};
5680 but, in a partial specialization, they're not allowed even
5681 there, as we have in [temp.class.spec]:
5683 The template parameter list of a specialization shall not
5684 contain default template argument values.
5686 So, for a partial specialization, or for a function template
5687 (in C++98/C++03), we look at all of them. */
5689 else
5690 /* But, for a primary class template that is not a partial
5691 specialization we look at all template parameters except the
5692 innermost ones. */
5693 parms = TREE_CHAIN (parms);
5695 /* Figure out what error message to issue. */
5696 if (is_friend_decl == 2)
5697 msg = G_("default template arguments may not be used in function template "
5698 "friend re-declaration");
5699 else if (is_friend_decl)
5700 msg = G_("default template arguments may not be used in template "
5701 "friend declarations");
5702 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5703 msg = G_("default template arguments may not be used in function templates "
5704 "without %<-std=c++11%> or %<-std=gnu++11%>");
5705 else if (is_partial)
5706 msg = G_("default template arguments may not be used in "
5707 "partial specializations");
5708 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5709 msg = G_("default argument for template parameter for class enclosing %qD");
5710 else
5711 /* Per [temp.param]/9, "A default template-argument shall not be
5712 specified in the template-parameter-lists of the definition of
5713 a member of a class template that appears outside of the member's
5714 class.", thus if we aren't handling a member of a class template
5715 there is no need to examine the parameters. */
5716 return true;
5718 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5719 /* If we're inside a class definition, there's no need to
5720 examine the parameters to the class itself. On the one
5721 hand, they will be checked when the class is defined, and,
5722 on the other, default arguments are valid in things like:
5723 template <class T = double>
5724 struct S { template <class U> void f(U); };
5725 Here the default argument for `S' has no bearing on the
5726 declaration of `f'. */
5727 last_level_to_check = template_class_depth (current_class_type) + 1;
5728 else
5729 /* Check everything. */
5730 last_level_to_check = 0;
5732 for (parm_level = parms;
5733 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5734 parm_level = TREE_CHAIN (parm_level))
5736 tree inner_parms = TREE_VALUE (parm_level);
5737 int i;
5738 int ntparms;
5740 ntparms = TREE_VEC_LENGTH (inner_parms);
5741 for (i = 0; i < ntparms; ++i)
5743 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5744 continue;
5746 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5748 if (msg)
5750 no_errors = false;
5751 if (is_friend_decl == 2)
5752 return no_errors;
5754 error (msg, decl);
5755 msg = 0;
5758 /* Clear out the default argument so that we are not
5759 confused later. */
5760 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5764 /* At this point, if we're still interested in issuing messages,
5765 they must apply to classes surrounding the object declared. */
5766 if (msg)
5767 msg = G_("default argument for template parameter for class "
5768 "enclosing %qD");
5771 return no_errors;
5774 /* Worker for push_template_decl_real, called via
5775 for_each_template_parm. DATA is really an int, indicating the
5776 level of the parameters we are interested in. If T is a template
5777 parameter of that level, return nonzero. */
5779 static int
5780 template_parm_this_level_p (tree t, void* data)
5782 int this_level = *(int *)data;
5783 int level;
5785 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5786 level = TEMPLATE_PARM_LEVEL (t);
5787 else
5788 level = TEMPLATE_TYPE_LEVEL (t);
5789 return level == this_level;
5792 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5793 DATA is really an int, indicating the innermost outer level of parameters.
5794 If T is a template parameter of that level or further out, return
5795 nonzero. */
5797 static int
5798 template_parm_outer_level (tree t, void *data)
5800 int this_level = *(int *)data;
5801 int level;
5803 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5804 level = TEMPLATE_PARM_LEVEL (t);
5805 else
5806 level = TEMPLATE_TYPE_LEVEL (t);
5807 return level <= this_level;
5810 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5811 parameters given by current_template_args, or reuses a
5812 previously existing one, if appropriate. Returns the DECL, or an
5813 equivalent one, if it is replaced via a call to duplicate_decls.
5815 If IS_FRIEND is true, DECL is a friend declaration. */
5817 tree
5818 push_template_decl (tree decl, bool is_friend)
5820 if (decl == error_mark_node || !current_template_parms)
5821 return error_mark_node;
5823 /* See if this is a partial specialization. */
5824 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5825 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5826 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5827 || (VAR_P (decl)
5828 && DECL_LANG_SPECIFIC (decl)
5829 && DECL_TEMPLATE_SPECIALIZATION (decl)
5830 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5832 /* No surprising friend functions. */
5833 gcc_checking_assert (is_friend
5834 || !(TREE_CODE (decl) == FUNCTION_DECL
5835 && DECL_UNIQUE_FRIEND_P (decl)));
5837 tree ctx;
5838 if (is_friend)
5839 /* For a friend, we want the context of the friend, not
5840 the type of which it is a friend. */
5841 ctx = CP_DECL_CONTEXT (decl);
5842 else if (CP_DECL_CONTEXT (decl)
5843 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5844 /* In the case of a virtual function, we want the class in which
5845 it is defined. */
5846 ctx = CP_DECL_CONTEXT (decl);
5847 else
5848 /* Otherwise, if we're currently defining some class, the DECL
5849 is assumed to be a member of the class. */
5850 ctx = current_scope ();
5852 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5853 ctx = NULL_TREE;
5855 if (!DECL_CONTEXT (decl))
5856 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5858 /* See if this is a primary template. */
5859 bool is_primary = false;
5860 if (is_friend && ctx
5861 && uses_template_parms_level (ctx, current_template_depth))
5862 /* A friend template that specifies a class context, i.e.
5863 template <typename T> friend void A<T>::f();
5864 is not primary. */
5866 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5867 /* Lambdas are not primary. */
5869 else
5870 is_primary = template_parm_scope_p ();
5872 /* True if the template is a member template, in the sense of
5873 [temp.mem]. */
5874 bool member_template_p = false;
5876 if (is_primary)
5878 warning (OPT_Wtemplates, "template %qD declared", decl);
5880 if (DECL_CLASS_SCOPE_P (decl))
5881 member_template_p = true;
5883 if (TREE_CODE (decl) == TYPE_DECL
5884 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5886 error ("template class without a name");
5887 return error_mark_node;
5889 else if (TREE_CODE (decl) == FUNCTION_DECL)
5891 if (member_template_p)
5893 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5894 error ("member template %qD may not have virt-specifiers", decl);
5896 if (DECL_DESTRUCTOR_P (decl))
5898 /* [temp.mem]
5900 A destructor shall not be a member template. */
5901 error_at (DECL_SOURCE_LOCATION (decl),
5902 "destructor %qD declared as member template", decl);
5903 return error_mark_node;
5905 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5906 && (!prototype_p (TREE_TYPE (decl))
5907 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5908 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5909 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5910 == void_list_node)))
5912 /* [basic.stc.dynamic.allocation]
5914 An allocation function can be a function
5915 template. ... Template allocation functions shall
5916 have two or more parameters. */
5917 error ("invalid template declaration of %qD", decl);
5918 return error_mark_node;
5921 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5922 && CLASS_TYPE_P (TREE_TYPE (decl)))
5923 /* Class template. */;
5924 else if (TREE_CODE (decl) == TYPE_DECL
5925 && TYPE_DECL_ALIAS_P (decl))
5926 /* alias-declaration */
5927 gcc_assert (!DECL_ARTIFICIAL (decl));
5928 else if (VAR_P (decl))
5929 /* C++14 variable template. */;
5930 else if (TREE_CODE (decl) == CONCEPT_DECL)
5931 /* C++20 concept definitions. */;
5932 else
5934 error ("template declaration of %q#D", decl);
5935 return error_mark_node;
5939 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5940 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5941 || (VAR_OR_FUNCTION_DECL_P (decl)
5942 && DECL_LOCAL_DECL_P (decl))));
5944 /* Check to see that the rules regarding the use of default
5945 arguments are not being violated. We check args for a friend
5946 functions when we know whether it's a definition, introducing
5947 declaration or re-declaration. */
5948 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5949 check_default_tmpl_args (decl, current_template_parms,
5950 is_primary, is_partial, is_friend);
5952 /* Ensure that there are no parameter packs in the type of this
5953 declaration that have not been expanded. */
5954 if (TREE_CODE (decl) == FUNCTION_DECL)
5956 /* Check each of the arguments individually to see if there are
5957 any bare parameter packs. */
5958 tree type = TREE_TYPE (decl);
5959 tree arg = DECL_ARGUMENTS (decl);
5960 tree argtype = TYPE_ARG_TYPES (type);
5962 while (arg && argtype)
5964 if (!DECL_PACK_P (arg)
5965 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5967 /* This is a PARM_DECL that contains unexpanded parameter
5968 packs. We have already complained about this in the
5969 check_for_bare_parameter_packs call, so just replace
5970 these types with ERROR_MARK_NODE. */
5971 TREE_TYPE (arg) = error_mark_node;
5972 TREE_VALUE (argtype) = error_mark_node;
5975 arg = DECL_CHAIN (arg);
5976 argtype = TREE_CHAIN (argtype);
5979 /* Check for bare parameter packs in the return type and the
5980 exception specifiers. */
5981 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5982 /* Errors were already issued, set return type to int
5983 as the frontend doesn't expect error_mark_node as
5984 the return type. */
5985 TREE_TYPE (type) = integer_type_node;
5986 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5987 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5989 else
5991 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5992 ? DECL_ORIGINAL_TYPE (decl)
5993 : TREE_TYPE (decl)))
5995 TREE_TYPE (decl) = error_mark_node;
5996 return error_mark_node;
5999 if (is_partial && VAR_P (decl)
6000 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
6001 return error_mark_node;
6004 if (is_partial)
6005 return process_partial_specialization (decl);
6007 tree args = current_template_args ();
6008 tree tmpl = NULL_TREE;
6009 bool new_template_p = false;
6010 if (local_p)
6012 /* Does not get a template head. */
6013 tmpl = NULL_TREE;
6014 gcc_checking_assert (!is_primary);
6016 else if (!ctx
6017 || TREE_CODE (ctx) == FUNCTION_DECL
6018 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6019 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6020 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6021 && DECL_TEMPLATE_INFO (decl))))
6023 if (DECL_LANG_SPECIFIC (decl)
6024 && DECL_TEMPLATE_INFO (decl)
6025 && DECL_TI_TEMPLATE (decl))
6026 tmpl = DECL_TI_TEMPLATE (decl);
6027 /* If DECL is a TYPE_DECL for a class-template, then there won't
6028 be DECL_LANG_SPECIFIC. The information equivalent to
6029 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6030 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6031 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6032 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6034 /* Since a template declaration already existed for this
6035 class-type, we must be redeclaring it here. Make sure
6036 that the redeclaration is valid. */
6037 redeclare_class_template (TREE_TYPE (decl),
6038 current_template_parms,
6039 current_template_constraints ());
6040 /* We don't need to create a new TEMPLATE_DECL; just use the
6041 one we already had. */
6042 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6044 else
6046 tmpl = build_template_decl (decl, current_template_parms,
6047 member_template_p);
6048 new_template_p = true;
6050 if (DECL_LANG_SPECIFIC (decl)
6051 && DECL_TEMPLATE_SPECIALIZATION (decl))
6053 /* A specialization of a member template of a template
6054 class. */
6055 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6056 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6057 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6061 else
6063 tree a, t, current, parms;
6064 int i;
6065 tree tinfo = get_template_info (decl);
6067 if (!tinfo)
6069 error ("template definition of non-template %q#D", decl);
6070 return error_mark_node;
6073 tmpl = TI_TEMPLATE (tinfo);
6075 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6076 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6077 && DECL_TEMPLATE_SPECIALIZATION (decl)
6078 && DECL_MEMBER_TEMPLATE_P (tmpl))
6080 /* The declaration is a specialization of a member
6081 template, declared outside the class. Therefore, the
6082 innermost template arguments will be NULL, so we
6083 replace them with the arguments determined by the
6084 earlier call to check_explicit_specialization. */
6085 args = DECL_TI_ARGS (decl);
6087 tree new_tmpl
6088 = build_template_decl (decl, current_template_parms,
6089 member_template_p);
6090 DECL_TI_TEMPLATE (decl) = new_tmpl;
6091 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6092 DECL_TEMPLATE_INFO (new_tmpl)
6093 = build_template_info (tmpl, args);
6095 register_specialization (new_tmpl,
6096 most_general_template (tmpl),
6097 args,
6098 is_friend, 0);
6099 return decl;
6102 /* Make sure the template headers we got make sense. */
6104 parms = DECL_TEMPLATE_PARMS (tmpl);
6105 i = TMPL_PARMS_DEPTH (parms);
6106 if (TMPL_ARGS_DEPTH (args) != i)
6108 error ("expected %d levels of template parms for %q#D, got %d",
6109 i, decl, TMPL_ARGS_DEPTH (args));
6110 DECL_INTERFACE_KNOWN (decl) = 1;
6111 return error_mark_node;
6113 else
6114 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6116 a = TMPL_ARGS_LEVEL (args, i);
6117 t = INNERMOST_TEMPLATE_PARMS (parms);
6119 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6121 if (current == decl)
6122 error ("got %d template parameters for %q#D",
6123 TREE_VEC_LENGTH (a), decl);
6124 else
6125 error ("got %d template parameters for %q#T",
6126 TREE_VEC_LENGTH (a), current);
6127 error (" but %d required", TREE_VEC_LENGTH (t));
6128 /* Avoid crash in import_export_decl. */
6129 DECL_INTERFACE_KNOWN (decl) = 1;
6130 return error_mark_node;
6133 if (current == decl)
6134 current = ctx;
6135 else if (current == NULL_TREE)
6136 /* Can happen in erroneous input. */
6137 break;
6138 else
6139 current = get_containing_scope (current);
6142 /* Check that the parms are used in the appropriate qualifying scopes
6143 in the declarator. */
6144 if (!comp_template_args
6145 (TI_ARGS (tinfo),
6146 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6148 error ("template arguments to %qD do not match original "
6149 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6150 if (!uses_template_parms (TI_ARGS (tinfo)))
6151 inform (input_location, "use %<template<>%> for"
6152 " an explicit specialization");
6153 /* Avoid crash in import_export_decl. */
6154 DECL_INTERFACE_KNOWN (decl) = 1;
6155 return error_mark_node;
6158 /* Check that the constraints for each enclosing template scope are
6159 consistent with the original declarations. */
6160 if (flag_concepts)
6162 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6163 tree scope_parms = current_template_parms;
6164 if (PRIMARY_TEMPLATE_P (tmpl))
6166 decl_parms = TREE_CHAIN (decl_parms);
6167 scope_parms = TREE_CHAIN (scope_parms);
6169 while (decl_parms)
6171 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6173 error ("redeclaration of %qD with different constraints",
6174 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6175 break;
6177 decl_parms = TREE_CHAIN (decl_parms);
6178 scope_parms = TREE_CHAIN (scope_parms);
6183 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6185 if (new_template_p)
6187 /* Push template declarations for global functions and types.
6188 Note that we do not try to push a global template friend
6189 declared in a template class; such a thing may well depend on
6190 the template parameters of the class and we'll push it when
6191 instantiating the befriending class. */
6192 if (!ctx
6193 && !(is_friend && template_class_depth (current_class_type) > 0))
6195 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6196 if (pushed == error_mark_node)
6197 return error_mark_node;
6199 /* pushdecl may have found an existing template. */
6200 if (pushed != tmpl)
6202 decl = DECL_TEMPLATE_RESULT (pushed);
6203 tmpl = NULL_TREE;
6206 else if (is_friend)
6208 /* Record this decl as belonging to the current class. It's
6209 not chained onto anything else. */
6210 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6211 gcc_checking_assert (!DECL_CHAIN (tmpl));
6212 DECL_CHAIN (tmpl) = current_scope ();
6215 else if (tmpl)
6216 /* The type may have been completed, or (erroneously) changed. */
6217 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6219 if (tmpl)
6221 if (is_primary)
6223 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6225 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6227 /* Give template template parms a DECL_CONTEXT of the template
6228 for which they are a parameter. */
6229 parms = INNERMOST_TEMPLATE_PARMS (parms);
6230 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6232 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6233 if (TREE_CODE (parm) == TEMPLATE_DECL)
6234 DECL_CONTEXT (parm) = tmpl;
6237 if (TREE_CODE (decl) == TYPE_DECL
6238 && TYPE_DECL_ALIAS_P (decl))
6240 if (tree constr
6241 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6243 /* ??? Why don't we do this here for all templates? */
6244 constr = build_constraints (constr, NULL_TREE);
6245 set_constraints (decl, constr);
6250 /* The DECL_TI_ARGS of DECL contains full set of arguments
6251 referring wback to its most general template. If TMPL is a
6252 specialization, ARGS may only have the innermost set of
6253 arguments. Add the missing argument levels if necessary. */
6254 if (DECL_TEMPLATE_INFO (tmpl))
6255 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6257 tree info = build_template_info (tmpl, args);
6259 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6260 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6261 else
6263 retrofit_lang_decl (decl);
6264 DECL_TEMPLATE_INFO (decl) = info;
6268 if (flag_implicit_templates
6269 && !is_friend
6270 && TREE_PUBLIC (decl)
6271 && VAR_OR_FUNCTION_DECL_P (decl))
6272 /* Set DECL_COMDAT on template instantiations; if we force
6273 them to be emitted by explicit instantiation,
6274 mark_needed will tell cgraph to do the right thing. */
6275 DECL_COMDAT (decl) = true;
6277 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6279 return decl;
6282 /* FN is an inheriting constructor that inherits from the constructor
6283 template INHERITED; turn FN into a constructor template with a matching
6284 template header. */
6286 tree
6287 add_inherited_template_parms (tree fn, tree inherited)
6289 tree inner_parms
6290 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6291 inner_parms = copy_node (inner_parms);
6292 tree parms
6293 = tree_cons (size_int (current_template_depth + 1),
6294 inner_parms, current_template_parms);
6295 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6296 tree args = template_parms_to_args (parms);
6297 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6298 DECL_ARTIFICIAL (tmpl) = true;
6299 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6300 return tmpl;
6303 /* Called when a class template TYPE is redeclared with the indicated
6304 template PARMS, e.g.:
6306 template <class T> struct S;
6307 template <class T> struct S {}; */
6309 bool
6310 redeclare_class_template (tree type, tree parms, tree cons)
6312 tree tmpl;
6313 tree tmpl_parms;
6314 int i;
6316 if (!TYPE_TEMPLATE_INFO (type))
6318 error ("%qT is not a template type", type);
6319 return false;
6322 tmpl = TYPE_TI_TEMPLATE (type);
6323 if (!PRIMARY_TEMPLATE_P (tmpl))
6324 /* The type is nested in some template class. Nothing to worry
6325 about here; there are no new template parameters for the nested
6326 type. */
6327 return true;
6329 if (!parms)
6331 error ("template specifiers not specified in declaration of %qD",
6332 tmpl);
6333 return false;
6336 parms = INNERMOST_TEMPLATE_PARMS (parms);
6337 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6339 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6341 error_n (input_location, TREE_VEC_LENGTH (parms),
6342 "redeclared with %d template parameter",
6343 "redeclared with %d template parameters",
6344 TREE_VEC_LENGTH (parms));
6345 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6346 "previous declaration %qD used %d template parameter",
6347 "previous declaration %qD used %d template parameters",
6348 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6349 return false;
6352 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6354 tree tmpl_parm;
6355 tree parm;
6357 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6358 || TREE_VEC_ELT (parms, i) == error_mark_node)
6359 continue;
6361 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6362 if (error_operand_p (tmpl_parm))
6363 return false;
6365 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6367 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6368 TEMPLATE_DECL. */
6369 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6370 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6371 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6372 || (TREE_CODE (tmpl_parm) != PARM_DECL
6373 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6374 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6375 || (TREE_CODE (tmpl_parm) == PARM_DECL
6376 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6377 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6379 auto_diagnostic_group d;
6380 error ("template parameter %q+#D", tmpl_parm);
6381 if (DECL_P (parm))
6382 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6383 else
6384 inform (input_location, "redeclared here");
6385 return false;
6388 /* The parameters can be declared to introduce different
6389 constraints. */
6390 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6391 tree p2 = TREE_VEC_ELT (parms, i);
6392 if (!template_parameter_constraints_equivalent_p (p1, p2))
6394 auto_diagnostic_group d;
6395 error ("declaration of template parameter %q+#D with different "
6396 "constraints", parm);
6397 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6398 "original declaration appeared here");
6399 return false;
6402 /* Give each template template parm in this redeclaration a
6403 DECL_CONTEXT of the template for which they are a parameter. */
6404 if (TREE_CODE (parm) == TEMPLATE_DECL)
6406 gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
6407 || DECL_CONTEXT (parm) == tmpl);
6408 DECL_CONTEXT (parm) = tmpl;
6412 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6413 return false;
6415 tree ci = get_constraints (tmpl);
6416 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6417 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6419 /* Two classes with different constraints declare different entities. */
6420 if (!cp_tree_equal (req1, req2))
6422 auto_diagnostic_group d;
6423 error_at (input_location, "redeclaration of %q#D with different "
6424 "constraints", tmpl);
6425 inform (DECL_SOURCE_LOCATION (tmpl),
6426 "original declaration appeared here");
6427 return false;
6430 return true;
6433 /* The actual substitution part of instantiate_non_dependent_expr,
6434 to be used when the caller has already checked
6435 !instantiation_dependent_uneval_expression_p (expr)
6436 and cleared processing_template_decl. */
6438 tree
6439 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6441 return tsubst_expr (expr, /*args=*/NULL_TREE, complain, /*in_decl=*/NULL_TREE);
6444 /* Instantiate the non-dependent expression EXPR. */
6446 tree
6447 instantiate_non_dependent_expr (tree expr,
6448 tsubst_flags_t complain /* = tf_error */)
6450 if (expr == NULL_TREE)
6451 return NULL_TREE;
6453 if (processing_template_decl)
6455 /* The caller should have checked this already. */
6456 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6457 processing_template_decl_sentinel s;
6458 expr = instantiate_non_dependent_expr_internal (expr, complain);
6460 return expr;
6463 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6464 expression is dependent or non-constant. */
6466 tree
6467 instantiate_non_dependent_or_null (tree expr)
6469 if (expr == NULL_TREE)
6470 return NULL_TREE;
6471 if (processing_template_decl)
6473 if (!is_nondependent_constant_expression (expr))
6474 expr = NULL_TREE;
6475 else
6477 processing_template_decl_sentinel s;
6478 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6481 return expr;
6484 /* True iff T is a specialization of a variable template. */
6486 bool
6487 variable_template_specialization_p (tree t)
6489 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6490 return false;
6491 tree tmpl = DECL_TI_TEMPLATE (t);
6492 return variable_template_p (tmpl);
6495 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6496 template declaration, or a TYPE_DECL for an alias declaration. */
6498 bool
6499 alias_type_or_template_p (tree t)
6501 if (t == NULL_TREE)
6502 return false;
6503 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6504 || (TYPE_P (t)
6505 && TYPE_NAME (t)
6506 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6507 || DECL_ALIAS_TEMPLATE_P (t));
6510 /* If T is a specialization of an alias template, return it; otherwise return
6511 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6513 tree
6514 alias_template_specialization_p (const_tree t,
6515 bool transparent_typedefs)
6517 if (!TYPE_P (t))
6518 return NULL_TREE;
6520 /* It's an alias template specialization if it's an alias and its
6521 TYPE_NAME is a specialization of a primary template. */
6522 if (typedef_variant_p (t))
6524 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6525 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6526 return CONST_CAST_TREE (t);
6527 if (transparent_typedefs)
6528 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6529 (TYPE_NAME (t)),
6530 transparent_typedefs);
6533 return NULL_TREE;
6536 /* A cache of the result of complex_alias_template_p. */
6538 static GTY((deletable)) hash_map<const_tree, tree> *complex_alias_tmpl_info;
6540 /* Data structure for complex_alias_template_*. */
6542 struct uses_all_template_parms_data
6544 int level;
6545 tree *seen;
6548 /* walk_tree callback for complex_alias_template_p. */
6550 static tree
6551 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6553 tree t = *tp;
6554 auto &data = *(struct uses_all_template_parms_data*)data_;
6556 switch (TREE_CODE (t))
6558 case TEMPLATE_TYPE_PARM:
6559 case TEMPLATE_PARM_INDEX:
6560 case TEMPLATE_TEMPLATE_PARM:
6561 case BOUND_TEMPLATE_TEMPLATE_PARM:
6563 tree idx = get_template_parm_index (t);
6564 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6565 data.seen[TEMPLATE_PARM_IDX (idx)] = boolean_true_node;
6568 default:;
6571 if (!PACK_EXPANSION_P (t))
6572 return 0;
6574 /* An alias template with a pack expansion that expands a pack from the
6575 enclosing class needs to be considered complex, to avoid confusion with
6576 the same pack being used as an argument to the alias's own template
6577 parameter (91966). */
6578 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6579 pack = TREE_CHAIN (pack))
6581 tree parm_pack = TREE_VALUE (pack);
6582 if (!TEMPLATE_PARM_P (parm_pack))
6583 continue;
6584 int idx, level;
6585 template_parm_level_and_index (parm_pack, &level, &idx);
6586 if (level < data.level)
6587 return t;
6589 /* Consider the expanded packs to be used outside the expansion... */
6590 data.seen[idx] = boolean_true_node;
6593 /* ...but don't walk into the pattern. Consider PR104008:
6595 template <typename T, typename... Ts>
6596 using IsOneOf = disjunction<is_same<T, Ts>...>;
6598 where IsOneOf seemingly uses all of its template parameters in its
6599 expansion (and does not expand a pack from the enclosing class), so the
6600 alias was not marked as complex. However, if it is used like
6601 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6602 expansion. So only Ts is considered used by the pack expansion. */
6603 *walk_subtrees = false;
6605 return 0;
6608 /* An alias template is complex from a SFINAE perspective if a template-id
6609 using that alias can be ill-formed when the expansion is not, as with
6610 the void_t template.
6612 If this predicate returns true in the ordinary case, the out parameter
6613 SEEN_OUT is set to a TREE_VEC containing boolean_true_node at element I if
6614 the I'th template parameter of the alias template is used in the alias. */
6616 static bool
6617 complex_alias_template_p (const_tree tmpl, tree *seen_out)
6619 tmpl = most_general_template (tmpl);
6620 if (!PRIMARY_TEMPLATE_P (tmpl))
6621 return false;
6623 /* A renaming alias isn't complex. */
6624 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6625 return false;
6627 /* Any other constrained alias is complex. */
6628 if (get_constraints (tmpl))
6629 return true;
6631 if (!complex_alias_tmpl_info)
6632 complex_alias_tmpl_info = hash_map<const_tree, tree>::create_ggc (13);
6634 if (tree *slot = complex_alias_tmpl_info->get (tmpl))
6636 tree result = *slot;
6637 if (result == boolean_false_node)
6638 return false;
6639 if (result == boolean_true_node)
6640 return true;
6641 gcc_assert (TREE_CODE (result) == TREE_VEC);
6642 if (seen_out)
6643 *seen_out = result;
6644 return true;
6647 struct uses_all_template_parms_data data;
6648 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6649 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6650 data.level = TMPL_PARMS_DEPTH (parms);
6651 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6652 tree seen = make_tree_vec (len);
6653 data.seen = TREE_VEC_BEGIN (seen);
6654 for (int i = 0; i < len; ++i)
6655 data.seen[i] = boolean_false_node;
6657 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6659 complex_alias_tmpl_info->put (tmpl, boolean_true_node);
6660 return true;
6663 for (int i = 0; i < len; ++i)
6664 if (data.seen[i] != boolean_true_node)
6666 complex_alias_tmpl_info->put (tmpl, seen);
6667 if (seen_out)
6668 *seen_out = seen;
6669 return true;
6672 complex_alias_tmpl_info->put (tmpl, boolean_false_node);
6673 return false;
6676 /* If T is a specialization of a complex alias template with a dependent
6677 argument for an unused template parameter, return it; otherwise return
6678 NULL_TREE. If T is a typedef to such a specialization, return the
6679 specialization. */
6681 tree
6682 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6684 if (t == error_mark_node)
6685 return NULL_TREE;
6686 gcc_assert (TYPE_P (t));
6688 if (!processing_template_decl || !typedef_variant_p (t))
6689 return NULL_TREE;
6691 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6693 tree seen = NULL_TREE;
6694 if (complex_alias_template_p (TI_TEMPLATE (tinfo), &seen))
6696 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6697 if (!seen)
6699 if (any_dependent_template_arguments_p (args))
6700 return CONST_CAST_TREE (t);
6702 else
6704 gcc_assert (TREE_VEC_LENGTH (args) == TREE_VEC_LENGTH (seen));
6705 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
6706 if (TREE_VEC_ELT (seen, i) != boolean_true_node
6707 && dependent_template_arg_p (TREE_VEC_ELT (args, i)))
6708 return CONST_CAST_TREE (t);
6711 return NULL_TREE;
6715 if (transparent_typedefs)
6717 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6718 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6721 return NULL_TREE;
6724 /* Return the number of innermost template parameters in TMPL. */
6726 static int
6727 num_innermost_template_parms (const_tree tmpl)
6729 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6730 return TREE_VEC_LENGTH (parms);
6733 /* Return either TMPL or another template that it is equivalent to under DR
6734 1286: An alias that just changes the name of a template is equivalent to
6735 the other template. */
6737 static tree
6738 get_underlying_template (tree tmpl)
6740 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6741 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6743 /* Determine if the alias is equivalent to an underlying template. */
6744 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6745 /* The underlying type may have been ill-formed. Don't proceed. */
6746 if (!orig_type)
6747 break;
6748 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6749 if (!tinfo)
6750 break;
6752 tree underlying = TI_TEMPLATE (tinfo);
6753 if (!PRIMARY_TEMPLATE_P (underlying)
6754 || (num_innermost_template_parms (tmpl)
6755 != num_innermost_template_parms (underlying)))
6756 break;
6758 /* Does the alias add cv-quals? */
6759 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6760 break;
6762 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6763 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6764 break;
6766 /* Are any default template arguments equivalent? */
6767 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6768 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6769 const int nparms = TREE_VEC_LENGTH (aparms);
6770 for (int i = 0; i < nparms; ++i)
6772 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6773 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6774 if (!template_args_equal (adefarg, udefarg))
6775 goto top_break;
6778 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6779 it's appropriate to treat a less-constrained alias as equivalent. */
6780 if (!at_least_as_constrained (underlying, tmpl))
6781 break;
6783 /* Alias is equivalent. Strip it and repeat. */
6784 tmpl = underlying;
6786 top_break:;
6788 return tmpl;
6791 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6792 must be a reference-to-function or a pointer-to-function type, as specified
6793 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6794 and check that the resulting function has external linkage. */
6796 static tree
6797 convert_nontype_argument_function (tree type, tree expr,
6798 tsubst_flags_t complain)
6800 tree fns = expr;
6801 tree fn, fn_no_ptr;
6802 linkage_kind linkage;
6804 fn = instantiate_type (type, fns, tf_none);
6805 if (fn == error_mark_node)
6806 return error_mark_node;
6808 if (value_dependent_expression_p (fn))
6809 goto accept;
6811 fn_no_ptr = fn;
6812 if (REFERENCE_REF_P (fn_no_ptr))
6813 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6814 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6815 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6816 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6817 if (BASELINK_P (fn_no_ptr))
6818 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6820 /* [temp.arg.nontype]/1
6822 A template-argument for a non-type, non-template template-parameter
6823 shall be one of:
6824 [...]
6825 -- the address of an object or function with external [C++11: or
6826 internal] linkage. */
6828 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6829 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6831 if (complain & tf_error)
6833 location_t loc = cp_expr_loc_or_input_loc (expr);
6834 error_at (loc, "%qE is not a valid template argument for type %qT",
6835 expr, type);
6836 if (TYPE_PTR_P (type))
6837 inform (loc, "it must be the address of a function "
6838 "with external linkage");
6839 else
6840 inform (loc, "it must be the name of a function with "
6841 "external linkage");
6843 return NULL_TREE;
6846 linkage = decl_linkage (fn_no_ptr);
6847 if ((cxx_dialect < cxx11 && linkage != lk_external)
6848 || (cxx_dialect < cxx17 && linkage == lk_none))
6850 if (complain & tf_error)
6852 location_t loc = cp_expr_loc_or_input_loc (expr);
6853 if (cxx_dialect >= cxx11)
6854 error_at (loc, "%qE is not a valid template argument for type "
6855 "%qT because %qD has no linkage",
6856 expr, type, fn_no_ptr);
6857 else
6858 error_at (loc, "%qE is not a valid template argument for type "
6859 "%qT because %qD does not have external linkage",
6860 expr, type, fn_no_ptr);
6862 return NULL_TREE;
6865 accept:
6866 if (TYPE_REF_P (type))
6868 if (REFERENCE_REF_P (fn))
6869 fn = TREE_OPERAND (fn, 0);
6870 else
6871 fn = build_address (fn);
6873 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6874 fn = build_nop (type, fn);
6876 return fn;
6879 /* Subroutine of convert_nontype_argument.
6880 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6881 Emit an error otherwise. */
6883 static bool
6884 check_valid_ptrmem_cst_expr (tree type, tree expr,
6885 tsubst_flags_t complain)
6887 tree orig_expr = expr;
6888 STRIP_NOPS (expr);
6889 if (null_ptr_cst_p (expr))
6890 return true;
6891 if (TREE_CODE (expr) == PTRMEM_CST
6892 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6893 PTRMEM_CST_CLASS (expr)))
6894 return true;
6895 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6896 return true;
6897 if (processing_template_decl
6898 && TREE_CODE (expr) == ADDR_EXPR
6899 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6900 return true;
6901 if (complain & tf_error)
6903 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6904 error_at (loc, "%qE is not a valid template argument for type %qT",
6905 orig_expr, type);
6906 if (TREE_CODE (expr) != PTRMEM_CST)
6907 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6908 else
6909 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6911 return false;
6914 /* Returns TRUE iff the address of OP is value-dependent.
6916 14.6.2.4 [temp.dep.temp]:
6917 A non-integral non-type template-argument is dependent if its type is
6918 dependent or it has either of the following forms
6919 qualified-id
6920 & qualified-id
6921 and contains a nested-name-specifier which specifies a class-name that
6922 names a dependent type.
6924 We generalize this to just say that the address of a member of a
6925 dependent class is value-dependent; the above doesn't cover the
6926 address of a static data member named with an unqualified-id. */
6928 static bool
6929 has_value_dependent_address (tree op)
6931 STRIP_ANY_LOCATION_WRAPPER (op);
6933 /* We could use get_inner_reference here, but there's no need;
6934 this is only relevant for template non-type arguments, which
6935 can only be expressed as &id-expression. */
6936 if (DECL_P (op))
6938 tree ctx = CP_DECL_CONTEXT (op);
6940 if (TYPE_P (ctx) && dependent_type_p (ctx))
6941 return true;
6943 if (VAR_P (op)
6944 && TREE_STATIC (op)
6945 && TREE_CODE (ctx) == FUNCTION_DECL
6946 && type_dependent_expression_p (ctx))
6947 return true;
6950 return false;
6953 /* The next set of functions are used for providing helpful explanatory
6954 diagnostics for failed overload resolution. Their messages should be
6955 indented by two spaces for consistency with the messages in
6956 call.cc */
6958 static int
6959 unify_success (bool /*explain_p*/)
6961 return 0;
6964 /* Other failure functions should call this one, to provide a single function
6965 for setting a breakpoint on. */
6967 static int
6968 unify_invalid (bool /*explain_p*/)
6970 return 1;
6973 static int
6974 unify_parameter_deduction_failure (bool explain_p, tree parm)
6976 if (explain_p)
6977 inform (input_location,
6978 " couldn%'t deduce template parameter %qD", parm);
6979 return unify_invalid (explain_p);
6982 static int
6983 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6985 if (explain_p)
6986 inform (input_location,
6987 " types %qT and %qT have incompatible cv-qualifiers",
6988 parm, arg);
6989 return unify_invalid (explain_p);
6992 static int
6993 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6995 if (explain_p)
6996 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6997 return unify_invalid (explain_p);
7000 static int
7001 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
7003 if (explain_p)
7004 inform (input_location,
7005 " template parameter %qD is not a parameter pack, but "
7006 "argument %qD is",
7007 parm, arg);
7008 return unify_invalid (explain_p);
7011 static int
7012 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
7014 if (explain_p)
7015 inform (input_location,
7016 " template argument %qE does not match "
7017 "pointer-to-member constant %qE",
7018 arg, parm);
7019 return unify_invalid (explain_p);
7022 static int
7023 unify_expression_unequal (bool explain_p, tree parm, tree arg)
7025 if (explain_p)
7026 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
7027 return unify_invalid (explain_p);
7030 static int
7031 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
7033 if (explain_p)
7034 inform (input_location,
7035 " inconsistent parameter pack deduction with %qT and %qT",
7036 old_arg, new_arg);
7037 return unify_invalid (explain_p);
7040 static int
7041 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
7043 if (explain_p)
7045 if (TYPE_P (parm))
7046 inform (input_location,
7047 " deduced conflicting types for parameter %qT (%qT and %qT)",
7048 parm, first, second);
7049 else
7050 inform (input_location,
7051 " deduced conflicting values for non-type parameter "
7052 "%qE (%qE and %qE)", parm, first, second);
7054 return unify_invalid (explain_p);
7057 static int
7058 unify_vla_arg (bool explain_p, tree arg)
7060 if (explain_p)
7061 inform (input_location,
7062 " variable-sized array type %qT is not "
7063 "a valid template argument",
7064 arg);
7065 return unify_invalid (explain_p);
7068 static int
7069 unify_method_type_error (bool explain_p, tree arg)
7071 if (explain_p)
7072 inform (input_location,
7073 " member function type %qT is not a valid template argument",
7074 arg);
7075 return unify_invalid (explain_p);
7078 static int
7079 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7081 if (explain_p)
7083 if (least_p)
7084 inform_n (input_location, wanted,
7085 " candidate expects at least %d argument, %d provided",
7086 " candidate expects at least %d arguments, %d provided",
7087 wanted, have);
7088 else
7089 inform_n (input_location, wanted,
7090 " candidate expects %d argument, %d provided",
7091 " candidate expects %d arguments, %d provided",
7092 wanted, have);
7094 return unify_invalid (explain_p);
7097 static int
7098 unify_too_many_arguments (bool explain_p, int have, int wanted)
7100 return unify_arity (explain_p, have, wanted);
7103 static int
7104 unify_too_few_arguments (bool explain_p, int have, int wanted,
7105 bool least_p = false)
7107 return unify_arity (explain_p, have, wanted, least_p);
7110 static int
7111 unify_arg_conversion (bool explain_p, tree to_type,
7112 tree from_type, tree arg)
7114 if (explain_p)
7115 inform (cp_expr_loc_or_input_loc (arg),
7116 " cannot convert %qE (type %qT) to type %qT",
7117 arg, from_type, to_type);
7118 return unify_invalid (explain_p);
7121 static int
7122 unify_no_common_base (bool explain_p, enum template_base_result r,
7123 tree parm, tree arg)
7125 if (explain_p)
7126 switch (r)
7128 case tbr_ambiguous_baseclass:
7129 inform (input_location, " %qT is an ambiguous base class of %qT",
7130 parm, arg);
7131 break;
7132 default:
7133 inform (input_location, " %qT is not derived from %qT", arg, parm);
7134 break;
7136 return unify_invalid (explain_p);
7139 static int
7140 unify_inconsistent_template_template_parameters (bool explain_p)
7142 if (explain_p)
7143 inform (input_location,
7144 " template parameters of a template template argument are "
7145 "inconsistent with other deduced template arguments");
7146 return unify_invalid (explain_p);
7149 static int
7150 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7152 if (explain_p)
7153 inform (input_location,
7154 " cannot deduce a template for %qT from non-template type %qT",
7155 parm, arg);
7156 return unify_invalid (explain_p);
7159 static int
7160 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7162 if (explain_p)
7163 inform (input_location,
7164 " template argument %qE does not match %qE", arg, parm);
7165 return unify_invalid (explain_p);
7168 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7169 argument for TYPE, points to an unsuitable object.
7171 Also adjust the type of the index in C++20 array subobject references. */
7173 static bool
7174 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7176 switch (TREE_CODE (expr))
7178 CASE_CONVERT:
7179 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7180 complain);
7182 case TARGET_EXPR:
7183 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7184 complain);
7186 case CONSTRUCTOR:
7188 for (auto &e: CONSTRUCTOR_ELTS (expr))
7189 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7190 return true;
7192 break;
7194 case ADDR_EXPR:
7196 tree decl = TREE_OPERAND (expr, 0);
7198 if (cxx_dialect >= cxx20)
7199 while (TREE_CODE (decl) == COMPONENT_REF
7200 || TREE_CODE (decl) == ARRAY_REF)
7202 tree &op = TREE_OPERAND (decl, 1);
7203 if (TREE_CODE (decl) == ARRAY_REF
7204 && TREE_CODE (op) == INTEGER_CST)
7205 /* Canonicalize array offsets to ptrdiff_t; how they were
7206 written doesn't matter for subobject identity. */
7207 op = fold_convert (ptrdiff_type_node, op);
7208 decl = TREE_OPERAND (decl, 0);
7211 if (!VAR_OR_FUNCTION_DECL_P (decl))
7213 if (complain & tf_error)
7214 error_at (cp_expr_loc_or_input_loc (expr),
7215 "%qE is not a valid template argument of type %qT "
7216 "because %qE is not a variable or function",
7217 expr, type, decl);
7218 return true;
7220 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7222 if (complain & tf_error)
7223 error_at (cp_expr_loc_or_input_loc (expr),
7224 "%qE is not a valid template argument of type %qT "
7225 "in C++98 because %qD does not have external linkage",
7226 expr, type, decl);
7227 return true;
7229 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7230 && decl_linkage (decl) == lk_none)
7232 if (complain & tf_error)
7233 error_at (cp_expr_loc_or_input_loc (expr),
7234 "%qE is not a valid template argument of type %qT "
7235 "because %qD has no linkage", expr, type, decl);
7236 return true;
7238 /* C++17: For a non-type template-parameter of reference or pointer
7239 type, the value of the constant expression shall not refer to (or
7240 for a pointer type, shall not be the address of):
7241 * a subobject (4.5),
7242 * a temporary object (15.2),
7243 * a string literal (5.13.5),
7244 * the result of a typeid expression (8.2.8), or
7245 * a predefined __func__ variable (11.4.1). */
7246 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl)
7247 && !DECL_NTTP_OBJECT_P (decl))
7249 gcc_checking_assert (DECL_TINFO_P (decl) || DECL_FNAME_P (decl));
7250 if (complain & tf_error)
7251 error ("the address of %qD is not a valid template argument",
7252 decl);
7253 return true;
7255 else if (cxx_dialect < cxx20
7256 && !(same_type_ignoring_top_level_qualifiers_p
7257 (strip_array_types (TREE_TYPE (type)),
7258 strip_array_types (TREE_TYPE (decl)))))
7260 if (complain & tf_error)
7261 error ("the address of the %qT subobject of %qD is not a "
7262 "valid template argument", TREE_TYPE (type), decl);
7263 return true;
7265 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7267 if (complain & tf_error)
7268 error ("the address of %qD is not a valid template argument "
7269 "because it does not have static storage duration",
7270 decl);
7271 return true;
7274 break;
7276 default:
7277 if (!INDIRECT_TYPE_P (type))
7278 /* We're only concerned about pointers and references here. */;
7279 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7280 /* Null pointer values are OK in C++11. */;
7281 else
7283 if (VAR_P (expr))
7285 if (complain & tf_error)
7286 error ("%qD is not a valid template argument "
7287 "because %qD is a variable, not the address of "
7288 "a variable", expr, expr);
7289 return true;
7291 else
7293 if (complain & tf_error)
7294 error ("%qE is not a valid template argument for %qT "
7295 "because it is not the address of a variable",
7296 expr, type);
7297 return true;
7301 return false;
7305 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7306 template argument EXPR. */
7308 static tree
7309 create_template_parm_object (tree expr, tsubst_flags_t complain)
7311 tree orig = expr;
7312 if (TREE_CODE (expr) == TARGET_EXPR)
7313 expr = TARGET_EXPR_INITIAL (expr);
7315 if (!TREE_CONSTANT (expr))
7317 if ((complain & tf_error)
7318 && require_rvalue_constant_expression (orig))
7319 cxx_constant_value (orig);
7320 return error_mark_node;
7322 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7323 return error_mark_node;
7325 /* This is no longer a compound literal. */
7326 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7328 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7331 /* The template arguments corresponding to template parameter objects of types
7332 that contain pointers to members. */
7334 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7336 /* Find or build an nttp object for (already-validated) EXPR with name
7337 NAME. */
7339 tree
7340 get_template_parm_object (tree expr, tree name)
7342 tree decl = get_global_binding (name);
7343 if (decl)
7344 return decl;
7346 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7347 decl = create_temporary_var (type);
7348 DECL_NTTP_OBJECT_P (decl) = true;
7349 DECL_CONTEXT (decl) = NULL_TREE;
7350 TREE_STATIC (decl) = true;
7351 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7352 TREE_READONLY (decl) = true;
7353 DECL_NAME (decl) = name;
7354 SET_DECL_ASSEMBLER_NAME (decl, name);
7355 comdat_linkage (decl);
7357 if (!zero_init_p (type))
7359 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7360 lower_var_init before we're done mangling. So store the original
7361 value elsewhere. */
7362 tree copy = unshare_constructor (expr);
7363 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7366 pushdecl_top_level_and_finish (decl, expr);
7368 return decl;
7371 /* Return the actual template argument corresponding to template parameter
7372 object VAR. */
7374 tree
7375 tparm_object_argument (tree var)
7377 if (zero_init_p (TREE_TYPE (var)))
7378 return DECL_INITIAL (var);
7379 return *(tparm_obj_values->get (var));
7382 /* Attempt to convert the non-type template parameter EXPR to the
7383 indicated TYPE. If the conversion is successful, return the
7384 converted value. If the conversion is unsuccessful, return
7385 NULL_TREE if we issued an error message, or error_mark_node if we
7386 did not. We issue error messages for out-and-out bad template
7387 parameters, but not simply because the conversion failed, since we
7388 might be just trying to do argument deduction. Both TYPE and EXPR
7389 must be non-dependent.
7391 The conversion follows the special rules described in
7392 [temp.arg.nontype], and it is much more strict than an implicit
7393 conversion.
7395 This function is called twice for each template argument (see
7396 lookup_template_class for a more accurate description of this
7397 problem). This means that we need to handle expressions which
7398 are not valid in a C++ source, but can be created from the
7399 first call (for instance, casts to perform conversions). These
7400 hacks can go away after we fix the double coercion problem. */
7402 static tree
7403 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7405 tree expr_type;
7406 location_t loc = cp_expr_loc_or_input_loc (expr);
7408 /* Detect immediately string literals as invalid non-type argument.
7409 This special-case is not needed for correctness (we would easily
7410 catch this later), but only to provide better diagnostic for this
7411 common user mistake. As suggested by DR 100, we do not mention
7412 linkage issues in the diagnostic as this is not the point. */
7413 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7415 if (complain & tf_error)
7416 error ("%qE is not a valid template argument for type %qT "
7417 "because string literals can never be used in this context",
7418 expr, type);
7419 return NULL_TREE;
7422 /* Add the ADDR_EXPR now for the benefit of
7423 value_dependent_expression_p. */
7424 if (TYPE_PTROBV_P (type)
7425 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7427 expr = decay_conversion (expr, complain);
7428 if (expr == error_mark_node)
7429 return error_mark_node;
7432 /* If we are in a template, EXPR may be non-dependent, but still
7433 have a syntactic, rather than semantic, form. For example, EXPR
7434 might be a SCOPE_REF, rather than the VAR_DECL to which the
7435 SCOPE_REF refers. Preserving the qualifying scope is necessary
7436 so that access checking can be performed when the template is
7437 instantiated -- but here we need the resolved form so that we can
7438 convert the argument. */
7439 bool non_dep = false;
7440 if (TYPE_REF_OBJ_P (type)
7441 && has_value_dependent_address (expr))
7442 /* If we want the address and it's value-dependent, don't fold. */;
7443 else if (processing_template_decl
7444 && !instantiation_dependent_expression_p (expr))
7445 non_dep = true;
7446 if (error_operand_p (expr))
7447 return error_mark_node;
7448 expr_type = TREE_TYPE (expr);
7450 /* If the argument is non-dependent, perform any conversions in
7451 non-dependent context as well. */
7452 processing_template_decl_sentinel s (non_dep);
7453 if (non_dep)
7454 expr = instantiate_non_dependent_expr_internal (expr, complain);
7456 bool val_dep_p = value_dependent_expression_p (expr);
7457 if (val_dep_p)
7458 expr = canonicalize_expr_argument (expr, complain);
7459 else
7460 STRIP_ANY_LOCATION_WRAPPER (expr);
7462 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7463 to a non-type argument of "nullptr". */
7464 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7465 expr = fold_simple (convert (type, expr));
7467 /* In C++11, integral or enumeration non-type template arguments can be
7468 arbitrary constant expressions. Pointer and pointer to
7469 member arguments can be general constant expressions that evaluate
7470 to a null value, but otherwise still need to be of a specific form. */
7471 if (cxx_dialect >= cxx11)
7473 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7474 /* A PTRMEM_CST is already constant, and a valid template
7475 argument for a parameter of pointer to member type, we just want
7476 to leave it in that form rather than lower it to a
7477 CONSTRUCTOR. */;
7478 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7479 || cxx_dialect >= cxx17)
7481 /* C++17: A template-argument for a non-type template-parameter shall
7482 be a converted constant expression (8.20) of the type of the
7483 template-parameter. */
7484 expr = build_converted_constant_expr (type, expr, complain);
7485 if (expr == error_mark_node)
7486 /* Make sure we return NULL_TREE only if we have really issued
7487 an error, as described above. */
7488 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7489 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7491 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7492 return expr;
7494 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7495 expr = convert_from_reference (expr);
7496 /* EXPR may have become value-dependent. */
7497 val_dep_p = value_dependent_expression_p (expr);
7499 else if (TYPE_PTR_OR_PTRMEM_P (type))
7501 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7502 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7503 : null_member_pointer_value_p (folded))
7504 expr = folded;
7508 if (TYPE_REF_P (type))
7509 expr = mark_lvalue_use (expr);
7510 else
7511 expr = mark_rvalue_use (expr);
7513 /* HACK: Due to double coercion, we can get a
7514 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7515 which is the tree that we built on the first call (see
7516 below when coercing to reference to object or to reference to
7517 function). We just strip everything and get to the arg.
7518 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7519 for examples. */
7520 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7522 /* Check this before we strip *& to avoid redundancy. */
7523 if (!mark_single_function (expr, complain))
7524 return error_mark_node;
7526 tree probe_type, probe = expr;
7527 if (REFERENCE_REF_P (probe))
7528 probe = TREE_OPERAND (probe, 0);
7529 probe_type = TREE_TYPE (probe);
7530 if (TREE_CODE (probe) == NOP_EXPR)
7532 /* ??? Maybe we could use convert_from_reference here, but we
7533 would need to relax its constraints because the NOP_EXPR
7534 could actually change the type to something more cv-qualified,
7535 and this is not folded by convert_from_reference. */
7536 tree addr = TREE_OPERAND (probe, 0);
7537 if (TYPE_REF_P (probe_type)
7538 && TREE_CODE (addr) == ADDR_EXPR
7539 && TYPE_PTR_P (TREE_TYPE (addr))
7540 && (same_type_ignoring_top_level_qualifiers_p
7541 (TREE_TYPE (probe_type),
7542 TREE_TYPE (TREE_TYPE (addr)))))
7544 expr = TREE_OPERAND (addr, 0);
7545 expr_type = TREE_TYPE (probe_type);
7550 /* [temp.arg.nontype]/5, bullet 1
7552 For a non-type template-parameter of integral or enumeration type,
7553 integral promotions (_conv.prom_) and integral conversions
7554 (_conv.integral_) are applied. */
7555 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7556 || SCALAR_FLOAT_TYPE_P (type))
7558 if (cxx_dialect < cxx11)
7560 tree t = build_converted_constant_expr (type, expr, complain);
7561 t = maybe_constant_value (t);
7562 if (t != error_mark_node)
7563 expr = t;
7566 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7567 return error_mark_node;
7569 /* Notice that there are constant expressions like '4 % 0' which
7570 do not fold into integer constants. */
7571 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7573 if (complain & tf_error)
7575 int errs = errorcount, warns = warningcount + werrorcount;
7576 if (!require_potential_constant_expression (expr))
7577 expr = error_mark_node;
7578 else
7579 expr = cxx_constant_value (expr);
7580 if (errorcount > errs || warningcount + werrorcount > warns)
7581 inform (loc, "in template argument for type %qT", type);
7582 if (expr == error_mark_node)
7583 return NULL_TREE;
7584 /* else cxx_constant_value complained but gave us
7585 a real constant, so go ahead. */
7586 if (!CONSTANT_CLASS_P (expr))
7588 /* Some assemble time constant expressions like
7589 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7590 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7591 as we can emit them into .rodata initializers of
7592 variables, yet they can't fold into an INTEGER_CST at
7593 compile time. Refuse them here. */
7594 gcc_checking_assert (reduced_constant_expression_p (expr));
7595 error_at (loc, "template argument %qE for type %qT not "
7596 "a compile-time constant", expr, type);
7597 return NULL_TREE;
7600 else
7601 return NULL_TREE;
7604 /* Avoid typedef problems. */
7605 if (TREE_TYPE (expr) != type)
7606 expr = fold_convert (type, expr);
7608 /* [temp.arg.nontype]/5, bullet 2
7610 For a non-type template-parameter of type pointer to object,
7611 qualification conversions (_conv.qual_) and the array-to-pointer
7612 conversion (_conv.array_) are applied. */
7613 else if (TYPE_PTROBV_P (type))
7615 tree decayed = expr;
7617 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7618 decay_conversion or an explicit cast. If it's a problematic cast,
7619 we'll complain about it below. */
7620 if (TREE_CODE (expr) == NOP_EXPR)
7622 tree probe = expr;
7623 STRIP_NOPS (probe);
7624 if (TREE_CODE (probe) == ADDR_EXPR
7625 && TYPE_PTR_P (TREE_TYPE (probe)))
7627 expr = probe;
7628 expr_type = TREE_TYPE (expr);
7632 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7634 A template-argument for a non-type, non-template template-parameter
7635 shall be one of: [...]
7637 -- the name of a non-type template-parameter;
7638 -- the address of an object or function with external linkage, [...]
7639 expressed as "& id-expression" where the & is optional if the name
7640 refers to a function or array, or if the corresponding
7641 template-parameter is a reference.
7643 Here, we do not care about functions, as they are invalid anyway
7644 for a parameter of type pointer-to-object. */
7646 if (val_dep_p)
7647 /* Non-type template parameters are OK. */
7649 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7650 /* Null pointer values are OK in C++11. */;
7651 else if (TREE_CODE (expr) != ADDR_EXPR
7652 && !INDIRECT_TYPE_P (expr_type))
7653 /* Other values, like integer constants, might be valid
7654 non-type arguments of some other type. */
7655 return error_mark_node;
7656 else if (invalid_tparm_referent_p (type, expr, complain))
7657 return NULL_TREE;
7659 expr = decayed;
7661 expr = perform_qualification_conversions (type, expr);
7662 if (expr == error_mark_node)
7663 return error_mark_node;
7665 /* [temp.arg.nontype]/5, bullet 3
7667 For a non-type template-parameter of type reference to object, no
7668 conversions apply. The type referred to by the reference may be more
7669 cv-qualified than the (otherwise identical) type of the
7670 template-argument. The template-parameter is bound directly to the
7671 template-argument, which must be an lvalue. */
7672 else if (TYPE_REF_OBJ_P (type))
7674 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7675 expr_type))
7676 return error_mark_node;
7678 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7680 if (complain & tf_error)
7681 error ("%qE is not a valid template argument for type %qT "
7682 "because of conflicts in cv-qualification", expr, type);
7683 return NULL_TREE;
7686 if (!lvalue_p (expr))
7688 if (complain & tf_error)
7689 error ("%qE is not a valid template argument for type %qT "
7690 "because it is not an lvalue", expr, type);
7691 return NULL_TREE;
7694 /* [temp.arg.nontype]/1
7696 A template-argument for a non-type, non-template template-parameter
7697 shall be one of: [...]
7699 -- the address of an object or function with external linkage. */
7700 if (INDIRECT_REF_P (expr)
7701 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7703 expr = TREE_OPERAND (expr, 0);
7704 if (DECL_P (expr))
7706 if (complain & tf_error)
7707 error ("%q#D is not a valid template argument for type %qT "
7708 "because a reference variable does not have a constant "
7709 "address", expr, type);
7710 return NULL_TREE;
7714 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7715 /* OK, dependent reference. We don't want to ask whether a DECL is
7716 itself value-dependent, since what we want here is its address. */;
7717 else
7719 expr = build_address (expr);
7721 if (invalid_tparm_referent_p (type, expr, complain))
7722 return NULL_TREE;
7725 if (!same_type_p (type, TREE_TYPE (expr)))
7726 expr = build_nop (type, expr);
7728 /* [temp.arg.nontype]/5, bullet 4
7730 For a non-type template-parameter of type pointer to function, only
7731 the function-to-pointer conversion (_conv.func_) is applied. If the
7732 template-argument represents a set of overloaded functions (or a
7733 pointer to such), the matching function is selected from the set
7734 (_over.over_). */
7735 else if (TYPE_PTRFN_P (type))
7737 /* If the argument is a template-id, we might not have enough
7738 context information to decay the pointer. */
7739 if (!type_unknown_p (expr_type))
7741 expr = decay_conversion (expr, complain);
7742 if (expr == error_mark_node)
7743 return error_mark_node;
7746 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7747 /* Null pointer values are OK in C++11. */
7748 return perform_qualification_conversions (type, expr);
7750 expr = convert_nontype_argument_function (type, expr, complain);
7751 if (!expr || expr == error_mark_node)
7752 return expr;
7754 /* [temp.arg.nontype]/5, bullet 5
7756 For a non-type template-parameter of type reference to function, no
7757 conversions apply. If the template-argument represents a set of
7758 overloaded functions, the matching function is selected from the set
7759 (_over.over_). */
7760 else if (TYPE_REFFN_P (type))
7762 if (TREE_CODE (expr) == ADDR_EXPR)
7764 if (complain & tf_error)
7766 error ("%qE is not a valid template argument for type %qT "
7767 "because it is a pointer", expr, type);
7768 inform (input_location, "try using %qE instead",
7769 TREE_OPERAND (expr, 0));
7771 return NULL_TREE;
7774 expr = convert_nontype_argument_function (type, expr, complain);
7775 if (!expr || expr == error_mark_node)
7776 return expr;
7778 /* [temp.arg.nontype]/5, bullet 6
7780 For a non-type template-parameter of type pointer to member function,
7781 no conversions apply. If the template-argument represents a set of
7782 overloaded member functions, the matching member function is selected
7783 from the set (_over.over_). */
7784 else if (TYPE_PTRMEMFUNC_P (type))
7786 expr = instantiate_type (type, expr, tf_none);
7787 if (expr == error_mark_node)
7788 return error_mark_node;
7790 /* [temp.arg.nontype] bullet 1 says the pointer to member
7791 expression must be a pointer-to-member constant. */
7792 if (!val_dep_p
7793 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7794 return NULL_TREE;
7796 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7797 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7798 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7799 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7801 /* [temp.arg.nontype]/5, bullet 7
7803 For a non-type template-parameter of type pointer to data member,
7804 qualification conversions (_conv.qual_) are applied. */
7805 else if (TYPE_PTRDATAMEM_P (type))
7807 /* [temp.arg.nontype] bullet 1 says the pointer to member
7808 expression must be a pointer-to-member constant. */
7809 if (!val_dep_p
7810 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7811 return NULL_TREE;
7813 expr = perform_qualification_conversions (type, expr);
7814 if (expr == error_mark_node)
7815 return expr;
7817 else if (NULLPTR_TYPE_P (type))
7819 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7821 if (complain & tf_error)
7822 error ("%qE is not a valid template argument for type %qT "
7823 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7824 return NULL_TREE;
7826 return expr;
7828 else if (CLASS_TYPE_P (type))
7830 /* Replace the argument with a reference to the corresponding template
7831 parameter object. */
7832 if (!val_dep_p)
7833 expr = create_template_parm_object (expr, complain);
7834 if (expr == error_mark_node)
7835 return NULL_TREE;
7837 /* A template non-type parameter must be one of the above. */
7838 else
7839 gcc_unreachable ();
7841 /* Sanity check: did we actually convert the argument to the
7842 right type? */
7843 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7844 (type, TREE_TYPE (expr)));
7845 return convert_from_reference (expr);
7848 /* Subroutine of coerce_template_template_parms, which returns 1 if
7849 PARM_PARM and ARG_PARM match using the rule for the template
7850 parameters of template template parameters. Both PARM and ARG are
7851 template parameters; the rest of the arguments are the same as for
7852 coerce_template_template_parms.
7854 static int
7855 coerce_template_template_parm (tree parm,
7856 tree arg,
7857 tsubst_flags_t complain,
7858 tree in_decl,
7859 tree outer_args)
7861 if (arg == NULL_TREE || error_operand_p (arg)
7862 || parm == NULL_TREE || error_operand_p (parm))
7863 return 0;
7865 if (TREE_CODE (arg) != TREE_CODE (parm))
7866 return 0;
7868 switch (TREE_CODE (parm))
7870 case TEMPLATE_DECL:
7871 /* We encounter instantiations of templates like
7872 template <template <template <class> class> class TT>
7873 class C; */
7875 if (!coerce_template_template_parms
7876 (parm, arg, complain, in_decl, outer_args))
7877 return 0;
7879 /* Fall through. */
7881 case TYPE_DECL:
7882 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7883 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7884 /* Argument is a parameter pack but parameter is not. */
7885 return 0;
7886 break;
7888 case PARM_DECL:
7889 /* The tsubst call is used to handle cases such as
7891 template <int> class C {};
7892 template <class T, template <T> class TT> class D {};
7893 D<int, C> d;
7895 i.e. the parameter list of TT depends on earlier parameters. */
7896 if (!uses_template_parms (TREE_TYPE (arg)))
7898 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7899 if (!uses_template_parms (t)
7900 && !same_type_p (t, TREE_TYPE (arg)))
7901 return 0;
7904 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7905 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7906 /* Argument is a parameter pack but parameter is not. */
7907 return 0;
7909 break;
7911 default:
7912 gcc_unreachable ();
7915 return 1;
7918 /* Coerce template argument list ARGLIST for use with template
7919 template-parameter TEMPL. */
7921 static tree
7922 coerce_template_args_for_ttp (tree templ, tree arglist,
7923 tsubst_flags_t complain)
7925 /* Consider an example where a template template parameter declared as
7927 template <class T, class U = std::allocator<T> > class TT
7929 The template parameter level of T and U are one level larger than
7930 of TT. To proper process the default argument of U, say when an
7931 instantiation `TT<int>' is seen, we need to build the full
7932 arguments containing {int} as the innermost level. Outer levels,
7933 available when not appearing as default template argument, can be
7934 obtained from the arguments of the enclosing template.
7936 Suppose that TT is later substituted with std::vector. The above
7937 instantiation is `TT<int, std::allocator<T> >' with TT at
7938 level 1, and T at level 2, while the template arguments at level 1
7939 becomes {std::vector} and the inner level 2 is {int}. */
7941 tree outer = DECL_CONTEXT (templ);
7942 if (outer)
7943 outer = generic_targs_for (outer);
7944 else if (current_template_parms)
7946 /* This is an argument of the current template, so we haven't set
7947 DECL_CONTEXT yet. We can also get here when level-lowering a
7948 bound ttp. */
7949 tree relevant_template_parms;
7951 /* Parameter levels that are greater than the level of the given
7952 template template parm are irrelevant. */
7953 relevant_template_parms = current_template_parms;
7954 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7955 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7956 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7958 outer = template_parms_to_args (relevant_template_parms);
7961 if (outer)
7962 arglist = add_to_template_args (outer, arglist);
7964 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7965 return coerce_template_parms (parmlist, arglist, templ, complain);
7968 /* A cache of template template parameters with match-all default
7969 arguments. */
7970 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7972 /* T is a bound template template-parameter. Copy its arguments into default
7973 arguments of the template template-parameter's template parameters. */
7975 static tree
7976 add_defaults_to_ttp (tree otmpl)
7978 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7979 return *c;
7981 tree ntmpl = copy_node (otmpl);
7983 tree ntype = copy_node (TREE_TYPE (otmpl));
7984 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7985 TYPE_MAIN_VARIANT (ntype) = ntype;
7986 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7987 TYPE_NAME (ntype) = ntmpl;
7988 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7990 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7991 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7992 TEMPLATE_PARM_DECL (idx) = ntmpl;
7993 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7995 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7996 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7997 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7998 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7999 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
8001 tree o = TREE_VEC_ELT (vec, i);
8002 if (!template_parameter_pack_p (TREE_VALUE (o)))
8004 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
8005 TREE_PURPOSE (n) = any_targ_node;
8009 tree oresult = DECL_TEMPLATE_RESULT (otmpl);
8010 tree gen_otmpl = DECL_TI_TEMPLATE (oresult);
8011 tree gen_ntmpl;
8012 if (gen_otmpl == otmpl)
8013 gen_ntmpl = ntmpl;
8014 else
8015 gen_ntmpl = add_defaults_to_ttp (gen_otmpl);
8017 tree nresult = copy_decl (oresult);
8018 DECL_TEMPLATE_INFO (nresult)
8019 = build_template_info (gen_ntmpl, TI_ARGS (DECL_TEMPLATE_INFO (oresult)));
8020 DECL_TEMPLATE_RESULT (ntmpl) = nresult;
8022 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
8023 return ntmpl;
8026 /* ARG is a bound potential template template-argument, and PARGS is a list
8027 of arguments for the corresponding template template-parameter. Adjust
8028 PARGS as appropriate for application to ARG's template, and if ARG is a
8029 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
8030 arguments to the template template parameter. */
8032 static tree
8033 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
8035 ++processing_template_decl;
8036 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
8037 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8039 /* When comparing two template template-parameters in partial ordering,
8040 rewrite the one currently being used as an argument to have default
8041 arguments for all parameters. */
8042 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
8043 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
8044 if (pargs != error_mark_node)
8045 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
8046 TYPE_TI_ARGS (arg));
8048 else
8050 tree aparms
8051 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
8052 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
8054 --processing_template_decl;
8055 return pargs;
8058 /* Subroutine of unify for the case when PARM is a
8059 BOUND_TEMPLATE_TEMPLATE_PARM. */
8061 static int
8062 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
8063 bool explain_p)
8065 tree parmvec = TYPE_TI_ARGS (parm);
8066 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
8068 /* The template template parm might be variadic and the argument
8069 not, so flatten both argument lists. */
8070 parmvec = expand_template_argument_pack (parmvec);
8071 argvec = expand_template_argument_pack (argvec);
8073 if (flag_new_ttp)
8075 /* In keeping with P0522R0, adjust P's template arguments
8076 to apply to A's template; then flatten it again. */
8077 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
8078 nparmvec = expand_template_argument_pack (nparmvec);
8080 if (unify (tparms, targs, nparmvec, argvec,
8081 UNIFY_ALLOW_NONE, explain_p))
8082 return 1;
8084 /* If the P0522 adjustment eliminated a pack expansion, deduce
8085 empty packs. */
8086 if (flag_new_ttp
8087 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8088 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8089 DEDUCE_EXACT, /*sub*/true, explain_p))
8090 return 1;
8092 else
8094 /* Deduce arguments T, i from TT<T> or TT<i>.
8095 We check each element of PARMVEC and ARGVEC individually
8096 rather than the whole TREE_VEC since they can have
8097 different number of elements, which is allowed under N2555. */
8099 int len = TREE_VEC_LENGTH (parmvec);
8101 /* Check if the parameters end in a pack, making them
8102 variadic. */
8103 int parm_variadic_p = 0;
8104 if (len > 0
8105 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8106 parm_variadic_p = 1;
8108 for (int i = 0; i < len - parm_variadic_p; ++i)
8109 /* If the template argument list of P contains a pack
8110 expansion that is not the last template argument, the
8111 entire template argument list is a non-deduced
8112 context. */
8113 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8114 return unify_success (explain_p);
8116 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8117 return unify_too_few_arguments (explain_p,
8118 TREE_VEC_LENGTH (argvec), len);
8120 for (int i = 0; i < len - parm_variadic_p; ++i)
8121 if (unify (tparms, targs,
8122 TREE_VEC_ELT (parmvec, i),
8123 TREE_VEC_ELT (argvec, i),
8124 UNIFY_ALLOW_NONE, explain_p))
8125 return 1;
8127 if (parm_variadic_p
8128 && unify_pack_expansion (tparms, targs,
8129 parmvec, argvec,
8130 DEDUCE_EXACT,
8131 /*subr=*/true, explain_p))
8132 return 1;
8135 return 0;
8138 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8139 template template parameters.
8141 Consider the example:
8142 template <class T> class A;
8143 template<template <class U> class TT> class B;
8145 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8146 and OUTER_ARGS contains A. */
8148 static int
8149 coerce_template_template_parms (tree parm_tmpl,
8150 tree arg_tmpl,
8151 tsubst_flags_t complain,
8152 tree in_decl,
8153 tree outer_args)
8155 int nparms, nargs, i;
8156 tree parm, arg;
8157 int variadic_p = 0;
8159 tree parm_parms = DECL_INNERMOST_TEMPLATE_PARMS (parm_tmpl);
8160 tree arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (arg_tmpl);
8161 tree gen_arg_tmpl = most_general_template (arg_tmpl);
8162 tree gen_arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_arg_tmpl);
8164 nparms = TREE_VEC_LENGTH (parm_parms);
8165 nargs = TREE_VEC_LENGTH (arg_parms);
8167 if (flag_new_ttp)
8169 /* P0522R0: A template template-parameter P is at least as specialized as
8170 a template template-argument A if, given the following rewrite to two
8171 function templates, the function template corresponding to P is at
8172 least as specialized as the function template corresponding to A
8173 according to the partial ordering rules for function templates
8174 ([temp.func.order]). Given an invented class template X with the
8175 template parameter list of A (including default arguments):
8177 * Each of the two function templates has the same template parameters,
8178 respectively, as P or A.
8180 * Each function template has a single function parameter whose type is
8181 a specialization of X with template arguments corresponding to the
8182 template parameters from the respective function template where, for
8183 each template parameter PP in the template parameter list of the
8184 function template, a corresponding template argument AA is formed. If
8185 PP declares a parameter pack, then AA is the pack expansion
8186 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8188 If the rewrite produces an invalid type, then P is not at least as
8189 specialized as A. */
8191 /* So coerce P's args to apply to A's parms, and then deduce between A's
8192 args and the converted args. If that succeeds, A is at least as
8193 specialized as P, so they match.*/
8194 processing_template_decl_sentinel ptds (/*reset*/false);
8195 ++processing_template_decl;
8197 tree pargs = template_parms_level_to_args (parm_parms);
8199 /* PARM and ARG might be at different template depths, and we want to
8200 pass the right additional levels of args when coercing PARGS to
8201 ARG_PARMS in case we need to do any substitution into non-type
8202 template parameter types.
8204 OUTER_ARGS are not the right outer levels in this case, as they are
8205 the args we're building up for PARM, and for the coercion we want the
8206 args for ARG. If DECL_CONTEXT isn't set for a template template
8207 parameter, we can assume that it's in the current scope. */
8208 tree ctx = DECL_CONTEXT (arg_tmpl);
8209 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8210 ctx = current_scope ();
8211 tree scope_args = NULL_TREE;
8212 if (tree tinfo = get_template_info (ctx))
8213 scope_args = TI_ARGS (tinfo);
8214 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8216 int level = TEMPLATE_TYPE_LEVEL (TREE_TYPE (gen_arg_tmpl));
8217 int scope_depth = TMPL_ARGS_DEPTH (scope_args);
8218 tree full_pargs = make_tree_vec (level + 1);
8220 /* Only use as many levels from the scope as needed
8221 (excluding the level of ARG). */
8222 for (int i = 0; i < level - 1; ++i)
8223 if (i < scope_depth)
8224 TREE_VEC_ELT (full_pargs, i) = TMPL_ARGS_LEVEL (scope_args, i + 1);
8225 else
8226 TREE_VEC_ELT (full_pargs, i) = make_tree_vec (0);
8228 /* Add the arguments that appear at the levels of ARG. */
8229 tree adjacent = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (arg_tmpl));
8230 adjacent = TMPL_ARGS_LEVEL (adjacent, TMPL_ARGS_DEPTH (adjacent) - 1);
8231 TREE_VEC_ELT (full_pargs, level - 1) = adjacent;
8233 TREE_VEC_ELT (full_pargs, level) = pargs;
8234 pargs = full_pargs;
8236 else
8237 pargs = add_to_template_args (scope_args, pargs);
8239 pargs = coerce_template_parms (gen_arg_parms, pargs,
8240 NULL_TREE, tf_none);
8241 if (pargs != error_mark_node)
8243 tree targs = make_tree_vec (nargs);
8244 tree aargs = template_parms_level_to_args (arg_parms);
8245 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8246 /*explain*/false))
8247 return 1;
8251 /* Determine whether we have a parameter pack at the end of the
8252 template template parameter's template parameter list. */
8253 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8255 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8257 if (error_operand_p (parm))
8258 return 0;
8260 switch (TREE_CODE (parm))
8262 case TEMPLATE_DECL:
8263 case TYPE_DECL:
8264 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8265 variadic_p = 1;
8266 break;
8268 case PARM_DECL:
8269 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8270 variadic_p = 1;
8271 break;
8273 default:
8274 gcc_unreachable ();
8278 if (nargs != nparms
8279 && !(variadic_p && nargs >= nparms - 1))
8280 return 0;
8282 /* Check all of the template parameters except the parameter pack at
8283 the end (if any). */
8284 for (i = 0; i < nparms - variadic_p; ++i)
8286 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8287 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8288 continue;
8290 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8291 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8293 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8294 outer_args))
8295 return 0;
8299 if (variadic_p)
8301 /* Check each of the template parameters in the template
8302 argument against the template parameter pack at the end of
8303 the template template parameter. */
8304 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8305 return 0;
8307 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8309 for (; i < nargs; ++i)
8311 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8312 continue;
8314 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8316 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8317 outer_args))
8318 return 0;
8322 return 1;
8325 /* Verifies that the deduced template arguments (in TARGS) for the
8326 template template parameters (in TPARMS) represent valid bindings,
8327 by comparing the template parameter list of each template argument
8328 to the template parameter list of its corresponding template
8329 template parameter, in accordance with DR150. This
8330 routine can only be called after all template arguments have been
8331 deduced. It will return TRUE if all of the template template
8332 parameter bindings are okay, FALSE otherwise. */
8333 bool
8334 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8336 int i, ntparms = TREE_VEC_LENGTH (tparms);
8337 bool ret = true;
8339 /* We're dealing with template parms in this process. */
8340 ++processing_template_decl;
8342 targs = INNERMOST_TEMPLATE_ARGS (targs);
8344 for (i = 0; i < ntparms; ++i)
8346 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8347 tree targ = TREE_VEC_ELT (targs, i);
8349 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8351 tree packed_args = NULL_TREE;
8352 int idx, len = 1;
8354 if (ARGUMENT_PACK_P (targ))
8356 /* Look inside the argument pack. */
8357 packed_args = ARGUMENT_PACK_ARGS (targ);
8358 len = TREE_VEC_LENGTH (packed_args);
8361 for (idx = 0; idx < len; ++idx)
8363 if (packed_args)
8364 /* Extract the next argument from the argument
8365 pack. */
8366 targ = TREE_VEC_ELT (packed_args, idx);
8368 if (PACK_EXPANSION_P (targ))
8369 /* Look at the pattern of the pack expansion. */
8370 targ = PACK_EXPANSION_PATTERN (targ);
8372 /* Extract the template parameters from the template
8373 argument. */
8374 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8375 targ = TYPE_NAME (targ);
8377 /* Verify that we can coerce the template template
8378 parameters from the template argument to the template
8379 parameter. This requires an exact match. */
8380 if (TREE_CODE (targ) == TEMPLATE_DECL
8381 && !coerce_template_template_parms
8382 (tparm,
8383 targ,
8384 tf_none,
8385 tparm,
8386 targs))
8388 ret = false;
8389 goto out;
8395 out:
8397 --processing_template_decl;
8398 return ret;
8401 /* Since type attributes aren't mangled, we need to strip them from
8402 template type arguments. */
8404 tree
8405 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8407 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8408 return arg;
8409 bool removed_attributes = false;
8410 tree canon = strip_typedefs (arg, &removed_attributes);
8411 if (removed_attributes
8412 && (complain & tf_warning))
8413 warning (OPT_Wignored_attributes,
8414 "ignoring attributes on template argument %qT", arg);
8415 return canon;
8418 /* And from inside dependent non-type arguments like sizeof(Type). */
8420 static tree
8421 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8423 if (!arg || arg == error_mark_node)
8424 return arg;
8425 bool removed_attributes = false;
8426 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8427 if (removed_attributes
8428 && (complain & tf_warning))
8429 warning (OPT_Wignored_attributes,
8430 "ignoring attributes in template argument %qE", arg);
8431 return canon;
8434 /* A template declaration can be substituted for a constrained
8435 template template parameter only when the argument is no more
8436 constrained than the parameter. */
8438 static bool
8439 is_compatible_template_arg (tree parm, tree arg, tree args)
8441 tree parm_cons = get_constraints (parm);
8443 /* For now, allow constrained template template arguments
8444 and unconstrained template template parameters. */
8445 if (parm_cons == NULL_TREE)
8446 return true;
8448 /* If the template parameter is constrained, we need to rewrite its
8449 constraints in terms of the ARG's template parameters. This ensures
8450 that all of the template parameter types will have the same depth.
8452 Note that this is only valid when coerce_template_template_parm is
8453 true for the innermost template parameters of PARM and ARG. In other
8454 words, because coercion is successful, this conversion will be valid. */
8455 tree new_args = NULL_TREE;
8456 if (parm_cons)
8458 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8459 new_args = template_parms_level_to_args (aparms);
8460 new_args = add_to_template_args (args, new_args);
8461 ++processing_template_decl;
8462 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8463 tf_none, NULL_TREE);
8464 --processing_template_decl;
8465 if (parm_cons == error_mark_node)
8466 return false;
8469 return weakly_subsumes (parm_cons, arg);
8472 // Convert a placeholder argument into a binding to the original
8473 // parameter. The original parameter is saved as the TREE_TYPE of
8474 // ARG.
8475 static inline tree
8476 convert_wildcard_argument (tree parm, tree arg)
8478 TREE_TYPE (arg) = parm;
8479 return arg;
8482 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8483 because one of them is dependent. But we need to represent the
8484 conversion for the benefit of cp_tree_equal. */
8486 static tree
8487 maybe_convert_nontype_argument (tree type, tree arg, bool force)
8489 /* Auto parms get no conversion. */
8490 if (type_uses_auto (type))
8491 return arg;
8492 /* ??? Do we need to push the IMPLICIT_CONV_EXPR into the pack expansion?
8493 That would complicate other things, and it doesn't seem necessary. */
8494 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
8495 return arg;
8496 /* We don't need or want to add this conversion now if we're going to use the
8497 argument for deduction. */
8498 if (!value_dependent_expression_p (arg))
8499 force = false;
8500 else if (!force)
8501 return arg;
8503 type = cv_unqualified (type);
8504 tree argtype = TREE_TYPE (arg);
8505 if (argtype && same_type_p (type, argtype))
8506 return arg;
8508 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8509 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8510 IMPLICIT_CONV_EXPR_FORCED (arg) = force;
8511 return arg;
8514 /* Convert the indicated template ARG as necessary to match the
8515 indicated template PARM. Returns the converted ARG, or
8516 error_mark_node if the conversion was unsuccessful. Error and
8517 warning messages are issued under control of COMPLAIN. This
8518 conversion is for the Ith parameter in the parameter list. ARGS is
8519 the full set of template arguments deduced so far. */
8521 static tree
8522 convert_template_argument (tree parm,
8523 tree arg,
8524 tree args,
8525 tsubst_flags_t complain,
8526 int i,
8527 tree in_decl)
8529 tree orig_arg;
8530 tree val;
8531 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8533 if (parm == error_mark_node || error_operand_p (arg))
8534 return error_mark_node;
8536 /* Trivially convert placeholders. */
8537 if (TREE_CODE (arg) == WILDCARD_DECL)
8538 return convert_wildcard_argument (parm, arg);
8540 if (arg == any_targ_node)
8541 return arg;
8543 if (TREE_CODE (arg) == TREE_LIST
8544 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8546 /* The template argument was the name of some
8547 member function. That's usually
8548 invalid, but static members are OK. In any
8549 case, grab the underlying fields/functions
8550 and issue an error later if required. */
8551 TREE_TYPE (arg) = unknown_type_node;
8554 orig_arg = arg;
8556 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8557 requires_type = (TREE_CODE (parm) == TYPE_DECL
8558 || requires_tmpl_type);
8560 /* When determining whether an argument pack expansion is a template,
8561 look at the pattern. */
8562 if (PACK_EXPANSION_P (arg))
8563 arg = PACK_EXPANSION_PATTERN (arg);
8565 /* Deal with an injected-class-name used as a template template arg. */
8566 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8568 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8569 if (TREE_CODE (t) == TEMPLATE_DECL)
8571 if (cxx_dialect >= cxx11)
8572 /* OK under DR 1004. */;
8573 else if (complain & tf_warning_or_error)
8574 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8575 " used as template template argument", TYPE_NAME (arg));
8576 else if (flag_pedantic_errors)
8577 t = arg;
8579 arg = t;
8583 is_tmpl_type =
8584 ((TREE_CODE (arg) == TEMPLATE_DECL
8585 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8586 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8587 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8588 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8590 if (is_tmpl_type
8591 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8592 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8593 arg = TYPE_STUB_DECL (arg);
8595 is_type = TYPE_P (arg) || is_tmpl_type;
8597 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8598 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8600 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8602 if (complain & tf_error)
8603 error ("invalid use of destructor %qE as a type", orig_arg);
8604 return error_mark_node;
8607 permerror (input_location,
8608 "to refer to a type member of a template parameter, "
8609 "use %<typename %E%>", orig_arg);
8611 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8612 TREE_OPERAND (arg, 1),
8613 typename_type,
8614 complain);
8615 arg = orig_arg;
8616 is_type = 1;
8618 if (is_type != requires_type)
8620 if (in_decl)
8622 if (complain & tf_error)
8624 error ("type/value mismatch at argument %d in template "
8625 "parameter list for %qD",
8626 i + 1, in_decl);
8627 if (is_type)
8629 /* The template argument is a type, but we're expecting
8630 an expression. */
8631 inform (input_location,
8632 " expected a constant of type %qT, got %qT",
8633 TREE_TYPE (parm),
8634 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8635 /* [temp.arg]/2: "In a template-argument, an ambiguity
8636 between a type-id and an expression is resolved to a
8637 type-id, regardless of the form of the corresponding
8638 template-parameter." So give the user a clue. */
8639 if (TREE_CODE (arg) == FUNCTION_TYPE)
8640 inform (input_location, " ambiguous template argument "
8641 "for non-type template parameter is treated as "
8642 "function type");
8644 else if (requires_tmpl_type)
8645 inform (input_location,
8646 " expected a class template, got %qE", orig_arg);
8647 else
8648 inform (input_location,
8649 " expected a type, got %qE", orig_arg);
8652 return error_mark_node;
8654 if (is_tmpl_type ^ requires_tmpl_type)
8656 if (in_decl && (complain & tf_error))
8658 error ("type/value mismatch at argument %d in template "
8659 "parameter list for %qD",
8660 i + 1, in_decl);
8661 if (is_tmpl_type)
8662 inform (input_location,
8663 " expected a type, got %qT", DECL_NAME (arg));
8664 else
8665 inform (input_location,
8666 " expected a class template, got %qT", orig_arg);
8668 return error_mark_node;
8671 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8672 /* We already did the appropriate conversion when packing args. */
8673 val = orig_arg;
8674 else if (is_type)
8676 if (requires_tmpl_type)
8678 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8679 /* The number of argument required is not known yet.
8680 Just accept it for now. */
8681 val = orig_arg;
8682 else
8684 /* Strip alias templates that are equivalent to another
8685 template. */
8686 arg = get_underlying_template (arg);
8688 if (coerce_template_template_parms (parm, arg,
8689 complain, in_decl,
8690 args))
8692 val = arg;
8694 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8695 TEMPLATE_DECL. */
8696 if (val != error_mark_node)
8698 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8699 val = TREE_TYPE (val);
8700 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8701 val = make_pack_expansion (val, complain);
8704 else
8706 if (in_decl && (complain & tf_error))
8708 error ("type/value mismatch at argument %d in "
8709 "template parameter list for %qD",
8710 i + 1, in_decl);
8711 inform (input_location,
8712 " expected a template of type %qD, got %qT",
8713 parm, orig_arg);
8716 val = error_mark_node;
8719 // Check that the constraints are compatible before allowing the
8720 // substitution.
8721 if (val != error_mark_node)
8722 if (!is_compatible_template_arg (parm, arg, args))
8724 if (in_decl && (complain & tf_error))
8726 error ("constraint mismatch at argument %d in "
8727 "template parameter list for %qD",
8728 i + 1, in_decl);
8729 inform (input_location, " expected %qD but got %qD",
8730 parm, arg);
8732 val = error_mark_node;
8736 else
8737 val = orig_arg;
8738 /* We only form one instance of each template specialization.
8739 Therefore, if we use a non-canonical variant (i.e., a
8740 typedef), any future messages referring to the type will use
8741 the typedef, which is confusing if those future uses do not
8742 themselves also use the typedef. */
8743 if (TYPE_P (val))
8744 val = canonicalize_type_argument (val, complain);
8746 else
8748 tree t = TREE_TYPE (parm);
8750 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8751 > TMPL_ARGS_DEPTH (args))
8752 /* We don't have enough levels of args to do any substitution. This
8753 can happen in the context of -fnew-ttp-matching. */;
8754 else if (tree a = type_uses_auto (t))
8756 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8757 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8758 if (t == error_mark_node)
8759 return error_mark_node;
8761 else
8762 t = tsubst (t, args, complain, in_decl);
8764 /* Perform array-to-pointer and function-to-pointer conversion
8765 as per [temp.param]/10. */
8766 t = type_decays_to (t);
8768 if (invalid_nontype_parm_type_p (t, complain))
8769 return error_mark_node;
8771 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8772 this non-type template parameter, as per [temp.param]/6. */
8773 t = cv_unqualified (t);
8775 if (t != TREE_TYPE (parm))
8776 t = canonicalize_type_argument (t, complain);
8778 /* We need to handle arguments for alias or concept templates
8779 differently: we need to force building an IMPLICIT_CONV_EXPR, because
8780 these arguments are going to be substituted directly into the
8781 dependent type; they might not get another chance at
8782 convert_nontype_argument. But if the argument ends up here again for
8783 a template that isn't one of those, remove the conversion for
8784 consistency between naming the same dependent type directly or through
8785 an alias. */
8786 bool force_conv = in_decl && (DECL_ALIAS_TEMPLATE_P (in_decl)
8787 || concept_definition_p (in_decl));
8788 if (!force_conv
8789 && TREE_CODE (orig_arg) == IMPLICIT_CONV_EXPR
8790 && IMPLICIT_CONV_EXPR_FORCED (orig_arg)
8791 && same_type_p (TREE_TYPE (orig_arg), t))
8792 orig_arg = TREE_OPERAND (orig_arg, 0);
8794 if (!type_dependent_expression_p (orig_arg)
8795 && !uses_template_parms (t))
8796 /* We used to call digest_init here. However, digest_init
8797 will report errors, which we don't want when complain
8798 is zero. More importantly, digest_init will try too
8799 hard to convert things: for example, `0' should not be
8800 converted to pointer type at this point according to
8801 the standard. Accepting this is not merely an
8802 extension, since deciding whether or not these
8803 conversions can occur is part of determining which
8804 function template to call, or whether a given explicit
8805 argument specification is valid. */
8806 val = convert_nontype_argument (t, orig_arg, complain);
8807 else
8809 val = canonicalize_expr_argument (orig_arg, complain);
8810 val = maybe_convert_nontype_argument (t, val, force_conv);
8813 if (val == NULL_TREE)
8814 val = error_mark_node;
8815 else if (val == error_mark_node && (complain & tf_error))
8816 error_at (cp_expr_loc_or_input_loc (orig_arg),
8817 "could not convert template argument %qE from %qT to %qT",
8818 orig_arg, TREE_TYPE (orig_arg), t);
8820 if (INDIRECT_REF_P (val))
8822 /* Reject template arguments that are references to built-in
8823 functions with no library fallbacks. */
8824 const_tree inner = TREE_OPERAND (val, 0);
8825 const_tree innertype = TREE_TYPE (inner);
8826 if (innertype
8827 && TYPE_REF_P (innertype)
8828 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8829 && TREE_OPERAND_LENGTH (inner) > 0
8830 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8831 return error_mark_node;
8834 if (TREE_CODE (val) == SCOPE_REF)
8836 /* Strip typedefs from the SCOPE_REF. */
8837 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8838 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8839 complain);
8840 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8841 QUALIFIED_NAME_IS_TEMPLATE (val));
8845 return val;
8848 /* Coerces the remaining template arguments in INNER_ARGS (from
8849 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8850 Returns the coerced argument pack. PARM_IDX is the position of this
8851 parameter in the template parameter list. ARGS is the original
8852 template argument list. */
8853 static tree
8854 coerce_template_parameter_pack (tree parms,
8855 int parm_idx,
8856 tree args,
8857 tree inner_args,
8858 int arg_idx,
8859 tree new_args,
8860 int* lost,
8861 tree in_decl,
8862 tsubst_flags_t complain)
8864 tree parm = TREE_VEC_ELT (parms, parm_idx);
8865 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8866 tree packed_args;
8867 tree argument_pack;
8868 tree packed_parms = NULL_TREE;
8870 if (arg_idx > nargs)
8871 arg_idx = nargs;
8873 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8875 /* When the template parameter is a non-type template parameter pack
8876 or template template parameter pack whose type or template
8877 parameters use parameter packs, we know exactly how many arguments
8878 we are looking for. Build a vector of the instantiated decls for
8879 these template parameters in PACKED_PARMS. */
8880 /* We can't use make_pack_expansion here because it would interpret a
8881 _DECL as a use rather than a declaration. */
8882 tree decl = TREE_VALUE (parm);
8883 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8884 PACK_EXPANSION_PATTERN (exp) = decl;
8885 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8886 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8888 TREE_VEC_LENGTH (args)--;
8889 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8890 TREE_VEC_LENGTH (args)++;
8892 if (packed_parms == error_mark_node)
8893 return error_mark_node;
8895 /* If we're doing a partial instantiation of a member template,
8896 verify that all of the types used for the non-type
8897 template parameter pack are, in fact, valid for non-type
8898 template parameters. */
8899 if (arg_idx < nargs
8900 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8902 int j, len = TREE_VEC_LENGTH (packed_parms);
8903 for (j = 0; j < len; ++j)
8905 tree t = TREE_VEC_ELT (packed_parms, j);
8906 if (TREE_CODE (t) == PARM_DECL
8907 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8908 return error_mark_node;
8910 /* We don't know how many args we have yet, just
8911 use the unconverted ones for now. */
8912 return NULL_TREE;
8915 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8917 /* Check if we have a placeholder pack, which indicates we're
8918 in the context of a introduction list. In that case we want
8919 to match this pack to the single placeholder. */
8920 else if (arg_idx < nargs
8921 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8922 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8924 nargs = arg_idx + 1;
8925 packed_args = make_tree_vec (1);
8927 else
8928 packed_args = make_tree_vec (nargs - arg_idx);
8930 /* Convert the remaining arguments, which will be a part of the
8931 parameter pack "parm". */
8932 int first_pack_arg = arg_idx;
8933 for (; arg_idx < nargs; ++arg_idx)
8935 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8936 tree actual_parm = TREE_VALUE (parm);
8937 int pack_idx = arg_idx - first_pack_arg;
8939 if (packed_parms)
8941 /* Once we've packed as many args as we have types, stop. */
8942 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8943 break;
8944 else if (PACK_EXPANSION_P (arg))
8945 /* We don't know how many args we have yet, just
8946 use the unconverted ones for now. */
8947 return NULL_TREE;
8948 else
8949 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8952 if (arg == error_mark_node)
8954 if (complain & tf_error)
8955 error ("template argument %d is invalid", arg_idx + 1);
8957 else
8958 arg = convert_template_argument (actual_parm,
8959 arg, new_args, complain, parm_idx,
8960 in_decl);
8961 if (arg == error_mark_node)
8962 (*lost)++;
8963 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8966 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8967 && TREE_VEC_LENGTH (packed_args) > 0)
8969 if (complain & tf_error)
8970 error ("wrong number of template arguments (%d, should be %d)",
8971 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8972 return error_mark_node;
8975 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8976 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8977 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8978 else
8980 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8981 TREE_CONSTANT (argument_pack) = 1;
8984 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8985 if (CHECKING_P)
8986 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8987 TREE_VEC_LENGTH (packed_args));
8988 return argument_pack;
8991 /* Returns the number of pack expansions in the template argument vector
8992 ARGS. */
8994 static int
8995 pack_expansion_args_count (tree args)
8997 int i;
8998 int count = 0;
8999 if (args)
9000 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
9002 tree elt = TREE_VEC_ELT (args, i);
9003 if (elt && PACK_EXPANSION_P (elt))
9004 ++count;
9006 return count;
9009 /* Convert all template arguments to their appropriate types, and
9010 return a vector containing the innermost resulting template
9011 arguments. If any error occurs, return error_mark_node. Error and
9012 warning messages are issued under control of COMPLAIN.
9014 If PARMS represents all template parameters levels, this function
9015 returns a vector of vectors representing all the resulting argument
9016 levels. Note that in this case, only the innermost arguments are
9017 coerced because the outermost ones are supposed to have been coerced
9018 already. Otherwise, if PARMS represents only (the innermost) vector
9019 of parameters, this function returns a vector containing just the
9020 innermost resulting arguments.
9022 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
9023 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
9024 arguments not specified in ARGS must have default arguments which
9025 we'll use to fill in ARGS. */
9027 tree
9028 coerce_template_parms (tree parms,
9029 tree args,
9030 tree in_decl,
9031 tsubst_flags_t complain,
9032 bool require_all_args /* = true */)
9034 int nparms, nargs, parm_idx, arg_idx, lost = 0;
9035 tree orig_inner_args;
9036 tree inner_args;
9038 /* When used as a boolean value, indicates whether this is a
9039 variadic template parameter list. Since it's an int, we can also
9040 subtract it from nparms to get the number of non-variadic
9041 parameters. */
9042 int variadic_p = 0;
9043 int variadic_args_p = 0;
9044 int post_variadic_parms = 0;
9046 /* Adjustment to nparms for fixed parameter packs. */
9047 int fixed_pack_adjust = 0;
9048 int fixed_packs = 0;
9049 int missing = 0;
9051 /* Likewise for parameters with default arguments. */
9052 int default_p = 0;
9054 if (args == error_mark_node)
9055 return error_mark_node;
9057 bool return_full_args = false;
9058 if (TREE_CODE (parms) == TREE_LIST)
9060 if (TMPL_PARMS_DEPTH (parms) > 1)
9062 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
9063 return_full_args = true;
9065 parms = INNERMOST_TEMPLATE_PARMS (parms);
9068 nparms = TREE_VEC_LENGTH (parms);
9070 /* Determine if there are any parameter packs or default arguments. */
9071 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
9073 tree parm = TREE_VEC_ELT (parms, parm_idx);
9074 if (variadic_p)
9075 ++post_variadic_parms;
9076 if (template_parameter_pack_p (TREE_VALUE (parm)))
9077 ++variadic_p;
9078 if (TREE_PURPOSE (parm))
9079 ++default_p;
9082 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
9083 /* If there are no parameters that follow a parameter pack, we need to
9084 expand any argument packs so that we can deduce a parameter pack from
9085 some non-packed args followed by an argument pack, as in variadic85.C.
9086 If there are such parameters, we need to leave argument packs intact
9087 so the arguments are assigned properly. This can happen when dealing
9088 with a nested class inside a partial specialization of a class
9089 template, as in variadic92.C, or when deducing a template parameter pack
9090 from a sub-declarator, as in variadic114.C. */
9091 if (!post_variadic_parms)
9092 inner_args = expand_template_argument_pack (inner_args);
9094 /* Count any pack expansion args. */
9095 variadic_args_p = pack_expansion_args_count (inner_args);
9097 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
9098 if ((nargs - variadic_args_p > nparms && !variadic_p)
9099 || (nargs < nparms - variadic_p
9100 && require_all_args
9101 && !variadic_args_p
9102 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
9103 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
9105 bad_nargs:
9106 if (complain & tf_error)
9108 if (variadic_p || default_p)
9110 nparms -= variadic_p + default_p;
9111 error ("wrong number of template arguments "
9112 "(%d, should be at least %d)", nargs, nparms);
9114 else
9115 error ("wrong number of template arguments "
9116 "(%d, should be %d)", nargs, nparms);
9118 if (in_decl)
9119 inform (DECL_SOURCE_LOCATION (in_decl),
9120 "provided for %qD", in_decl);
9123 return error_mark_node;
9125 /* We can't pass a pack expansion to a non-pack parameter of an alias
9126 template (DR 1430). */
9127 else if (in_decl
9128 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9129 || concept_definition_p (in_decl))
9130 && variadic_args_p
9131 && nargs - variadic_args_p < nparms - variadic_p)
9133 if (complain & tf_error)
9135 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9137 tree arg = TREE_VEC_ELT (inner_args, i);
9138 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9140 if (PACK_EXPANSION_P (arg)
9141 && !template_parameter_pack_p (parm))
9143 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9144 error_at (location_of (arg),
9145 "pack expansion argument for non-pack parameter "
9146 "%qD of alias template %qD", parm, in_decl);
9147 else
9148 error_at (location_of (arg),
9149 "pack expansion argument for non-pack parameter "
9150 "%qD of concept %qD", parm, in_decl);
9151 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9152 goto found;
9155 gcc_unreachable ();
9156 found:;
9158 return error_mark_node;
9161 /* We need to evaluate the template arguments, even though this
9162 template-id may be nested within a "sizeof". */
9163 cp_evaluated ev;
9165 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9166 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9167 int pack_adjust = 0;
9168 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9170 tree arg;
9171 tree parm;
9173 /* Get the Ith template parameter. */
9174 parm = TREE_VEC_ELT (parms, parm_idx);
9176 if (parm == error_mark_node)
9178 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9179 continue;
9182 /* Calculate the next argument. */
9183 if (arg_idx < nargs)
9184 arg = TREE_VEC_ELT (inner_args, arg_idx);
9185 else
9186 arg = NULL_TREE;
9188 if (template_parameter_pack_p (TREE_VALUE (parm))
9189 && (arg || require_all_args || !(complain & tf_partial))
9190 && !(arg && ARGUMENT_PACK_P (arg)))
9192 /* Some arguments will be placed in the
9193 template parameter pack PARM. */
9194 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9195 inner_args, arg_idx,
9196 new_args, &lost,
9197 in_decl, complain);
9199 if (arg == NULL_TREE)
9201 /* We don't know how many args we have yet, just use the
9202 unconverted (and still packed) ones for now. */
9203 new_inner_args = orig_inner_args;
9204 arg_idx = nargs;
9205 break;
9208 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9210 /* Store this argument. */
9211 if (arg == error_mark_node)
9213 lost++;
9214 /* We are done with all of the arguments. */
9215 arg_idx = nargs;
9216 break;
9218 else
9220 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9221 arg_idx += pack_adjust;
9222 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9224 ++fixed_packs;
9225 fixed_pack_adjust += pack_adjust;
9229 continue;
9231 else if (arg)
9233 if (PACK_EXPANSION_P (arg))
9235 /* "If every valid specialization of a variadic template
9236 requires an empty template parameter pack, the template is
9237 ill-formed, no diagnostic required." So check that the
9238 pattern works with this parameter. */
9239 tree pattern = PACK_EXPANSION_PATTERN (arg);
9240 tree conv = convert_template_argument (TREE_VALUE (parm),
9241 pattern, new_args,
9242 complain, parm_idx,
9243 in_decl);
9244 if (conv == error_mark_node)
9246 if (complain & tf_error)
9247 inform (input_location, "so any instantiation with a "
9248 "non-empty parameter pack would be ill-formed");
9249 ++lost;
9251 else if (TYPE_P (conv) && !TYPE_P (pattern))
9252 /* Recover from missing typename. */
9253 TREE_VEC_ELT (inner_args, arg_idx)
9254 = make_pack_expansion (conv, complain);
9256 /* We don't know how many args we have yet, just
9257 use the unconverted ones for now. */
9258 new_inner_args = inner_args;
9259 arg_idx = nargs;
9260 break;
9263 else if (require_all_args)
9265 /* There must be a default arg in this case. */
9266 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9267 complain, in_decl);
9268 /* The position of the first default template argument,
9269 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9270 Record that. */
9271 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9272 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9273 arg_idx - pack_adjust);
9275 else
9276 break;
9278 if (arg == error_mark_node)
9280 if (complain & tf_error)
9281 error ("template argument %d is invalid", arg_idx + 1);
9283 else if (!arg)
9285 /* This can occur if there was an error in the template
9286 parameter list itself (which we would already have
9287 reported) that we are trying to recover from, e.g., a class
9288 template with a parameter list such as
9289 template<typename..., typename> (cpp0x/variadic150.C). */
9290 ++lost;
9292 /* This can also happen with a fixed parameter pack (71834). */
9293 if (arg_idx >= nargs)
9294 ++missing;
9296 else
9297 arg = convert_template_argument (TREE_VALUE (parm),
9298 arg, new_args, complain,
9299 parm_idx, in_decl);
9301 if (arg == error_mark_node)
9302 lost++;
9304 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9307 if (missing || arg_idx < nargs - variadic_args_p)
9309 /* If we had fixed parameter packs, we didn't know how many arguments we
9310 actually needed earlier; now we do. */
9311 nparms += fixed_pack_adjust;
9312 variadic_p -= fixed_packs;
9313 goto bad_nargs;
9316 if (arg_idx < nargs)
9318 /* We had some pack expansion arguments that will only work if the packs
9319 are empty, but wait until instantiation time to complain.
9320 See variadic-ttp3.C. */
9322 /* Except that we can't provide empty packs to alias templates or
9323 concepts when there are no corresponding parameters. Basically,
9324 we can get here with this:
9326 template<typename T> concept C = true;
9328 template<typename... Args>
9329 requires C<Args...>
9330 void f();
9332 When parsing C<Args...>, we try to form a concept check of
9333 C<?, Args...>. Without the extra check for substituting an empty
9334 pack past the last parameter, we can accept the check as valid.
9336 FIXME: This may be valid for alias templates (but I doubt it).
9338 FIXME: The error could be better also. */
9339 if (in_decl && concept_definition_p (in_decl))
9341 if (complain & tf_error)
9342 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9343 "too many arguments");
9344 return error_mark_node;
9347 int len = nparms + (nargs - arg_idx);
9348 tree args = make_tree_vec (len);
9349 int i = 0;
9350 for (; i < nparms; ++i)
9351 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9352 for (; i < len; ++i, ++arg_idx)
9353 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9354 arg_idx - pack_adjust);
9355 new_inner_args = args;
9358 if (lost)
9360 gcc_assert (!(complain & tf_error) || seen_error ());
9361 return error_mark_node;
9364 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9365 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9366 TREE_VEC_LENGTH (new_inner_args));
9368 return return_full_args ? new_args : new_inner_args;
9371 /* Returns true if T is a wrapper to make a C++20 template parameter
9372 object const. */
9374 static bool
9375 class_nttp_const_wrapper_p (tree t)
9377 if (cxx_dialect < cxx20)
9378 return false;
9379 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9380 && CP_TYPE_CONST_P (TREE_TYPE (t))
9381 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9384 /* Returns 1 if template args OT and NT are equivalent. */
9387 template_args_equal (tree ot, tree nt)
9389 if (nt == ot)
9390 return 1;
9391 if (nt == NULL_TREE || ot == NULL_TREE)
9392 return false;
9393 if (nt == any_targ_node || ot == any_targ_node)
9394 return true;
9396 if (class_nttp_const_wrapper_p (nt))
9397 nt = TREE_OPERAND (nt, 0);
9398 if (class_nttp_const_wrapper_p (ot))
9399 ot = TREE_OPERAND (ot, 0);
9401 /* DR 1558: Don't treat an alias template specialization with dependent
9402 arguments as equivalent to its underlying type when used as a template
9403 argument; we need them to be distinct so that we substitute into the
9404 specialization arguments at instantiation time. And aliases can't be
9405 equivalent without being ==, so we don't need to look any deeper.
9407 During partial ordering, however, we need to treat them normally so we can
9408 order uses of the same alias with different cv-qualification (79960). */
9409 auto cso = make_temp_override (comparing_dependent_aliases);
9410 if (!comparing_for_partial_ordering)
9411 ++comparing_dependent_aliases;
9413 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9414 /* For member templates */
9415 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9416 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9417 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9418 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9419 PACK_EXPANSION_PATTERN (nt))
9420 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9421 PACK_EXPANSION_EXTRA_ARGS (nt)));
9422 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9423 return cp_tree_equal (ot, nt);
9424 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9425 gcc_unreachable ();
9426 else if (TYPE_P (nt) || TYPE_P (ot))
9428 if (!(TYPE_P (nt) && TYPE_P (ot)))
9429 return false;
9430 return same_type_p (ot, nt);
9432 else
9434 /* Try to treat a template non-type argument that has been converted
9435 to the parameter type as equivalent to one that hasn't yet. */
9436 for (enum tree_code code1 = TREE_CODE (ot);
9437 CONVERT_EXPR_CODE_P (code1)
9438 || code1 == NON_LVALUE_EXPR;
9439 code1 = TREE_CODE (ot))
9440 ot = TREE_OPERAND (ot, 0);
9442 for (enum tree_code code2 = TREE_CODE (nt);
9443 CONVERT_EXPR_CODE_P (code2)
9444 || code2 == NON_LVALUE_EXPR;
9445 code2 = TREE_CODE (nt))
9446 nt = TREE_OPERAND (nt, 0);
9448 return cp_tree_equal (ot, nt);
9452 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9453 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9454 NEWARG_PTR with the offending arguments if they are non-NULL. */
9456 bool
9457 comp_template_args (tree oldargs, tree newargs,
9458 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */)
9460 if (oldargs == newargs)
9461 return true;
9463 if (!oldargs || !newargs)
9464 return false;
9466 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9467 return false;
9469 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9471 tree nt = TREE_VEC_ELT (newargs, i);
9472 tree ot = TREE_VEC_ELT (oldargs, i);
9474 if (! template_args_equal (ot, nt))
9476 if (oldarg_ptr != NULL)
9477 *oldarg_ptr = ot;
9478 if (newarg_ptr != NULL)
9479 *newarg_ptr = nt;
9480 return false;
9483 return true;
9486 static bool
9487 comp_template_args_porder (tree oargs, tree nargs)
9489 ++comparing_for_partial_ordering;
9490 bool equal = comp_template_args (oargs, nargs);
9491 --comparing_for_partial_ordering;
9492 return equal;
9495 /* Implement a freelist interface for objects of type T.
9497 Head is a separate object, rather than a regular member, so that we
9498 can define it as a GTY deletable pointer, which is highly
9499 desirable. A data member could be declared that way, but then the
9500 containing object would implicitly get GTY((user)), which would
9501 prevent us from instantiating freelists as global objects.
9502 Although this way we can create freelist global objects, they're
9503 such thin wrappers that instantiating temporaries at every use
9504 loses nothing and saves permanent storage for the freelist object.
9506 Member functions next, anew, poison and reinit have default
9507 implementations that work for most of the types we're interested
9508 in, but if they don't work for some type, they should be explicitly
9509 specialized. See the comments before them for requirements, and
9510 the example specializations for the tree_list_freelist. */
9511 template <typename T>
9512 class freelist
9514 /* Return the next object in a chain. We could just do type
9515 punning, but if we access the object with its underlying type, we
9516 avoid strict-aliasing trouble. This needs only work between
9517 poison and reinit. */
9518 static T *&next (T *obj) { return obj->next; }
9520 /* Return a newly allocated, uninitialized or minimally-initialized
9521 object of type T. Any initialization performed by anew should
9522 either remain across the life of the object and the execution of
9523 poison, or be redone by reinit. */
9524 static T *anew () { return ggc_alloc<T> (); }
9526 /* Optionally scribble all over the bits holding the object, so that
9527 they become (mostly?) uninitialized memory. This is called while
9528 preparing to make the object part of the free list. */
9529 static void poison (T *obj) {
9530 T *p ATTRIBUTE_UNUSED = obj;
9531 T **q ATTRIBUTE_UNUSED = &next (obj);
9533 #ifdef ENABLE_GC_CHECKING
9534 /* Poison the data, to indicate the data is garbage. */
9535 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9536 memset (p, 0xa5, sizeof (*p));
9537 #endif
9538 /* Let valgrind know the object is free. */
9539 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9541 /* Let valgrind know the next portion of the object is available,
9542 but uninitialized. */
9543 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9546 /* Bring an object that underwent at least one lifecycle after anew
9547 and before the most recent free and poison, back to a usable
9548 state, reinitializing whatever is needed for it to be
9549 functionally equivalent to an object just allocated and returned
9550 by anew. This may poison or clear the next field, used by
9551 freelist housekeeping after poison was called. */
9552 static void reinit (T *obj) {
9553 T **q ATTRIBUTE_UNUSED = &next (obj);
9555 #ifdef ENABLE_GC_CHECKING
9556 memset (q, 0xa5, sizeof (*q));
9557 #endif
9558 /* Let valgrind know the entire object is available, but
9559 uninitialized. */
9560 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9563 /* Reference a GTY-deletable pointer that points to the first object
9564 in the free list proper. */
9565 T *&head;
9566 public:
9567 /* Construct a freelist object chaining objects off of HEAD. */
9568 freelist (T *&head) : head(head) {}
9570 /* Add OBJ to the free object list. The former head becomes OBJ's
9571 successor. */
9572 void free (T *obj)
9574 poison (obj);
9575 next (obj) = head;
9576 head = obj;
9579 /* Take an object from the free list, if one is available, or
9580 allocate a new one. Objects taken from the free list should be
9581 regarded as filled with garbage, except for bits that are
9582 configured to be preserved across free and alloc. */
9583 T *alloc ()
9585 if (head)
9587 T *obj = head;
9588 head = next (head);
9589 reinit (obj);
9590 return obj;
9592 else
9593 return anew ();
9597 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9598 want to allocate a TREE_LIST using the usual interface, and ensure
9599 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9600 build_tree_list logic in reinit, so this could go out of sync. */
9601 template <>
9602 inline tree &
9603 freelist<tree_node>::next (tree obj)
9605 return TREE_CHAIN (obj);
9607 template <>
9608 inline tree
9609 freelist<tree_node>::anew ()
9611 return build_tree_list (NULL, NULL);
9613 template <>
9614 inline void
9615 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9617 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9618 tree p ATTRIBUTE_UNUSED = obj;
9619 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9620 tree *q ATTRIBUTE_UNUSED = &next (obj);
9622 #ifdef ENABLE_GC_CHECKING
9623 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9625 /* Poison the data, to indicate the data is garbage. */
9626 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9627 memset (p, 0xa5, size);
9628 #endif
9629 /* Let valgrind know the object is free. */
9630 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9631 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9632 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9633 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9635 #ifdef ENABLE_GC_CHECKING
9636 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9637 /* Keep TREE_CHAIN functional. */
9638 TREE_SET_CODE (obj, TREE_LIST);
9639 #else
9640 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9641 #endif
9643 template <>
9644 inline void
9645 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9647 tree_common *c ATTRIBUTE_UNUSED = &obj->common;
9649 #ifdef ENABLE_GC_CHECKING
9650 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9651 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9652 memset (obj, 0, sizeof (tree_list));
9653 #endif
9655 /* Let valgrind know the entire object is available, but
9656 uninitialized. */
9657 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9659 #ifdef ENABLE_GC_CHECKING
9660 TREE_SET_CODE (obj, TREE_LIST);
9661 #else
9662 TREE_CHAIN (obj) = NULL_TREE;
9663 TREE_TYPE (obj) = NULL_TREE;
9664 #endif
9665 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (c, sizeof (*c)));
9668 /* Point to the first object in the TREE_LIST freelist. */
9669 static GTY((deletable)) tree tree_list_freelist_head;
9670 /* Return the/an actual TREE_LIST freelist. */
9671 static inline freelist<tree_node>
9672 tree_list_freelist ()
9674 return tree_list_freelist_head;
9677 /* Point to the first object in the tinst_level freelist. */
9678 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9679 /* Return the/an actual tinst_level freelist. */
9680 static inline freelist<tinst_level>
9681 tinst_level_freelist ()
9683 return tinst_level_freelist_head;
9686 /* Point to the first object in the pending_template freelist. */
9687 static GTY((deletable)) pending_template *pending_template_freelist_head;
9688 /* Return the/an actual pending_template freelist. */
9689 static inline freelist<pending_template>
9690 pending_template_freelist ()
9692 return pending_template_freelist_head;
9695 /* Build the TREE_LIST object out of a split list, store it
9696 permanently, and return it. */
9697 tree
9698 tinst_level::to_list ()
9700 gcc_assert (split_list_p ());
9701 tree ret = tree_list_freelist ().alloc ();
9702 TREE_PURPOSE (ret) = tldcl;
9703 TREE_VALUE (ret) = targs;
9704 tldcl = ret;
9705 targs = NULL;
9706 gcc_assert (tree_list_p ());
9707 return ret;
9710 const unsigned short tinst_level::refcount_infinity;
9712 /* Increment OBJ's refcount unless it is already infinite. */
9713 static tinst_level *
9714 inc_refcount_use (tinst_level *obj)
9716 if (obj && obj->refcount != tinst_level::refcount_infinity)
9717 ++obj->refcount;
9718 return obj;
9721 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9722 void
9723 tinst_level::free (tinst_level *obj)
9725 if (obj->tree_list_p ())
9726 tree_list_freelist ().free (obj->get_node ());
9727 tinst_level_freelist ().free (obj);
9730 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9731 OBJ's DECL and OBJ, and start over with the tinst_level object that
9732 used to be referenced by OBJ's NEXT. */
9733 static void
9734 dec_refcount_use (tinst_level *obj)
9736 while (obj
9737 && obj->refcount != tinst_level::refcount_infinity
9738 && !--obj->refcount)
9740 tinst_level *next = obj->next;
9741 tinst_level::free (obj);
9742 obj = next;
9746 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9747 and of the former PTR. Omitting the second argument is equivalent
9748 to passing (T*)NULL; this is allowed because passing the
9749 zero-valued integral constant NULL confuses type deduction and/or
9750 overload resolution. */
9751 template <typename T>
9752 static void
9753 set_refcount_ptr (T *& ptr, T *obj = NULL)
9755 T *save = ptr;
9756 ptr = inc_refcount_use (obj);
9757 dec_refcount_use (save);
9760 static void
9761 add_pending_template (tree d)
9763 tree ti = (TYPE_P (d)
9764 ? CLASSTYPE_TEMPLATE_INFO (d)
9765 : DECL_TEMPLATE_INFO (d));
9766 struct pending_template *pt;
9767 int level;
9769 if (TI_PENDING_TEMPLATE_FLAG (ti))
9770 return;
9772 /* We are called both from instantiate_decl, where we've already had a
9773 tinst_level pushed, and instantiate_template, where we haven't.
9774 Compensate. */
9775 gcc_assert (TREE_CODE (d) != TREE_LIST);
9776 level = !current_tinst_level
9777 || current_tinst_level->maybe_get_node () != d;
9779 if (level)
9780 push_tinst_level (d);
9782 pt = pending_template_freelist ().alloc ();
9783 pt->next = NULL;
9784 pt->tinst = NULL;
9785 set_refcount_ptr (pt->tinst, current_tinst_level);
9786 if (last_pending_template)
9787 last_pending_template->next = pt;
9788 else
9789 pending_templates = pt;
9791 last_pending_template = pt;
9793 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9795 if (level)
9796 pop_tinst_level ();
9800 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9801 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9802 documentation for TEMPLATE_ID_EXPR. */
9804 tree
9805 lookup_template_function (tree fns, tree arglist)
9807 if (fns == error_mark_node || arglist == error_mark_node)
9808 return error_mark_node;
9810 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9812 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9814 error ("%q#D is not a function template", fns);
9815 return error_mark_node;
9818 if (BASELINK_P (fns))
9820 fns = copy_node (fns);
9821 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9822 unknown_type_node,
9823 BASELINK_FUNCTIONS (fns),
9824 arglist);
9825 return fns;
9828 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9831 /* Within the scope of a template class S<T>, the name S gets bound
9832 (in build_self_reference) to a TYPE_DECL for the class, not a
9833 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9834 or one of its enclosing classes, and that type is a template,
9835 return the associated TEMPLATE_DECL. Otherwise, the original
9836 DECL is returned.
9838 Also handle the case when DECL is a TREE_LIST of ambiguous
9839 injected-class-names from different bases. */
9841 tree
9842 maybe_get_template_decl_from_type_decl (tree decl)
9844 if (decl == NULL_TREE)
9845 return decl;
9847 /* DR 176: A lookup that finds an injected-class-name (10.2
9848 [class.member.lookup]) can result in an ambiguity in certain cases
9849 (for example, if it is found in more than one base class). If all of
9850 the injected-class-names that are found refer to specializations of
9851 the same class template, and if the name is followed by a
9852 template-argument-list, the reference refers to the class template
9853 itself and not a specialization thereof, and is not ambiguous. */
9854 if (TREE_CODE (decl) == TREE_LIST)
9856 tree t, tmpl = NULL_TREE;
9857 for (t = decl; t; t = TREE_CHAIN (t))
9859 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9860 if (!tmpl)
9861 tmpl = elt;
9862 else if (tmpl != elt)
9863 break;
9865 if (tmpl && t == NULL_TREE)
9866 return tmpl;
9867 else
9868 return decl;
9871 return (decl != NULL_TREE
9872 && DECL_SELF_REFERENCE_P (decl)
9873 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9874 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9877 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9878 parameters, find the desired type.
9880 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9882 IN_DECL, if non-NULL, is the template declaration we are trying to
9883 instantiate.
9885 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9886 the class we are looking up.
9888 Issue error and warning messages under control of COMPLAIN.
9890 If the template class is really a local class in a template
9891 function, then the FUNCTION_CONTEXT is the function in which it is
9892 being instantiated.
9894 ??? Note that this function is currently called *twice* for each
9895 template-id: the first time from the parser, while creating the
9896 incomplete type (finish_template_type), and the second type during the
9897 real instantiation (instantiate_template_class). This is surely something
9898 that we want to avoid. It also causes some problems with argument
9899 coercion (see convert_nontype_argument for more information on this). */
9901 tree
9902 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9903 int entering_scope, tsubst_flags_t complain)
9905 auto_timevar tv (TV_TEMPLATE_INST);
9907 tree templ = NULL_TREE, parmlist;
9908 tree t;
9909 spec_entry **slot;
9910 spec_entry *entry;
9911 spec_entry elt;
9912 hashval_t hash;
9914 if (identifier_p (d1))
9916 tree value = innermost_non_namespace_value (d1);
9917 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9918 templ = value;
9919 else
9921 if (context)
9922 push_decl_namespace (context);
9923 templ = lookup_name (d1);
9924 templ = maybe_get_template_decl_from_type_decl (templ);
9925 if (context)
9926 pop_decl_namespace ();
9929 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9931 tree type = TREE_TYPE (d1);
9933 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9934 an implicit typename for the second A. Deal with it. */
9935 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9936 type = TREE_TYPE (type);
9938 if (CLASSTYPE_TEMPLATE_INFO (type))
9940 templ = CLASSTYPE_TI_TEMPLATE (type);
9941 d1 = DECL_NAME (templ);
9944 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9945 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9947 templ = TYPE_TI_TEMPLATE (d1);
9948 d1 = DECL_NAME (templ);
9950 else if (DECL_TYPE_TEMPLATE_P (d1))
9952 templ = d1;
9953 d1 = DECL_NAME (templ);
9955 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9957 templ = d1;
9958 d1 = DECL_NAME (templ);
9961 /* Issue an error message if we didn't find a template. */
9962 if (! templ)
9964 if (complain & tf_error)
9965 error ("%qT is not a template", d1);
9966 return error_mark_node;
9969 if (TREE_CODE (templ) != TEMPLATE_DECL
9970 /* Make sure it's a user visible template, if it was named by
9971 the user. */
9972 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9973 && !PRIMARY_TEMPLATE_P (templ)))
9975 if (complain & tf_error)
9977 error ("non-template type %qT used as a template", d1);
9978 if (in_decl)
9979 error ("for template declaration %q+D", in_decl);
9981 return error_mark_node;
9984 complain &= ~tf_user;
9986 /* An alias that just changes the name of a template is equivalent to the
9987 other template, so if any of the arguments are pack expansions, strip
9988 the alias to avoid problems with a pack expansion passed to a non-pack
9989 alias template parameter (DR 1430). */
9990 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9991 templ = get_underlying_template (templ);
9993 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9995 tree parm;
9996 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9997 if (arglist2 == error_mark_node
9998 || (!uses_template_parms (arglist2)
9999 && check_instantiated_args (templ, arglist2, complain)))
10000 return error_mark_node;
10002 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
10003 return parm;
10005 else
10007 tree template_type = TREE_TYPE (templ);
10008 tree gen_tmpl;
10009 tree type_decl;
10010 tree found = NULL_TREE;
10011 int arg_depth;
10012 int parm_depth;
10013 int is_dependent_type;
10014 int use_partial_inst_tmpl = false;
10016 if (template_type == error_mark_node)
10017 /* An error occurred while building the template TEMPL, and a
10018 diagnostic has most certainly been emitted for that
10019 already. Let's propagate that error. */
10020 return error_mark_node;
10022 gen_tmpl = most_general_template (templ);
10023 if (modules_p ())
10024 lazy_load_pendings (gen_tmpl);
10026 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
10027 parm_depth = TMPL_PARMS_DEPTH (parmlist);
10028 arg_depth = TMPL_ARGS_DEPTH (arglist);
10030 if (arg_depth == 1 && parm_depth > 1)
10032 /* We've been given an incomplete set of template arguments.
10033 For example, given:
10035 template <class T> struct S1 {
10036 template <class U> struct S2 {};
10037 template <class U> struct S2<U*> {};
10040 we will be called with an ARGLIST of `U*', but the
10041 TEMPLATE will be `template <class T> template
10042 <class U> struct S1<T>::S2'. We must fill in the missing
10043 arguments. */
10044 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
10045 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
10046 arg_depth = TMPL_ARGS_DEPTH (arglist);
10049 /* Now we should have enough arguments. */
10050 gcc_assert (parm_depth == arg_depth);
10052 /* From here on, we're only interested in the most general
10053 template. */
10055 /* Shortcut looking up the current class scope again. */
10056 for (tree cur = current_nonlambda_class_type ();
10057 cur != NULL_TREE;
10058 cur = get_containing_scope (cur))
10060 if (!CLASS_TYPE_P (cur))
10061 continue;
10063 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
10064 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
10065 break;
10067 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
10068 && comp_template_args (arglist, TI_ARGS (ti)))
10069 return cur;
10072 /* Calculate the BOUND_ARGS. These will be the args that are
10073 actually tsubst'd into the definition to create the
10074 instantiation. */
10075 if (PRIMARY_TEMPLATE_P (gen_tmpl))
10076 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
10078 if (arglist == error_mark_node)
10079 /* We were unable to bind the arguments. */
10080 return error_mark_node;
10082 /* In the scope of a template class, explicit references to the
10083 template class refer to the type of the template, not any
10084 instantiation of it. For example, in:
10086 template <class T> class C { void f(C<T>); }
10088 the `C<T>' is just the same as `C'. Outside of the
10089 class, however, such a reference is an instantiation. */
10090 if (entering_scope
10091 || !PRIMARY_TEMPLATE_P (gen_tmpl)
10092 || currently_open_class (template_type))
10094 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10096 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10097 return template_type;
10100 /* If we already have this specialization, return it. */
10101 elt.tmpl = gen_tmpl;
10102 elt.args = arglist;
10103 elt.spec = NULL_TREE;
10104 hash = spec_hasher::hash (&elt);
10105 entry = type_specializations->find_with_hash (&elt, hash);
10107 if (entry)
10108 return entry->spec;
10110 /* If the template's constraints are not satisfied,
10111 then we cannot form a valid type.
10113 Note that the check is deferred until after the hash
10114 lookup. This prevents redundant checks on previously
10115 instantiated specializations. */
10116 if (flag_concepts
10117 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
10118 && !constraints_satisfied_p (gen_tmpl, arglist))
10120 if (complain & tf_error)
10122 auto_diagnostic_group d;
10123 error ("template constraint failure for %qD", gen_tmpl);
10124 diagnose_constraints (input_location, gen_tmpl, arglist);
10126 return error_mark_node;
10129 is_dependent_type = uses_template_parms (arglist);
10131 /* If the deduced arguments are invalid, then the binding
10132 failed. */
10133 if (!is_dependent_type
10134 && check_instantiated_args (gen_tmpl,
10135 INNERMOST_TEMPLATE_ARGS (arglist),
10136 complain))
10137 return error_mark_node;
10139 if (!is_dependent_type
10140 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10141 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10142 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10143 /* This occurs when the user has tried to define a tagged type
10144 in a scope that forbids it. We emitted an error during the
10145 parse. We didn't complete the bail out then, so here we
10146 are. */
10147 return error_mark_node;
10149 context = DECL_CONTEXT (gen_tmpl);
10150 if (context && TYPE_P (context))
10152 if (!uses_template_parms (DECL_CONTEXT (templ)))
10153 /* If the context of the partially instantiated template is
10154 already non-dependent, then we might as well use it. */
10155 context = DECL_CONTEXT (templ);
10156 else
10158 context = tsubst_aggr_type (context, arglist,
10159 complain, in_decl, true);
10160 /* Try completing the enclosing context if it's not already so. */
10161 if (context != error_mark_node
10162 && !COMPLETE_TYPE_P (context))
10164 context = complete_type (context);
10165 if (COMPLETE_TYPE_P (context))
10167 /* Completion could have caused us to register the desired
10168 specialization already, so check the table again. */
10169 entry = type_specializations->find_with_hash (&elt, hash);
10170 if (entry)
10171 return entry->spec;
10176 else
10177 context = tsubst (context, arglist, complain, in_decl);
10179 if (context == error_mark_node)
10180 return error_mark_node;
10182 if (!context)
10183 context = global_namespace;
10185 /* Create the type. */
10186 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10188 /* The user referred to a specialization of an alias
10189 template represented by GEN_TMPL.
10191 [temp.alias]/2 says:
10193 When a template-id refers to the specialization of an
10194 alias template, it is equivalent to the associated
10195 type obtained by substitution of its
10196 template-arguments for the template-parameters in the
10197 type-id of the alias template. */
10199 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10200 /* Note that the call above (by indirectly calling
10201 register_specialization in tsubst_decl) registers the
10202 TYPE_DECL representing the specialization of the alias
10203 template. So next time someone substitutes ARGLIST for
10204 the template parms into the alias template (GEN_TMPL),
10205 she'll get that TYPE_DECL back. */
10207 if (t == error_mark_node)
10208 return t;
10210 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10212 if (!is_dependent_type)
10214 set_current_access_from_decl (TYPE_NAME (template_type));
10215 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10216 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10217 arglist, complain, in_decl),
10218 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10219 arglist, complain, in_decl),
10220 SCOPED_ENUM_P (template_type), NULL);
10222 if (t == error_mark_node)
10223 return t;
10225 else
10227 /* We don't want to call start_enum for this type, since
10228 the values for the enumeration constants may involve
10229 template parameters. And, no one should be interested
10230 in the enumeration constants for such a type. */
10231 t = cxx_make_type (ENUMERAL_TYPE);
10232 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10234 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10235 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10236 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10238 else if (CLASS_TYPE_P (template_type))
10240 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10241 instantiated here. */
10242 gcc_assert (!LAMBDA_TYPE_P (template_type));
10244 t = make_class_type (TREE_CODE (template_type));
10245 CLASSTYPE_DECLARED_CLASS (t)
10246 = CLASSTYPE_DECLARED_CLASS (template_type);
10247 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10249 /* A local class. Make sure the decl gets registered properly. */
10250 if (context == current_function_decl)
10251 if (pushtag (DECL_NAME (gen_tmpl), t)
10252 == error_mark_node)
10253 return error_mark_node;
10255 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10256 /* This instantiation is another name for the primary
10257 template type. Set the TYPE_CANONICAL field
10258 appropriately. */
10259 TYPE_CANONICAL (t) = template_type;
10260 else if (any_template_arguments_need_structural_equality_p (arglist))
10261 SET_TYPE_STRUCTURAL_EQUALITY (t);
10263 else
10264 gcc_unreachable ();
10266 /* If we called start_enum or pushtag above, this information
10267 will already be set up. */
10268 type_decl = TYPE_NAME (t);
10269 if (!type_decl)
10271 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10273 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10274 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10275 DECL_SOURCE_LOCATION (type_decl)
10276 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10279 set_instantiating_module (type_decl);
10280 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10281 of export flag. We want to propagate this because it might
10282 be a friend declaration that pushes a new hidden binding. */
10283 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10285 if (CLASS_TYPE_P (template_type))
10287 TREE_PRIVATE (type_decl)
10288 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10289 TREE_PROTECTED (type_decl)
10290 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10291 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10293 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10294 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10298 if (OVERLOAD_TYPE_P (t)
10299 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10301 static const char *tags[] = {"abi_tag", "may_alias"};
10303 for (unsigned ix = 0; ix != 2; ix++)
10305 tree attributes
10306 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10308 if (attributes)
10309 TYPE_ATTRIBUTES (t)
10310 = tree_cons (TREE_PURPOSE (attributes),
10311 TREE_VALUE (attributes),
10312 TYPE_ATTRIBUTES (t));
10316 /* Let's consider the explicit specialization of a member
10317 of a class template specialization that is implicitly instantiated,
10318 e.g.:
10319 template<class T>
10320 struct S
10322 template<class U> struct M {}; //#0
10325 template<>
10326 template<>
10327 struct S<int>::M<char> //#1
10329 int i;
10331 [temp.expl.spec]/4 says this is valid.
10333 In this case, when we write:
10334 S<int>::M<char> m;
10336 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10337 the one of #0.
10339 When we encounter #1, we want to store the partial instantiation
10340 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10342 For all cases other than this "explicit specialization of member of a
10343 class template", we just want to store the most general template into
10344 the CLASSTYPE_TI_TEMPLATE of M.
10346 This case of "explicit specialization of member of a class template"
10347 only happens when:
10348 1/ the enclosing class is an instantiation of, and therefore not
10349 the same as, the context of the most general template, and
10350 2/ we aren't looking at the partial instantiation itself, i.e.
10351 the innermost arguments are not the same as the innermost parms of
10352 the most general template.
10354 So it's only when 1/ and 2/ happens that we want to use the partial
10355 instantiation of the member template in lieu of its most general
10356 template. */
10358 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10359 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10360 /* the enclosing class must be an instantiation... */
10361 && CLASS_TYPE_P (context)
10362 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10364 TREE_VEC_LENGTH (arglist)--;
10365 ++processing_template_decl;
10366 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10367 tree partial_inst_args =
10368 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10369 arglist, complain, NULL_TREE);
10370 --processing_template_decl;
10371 TREE_VEC_LENGTH (arglist)++;
10372 if (partial_inst_args == error_mark_node)
10373 return error_mark_node;
10374 use_partial_inst_tmpl =
10375 /*...and we must not be looking at the partial instantiation
10376 itself. */
10377 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10378 partial_inst_args);
10381 if (!use_partial_inst_tmpl)
10382 /* This case is easy; there are no member templates involved. */
10383 found = gen_tmpl;
10384 else
10386 /* This is a full instantiation of a member template. Find
10387 the partial instantiation of which this is an instance. */
10389 /* Temporarily reduce by one the number of levels in the ARGLIST
10390 so as to avoid comparing the last set of arguments. */
10391 TREE_VEC_LENGTH (arglist)--;
10392 /* We don't use COMPLAIN in the following call because this isn't
10393 the immediate context of deduction. For instance, tf_partial
10394 could be set here as we might be at the beginning of template
10395 argument deduction when any explicitly specified template
10396 arguments are substituted into the function type. tf_partial
10397 could lead into trouble because we wouldn't find the partial
10398 instantiation that might have been created outside tf_partial
10399 context, because the levels of template parameters wouldn't
10400 match, because in a tf_partial context, tsubst doesn't reduce
10401 TEMPLATE_PARM_LEVEL. */
10402 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10403 TREE_VEC_LENGTH (arglist)++;
10404 /* FOUND is either a proper class type, or an alias
10405 template specialization. In the later case, it's a
10406 TYPE_DECL, resulting from the substituting of arguments
10407 for parameters in the TYPE_DECL of the alias template
10408 done earlier. So be careful while getting the template
10409 of FOUND. */
10410 found = (TREE_CODE (found) == TEMPLATE_DECL
10411 ? found
10412 : (TREE_CODE (found) == TYPE_DECL
10413 ? DECL_TI_TEMPLATE (found)
10414 : CLASSTYPE_TI_TEMPLATE (found)));
10416 if (DECL_CLASS_TEMPLATE_P (found)
10417 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10419 /* If this partial instantiation is specialized, we want to
10420 use it for hash table lookup. */
10421 elt.tmpl = found;
10422 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10423 hash = spec_hasher::hash (&elt);
10427 /* Build template info for the new specialization. */
10428 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10430 elt.spec = t;
10431 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10432 gcc_checking_assert (*slot == NULL);
10433 entry = ggc_alloc<spec_entry> ();
10434 *entry = elt;
10435 *slot = entry;
10437 /* Note this use of the partial instantiation so we can check it
10438 later in maybe_process_partial_specialization. */
10439 DECL_TEMPLATE_INSTANTIATIONS (found)
10440 = tree_cons (arglist, t,
10441 DECL_TEMPLATE_INSTANTIATIONS (found));
10443 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10444 && !uses_template_parms (current_nonlambda_scope ())
10445 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10446 /* Now that the type has been registered on the instantiations
10447 list, we set up the enumerators. Because the enumeration
10448 constants may involve the enumeration type itself, we make
10449 sure to register the type first, and then create the
10450 constants. That way, doing tsubst_expr for the enumeration
10451 constants won't result in recursive calls here; we'll find
10452 the instantiation and exit above. */
10453 tsubst_enum (template_type, t, arglist);
10455 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10456 /* If the type makes use of template parameters, the
10457 code that generates debugging information will crash. */
10458 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10460 /* Possibly limit visibility based on template args. */
10461 TREE_PUBLIC (type_decl) = 1;
10462 determine_visibility (type_decl);
10464 inherit_targ_abi_tags (t);
10466 return t;
10470 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10472 tree
10473 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
10475 if (flag_concepts && variable_concept_p (templ))
10476 return build_concept_check (templ, arglist, tf_none);
10478 tree gen_templ = most_general_template (templ);
10479 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
10480 arglist = add_outermost_template_args (templ, arglist);
10481 arglist = coerce_template_parms (parms, arglist, templ, complain);
10482 if (arglist == error_mark_node)
10483 return error_mark_node;
10485 /* The type of the expression is NULL_TREE since the template-id could refer
10486 to an explicit or partial specialization. */
10487 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10490 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10491 not dependent. */
10493 tree
10494 finish_template_variable (tree var, tsubst_flags_t complain)
10496 tree templ = TREE_OPERAND (var, 0);
10497 tree arglist = TREE_OPERAND (var, 1);
10499 /* If the template or arguments are dependent, then we
10500 can't resolve the TEMPLATE_ID_EXPR yet. */
10501 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10502 || any_dependent_template_arguments_p (arglist))
10503 return var;
10505 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10507 if (complain & tf_error)
10509 auto_diagnostic_group d;
10510 error ("use of invalid variable template %qE", var);
10511 diagnose_constraints (location_of (var), templ, arglist);
10513 return error_mark_node;
10516 return instantiate_template (templ, arglist, complain);
10519 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10520 TARGS template args, and instantiate it if it's not dependent. */
10522 tree
10523 lookup_and_finish_template_variable (tree templ, tree targs,
10524 tsubst_flags_t complain)
10526 tree var = lookup_template_variable (templ, targs, complain);
10527 if (var == error_mark_node)
10528 return error_mark_node;
10529 var = finish_template_variable (var, complain);
10530 mark_used (var);
10531 return var;
10534 /* If the set of template parameters PARMS contains a template parameter
10535 at the given LEVEL and INDEX, then return this parameter. Otherwise
10536 return NULL_TREE. */
10538 static tree
10539 corresponding_template_parameter_list (tree parms, int level, int index)
10541 while (TMPL_PARMS_DEPTH (parms) > level)
10542 parms = TREE_CHAIN (parms);
10544 if (TMPL_PARMS_DEPTH (parms) != level
10545 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10546 return NULL_TREE;
10548 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10551 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10552 corresponds to the template parameter PARM, or else return NULL_TREE. */
10554 static tree
10555 corresponding_template_parameter_list (tree parms, tree parm)
10557 int level, index;
10558 template_parm_level_and_index (parm, &level, &index);
10559 return corresponding_template_parameter_list (parms, level, index);
10562 /* As above, but pull out the actual parameter. */
10564 static tree
10565 corresponding_template_parameter (tree parms, tree parm)
10567 tree list = corresponding_template_parameter_list (parms, parm);
10568 if (!list)
10569 return NULL_TREE;
10571 tree t = TREE_VALUE (list);
10572 /* As in template_parm_to_arg. */
10573 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10574 t = TREE_TYPE (t);
10575 else
10576 t = DECL_INITIAL (t);
10578 gcc_assert (TEMPLATE_PARM_P (t));
10579 return t;
10582 struct pair_fn_data
10584 tree_fn_t fn;
10585 tree_fn_t any_fn;
10586 void *data;
10587 /* True when we should also visit template parameters that occur in
10588 non-deduced contexts. */
10589 bool include_nondeduced_p;
10590 hash_set<tree> *visited;
10593 /* Called from for_each_template_parm via walk_tree. */
10595 static tree
10596 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10598 tree t = *tp;
10599 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10600 tree_fn_t fn = pfd->fn;
10601 void *data = pfd->data;
10602 tree result = NULL_TREE;
10604 #define WALK_SUBTREE(NODE) \
10605 do \
10607 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10608 pfd->include_nondeduced_p, \
10609 pfd->any_fn); \
10610 if (result) goto out; \
10612 while (0)
10614 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10615 return t;
10617 if (TYPE_P (t)
10618 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10619 WALK_SUBTREE (TYPE_CONTEXT (t));
10621 switch (TREE_CODE (t))
10623 case RECORD_TYPE:
10624 if (TYPE_PTRMEMFUNC_P (t))
10625 break;
10626 /* Fall through. */
10628 case UNION_TYPE:
10629 case ENUMERAL_TYPE:
10630 if (!TYPE_TEMPLATE_INFO (t))
10631 *walk_subtrees = 0;
10632 else
10633 WALK_SUBTREE (TYPE_TI_ARGS (t));
10634 break;
10636 case INTEGER_TYPE:
10637 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10638 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10639 break;
10641 case METHOD_TYPE:
10642 /* Since we're not going to walk subtrees, we have to do this
10643 explicitly here. */
10644 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10645 /* Fall through. */
10647 case FUNCTION_TYPE:
10648 /* Check the return type. */
10649 WALK_SUBTREE (TREE_TYPE (t));
10651 /* Check the parameter types. Since default arguments are not
10652 instantiated until they are needed, the TYPE_ARG_TYPES may
10653 contain expressions that involve template parameters. But,
10654 no-one should be looking at them yet. And, once they're
10655 instantiated, they don't contain template parameters, so
10656 there's no point in looking at them then, either. */
10658 tree parm;
10660 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10661 WALK_SUBTREE (TREE_VALUE (parm));
10663 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10664 want walk_tree walking into them itself. */
10665 *walk_subtrees = 0;
10668 if (flag_noexcept_type)
10670 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10671 if (spec)
10672 WALK_SUBTREE (TREE_PURPOSE (spec));
10674 break;
10676 case TYPEOF_TYPE:
10677 case DECLTYPE_TYPE:
10678 if (pfd->include_nondeduced_p
10679 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10680 pfd->visited,
10681 pfd->include_nondeduced_p,
10682 pfd->any_fn))
10683 return error_mark_node;
10684 *walk_subtrees = false;
10685 break;
10687 case TRAIT_TYPE:
10688 if (pfd->include_nondeduced_p)
10690 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10691 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10693 *walk_subtrees = false;
10694 break;
10696 case FUNCTION_DECL:
10697 case VAR_DECL:
10698 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10699 WALK_SUBTREE (DECL_TI_ARGS (t));
10700 break;
10702 case PARM_DECL:
10703 WALK_SUBTREE (TREE_TYPE (t));
10704 break;
10706 case CONST_DECL:
10707 if (DECL_TEMPLATE_PARM_P (t))
10708 WALK_SUBTREE (DECL_INITIAL (t));
10709 if (DECL_CONTEXT (t)
10710 && pfd->include_nondeduced_p)
10711 WALK_SUBTREE (DECL_CONTEXT (t));
10712 break;
10714 case BOUND_TEMPLATE_TEMPLATE_PARM:
10715 /* Record template parameters such as `T' inside `TT<T>'. */
10716 WALK_SUBTREE (TYPE_TI_ARGS (t));
10717 /* Fall through. */
10719 case TEMPLATE_TEMPLATE_PARM:
10720 case TEMPLATE_TYPE_PARM:
10721 case TEMPLATE_PARM_INDEX:
10722 if (fn && (*fn)(t, data))
10723 return t;
10724 else if (!fn)
10725 return t;
10726 break;
10728 case TEMPLATE_DECL:
10729 /* A template template parameter is encountered. */
10730 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10731 WALK_SUBTREE (TREE_TYPE (t));
10733 /* Already substituted template template parameter */
10734 *walk_subtrees = 0;
10735 break;
10737 case TYPENAME_TYPE:
10738 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10739 partial instantiation. */
10740 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10741 *walk_subtrees = 0;
10742 break;
10744 case INDIRECT_REF:
10745 case COMPONENT_REF:
10746 /* If there's no type, then this thing must be some expression
10747 involving template parameters. */
10748 if (!fn && !TREE_TYPE (t))
10749 return error_mark_node;
10750 break;
10752 case CONSTRUCTOR:
10753 case TRAIT_EXPR:
10754 case PLUS_EXPR:
10755 case MULT_EXPR:
10756 case SCOPE_REF:
10757 /* These are non-deduced contexts. */
10758 if (!pfd->include_nondeduced_p)
10759 *walk_subtrees = 0;
10760 break;
10762 case MODOP_EXPR:
10763 case CAST_EXPR:
10764 case IMPLICIT_CONV_EXPR:
10765 case REINTERPRET_CAST_EXPR:
10766 case CONST_CAST_EXPR:
10767 case STATIC_CAST_EXPR:
10768 case DYNAMIC_CAST_EXPR:
10769 case ARROW_EXPR:
10770 case DOTSTAR_EXPR:
10771 case TYPEID_EXPR:
10772 case PSEUDO_DTOR_EXPR:
10773 if (!fn)
10774 return error_mark_node;
10775 break;
10777 default:
10778 break;
10781 #undef WALK_SUBTREE
10783 /* We didn't find any template parameters we liked. */
10784 out:
10785 return result;
10788 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10789 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10790 call FN with the parameter and the DATA.
10791 If FN returns nonzero, the iteration is terminated, and
10792 for_each_template_parm returns 1. Otherwise, the iteration
10793 continues. If FN never returns a nonzero value, the value
10794 returned by for_each_template_parm is 0. If FN is NULL, it is
10795 considered to be the function which always returns 1.
10797 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10798 parameters that occur in non-deduced contexts. When false, only
10799 visits those template parameters that can be deduced. */
10801 static tree
10802 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10803 hash_set<tree> *visited,
10804 bool include_nondeduced_p,
10805 tree_fn_t any_fn)
10807 struct pair_fn_data pfd;
10808 tree result;
10810 /* Set up. */
10811 pfd.fn = fn;
10812 pfd.any_fn = any_fn;
10813 pfd.data = data;
10814 pfd.include_nondeduced_p = include_nondeduced_p;
10816 /* Walk the tree. (Conceptually, we would like to walk without
10817 duplicates, but for_each_template_parm_r recursively calls
10818 for_each_template_parm, so we would need to reorganize a fair
10819 bit to use walk_tree_without_duplicates, so we keep our own
10820 visited list.) */
10821 if (visited)
10822 pfd.visited = visited;
10823 else
10824 pfd.visited = new hash_set<tree>;
10825 result = cp_walk_tree (&t,
10826 for_each_template_parm_r,
10827 &pfd,
10828 pfd.visited);
10830 /* Clean up. */
10831 if (!visited)
10833 delete pfd.visited;
10834 pfd.visited = 0;
10837 return result;
10840 struct find_template_parameter_info
10842 explicit find_template_parameter_info (tree ctx_parms)
10843 : ctx_parms (ctx_parms),
10844 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10847 hash_set<tree> visited;
10848 hash_set<tree> parms;
10849 tree parm_list = NULL_TREE;
10850 tree *parm_list_tail = &parm_list;
10851 tree ctx_parms;
10852 int max_depth;
10854 tree find_in (tree);
10855 tree find_in_recursive (tree);
10856 bool found (tree);
10857 unsigned num_found () { return parms.elements (); }
10860 /* Appends the declaration of T to the list in DATA. */
10862 static int
10863 keep_template_parm (tree t, void* data)
10865 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10867 /* Template parameters declared within the expression are not part of
10868 the parameter mapping. For example, in this concept:
10870 template<typename T>
10871 concept C = requires { <expr> } -> same_as<int>;
10873 the return specifier same_as<int> declares a new decltype parameter
10874 that must not be part of the parameter mapping. The same is true
10875 for generic lambda parameters, lambda template parameters, etc. */
10876 int level;
10877 int index;
10878 template_parm_level_and_index (t, &level, &index);
10879 if (level == 0 || level > ftpi->max_depth)
10880 return 0;
10882 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10883 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10884 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10885 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10887 /* This template parameter might be an argument to a cached dependent
10888 specalization that was formed earlier inside some other template, in
10889 which case the parameter is not among the ones that are in-scope.
10890 Look in CTX_PARMS to find the corresponding in-scope template
10891 parameter, and use it instead. */
10892 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10893 t = in_scope;
10895 /* Arguments like const T yield parameters like const T. This means that
10896 a template-id like X<T, const T> would yield two distinct parameters:
10897 T and const T. Adjust types to their unqualified versions. */
10898 if (TYPE_P (t))
10899 t = TYPE_MAIN_VARIANT (t);
10900 if (!ftpi->parms.add (t))
10902 /* Append T to PARM_LIST. */
10903 tree node = build_tree_list (NULL_TREE, t);
10904 *ftpi->parm_list_tail = node;
10905 ftpi->parm_list_tail = &TREE_CHAIN (node);
10908 /* Verify the parameter we found has a valid index. */
10909 if (flag_checking)
10911 tree parms = ftpi->ctx_parms;
10912 while (TMPL_PARMS_DEPTH (parms) > level)
10913 parms = TREE_CHAIN (parms);
10914 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10915 gcc_assert (index < len);
10918 return 0;
10921 /* Ensure that we recursively examine certain terms that are not normally
10922 visited in for_each_template_parm_r. */
10924 static int
10925 any_template_parm_r (tree t, void *data)
10927 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10929 #define WALK_SUBTREE(NODE) \
10930 do \
10932 for_each_template_parm (NODE, keep_template_parm, data, \
10933 &ftpi->visited, true, \
10934 any_template_parm_r); \
10936 while (0)
10938 /* A mention of a member alias/typedef is a use of all of its template
10939 arguments, including those from the enclosing class, so we don't use
10940 alias_template_specialization_p here. */
10941 if (TYPE_P (t) && typedef_variant_p (t))
10942 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10943 WALK_SUBTREE (TI_ARGS (tinfo));
10945 switch (TREE_CODE (t))
10947 case TEMPLATE_TYPE_PARM:
10948 /* Type constraints of a placeholder type may contain parameters. */
10949 if (is_auto (t))
10950 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10951 WALK_SUBTREE (constr);
10952 break;
10954 case TEMPLATE_ID_EXPR:
10955 /* Search through references to variable templates. */
10956 WALK_SUBTREE (TREE_OPERAND (t, 0));
10957 WALK_SUBTREE (TREE_OPERAND (t, 1));
10958 break;
10960 case TEMPLATE_PARM_INDEX:
10961 WALK_SUBTREE (TREE_TYPE (t));
10962 break;
10964 case TEMPLATE_DECL:
10965 /* If T is a member template that shares template parameters with
10966 ctx_parms, we need to mark all those parameters for mapping.
10967 To that end, it should suffice to just walk the DECL_CONTEXT of
10968 the template (assuming the template is not overly general). */
10969 WALK_SUBTREE (DECL_CONTEXT (t));
10970 break;
10972 case LAMBDA_EXPR:
10974 /* Look in the parms and body. */
10975 tree fn = lambda_function (t);
10976 WALK_SUBTREE (TREE_TYPE (fn));
10977 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10979 break;
10981 case IDENTIFIER_NODE:
10982 if (IDENTIFIER_CONV_OP_P (t))
10983 /* The conversion-type-id of a conversion operator may be dependent. */
10984 WALK_SUBTREE (TREE_TYPE (t));
10985 break;
10987 case CONVERT_EXPR:
10988 if (is_dummy_object (t))
10989 WALK_SUBTREE (TREE_TYPE (t));
10990 break;
10992 default:
10993 break;
10996 /* Keep walking. */
10997 return 0;
11000 /* Look through T for template parameters. */
11002 tree
11003 find_template_parameter_info::find_in (tree t)
11005 return for_each_template_parm (t, keep_template_parm, this, &visited,
11006 /*include_nondeduced*/true,
11007 any_template_parm_r);
11010 /* As above, but also recursively look into the default arguments of template
11011 parameters we found. Used for alias CTAD. */
11013 tree
11014 find_template_parameter_info::find_in_recursive (tree t)
11016 if (tree r = find_in (t))
11017 return r;
11018 /* Since newly found parms are added to the end of the list, we
11019 can just walk it until we reach the end. */
11020 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
11022 tree parm = TREE_VALUE (pl);
11023 tree list = corresponding_template_parameter_list (ctx_parms, parm);
11024 if (tree r = find_in (TREE_PURPOSE (list)))
11025 return r;
11027 return NULL_TREE;
11030 /* True if PARM was found by a previous call to find_in. PARM can be a
11031 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
11033 bool
11034 find_template_parameter_info::found (tree parm)
11036 if (TREE_CODE (parm) == TREE_LIST)
11037 parm = TREE_VALUE (parm);
11038 if (TREE_CODE (parm) == TYPE_DECL)
11039 parm = TREE_TYPE (parm);
11040 else
11041 parm = DECL_INITIAL (parm);
11042 gcc_checking_assert (TEMPLATE_PARM_P (parm));
11043 return parms.contains (parm);
11046 /* Returns a list of unique template parameters found within T, where CTX_PARMS
11047 are the template parameters in scope. */
11049 tree
11050 find_template_parameters (tree t, tree ctx_parms)
11052 if (!ctx_parms)
11053 return NULL_TREE;
11055 find_template_parameter_info ftpi (ctx_parms);
11056 ftpi.find_in (t);
11057 return ftpi.parm_list;
11060 /* Returns true if T depends on any template parameter. */
11062 bool
11063 uses_template_parms (tree t)
11065 if (t == NULL_TREE || t == error_mark_node)
11066 return false;
11068 /* Namespaces can't depend on any template parameters. */
11069 if (TREE_CODE (t) == NAMESPACE_DECL)
11070 return false;
11072 processing_template_decl_sentinel ptds (/*reset*/false);
11073 ++processing_template_decl;
11075 if (TYPE_P (t))
11076 return dependent_type_p (t);
11077 else if (TREE_CODE (t) == TREE_VEC)
11078 return any_dependent_template_arguments_p (t);
11079 else if (TREE_CODE (t) == TREE_LIST)
11080 return (uses_template_parms (TREE_VALUE (t))
11081 || uses_template_parms (TREE_CHAIN (t)));
11082 else if (TREE_CODE (t) == TYPE_DECL)
11083 return dependent_type_p (TREE_TYPE (t));
11084 else
11085 return instantiation_dependent_expression_p (t);
11088 /* Returns true if T depends on any template parameter with level LEVEL. */
11090 bool
11091 uses_template_parms_level (tree t, int level)
11093 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
11094 /*include_nondeduced_p=*/true);
11097 /* Returns true if the signature of DECL depends on any template parameter from
11098 its enclosing class. */
11100 static bool
11101 uses_outer_template_parms (tree decl)
11103 int depth;
11104 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11105 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
11106 else
11107 depth = template_class_depth (CP_DECL_CONTEXT (decl));
11108 if (depth == 0)
11109 return false;
11110 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
11111 &depth, NULL, /*include_nondeduced_p=*/true))
11112 return true;
11113 if (PRIMARY_TEMPLATE_P (decl)
11114 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11116 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
11117 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
11119 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
11120 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
11121 if (TREE_CODE (parm) == PARM_DECL
11122 && for_each_template_parm (TREE_TYPE (parm),
11123 template_parm_outer_level,
11124 &depth, NULL, /*nondeduced*/true))
11125 return true;
11126 if (TREE_CODE (parm) == TEMPLATE_DECL
11127 && uses_outer_template_parms (parm))
11128 return true;
11129 if (defarg
11130 && for_each_template_parm (defarg, template_parm_outer_level,
11131 &depth, NULL, /*nondeduced*/true))
11132 return true;
11135 if (uses_outer_template_parms_in_constraints (decl))
11136 return true;
11137 return false;
11140 /* Returns true if the constraints of DECL depend on any template parameters
11141 from its enclosing scope. */
11143 bool
11144 uses_outer_template_parms_in_constraints (tree decl, tree ctx/*=NULL_TREE*/)
11146 tree ci = get_constraints (decl);
11147 if (ci)
11148 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11149 if (!ci)
11150 return false;
11151 if (!ctx)
11153 if (tree fc = DECL_FRIEND_CONTEXT (decl))
11154 ctx = fc;
11155 else
11156 ctx = CP_DECL_CONTEXT (decl);
11158 int depth = template_class_depth (ctx);
11159 if (depth == 0)
11160 return false;
11161 return for_each_template_parm (ci, template_parm_outer_level,
11162 &depth, NULL, /*nondeduced*/true);
11165 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11166 ill-formed translation unit, i.e. a variable or function that isn't
11167 usable in a constant expression. */
11169 static inline bool
11170 neglectable_inst_p (tree d)
11172 return (d && DECL_P (d)
11173 && !undeduced_auto_decl (d)
11174 && !(TREE_CODE (d) == FUNCTION_DECL
11175 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11176 : decl_maybe_constant_var_p (d)));
11179 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11180 neglectable and instantiated from within an erroneous instantiation. */
11182 static bool
11183 limit_bad_template_recursion (tree decl)
11185 struct tinst_level *lev = current_tinst_level;
11186 int errs = errorcount + sorrycount;
11187 if (errs == 0 || !neglectable_inst_p (decl))
11188 return false;
11190 /* Avoid instantiating members of an ill-formed class. */
11191 bool refuse
11192 = (DECL_CLASS_SCOPE_P (decl)
11193 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11195 if (!refuse)
11197 for (; lev; lev = lev->next)
11198 if (neglectable_inst_p (lev->maybe_get_node ()))
11199 break;
11200 refuse = (lev && errs > lev->errors);
11203 if (refuse)
11205 /* Don't warn about it not being defined. */
11206 suppress_warning (decl, OPT_Wunused);
11207 tree clone;
11208 FOR_EACH_CLONE (clone, decl)
11209 suppress_warning (clone, OPT_Wunused);
11211 return refuse;
11214 static int tinst_depth;
11215 extern int max_tinst_depth;
11216 int depth_reached;
11218 static GTY(()) struct tinst_level *last_error_tinst_level;
11220 /* We're starting to instantiate D; record the template instantiation context
11221 at LOC for diagnostics and to restore it later. */
11223 bool
11224 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11226 struct tinst_level *new_level;
11228 if (tinst_depth >= max_tinst_depth)
11230 /* Tell error.cc not to try to instantiate any templates. */
11231 at_eof = 3;
11232 fatal_error (input_location,
11233 "template instantiation depth exceeds maximum of %d"
11234 " (use %<-ftemplate-depth=%> to increase the maximum)",
11235 max_tinst_depth);
11236 return false;
11239 /* If the current instantiation caused problems, don't let it instantiate
11240 anything else. Do allow deduction substitution and decls usable in
11241 constant expressions. */
11242 if (!targs && limit_bad_template_recursion (tldcl))
11244 /* Avoid no_linkage_errors and unused function (and all other)
11245 warnings for this decl. */
11246 suppress_warning (tldcl);
11247 return false;
11250 /* When not -quiet, dump template instantiations other than functions, since
11251 announce_function will take care of those. */
11252 if (!quiet_flag && !targs
11253 && TREE_CODE (tldcl) != TREE_LIST
11254 && TREE_CODE (tldcl) != FUNCTION_DECL)
11255 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11257 new_level = tinst_level_freelist ().alloc ();
11258 new_level->tldcl = tldcl;
11259 new_level->targs = targs;
11260 new_level->locus = loc;
11261 new_level->errors = errorcount + sorrycount;
11262 new_level->next = NULL;
11263 new_level->refcount = 0;
11264 new_level->path = new_level->visible = nullptr;
11265 set_refcount_ptr (new_level->next, current_tinst_level);
11266 set_refcount_ptr (current_tinst_level, new_level);
11268 ++tinst_depth;
11269 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11270 depth_reached = tinst_depth;
11272 return true;
11275 /* We're starting substitution of TMPL<ARGS>; record the template
11276 substitution context for diagnostics and to restore it later. */
11278 bool
11279 push_tinst_level (tree tmpl, tree args)
11281 return push_tinst_level_loc (tmpl, args, input_location);
11284 /* We're starting to instantiate D; record INPUT_LOCATION and the
11285 template instantiation context for diagnostics and to restore it
11286 later. */
11288 bool
11289 push_tinst_level (tree d)
11291 return push_tinst_level_loc (d, input_location);
11294 /* Likewise, but record LOC as the program location. */
11296 bool
11297 push_tinst_level_loc (tree d, location_t loc)
11299 gcc_assert (TREE_CODE (d) != TREE_LIST);
11300 return push_tinst_level_loc (d, NULL, loc);
11303 /* We're done instantiating this template; return to the instantiation
11304 context. */
11306 void
11307 pop_tinst_level (void)
11309 /* Restore the filename and line number stashed away when we started
11310 this instantiation. */
11311 input_location = current_tinst_level->locus;
11312 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11313 --tinst_depth;
11316 /* We're instantiating a deferred template; restore the template
11317 instantiation context in which the instantiation was requested, which
11318 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11320 static tree
11321 reopen_tinst_level (struct tinst_level *level)
11323 struct tinst_level *t;
11325 tinst_depth = 0;
11326 for (t = level; t; t = t->next)
11327 ++tinst_depth;
11329 set_refcount_ptr (current_tinst_level, level);
11330 pop_tinst_level ();
11331 if (current_tinst_level)
11332 current_tinst_level->errors = errorcount+sorrycount;
11333 return level->maybe_get_node ();
11336 /* Returns the TINST_LEVEL which gives the original instantiation
11337 context. */
11339 struct tinst_level *
11340 outermost_tinst_level (void)
11342 struct tinst_level *level = current_tinst_level;
11343 if (level)
11344 while (level->next)
11345 level = level->next;
11346 return level;
11349 /* True iff T is a friend function declaration that is not itself a template
11350 and is not defined in a class template. */
11352 bool
11353 non_templated_friend_p (tree t)
11355 if (t && TREE_CODE (t) == FUNCTION_DECL
11356 && DECL_UNIQUE_FRIEND_P (t))
11358 tree ti = DECL_TEMPLATE_INFO (t);
11359 if (!ti)
11360 return true;
11361 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11362 if (DECL_FRIEND_CONTEXT (t))
11363 return false;
11364 /* Non-templated friends in a class template are still represented with a
11365 TEMPLATE_DECL; check that its primary template is the befriending
11366 class. Note that DECL_PRIMARY_TEMPLATE is null for
11367 template <class T> friend A<T>::f(); */
11368 tree tmpl = TI_TEMPLATE (ti);
11369 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11370 return (primary && primary != tmpl);
11372 else
11373 return false;
11376 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11377 vector of template arguments, as for tsubst.
11379 Returns an appropriate tsubst'd friend declaration. */
11381 static tree
11382 tsubst_friend_function (tree decl, tree args)
11384 tree new_friend;
11386 if (TREE_CODE (decl) == FUNCTION_DECL
11387 && DECL_TEMPLATE_INSTANTIATION (decl)
11388 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11389 /* This was a friend declared with an explicit template
11390 argument list, e.g.:
11392 friend void f<>(T);
11394 to indicate that f was a template instantiation, not a new
11395 function declaration. Now, we have to figure out what
11396 instantiation of what template. */
11398 tree template_id, arglist, fns;
11399 tree new_args;
11400 tree tmpl;
11401 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11403 /* Friend functions are looked up in the containing namespace scope.
11404 We must enter that scope, to avoid finding member functions of the
11405 current class with same name. */
11406 push_nested_namespace (ns);
11407 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11408 tf_warning_or_error, NULL_TREE);
11409 pop_nested_namespace (ns);
11410 arglist = tsubst (DECL_TI_ARGS (decl), args,
11411 tf_warning_or_error, NULL_TREE);
11412 template_id = lookup_template_function (fns, arglist);
11414 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11415 tmpl = determine_specialization (template_id, new_friend,
11416 &new_args,
11417 /*need_member_template=*/0,
11418 TREE_VEC_LENGTH (args),
11419 tsk_none);
11420 return instantiate_template (tmpl, new_args, tf_error);
11423 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11424 if (new_friend == error_mark_node)
11425 return error_mark_node;
11427 /* The NEW_FRIEND will look like an instantiation, to the
11428 compiler, but is not an instantiation from the point of view of
11429 the language. For example, we might have had:
11431 template <class T> struct S {
11432 template <class U> friend void f(T, U);
11435 Then, in S<int>, template <class U> void f(int, U) is not an
11436 instantiation of anything. */
11438 DECL_USE_TEMPLATE (new_friend) = 0;
11439 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11441 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11442 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11443 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11444 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11446 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11447 match in decls_match. */
11448 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11449 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11450 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11451 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11453 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11454 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11455 tsubst_each_template_parm_constraints (parms, args,
11456 tf_warning_or_error);
11460 /* The mangled name for the NEW_FRIEND is incorrect. The function
11461 is not a template instantiation and should not be mangled like
11462 one. Therefore, we forget the mangling here; we'll recompute it
11463 later if we need it. */
11464 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11466 SET_DECL_RTL (new_friend, NULL);
11467 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11470 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11472 tree old_decl;
11473 tree ns;
11475 /* We must save some information from NEW_FRIEND before calling
11476 duplicate decls since that function will free NEW_FRIEND if
11477 possible. */
11478 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11479 tree new_friend_result_template_info = NULL_TREE;
11480 bool new_friend_is_defn =
11481 (new_friend_template_info
11482 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11483 (template_for_substitution (new_friend)))
11484 != NULL_TREE));
11485 tree not_tmpl = new_friend;
11487 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11489 /* This declaration is a `primary' template. */
11490 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11492 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11493 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11496 /* Inside pushdecl_namespace_level, we will push into the
11497 current namespace. However, the friend function should go
11498 into the namespace of the template. */
11499 ns = decl_namespace_context (new_friend);
11500 push_nested_namespace (ns);
11501 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11502 pop_nested_namespace (ns);
11504 if (old_decl == error_mark_node)
11505 return error_mark_node;
11507 if (old_decl != new_friend)
11509 /* This new friend declaration matched an existing
11510 declaration. For example, given:
11512 template <class T> void f(T);
11513 template <class U> class C {
11514 template <class T> friend void f(T) {}
11517 the friend declaration actually provides the definition
11518 of `f', once C has been instantiated for some type. So,
11519 old_decl will be the out-of-class template declaration,
11520 while new_friend is the in-class definition.
11522 But, if `f' was called before this point, the
11523 instantiation of `f' will have DECL_TI_ARGS corresponding
11524 to `T' but not to `U', references to which might appear
11525 in the definition of `f'. Previously, the most general
11526 template for an instantiation of `f' was the out-of-class
11527 version; now it is the in-class version. Therefore, we
11528 run through all specialization of `f', adding to their
11529 DECL_TI_ARGS appropriately. In particular, they need a
11530 new set of outer arguments, corresponding to the
11531 arguments for this class instantiation.
11533 The same situation can arise with something like this:
11535 friend void f(int);
11536 template <class T> class C {
11537 friend void f(T) {}
11540 when `C<int>' is instantiated. Now, `f(int)' is defined
11541 in the class. */
11543 if (!new_friend_is_defn)
11544 /* On the other hand, if the in-class declaration does
11545 *not* provide a definition, then we don't want to alter
11546 existing definitions. We can just leave everything
11547 alone. */
11549 else
11551 tree new_template = TI_TEMPLATE (new_friend_template_info);
11552 tree new_args = TI_ARGS (new_friend_template_info);
11554 /* Overwrite whatever template info was there before, if
11555 any, with the new template information pertaining to
11556 the declaration. */
11557 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11559 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11561 /* We should have called reregister_specialization in
11562 duplicate_decls. */
11563 gcc_assert (retrieve_specialization (new_template,
11564 new_args, 0)
11565 == old_decl);
11567 /* Instantiate it if the global has already been used. */
11568 if (DECL_ODR_USED (old_decl))
11569 instantiate_decl (old_decl, /*defer_ok=*/true,
11570 /*expl_inst_class_mem_p=*/false);
11572 else
11574 tree t;
11576 /* Indicate that the old function template is a partial
11577 instantiation. */
11578 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11579 = new_friend_result_template_info;
11581 gcc_assert (new_template
11582 == most_general_template (new_template));
11583 gcc_assert (new_template != old_decl);
11585 /* Reassign any specializations already in the hash table
11586 to the new more general template, and add the
11587 additional template args. */
11588 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11589 t != NULL_TREE;
11590 t = TREE_CHAIN (t))
11592 tree spec = TREE_VALUE (t);
11593 spec_entry elt;
11595 elt.tmpl = old_decl;
11596 elt.args = DECL_TI_ARGS (spec);
11597 elt.spec = NULL_TREE;
11599 decl_specializations->remove_elt (&elt);
11601 DECL_TI_ARGS (spec)
11602 = add_outermost_template_args (new_args,
11603 DECL_TI_ARGS (spec));
11605 register_specialization
11606 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11609 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11613 /* The information from NEW_FRIEND has been merged into OLD_DECL
11614 by duplicate_decls. */
11615 new_friend = old_decl;
11618 /* We've just introduced a namespace-scope function in the purview
11619 without necessarily having opened the enclosing namespace, so
11620 make sure the namespace is in the purview now too. */
11621 if (modules_p ()
11622 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11623 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11624 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11626 else
11628 tree context = DECL_CONTEXT (new_friend);
11629 bool dependent_p;
11631 /* In the code
11632 template <class T> class C {
11633 template <class U> friend void C1<U>::f (); // case 1
11634 friend void C2<T>::f (); // case 2
11636 we only need to make sure CONTEXT is a complete type for
11637 case 2. To distinguish between the two cases, we note that
11638 CONTEXT of case 1 remains dependent type after tsubst while
11639 this isn't true for case 2. */
11640 ++processing_template_decl;
11641 dependent_p = dependent_type_p (context);
11642 --processing_template_decl;
11644 if (!dependent_p
11645 && !complete_type_or_else (context, NULL_TREE))
11646 return error_mark_node;
11648 if (COMPLETE_TYPE_P (context))
11650 tree fn = new_friend;
11651 /* do_friend adds the TEMPLATE_DECL for any member friend
11652 template even if it isn't a member template, i.e.
11653 template <class T> friend A<T>::f();
11654 Look through it in that case. */
11655 if (TREE_CODE (fn) == TEMPLATE_DECL
11656 && !PRIMARY_TEMPLATE_P (fn))
11657 fn = DECL_TEMPLATE_RESULT (fn);
11658 /* Check to see that the declaration is really present, and,
11659 possibly obtain an improved declaration. */
11660 fn = check_classfn (context, fn, NULL_TREE);
11662 if (fn)
11663 new_friend = fn;
11667 return new_friend;
11670 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11671 template arguments, as for tsubst.
11673 Returns an appropriate tsubst'd friend type or error_mark_node on
11674 failure. */
11676 static tree
11677 tsubst_friend_class (tree friend_tmpl, tree args)
11679 tree tmpl;
11681 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11683 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11684 return TREE_TYPE (tmpl);
11687 tree context = CP_DECL_CONTEXT (friend_tmpl);
11688 if (TREE_CODE (context) == NAMESPACE_DECL)
11689 push_nested_namespace (context);
11690 else
11692 context = tsubst (context, args, tf_error, NULL_TREE);
11693 push_nested_class (context);
11696 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11697 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11699 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11701 /* The friend template has already been declared. Just
11702 check to see that the declarations match, and install any new
11703 default parameters. We must tsubst the default parameters,
11704 of course. We only need the innermost template parameters
11705 because that is all that redeclare_class_template will look
11706 at. */
11707 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11708 > TMPL_ARGS_DEPTH (args))
11710 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11711 args, tf_warning_or_error);
11712 tsubst_each_template_parm_constraints (parms, args,
11713 tf_warning_or_error);
11714 location_t saved_input_location = input_location;
11715 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11716 tree cons = get_constraints (friend_tmpl);
11717 ++processing_template_decl;
11718 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11719 DECL_FRIEND_CONTEXT (friend_tmpl));
11720 --processing_template_decl;
11721 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11722 input_location = saved_input_location;
11725 else
11727 /* The friend template has not already been declared. In this
11728 case, the instantiation of the template class will cause the
11729 injection of this template into the namespace scope. */
11730 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11732 if (tmpl != error_mark_node)
11734 /* The new TMPL is not an instantiation of anything, so we
11735 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11736 for the new type because that is supposed to be the
11737 corresponding template decl, i.e., TMPL. */
11738 DECL_USE_TEMPLATE (tmpl) = 0;
11739 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11740 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11741 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11742 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11744 /* Substitute into and set the constraints on the new declaration. */
11745 if (tree ci = get_constraints (friend_tmpl))
11747 ++processing_template_decl;
11748 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11749 DECL_FRIEND_CONTEXT (friend_tmpl));
11750 --processing_template_decl;
11751 set_constraints (tmpl, ci);
11752 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11753 args, tf_warning_or_error);
11756 /* Inject this template into the enclosing namspace scope. */
11757 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11761 if (TREE_CODE (context) == NAMESPACE_DECL)
11762 pop_nested_namespace (context);
11763 else
11764 pop_nested_class ();
11766 return TREE_TYPE (tmpl);
11769 /* Returns zero if TYPE cannot be completed later due to circularity.
11770 Otherwise returns one. */
11772 static int
11773 can_complete_type_without_circularity (tree type)
11775 if (type == NULL_TREE || type == error_mark_node)
11776 return 0;
11777 else if (COMPLETE_TYPE_P (type))
11778 return 1;
11779 else if (TREE_CODE (type) == ARRAY_TYPE)
11780 return can_complete_type_without_circularity (TREE_TYPE (type));
11781 else if (CLASS_TYPE_P (type)
11782 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11783 return 0;
11784 else
11785 return 1;
11788 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11789 tsubst_flags_t, tree);
11791 /* Instantiate the contract statement. */
11793 static tree
11794 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11795 tree in_decl)
11797 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11798 bool auto_p = type_uses_auto (type);
11800 tree r = copy_node (t);
11802 /* Rebuild the result variable. */
11803 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11805 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11807 tree newvar = copy_node (oldvar);
11808 TREE_TYPE (newvar) = type;
11809 DECL_CONTEXT (newvar) = decl;
11810 POSTCONDITION_IDENTIFIER (r) = newvar;
11812 /* Make sure the postcondition is valid. */
11813 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11814 if (!auto_p)
11815 if (!check_postcondition_result (decl, type, loc))
11816 return invalidate_contract (r);
11818 /* Make the variable available for lookup. */
11819 register_local_specialization (newvar, oldvar);
11822 /* Instantiate the condition. If the return type is undeduced, process
11823 the expression as if inside a template to avoid spurious type errors. */
11824 if (auto_p)
11825 ++processing_template_decl;
11826 ++processing_contract_condition;
11827 CONTRACT_CONDITION (r)
11828 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11829 --processing_contract_condition;
11830 if (auto_p)
11831 --processing_template_decl;
11833 /* And the comment. */
11834 CONTRACT_COMMENT (r)
11835 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11837 return r;
11840 /* Update T by instantiating its contract attribute. */
11842 static void
11843 tsubst_contract_attribute (tree decl, tree t, tree args,
11844 tsubst_flags_t complain, tree in_decl)
11846 /* For non-specializations, adjust the current declaration to the most general
11847 version of in_decl. Because we defer the instantiation of contracts as long
11848 as possible, they are still written in terms of the parameters (and return
11849 type) of the most general template. */
11850 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11851 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11852 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11853 local_specialization_stack specs (lss_copy);
11854 register_parameter_specializations (in_decl, decl);
11856 /* Get the contract to be instantiated. */
11857 tree contract = CONTRACT_STATEMENT (t);
11859 /* Use the complete set of template arguments for instantiation. The
11860 contract may not have been instantiated and still refer to outer levels
11861 of template parameters. */
11862 args = DECL_TI_ARGS (decl);
11864 /* For member functions, make this available for semantic analysis. */
11865 tree save_ccp = current_class_ptr;
11866 tree save_ccr = current_class_ref;
11867 if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
11869 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11870 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11871 inject_this_parameter (this_type, cp_type_quals (this_type));
11874 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11876 current_class_ptr = save_ccp;
11877 current_class_ref = save_ccr;
11879 /* Rebuild the attribute. */
11880 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11883 /* Rebuild the attribute list for DECL, substituting into contracts
11884 as needed. */
11886 void
11887 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11889 tree list = copy_list (DECL_ATTRIBUTES (decl));
11890 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11892 if (cxx_contract_attribute_p (attr))
11893 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11895 DECL_ATTRIBUTES (decl) = list;
11898 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11899 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11901 static tree
11902 tsubst_attribute (tree t, tree *decl_p, tree args,
11903 tsubst_flags_t complain, tree in_decl)
11905 gcc_assert (ATTR_IS_DEPENDENT (t));
11907 /* Note that contract attributes are never substituted from this function.
11908 Their instantiation is triggered by regenerate_from_template_decl when
11909 we instantiate the body of the function. */
11911 tree val = TREE_VALUE (t);
11912 if (val == NULL_TREE)
11913 /* Nothing to do. */;
11914 else if ((flag_openmp || flag_openmp_simd)
11915 && is_attribute_p ("omp declare simd",
11916 get_attribute_name (t)))
11918 tree clauses = TREE_VALUE (val);
11919 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11920 complain, in_decl);
11921 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11922 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11923 tree parms = DECL_ARGUMENTS (*decl_p);
11924 clauses
11925 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11926 if (clauses)
11927 val = build_tree_list (NULL_TREE, clauses);
11928 else
11929 val = NULL_TREE;
11931 else if (flag_openmp
11932 && is_attribute_p ("omp declare variant base",
11933 get_attribute_name (t)))
11935 ++cp_unevaluated_operand;
11936 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11937 --cp_unevaluated_operand;
11938 tree chain = TREE_CHAIN (val);
11939 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11940 tree ctx = copy_list (TREE_VALUE (val));
11941 for (tree tss = ctx; tss; tss = TREE_CHAIN (tss))
11943 enum omp_tss_code set = OMP_TSS_CODE (tss);
11944 tree selectors = NULL_TREE;
11945 for (tree ts = OMP_TSS_TRAIT_SELECTORS (tss); ts;
11946 ts = TREE_CHAIN (ts))
11948 tree properties = NULL_TREE;
11949 tree scoreval = NULL_TREE;
11950 /* FIXME: The body of this loop should really be dispatching
11951 according to omp_ts_map[OMP_TS_CODE (TS)].tp_type instead
11952 of having hard-wired knowledge of specific selectors. */
11953 if (OMP_TS_CODE (ts) == OMP_TRAIT_CONSTRUCT_SIMD
11954 && set == OMP_TRAIT_SET_CONSTRUCT)
11956 tree clauses = OMP_TS_PROPERTIES (ts);
11957 clauses = tsubst_omp_clauses (clauses,
11958 C_ORT_OMP_DECLARE_SIMD, args,
11959 complain, in_decl);
11960 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11961 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11962 properties = clauses;
11964 else
11966 tree v = OMP_TS_SCORE (ts);
11967 if (v)
11969 v = tsubst_expr (v, args, complain, in_decl);
11970 v = fold_non_dependent_expr (v);
11971 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11972 || TREE_CODE (v) != INTEGER_CST)
11974 location_t loc
11975 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
11976 match_loc);
11977 error_at (loc, "score argument must be "
11978 "constant integer expression");
11979 return NULL_TREE;
11981 else if (tree_int_cst_sgn (v) < 0)
11983 location_t loc
11984 = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
11985 match_loc);
11986 error_at (loc, "score argument must be "
11987 "non-negative");
11988 return NULL_TREE;
11990 scoreval = v;
11992 properties = copy_list (OMP_TS_PROPERTIES (ts));
11993 for (tree p = properties; p; p = TREE_CHAIN (p))
11994 if (OMP_TP_NAME (p) == OMP_TP_NAMELIST_NODE)
11995 continue;
11996 else if (OMP_TP_VALUE (p))
11998 bool allow_string
11999 = (OMP_TS_CODE (ts) != OMP_TRAIT_USER_CONDITION
12000 || set != OMP_TRAIT_SET_USER);
12001 tree v = OMP_TP_VALUE (p);
12002 if (TREE_CODE (v) == STRING_CST && allow_string)
12003 continue;
12004 v = tsubst_expr (v, args, complain, in_decl);
12005 v = fold_non_dependent_expr (v);
12006 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
12007 || !tree_fits_shwi_p (v))
12009 location_t loc
12010 = cp_expr_loc_or_loc (OMP_TP_VALUE (p),
12011 match_loc);
12012 if (allow_string)
12013 error_at (loc, "property must be constant "
12014 "integer expression or string "
12015 "literal");
12016 else
12017 error_at (loc, "property must be constant "
12018 "integer expression");
12019 return NULL_TREE;
12021 OMP_TP_VALUE (p) = v;
12024 selectors = make_trait_selector (OMP_TS_CODE (ts), scoreval,
12025 properties, selectors);
12027 OMP_TSS_TRAIT_SELECTORS (tss) = nreverse (selectors);
12029 val = tree_cons (varid, ctx, chain);
12031 /* If the first attribute argument is an identifier, don't
12032 pass it through tsubst. Attributes like mode, format,
12033 cleanup and several target specific attributes expect it
12034 unmodified. */
12035 else if (attribute_takes_identifier_p (get_attribute_name (t)))
12037 tree chain
12038 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
12039 if (chain != TREE_CHAIN (val))
12040 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
12042 else if (PACK_EXPANSION_P (val))
12044 /* An attribute pack expansion. */
12045 tree purp = TREE_PURPOSE (t);
12046 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
12047 if (pack == error_mark_node)
12048 return error_mark_node;
12049 int len = TREE_VEC_LENGTH (pack);
12050 tree list = NULL_TREE;
12051 tree *q = &list;
12052 for (int i = 0; i < len; ++i)
12054 tree elt = TREE_VEC_ELT (pack, i);
12055 *q = build_tree_list (purp, elt);
12056 q = &TREE_CHAIN (*q);
12058 return list;
12060 else
12061 val = tsubst_expr (val, args, complain, in_decl);
12063 if (val == error_mark_node)
12064 return error_mark_node;
12065 if (val != TREE_VALUE (t))
12066 return build_tree_list (TREE_PURPOSE (t), val);
12067 return t;
12070 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
12071 unchanged or a new TREE_LIST chain. */
12073 static tree
12074 tsubst_attributes (tree attributes, tree args,
12075 tsubst_flags_t complain, tree in_decl)
12077 tree last_dep = NULL_TREE;
12079 for (tree t = attributes; t; t = TREE_CHAIN (t))
12080 if (ATTR_IS_DEPENDENT (t))
12082 last_dep = t;
12083 attributes = copy_list (attributes);
12084 break;
12087 if (last_dep)
12088 for (tree *p = &attributes; *p; )
12090 tree t = *p;
12091 if (ATTR_IS_DEPENDENT (t))
12093 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
12094 if (subst != t)
12096 *p = subst;
12097 while (*p)
12098 p = &TREE_CHAIN (*p);
12099 *p = TREE_CHAIN (t);
12100 continue;
12103 p = &TREE_CHAIN (*p);
12106 return attributes;
12109 /* Apply any attributes which had to be deferred until instantiation
12110 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
12111 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
12112 false on error. */
12114 static bool
12115 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
12116 tree args, tsubst_flags_t complain, tree in_decl)
12118 tree t;
12119 tree *p;
12121 if (attributes == NULL_TREE)
12122 return true;
12124 if (DECL_P (*decl_p))
12126 if (TREE_TYPE (*decl_p) == error_mark_node)
12127 return false;
12128 p = &DECL_ATTRIBUTES (*decl_p);
12129 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
12130 to our attributes parameter. */
12131 gcc_assert (*p == attributes);
12133 else
12135 p = &TYPE_ATTRIBUTES (*decl_p);
12136 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
12137 lookup_template_class_1, and should be preserved. */
12138 gcc_assert (*p != attributes);
12139 while (*p)
12140 p = &TREE_CHAIN (*p);
12143 /* save_template_attributes puts the dependent attributes at the beginning of
12144 the list; find the non-dependent ones. */
12145 for (t = attributes; t; t = TREE_CHAIN (t))
12146 if (!ATTR_IS_DEPENDENT (t))
12147 break;
12148 tree nondep = t;
12150 /* Apply any non-dependent attributes. */
12151 *p = nondep;
12153 if (nondep == attributes)
12154 return true;
12156 /* And then any dependent ones. */
12157 tree late_attrs = NULL_TREE;
12158 tree *q = &late_attrs;
12159 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12161 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12162 if (*q == error_mark_node)
12163 return false;
12164 if (*q == t)
12166 *q = copy_node (t);
12167 TREE_CHAIN (*q) = NULL_TREE;
12169 while (*q)
12170 q = &TREE_CHAIN (*q);
12173 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12174 those attributes should have been added already when those templates were
12175 parsed, and shouldn't be added based on from which context they are
12176 first time instantiated. */
12177 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12178 auto o2 = make_temp_override (optimization_current_node,
12179 optimization_default_node);
12180 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12181 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12182 NULL);
12183 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12185 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12187 return true;
12190 /* The template TMPL is being instantiated with the template arguments TARGS.
12191 Perform the access checks that we deferred when parsing the template. */
12193 static void
12194 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12196 unsigned i;
12197 deferred_access_check *chk;
12199 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12200 return;
12202 if (vec<deferred_access_check, va_gc> *access_checks
12203 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12204 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12206 tree decl = chk->decl;
12207 tree diag_decl = chk->diag_decl;
12208 tree type_scope = TREE_TYPE (chk->binfo);
12210 if (uses_template_parms (type_scope))
12211 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12213 /* Make access check error messages point to the location
12214 of the use of the typedef. */
12215 iloc_sentinel ils (chk->loc);
12216 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12217 decl, diag_decl, tf_warning_or_error);
12221 tree
12222 instantiate_class_template (tree type)
12224 auto_timevar tv (TV_TEMPLATE_INST);
12226 tree templ, args, pattern, t, member;
12227 tree typedecl;
12228 tree pbinfo;
12229 tree base_list;
12230 unsigned int saved_maximum_field_alignment;
12231 tree fn_context;
12233 if (type == error_mark_node)
12234 return error_mark_node;
12236 if (COMPLETE_OR_OPEN_TYPE_P (type)
12237 || uses_template_parms (type))
12238 return type;
12240 /* Figure out which template is being instantiated. */
12241 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12242 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12244 /* Mark the type as in the process of being defined. */
12245 TYPE_BEING_DEFINED (type) = 1;
12247 /* We may be in the middle of deferred access check. Disable
12248 it now. */
12249 deferring_access_check_sentinel acs (dk_no_deferred);
12251 /* Determine what specialization of the original template to
12252 instantiate. */
12253 t = most_specialized_partial_spec (type, tf_warning_or_error);
12254 if (t == error_mark_node)
12255 return error_mark_node;
12256 else if (t)
12258 /* This TYPE is actually an instantiation of a partial
12259 specialization. We replace the innermost set of ARGS with
12260 the arguments appropriate for substitution. For example,
12261 given:
12263 template <class T> struct S {};
12264 template <class T> struct S<T*> {};
12266 and supposing that we are instantiating S<int*>, ARGS will
12267 presently be {int*} -- but we need {int}. */
12268 pattern = TREE_TYPE (TI_TEMPLATE (t));
12269 args = TI_ARGS (t);
12271 else
12273 pattern = TREE_TYPE (templ);
12274 args = CLASSTYPE_TI_ARGS (type);
12277 /* If the template we're instantiating is incomplete, then clearly
12278 there's nothing we can do. */
12279 if (!COMPLETE_TYPE_P (pattern))
12281 /* We can try again later. */
12282 TYPE_BEING_DEFINED (type) = 0;
12283 return type;
12286 /* If we've recursively instantiated too many templates, stop. */
12287 if (! push_tinst_level (type))
12288 return type;
12290 int saved_unevaluated_operand = cp_unevaluated_operand;
12291 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12293 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12294 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12295 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12296 fn_context = error_mark_node;
12297 if (!fn_context)
12298 push_to_top_level ();
12299 else
12301 cp_unevaluated_operand = 0;
12302 c_inhibit_evaluation_warnings = 0;
12305 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12307 /* Use #pragma pack from the template context. */
12308 saved_maximum_field_alignment = maximum_field_alignment;
12309 maximum_field_alignment = TYPE_PRECISION (pattern);
12311 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12313 /* Set the input location to the most specialized template definition.
12314 This is needed if tsubsting causes an error. */
12315 typedecl = TYPE_MAIN_DECL (pattern);
12316 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12317 DECL_SOURCE_LOCATION (typedecl);
12319 set_instantiating_module (TYPE_NAME (type));
12321 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12322 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12323 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12324 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12325 if (ANON_AGGR_TYPE_P (pattern))
12326 SET_ANON_AGGR_TYPE_P (type);
12327 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12329 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12330 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12331 /* Adjust visibility for template arguments. */
12332 determine_visibility (TYPE_MAIN_DECL (type));
12334 if (CLASS_TYPE_P (type))
12335 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12337 pbinfo = TYPE_BINFO (pattern);
12339 /* We should never instantiate a nested class before its enclosing
12340 class; we need to look up the nested class by name before we can
12341 instantiate it, and that lookup should instantiate the enclosing
12342 class. */
12343 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12344 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12346 base_list = NULL_TREE;
12347 /* Defer access checking while we substitute into the types named in
12348 the base-clause. */
12349 push_deferring_access_checks (dk_deferred);
12350 if (BINFO_N_BASE_BINFOS (pbinfo))
12352 tree pbase_binfo;
12353 int i;
12355 /* Substitute into each of the bases to determine the actual
12356 basetypes. */
12357 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12359 tree base;
12360 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12361 tree expanded_bases = NULL_TREE;
12362 int idx, len = 1;
12364 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12366 expanded_bases =
12367 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12368 args, tf_error, NULL_TREE);
12369 if (expanded_bases == error_mark_node)
12370 continue;
12372 len = TREE_VEC_LENGTH (expanded_bases);
12375 for (idx = 0; idx < len; idx++)
12377 if (expanded_bases)
12378 /* Extract the already-expanded base class. */
12379 base = TREE_VEC_ELT (expanded_bases, idx);
12380 else
12381 /* Substitute to figure out the base class. */
12382 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12383 NULL_TREE);
12385 if (base == error_mark_node)
12386 continue;
12388 base_list = tree_cons (access, base, base_list);
12389 if (BINFO_VIRTUAL_P (pbase_binfo))
12390 TREE_TYPE (base_list) = integer_type_node;
12394 /* The list is now in reverse order; correct that. */
12395 base_list = nreverse (base_list);
12397 /* Now call xref_basetypes to set up all the base-class
12398 information. */
12399 xref_basetypes (type, base_list);
12401 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12402 (int) ATTR_FLAG_TYPE_IN_PLACE,
12403 args, tf_error, NULL_TREE);
12404 fixup_attribute_variants (type);
12406 /* Now that our base classes are set up, enter the scope of the
12407 class, so that name lookups into base classes, etc. will work
12408 correctly. This is precisely analogous to what we do in
12409 begin_class_definition when defining an ordinary non-template
12410 class, except we also need to push the enclosing classes. */
12411 push_nested_class (type);
12413 /* Now check accessibility of the types named in its base-clause,
12414 relative to the scope of the class. */
12415 pop_to_parent_deferring_access_checks ();
12417 /* A vector to hold members marked with attribute used. */
12418 auto_vec<tree> used;
12420 /* Now members are processed in the order of declaration. */
12421 for (member = CLASSTYPE_DECL_LIST (pattern);
12422 member; member = TREE_CHAIN (member))
12424 tree t = TREE_VALUE (member);
12426 if (TREE_PURPOSE (member))
12428 if (TYPE_P (t))
12430 if (LAMBDA_TYPE_P (t))
12431 /* A closure type for a lambda in an NSDMI or default argument.
12432 Ignore it; it will be regenerated when needed. */
12433 continue;
12435 /* If the member is a class template, we've
12436 already substituted its type. */
12437 if (CLASS_TYPE_P (t)
12438 && CLASSTYPE_IS_TEMPLATE (t))
12439 continue;
12441 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12442 if (newtag == error_mark_node)
12443 continue;
12445 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12447 tree name = TYPE_IDENTIFIER (t);
12449 /* Now, install the tag. We don't use pushtag
12450 because that does too much work -- creating an
12451 implicit typedef, which we've already done. */
12452 set_identifier_type_value (name, TYPE_NAME (newtag));
12453 maybe_add_class_template_decl_list (type, newtag, false);
12454 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12455 determine_visibility (TYPE_NAME (newtag));
12458 else if (DECL_DECLARES_FUNCTION_P (t))
12460 tree r;
12462 if (TREE_CODE (t) == TEMPLATE_DECL)
12463 ++processing_template_decl;
12464 r = tsubst (t, args, tf_error, NULL_TREE);
12465 if (TREE_CODE (t) == TEMPLATE_DECL)
12466 --processing_template_decl;
12468 set_current_access_from_decl (r);
12469 finish_member_declaration (r);
12470 /* Instantiate members marked with attribute used. */
12471 if (r != error_mark_node && DECL_PRESERVE_P (r))
12472 used.safe_push (r);
12473 if (TREE_CODE (r) == FUNCTION_DECL
12474 && DECL_OMP_DECLARE_REDUCTION_P (r))
12475 cp_check_omp_declare_reduction (r);
12477 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12478 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12479 /* A closure type for a lambda in an NSDMI or default argument.
12480 Ignore it; it will be regenerated when needed. */;
12481 else
12483 /* Build new TYPE_FIELDS. */
12484 if (TREE_CODE (t) == STATIC_ASSERT)
12485 tsubst_stmt (t, args, tf_warning_or_error, NULL_TREE);
12486 else if (TREE_CODE (t) != CONST_DECL)
12488 tree r;
12489 tree vec = NULL_TREE;
12490 int len = 1;
12492 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12493 /* The file and line for this declaration, to
12494 assist in error message reporting. Since we
12495 called push_tinst_level above, we don't need to
12496 restore these. */
12497 input_location = DECL_SOURCE_LOCATION (t);
12499 if (TREE_CODE (t) == TEMPLATE_DECL)
12500 ++processing_template_decl;
12501 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12502 if (TREE_CODE (t) == TEMPLATE_DECL)
12503 --processing_template_decl;
12505 if (TREE_CODE (r) == TREE_VEC)
12507 /* A capture pack became multiple fields. */
12508 vec = r;
12509 len = TREE_VEC_LENGTH (vec);
12512 for (int i = 0; i < len; ++i)
12514 if (vec)
12515 r = TREE_VEC_ELT (vec, i);
12516 if (VAR_P (r))
12518 /* In [temp.inst]:
12520 [t]he initialization (and any associated
12521 side-effects) of a static data member does
12522 not occur unless the static data member is
12523 itself used in a way that requires the
12524 definition of the static data member to
12525 exist.
12527 Therefore, we do not substitute into the
12528 initialized for the static data member here. */
12529 finish_static_data_member_decl
12531 /*init=*/NULL_TREE,
12532 /*init_const_expr_p=*/false,
12533 /*asmspec_tree=*/NULL_TREE,
12534 /*flags=*/0);
12535 /* Instantiate members marked with attribute used. */
12536 if (r != error_mark_node && DECL_PRESERVE_P (r))
12537 used.safe_push (r);
12539 else if (TREE_CODE (r) == FIELD_DECL)
12541 /* Determine whether R has a valid type and can be
12542 completed later. If R is invalid, then its type
12543 is replaced by error_mark_node. */
12544 tree rtype = TREE_TYPE (r);
12545 if (can_complete_type_without_circularity (rtype))
12546 complete_type (rtype);
12548 if (!complete_or_array_type_p (rtype))
12550 /* If R's type couldn't be completed and
12551 it isn't a flexible array member (whose
12552 type is incomplete by definition) give
12553 an error. */
12554 cxx_incomplete_type_error (r, rtype);
12555 TREE_TYPE (r) = error_mark_node;
12557 else if (TREE_CODE (rtype) == ARRAY_TYPE
12558 && TYPE_DOMAIN (rtype) == NULL_TREE
12559 && (TREE_CODE (type) == UNION_TYPE
12560 || TREE_CODE (type) == QUAL_UNION_TYPE))
12562 error ("flexible array member %qD in union", r);
12563 TREE_TYPE (r) = error_mark_node;
12565 else if (!verify_type_context (input_location,
12566 TCTX_FIELD, rtype))
12567 TREE_TYPE (r) = error_mark_node;
12570 /* If it is a TYPE_DECL for a class-scoped
12571 ENUMERAL_TYPE, such a thing will already have
12572 been added to the field list by tsubst_enum
12573 in finish_member_declaration case above. */
12574 if (!(TREE_CODE (r) == TYPE_DECL
12575 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12576 && DECL_ARTIFICIAL (r)))
12578 set_current_access_from_decl (r);
12579 finish_member_declaration (r);
12585 else
12587 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12588 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12590 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12592 tree friend_type = t;
12593 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12595 /* template <class T> friend class C; */
12596 friend_type = tsubst_friend_class (friend_type, args);
12598 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12600 /* template <class T> friend class C::D; */
12601 friend_type = tsubst (friend_type, args,
12602 tf_warning_or_error, NULL_TREE);
12603 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12604 friend_type = TREE_TYPE (friend_type);
12606 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12607 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12609 /* This could be either
12611 friend class T::C;
12613 when dependent_type_p is false or
12615 template <class U> friend class T::C;
12617 otherwise. */
12618 /* Bump processing_template_decl in case this is something like
12619 template <class T> friend struct A<T>::B. */
12620 ++processing_template_decl;
12621 friend_type = tsubst (friend_type, args,
12622 tf_warning_or_error, NULL_TREE);
12623 --processing_template_decl;
12625 else if (uses_template_parms (friend_type))
12626 /* friend class C<T>; */
12627 friend_type = tsubst (friend_type, args,
12628 tf_warning_or_error, NULL_TREE);
12630 /* Otherwise it's
12632 friend class C;
12634 where C is already declared or
12636 friend class C<int>;
12638 We don't have to do anything in these cases. */
12640 if (friend_type != error_mark_node)
12641 make_friend_class (type, friend_type, /*complain=*/false);
12643 else
12645 /* Build new DECL_FRIENDLIST. */
12646 tree r;
12648 /* The file and line for this declaration, to
12649 assist in error message reporting. Since we
12650 called push_tinst_level above, we don't need to
12651 restore these. */
12652 input_location = DECL_SOURCE_LOCATION (t);
12654 if (TREE_CODE (t) == TEMPLATE_DECL)
12656 ++processing_template_decl;
12657 push_deferring_access_checks (dk_no_check);
12660 r = tsubst_friend_function (t, args);
12661 add_friend (type, r, /*complain=*/false);
12662 if (TREE_CODE (t) == TEMPLATE_DECL)
12664 pop_deferring_access_checks ();
12665 --processing_template_decl;
12671 if (fn_context)
12673 /* Restore these before substituting into the lambda capture
12674 initializers. */
12675 cp_unevaluated_operand = saved_unevaluated_operand;
12676 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12679 /* Set the file and line number information to whatever is given for
12680 the class itself. This puts error messages involving generated
12681 implicit functions at a predictable point, and the same point
12682 that would be used for non-template classes. */
12683 input_location = DECL_SOURCE_LOCATION (typedecl);
12685 unreverse_member_declarations (type);
12686 finish_struct_1 (type);
12687 TYPE_BEING_DEFINED (type) = 0;
12689 /* Remember if instantiating this class ran into errors, so we can avoid
12690 instantiating member functions in limit_bad_template_recursion. We set
12691 this flag even if the problem was in another instantiation triggered by
12692 this one, as that will likely also cause trouble for member functions. */
12693 if (errorcount + sorrycount > current_tinst_level->errors)
12694 CLASSTYPE_ERRONEOUS (type) = true;
12696 /* We don't instantiate default arguments for member functions. 14.7.1:
12698 The implicit instantiation of a class template specialization causes
12699 the implicit instantiation of the declarations, but not of the
12700 definitions or default arguments, of the class member functions,
12701 member classes, static data members and member templates.... */
12703 perform_instantiation_time_access_checks (pattern, args);
12704 perform_deferred_access_checks (tf_warning_or_error);
12706 /* Now that we've gone through all the members, instantiate those
12707 marked with attribute used. We must do this in the context of
12708 the class -- not the context we pushed from, as that might be
12709 inside a template and change the behaviour of mark_used. */
12710 for (tree x : used)
12711 mark_used (x);
12713 pop_nested_class ();
12714 maximum_field_alignment = saved_maximum_field_alignment;
12715 if (!fn_context)
12716 pop_from_top_level ();
12717 pop_tinst_level ();
12719 /* The vtable for a template class can be emitted in any translation
12720 unit in which the class is instantiated. When there is no key
12721 method, however, finish_struct_1 will already have added TYPE to
12722 the keyed_classes. */
12723 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12724 vec_safe_push (keyed_classes, type);
12726 return type;
12729 tree
12730 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12732 tree r;
12734 if (!t)
12735 r = t;
12736 else if (TYPE_P (t))
12737 r = tsubst (t, args, complain, in_decl);
12738 else
12740 if (!(complain & tf_warning))
12741 ++c_inhibit_evaluation_warnings;
12742 r = tsubst_expr (t, args, complain, in_decl);
12743 if (!(complain & tf_warning))
12744 --c_inhibit_evaluation_warnings;
12747 return r;
12750 /* Given a function parameter pack TMPL_PARM and some function parameters
12751 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12752 and set *SPEC_P to point at the next point in the list. */
12754 tree
12755 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12757 /* Collect all of the extra "packed" parameters into an
12758 argument pack. */
12759 tree argpack;
12760 tree spec_parm = *spec_p;
12761 int len;
12763 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12764 if (tmpl_parm
12765 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12766 break;
12768 spec_parm = *spec_p;
12769 if (len == 1 && DECL_PACK_P (spec_parm))
12771 /* The instantiation is still a parameter pack; don't wrap it in a
12772 NONTYPE_ARGUMENT_PACK. */
12773 argpack = spec_parm;
12774 spec_parm = DECL_CHAIN (spec_parm);
12776 else
12778 /* Fill in PARMVEC with all of the parameters. */
12779 tree parmvec = make_tree_vec (len);
12780 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12781 for (int i = 0; i < len; i++)
12783 tree elt = spec_parm;
12784 if (DECL_PACK_P (elt))
12785 elt = make_pack_expansion (elt);
12786 TREE_VEC_ELT (parmvec, i) = elt;
12787 spec_parm = DECL_CHAIN (spec_parm);
12790 /* Build the argument packs. */
12791 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12793 *spec_p = spec_parm;
12795 return argpack;
12798 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12799 NONTYPE_ARGUMENT_PACK. */
12801 static tree
12802 make_fnparm_pack (tree spec_parm)
12804 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12807 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12808 pack expansion with no extra args, 2 if it has extra args, or 0
12809 if it is not a pack expansion. */
12811 static int
12812 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12814 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12815 /* We're being called before this happens in tsubst_pack_expansion. */
12816 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12817 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12818 if (i >= TREE_VEC_LENGTH (vec))
12819 return 0;
12820 tree elt = TREE_VEC_ELT (vec, i);
12821 if (DECL_P (elt))
12822 /* A decl pack is itself an expansion. */
12823 elt = TREE_TYPE (elt);
12824 if (!PACK_EXPANSION_P (elt))
12825 return 0;
12826 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12827 return 2;
12828 return 1;
12832 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12834 static tree
12835 make_argument_pack_select (tree arg_pack, unsigned index)
12837 tree aps = make_node (ARGUMENT_PACK_SELECT);
12839 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12840 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12842 return aps;
12845 /* This is a subroutine of tsubst_pack_expansion.
12847 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12848 mechanism to store the (non complete list of) arguments of the
12849 substitution and return a non substituted pack expansion, in order
12850 to wait for when we have enough arguments to really perform the
12851 substitution. */
12853 static bool
12854 use_pack_expansion_extra_args_p (tree t,
12855 tree parm_packs,
12856 int arg_pack_len,
12857 bool has_empty_arg)
12859 if (has_empty_arg
12860 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12861 return true;
12863 /* If one pack has an expansion and another pack has a normal
12864 argument or if one pack has an empty argument and an another
12865 one hasn't then tsubst_pack_expansion cannot perform the
12866 substitution and need to fall back on the
12867 PACK_EXPANSION_EXTRA mechanism. */
12868 if (parm_packs == NULL_TREE)
12869 return false;
12870 else if (has_empty_arg)
12872 /* If all the actual packs are pack expansions, we can still
12873 subsitute directly. */
12874 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12876 tree a = TREE_VALUE (p);
12877 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12878 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12879 a = ARGUMENT_PACK_ARGS (a);
12880 if (TREE_VEC_LENGTH (a) == 1)
12881 a = TREE_VEC_ELT (a, 0);
12882 if (PACK_EXPANSION_P (a))
12883 continue;
12884 return true;
12886 return false;
12889 for (int i = 0 ; i < arg_pack_len; ++i)
12891 bool has_expansion_arg = false;
12892 bool has_non_expansion_arg = false;
12893 for (tree parm_pack = parm_packs;
12894 parm_pack;
12895 parm_pack = TREE_CHAIN (parm_pack))
12897 tree arg = TREE_VALUE (parm_pack);
12899 int exp = argument_pack_element_is_expansion_p (arg, i);
12900 if (exp == 2)
12901 /* We can't substitute a pack expansion with extra args into
12902 our pattern. */
12903 return true;
12904 else if (exp)
12905 has_expansion_arg = true;
12906 else
12907 has_non_expansion_arg = true;
12910 if (has_expansion_arg && has_non_expansion_arg)
12912 gcc_checking_assert (false);
12913 return true;
12916 return false;
12919 /* [temp.variadic]/6 says that:
12921 The instantiation of a pack expansion [...]
12922 produces a list E1,E2, ..., En, where N is the number of elements
12923 in the pack expansion parameters.
12925 This subroutine of tsubst_pack_expansion produces one of these Ei.
12927 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12928 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12929 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12930 INDEX is the index 'i' of the element Ei to produce. ARGS,
12931 COMPLAIN, and IN_DECL are the same parameters as for the
12932 tsubst_pack_expansion function.
12934 The function returns the resulting Ei upon successful completion,
12935 or error_mark_node.
12937 Note that this function possibly modifies the ARGS parameter, so
12938 it's the responsibility of the caller to restore it. */
12940 static tree
12941 gen_elem_of_pack_expansion_instantiation (tree pattern,
12942 tree parm_packs,
12943 unsigned index,
12944 tree args /* This parm gets
12945 modified. */,
12946 tsubst_flags_t complain,
12947 tree in_decl)
12949 tree t;
12950 bool ith_elem_is_expansion = false;
12952 /* For each parameter pack, change the substitution of the parameter
12953 pack to the ith argument in its argument pack, then expand the
12954 pattern. */
12955 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12957 tree parm = TREE_PURPOSE (pack);
12958 tree arg_pack = TREE_VALUE (pack);
12959 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12961 ith_elem_is_expansion |=
12962 argument_pack_element_is_expansion_p (arg_pack, index);
12964 /* Select the Ith argument from the pack. */
12965 if (TREE_CODE (parm) == PARM_DECL
12966 || VAR_P (parm)
12967 || TREE_CODE (parm) == FIELD_DECL)
12969 if (index == 0)
12971 aps = make_argument_pack_select (arg_pack, index);
12972 if (!mark_used (parm, complain) && !(complain & tf_error))
12973 return error_mark_node;
12974 register_local_specialization (aps, parm);
12976 else
12977 aps = retrieve_local_specialization (parm);
12979 else
12981 int idx, level;
12982 template_parm_level_and_index (parm, &level, &idx);
12984 if (index == 0)
12986 aps = make_argument_pack_select (arg_pack, index);
12987 /* Update the corresponding argument. */
12988 TMPL_ARG (args, level, idx) = aps;
12990 else
12991 /* Re-use the ARGUMENT_PACK_SELECT. */
12992 aps = TMPL_ARG (args, level, idx);
12994 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12997 /* Substitute into the PATTERN with the (possibly altered)
12998 arguments. */
12999 if (pattern == in_decl)
13000 /* Expanding a fixed parameter pack from
13001 coerce_template_parameter_pack. */
13002 t = tsubst_decl (pattern, args, complain);
13003 else if (pattern == error_mark_node)
13004 t = error_mark_node;
13005 else if (!TYPE_P (pattern))
13006 t = tsubst_expr (pattern, args, complain, in_decl);
13007 else
13009 t = tsubst (pattern, args, complain, in_decl);
13010 if (is_auto (t) && !ith_elem_is_expansion)
13011 /* When expanding the fake auto... pack expansion from add_capture, we
13012 need to mark that the expansion is no longer a pack. */
13013 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
13016 /* If the Ith argument pack element is a pack expansion, then
13017 the Ith element resulting from the substituting is going to
13018 be a pack expansion as well. */
13019 if (ith_elem_is_expansion)
13020 t = make_pack_expansion (t, complain);
13022 return t;
13025 /* When the unexpanded parameter pack in a fold expression expands to an empty
13026 sequence, the value of the expression is as follows; the program is
13027 ill-formed if the operator is not listed in this table.
13029 && true
13030 || false
13031 , void() */
13033 tree
13034 expand_empty_fold (tree t, tsubst_flags_t complain)
13036 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
13037 if (!FOLD_EXPR_MODIFY_P (t))
13038 switch (code)
13040 case TRUTH_ANDIF_EXPR:
13041 return boolean_true_node;
13042 case TRUTH_ORIF_EXPR:
13043 return boolean_false_node;
13044 case COMPOUND_EXPR:
13045 return void_node;
13046 default:
13047 break;
13050 if (complain & tf_error)
13051 error_at (location_of (t),
13052 "fold of empty expansion over %O", code);
13053 return error_mark_node;
13056 /* Given a fold-expression T and a current LEFT and RIGHT operand,
13057 form an expression that combines the two terms using the
13058 operator of T. */
13060 static tree
13061 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
13063 tree_code code = FOLD_EXPR_OP (t);
13065 tree lookups = templated_operator_saved_lookups (t);
13067 // Handle compound assignment operators.
13068 if (FOLD_EXPR_MODIFY_P (t))
13069 return build_x_modify_expr (input_location, left, code, right,
13070 lookups, complain);
13072 warning_sentinel s(warn_parentheses);
13073 switch (code)
13075 case COMPOUND_EXPR:
13076 return build_x_compound_expr (input_location, left, right,
13077 lookups, complain);
13078 default:
13079 return build_x_binary_op (input_location, code,
13080 left, TREE_CODE (left),
13081 right, TREE_CODE (right),
13082 lookups, /*overload=*/NULL,
13083 complain);
13087 /* Substitute ARGS into the pack of a fold expression T. */
13089 static inline tree
13090 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13092 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
13095 /* Substitute ARGS into the pack of a fold expression T. */
13097 static inline tree
13098 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13100 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
13103 /* Expand a PACK of arguments into a grouped as left fold.
13104 Given a pack containing elements A0, A1, ..., An and an
13105 operator @, this builds the expression:
13107 ((A0 @ A1) @ A2) ... @ An
13109 Note that PACK must not be empty.
13111 The operator is defined by the original fold expression T. */
13113 static tree
13114 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
13116 tree left = TREE_VEC_ELT (pack, 0);
13117 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
13119 tree right = TREE_VEC_ELT (pack, i);
13120 left = fold_expression (t, left, right, complain);
13122 return left;
13125 /* Substitute into a unary left fold expression. */
13127 static tree
13128 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
13129 tree in_decl)
13131 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13132 if (pack == error_mark_node)
13133 return error_mark_node;
13134 if (PACK_EXPANSION_P (pack))
13136 tree r = copy_node (t);
13137 FOLD_EXPR_PACK (r) = pack;
13138 return r;
13140 if (TREE_VEC_LENGTH (pack) == 0)
13141 return expand_empty_fold (t, complain);
13142 else
13143 return expand_left_fold (t, pack, complain);
13146 /* Substitute into a binary left fold expression.
13148 Do ths by building a single (non-empty) vector of argumnts and
13149 building the expression from those elements. */
13151 static tree
13152 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13153 tree in_decl)
13155 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13156 if (pack == error_mark_node)
13157 return error_mark_node;
13158 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13159 if (init == error_mark_node)
13160 return error_mark_node;
13162 if (PACK_EXPANSION_P (pack))
13164 tree r = copy_node (t);
13165 FOLD_EXPR_PACK (r) = pack;
13166 FOLD_EXPR_INIT (r) = init;
13167 return r;
13170 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13171 TREE_VEC_ELT (vec, 0) = init;
13172 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13173 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13175 return expand_left_fold (t, vec, complain);
13178 /* Expand a PACK of arguments into a grouped as right fold.
13179 Given a pack containing elementns A0, A1, ..., and an
13180 operator @, this builds the expression:
13182 A0@ ... (An-2 @ (An-1 @ An))
13184 Note that PACK must not be empty.
13186 The operator is defined by the original fold expression T. */
13188 tree
13189 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13191 // Build the expression.
13192 int n = TREE_VEC_LENGTH (pack);
13193 tree right = TREE_VEC_ELT (pack, n - 1);
13194 for (--n; n != 0; --n)
13196 tree left = TREE_VEC_ELT (pack, n - 1);
13197 right = fold_expression (t, left, right, complain);
13199 return right;
13202 /* Substitute into a unary right fold expression. */
13204 static tree
13205 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13206 tree in_decl)
13208 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13209 if (pack == error_mark_node)
13210 return error_mark_node;
13211 if (PACK_EXPANSION_P (pack))
13213 tree r = copy_node (t);
13214 FOLD_EXPR_PACK (r) = pack;
13215 return r;
13217 if (TREE_VEC_LENGTH (pack) == 0)
13218 return expand_empty_fold (t, complain);
13219 else
13220 return expand_right_fold (t, pack, complain);
13223 /* Substitute into a binary right fold expression.
13225 Do ths by building a single (non-empty) vector of arguments and
13226 building the expression from those elements. */
13228 static tree
13229 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13230 tree in_decl)
13232 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13233 if (pack == error_mark_node)
13234 return error_mark_node;
13235 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13236 if (init == error_mark_node)
13237 return error_mark_node;
13239 if (PACK_EXPANSION_P (pack))
13241 tree r = copy_node (t);
13242 FOLD_EXPR_PACK (r) = pack;
13243 FOLD_EXPR_INIT (r) = init;
13244 return r;
13247 int n = TREE_VEC_LENGTH (pack);
13248 tree vec = make_tree_vec (n + 1);
13249 for (int i = 0; i < n; ++i)
13250 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13251 TREE_VEC_ELT (vec, n) = init;
13253 return expand_right_fold (t, vec, complain);
13256 /* Walk through the pattern of a pack expansion, adding everything in
13257 local_specializations to a list. */
13259 class el_data
13261 public:
13262 /* Set of variables declared within the pattern. */
13263 hash_set<tree> internal;
13264 /* Set of AST nodes that have been visited by the traversal. */
13265 hash_set<tree> visited;
13266 /* List of local_specializations used within the pattern. */
13267 tree extra;
13268 tsubst_flags_t complain;
13269 /* True iff we don't want to walk into unevaluated contexts. */
13270 bool skip_unevaluated_operands = false;
13271 /* The unevaluated contexts that we avoided walking. */
13272 auto_vec<tree> skipped_trees;
13274 el_data (tsubst_flags_t c)
13275 : extra (NULL_TREE), complain (c) {}
13277 static tree
13278 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13280 el_data &data = *reinterpret_cast<el_data*>(data_);
13281 tree *extra = &data.extra;
13282 tsubst_flags_t complain = data.complain;
13284 if (data.skip_unevaluated_operands
13285 && unevaluated_p (TREE_CODE (*tp)))
13287 data.skipped_trees.safe_push (*tp);
13288 *walk_subtrees = 0;
13289 return NULL_TREE;
13292 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13293 /* Remember local typedefs (85214). */
13294 tp = &TYPE_NAME (*tp);
13296 if (TREE_CODE (*tp) == DECL_EXPR)
13298 tree decl = DECL_EXPR_DECL (*tp);
13299 data.internal.add (decl);
13300 if (VAR_P (decl)
13301 && DECL_DECOMPOSITION_P (decl)
13302 && TREE_TYPE (decl) != error_mark_node)
13304 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13305 for (tree decl2 = DECL_CHAIN (decl);
13306 decl2
13307 && VAR_P (decl2)
13308 && DECL_DECOMPOSITION_P (decl2)
13309 && DECL_NAME (decl2)
13310 && TREE_TYPE (decl2) != error_mark_node;
13311 decl2 = DECL_CHAIN (decl2))
13313 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13314 data.internal.add (decl2);
13318 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13320 /* Since we defer implicit capture, look in the parms and body. */
13321 tree fn = lambda_function (*tp);
13322 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13323 &data.visited);
13324 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13325 &data.visited);
13327 else if (tree spec = retrieve_local_specialization (*tp))
13329 if (data.internal.contains (*tp))
13330 /* Don't mess with variables declared within the pattern. */
13331 return NULL_TREE;
13332 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13334 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13335 tree args = ARGUMENT_PACK_ARGS (spec);
13336 if (TREE_VEC_LENGTH (args) == 1)
13338 tree elt = TREE_VEC_ELT (args, 0);
13339 if (PACK_EXPANSION_P (elt))
13340 elt = PACK_EXPANSION_PATTERN (elt);
13341 if (DECL_PACK_P (elt))
13342 spec = elt;
13344 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13346 /* Handle lambda capture here, since we aren't doing any
13347 substitution now, and so tsubst_copy won't call
13348 process_outer_var_ref. */
13349 tree args = ARGUMENT_PACK_ARGS (spec);
13350 int len = TREE_VEC_LENGTH (args);
13351 for (int i = 0; i < len; ++i)
13353 tree arg = TREE_VEC_ELT (args, i);
13354 tree carg = arg;
13355 if (outer_automatic_var_p (arg))
13356 carg = process_outer_var_ref (arg, complain);
13357 if (carg != arg)
13359 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13360 proxies. */
13361 if (i == 0)
13363 spec = copy_node (spec);
13364 args = copy_node (args);
13365 ARGUMENT_PACK_ARGS (spec) = args;
13366 register_local_specialization (spec, *tp);
13368 TREE_VEC_ELT (args, i) = carg;
13373 if (outer_automatic_var_p (spec))
13374 spec = process_outer_var_ref (spec, complain);
13375 *extra = tree_cons (*tp, spec, *extra);
13377 return NULL_TREE;
13379 static tree
13380 extract_local_specs (tree pattern, tsubst_flags_t complain)
13382 el_data data (complain);
13383 /* Walk the pattern twice, ignoring unevaluated operands the first time
13384 around, so that if a local specialization appears in both an evaluated
13385 and unevaluated context we prefer to process it in the evaluated context
13386 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13387 context). */
13388 data.skip_unevaluated_operands = true;
13389 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13390 /* Now walk the unevaluated contexts we skipped the first time around. */
13391 data.skip_unevaluated_operands = false;
13392 for (tree t : data.skipped_trees)
13394 data.visited.remove (t);
13395 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13397 return data.extra;
13400 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13401 for use in PACK_EXPANSION_EXTRA_ARGS. */
13403 tree
13404 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13406 /* Make a copy of the extra arguments so that they won't get changed
13407 out from under us. */
13408 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13409 if (local_specializations)
13410 if (tree locals = extract_local_specs (pattern, complain))
13411 extra = tree_cons (NULL_TREE, extra, locals);
13412 return extra;
13415 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13416 normal template args to ARGS. */
13418 tree
13419 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13421 if (extra && TREE_CODE (extra) == TREE_LIST)
13423 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13425 /* The partial instantiation involved local declarations collected in
13426 extract_local_specs; map from the general template to our local
13427 context. */
13428 tree gen = TREE_PURPOSE (elt);
13429 tree inst = TREE_VALUE (elt);
13430 if (DECL_P (inst))
13431 if (tree local = retrieve_local_specialization (inst))
13432 inst = local;
13433 /* else inst is already a full instantiation of the pack. */
13434 register_local_specialization (inst, gen);
13436 gcc_assert (!TREE_PURPOSE (extra));
13437 extra = TREE_VALUE (extra);
13439 if (uses_template_parms (extra))
13441 /* This can happen after dependent substitution into a
13442 requires-expr or a lambda that uses constexpr if. */
13443 extra = tsubst_template_args (extra, args, complain, in_decl);
13444 args = add_outermost_template_args (args, extra);
13446 else
13447 args = add_to_template_args (extra, args);
13448 return args;
13451 /* Substitute ARGS into T, which is an pack expansion
13452 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13453 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13454 (if only a partial substitution could be performed) or
13455 ERROR_MARK_NODE if there was an error. */
13456 tree
13457 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13458 tree in_decl)
13460 tree pattern;
13461 tree pack, packs = NULL_TREE;
13462 bool unsubstituted_packs = false;
13463 int i, len = -1;
13464 tree result;
13465 bool need_local_specializations = false;
13466 int levels;
13468 gcc_assert (PACK_EXPANSION_P (t));
13469 pattern = PACK_EXPANSION_PATTERN (t);
13471 /* Add in any args remembered from an earlier partial instantiation. */
13472 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13474 levels = TMPL_ARGS_DEPTH (args);
13476 /* Determine the argument packs that will instantiate the parameter
13477 packs used in the expansion expression. While we're at it,
13478 compute the number of arguments to be expanded and make sure it
13479 is consistent. */
13480 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13481 pack = TREE_CHAIN (pack))
13483 tree parm_pack = TREE_VALUE (pack);
13484 tree arg_pack = NULL_TREE;
13485 tree orig_arg = NULL_TREE;
13486 int level = 0;
13488 if (TREE_CODE (parm_pack) == BASES)
13490 gcc_assert (parm_pack == pattern);
13491 tree type = tsubst (BASES_TYPE (parm_pack), args, complain, in_decl);
13492 if (BASES_DIRECT (parm_pack))
13493 return calculate_direct_bases (type, complain);
13494 else
13495 return calculate_bases (type, complain);
13497 else if (builtin_pack_call_p (parm_pack))
13499 if (parm_pack != pattern)
13501 if (complain & tf_error)
13502 sorry ("%qE is not the entire pattern of the pack expansion",
13503 parm_pack);
13504 return error_mark_node;
13506 return expand_builtin_pack_call (parm_pack, args,
13507 complain, in_decl);
13509 else if (TREE_CODE (parm_pack) == PARM_DECL)
13511 /* We know we have correct local_specializations if this
13512 expansion is at function scope, or if we're dealing with a
13513 local parameter in a requires expression; for the latter,
13514 tsubst_requires_expr set it up appropriately. */
13515 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13516 arg_pack = retrieve_local_specialization (parm_pack);
13517 else
13518 /* We can't rely on local_specializations for a parameter
13519 name used later in a function declaration (such as in a
13520 late-specified return type). Even if it exists, it might
13521 have the wrong value for a recursive call. */
13522 need_local_specializations = true;
13524 if (!arg_pack)
13526 /* This parameter pack was used in an unevaluated context. Just
13527 make a dummy decl, since it's only used for its type. */
13528 ++cp_unevaluated_operand;
13529 arg_pack = tsubst_decl (parm_pack, args, complain);
13530 --cp_unevaluated_operand;
13531 if (arg_pack && DECL_PACK_P (arg_pack))
13532 /* Partial instantiation of the parm_pack, we can't build
13533 up an argument pack yet. */
13534 arg_pack = NULL_TREE;
13535 else
13536 arg_pack = make_fnparm_pack (arg_pack);
13538 else if (DECL_PACK_P (arg_pack))
13539 /* This argument pack isn't fully instantiated yet. */
13540 arg_pack = NULL_TREE;
13542 else if (is_capture_proxy (parm_pack))
13544 arg_pack = retrieve_local_specialization (parm_pack);
13545 if (DECL_PACK_P (arg_pack))
13546 arg_pack = NULL_TREE;
13548 else
13550 int idx;
13551 template_parm_level_and_index (parm_pack, &level, &idx);
13552 if (level <= levels)
13553 arg_pack = TMPL_ARG (args, level, idx);
13555 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13556 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13557 arg_pack = NULL_TREE;
13560 orig_arg = arg_pack;
13561 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13562 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13564 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13565 /* This can only happen if we forget to expand an argument
13566 pack somewhere else. Just return an error, silently. */
13568 result = make_tree_vec (1);
13569 TREE_VEC_ELT (result, 0) = error_mark_node;
13570 return result;
13573 if (arg_pack)
13575 int my_len =
13576 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13578 /* Don't bother trying to do a partial substitution with
13579 incomplete packs; we'll try again after deduction. */
13580 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13581 return t;
13583 if (len < 0)
13584 len = my_len;
13585 else if (len != my_len)
13587 if (!(complain & tf_error))
13588 /* Fail quietly. */;
13589 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13590 error ("mismatched argument pack lengths while expanding %qT",
13591 pattern);
13592 else
13593 error ("mismatched argument pack lengths while expanding %qE",
13594 pattern);
13595 return error_mark_node;
13598 /* Keep track of the parameter packs and their corresponding
13599 argument packs. */
13600 packs = tree_cons (parm_pack, arg_pack, packs);
13601 TREE_TYPE (packs) = orig_arg;
13603 else
13605 /* We can't substitute for this parameter pack. We use a flag as
13606 well as the missing_level counter because function parameter
13607 packs don't have a level. */
13608 gcc_assert (processing_template_decl || is_auto (parm_pack));
13609 unsubstituted_packs = true;
13613 /* If the expansion is just T..., return the matching argument pack, unless
13614 we need to call convert_from_reference on all the elements. This is an
13615 important optimization; see c++/68422. */
13616 if (!unsubstituted_packs
13617 && TREE_PURPOSE (packs) == pattern)
13619 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13621 /* If the argument pack is a single pack expansion, pull it out. */
13622 if (TREE_VEC_LENGTH (args) == 1
13623 && pack_expansion_args_count (args))
13625 tree arg = TREE_VEC_ELT (args, 0);
13626 if (PACK_EXPANSION_SIZEOF_P (t)
13627 && !TEMPLATE_PARM_P (PACK_EXPANSION_PATTERN (arg)))
13628 /* Except if this isn't a simple sizeof...(T) which gets sZ
13629 mangling, keep the TREE_VEC to get sP mangling. */;
13630 else
13631 return TREE_VEC_ELT (args, 0);
13634 /* Types need no adjustment, nor does sizeof..., and if we still have
13635 some pack expansion args we won't do anything yet. */
13636 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13637 || PACK_EXPANSION_SIZEOF_P (t)
13638 || pack_expansion_args_count (args))
13639 return args;
13640 /* Also optimize expression pack expansions if we can tell that the
13641 elements won't have reference type. */
13642 tree type = TREE_TYPE (pattern);
13643 if (type && !TYPE_REF_P (type)
13644 && !PACK_EXPANSION_P (type)
13645 && !WILDCARD_TYPE_P (type))
13646 return args;
13647 /* Otherwise use the normal path so we get convert_from_reference. */
13650 /* We cannot expand this expansion expression, because we don't have
13651 all of the argument packs we need. */
13652 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13654 /* We got some full packs, but we can't substitute them in until we
13655 have values for all the packs. So remember these until then. */
13657 t = make_pack_expansion (pattern, complain);
13658 PACK_EXPANSION_EXTRA_ARGS (t)
13659 = build_extra_args (pattern, args, complain);
13660 return t;
13663 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13664 type, so create our own local specializations map; the current map is
13665 either NULL or (in the case of recursive unification) might have
13666 bindings that we don't want to use or alter. */
13667 local_specialization_stack lss (need_local_specializations
13668 ? lss_blank : lss_nop);
13670 if (unsubstituted_packs)
13672 /* There were no real arguments, we're just replacing a parameter
13673 pack with another version of itself. Substitute into the
13674 pattern and return a PACK_EXPANSION_*. The caller will need to
13675 deal with that. */
13676 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13677 result = tsubst_expr (pattern, args, complain, in_decl);
13678 else
13679 result = tsubst (pattern, args, complain, in_decl);
13680 result = make_pack_expansion (result, complain);
13681 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13682 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13683 if (PACK_EXPANSION_AUTO_P (t))
13685 /* This is a fake auto... pack expansion created in add_capture with
13686 _PACKS that don't appear in the pattern. Copy one over. */
13687 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13688 pack = retrieve_local_specialization (TREE_VALUE (packs));
13689 gcc_checking_assert (DECL_PACK_P (pack));
13690 PACK_EXPANSION_PARAMETER_PACKS (result)
13691 = build_tree_list (NULL_TREE, pack);
13692 PACK_EXPANSION_AUTO_P (result) = true;
13694 return result;
13697 gcc_assert (len >= 0);
13699 /* For each argument in each argument pack, substitute into the
13700 pattern. */
13701 result = make_tree_vec (len);
13702 tree elem_args = copy_template_args (args);
13703 for (i = 0; i < len; ++i)
13705 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13707 elem_args, complain,
13708 in_decl);
13709 TREE_VEC_ELT (result, i) = t;
13710 if (t == error_mark_node)
13712 result = error_mark_node;
13713 break;
13717 /* Update ARGS to restore the substitution from parameter packs to
13718 their argument packs. */
13719 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13721 tree parm = TREE_PURPOSE (pack);
13723 if (TREE_CODE (parm) == PARM_DECL
13724 || VAR_P (parm)
13725 || TREE_CODE (parm) == FIELD_DECL)
13726 register_local_specialization (TREE_TYPE (pack), parm);
13727 else
13729 int idx, level;
13731 if (TREE_VALUE (pack) == NULL_TREE)
13732 continue;
13734 template_parm_level_and_index (parm, &level, &idx);
13736 /* Update the corresponding argument. */
13737 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13738 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13739 TREE_TYPE (pack);
13740 else
13741 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13745 /* If the dependent pack arguments were such that we end up with only a
13746 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13747 if (len == 1 && TREE_CODE (result) == TREE_VEC
13748 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13749 return TREE_VEC_ELT (result, 0);
13751 return result;
13754 /* Make an argument pack out of the TREE_VEC VEC. */
13756 static tree
13757 make_argument_pack (tree vec)
13759 tree pack;
13761 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13762 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13763 else
13765 pack = make_node (NONTYPE_ARGUMENT_PACK);
13766 TREE_CONSTANT (pack) = 1;
13768 ARGUMENT_PACK_ARGS (pack) = vec;
13769 return pack;
13772 /* Return an exact copy of template args T that can be modified
13773 independently. */
13775 static tree
13776 copy_template_args (tree t)
13778 if (t == error_mark_node)
13779 return t;
13781 int len = TREE_VEC_LENGTH (t);
13782 tree new_vec = make_tree_vec (len);
13784 for (int i = 0; i < len; ++i)
13786 tree elt = TREE_VEC_ELT (t, i);
13787 if (elt && TREE_CODE (elt) == TREE_VEC)
13788 elt = copy_template_args (elt);
13789 TREE_VEC_ELT (new_vec, i) = elt;
13792 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13793 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13795 return new_vec;
13798 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13800 tree
13801 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13802 tree in_decl)
13804 /* This flag is used only during deduction, and we don't expect to
13805 substitute such ARGUMENT_PACKs. */
13806 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13808 /* Substitute into each of the arguments. */
13809 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13810 args, complain, in_decl);
13811 if (pack_args == error_mark_node)
13812 return error_mark_node;
13814 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13815 return orig_arg;
13817 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13818 template parameter, we might be able to avoid allocating a new
13819 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13820 if the substituted result is identical to it. */
13821 if (tree parm = template_arg_to_parm (orig_arg))
13823 int level, index;
13824 template_parm_level_and_index (parm, &level, &index);
13825 if (TMPL_ARGS_DEPTH (args) >= level)
13826 if (tree arg = TMPL_ARG (args, level, index))
13827 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13828 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13830 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13831 return arg;
13835 tree new_arg;
13836 if (TYPE_P (orig_arg))
13838 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13839 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13841 else
13843 new_arg = make_node (TREE_CODE (orig_arg));
13844 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13846 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13847 return new_arg;
13850 /* Substitute ARGS into the vector or list of template arguments T. */
13852 tree
13853 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13855 if (t == error_mark_node)
13856 return error_mark_node;
13858 /* In "sizeof(X<I>)" we need to evaluate "I". */
13859 cp_evaluated ev;
13861 const int len = TREE_VEC_LENGTH (t);
13862 tree *elts = XALLOCAVEC (tree, len);
13863 int expanded_len_adjust = 0;
13865 /* True iff the substituted result is identical to T. */
13866 bool const_subst_p = true;
13868 for (int i = 0; i < len; i++)
13870 tree orig_arg = TREE_VEC_ELT (t, i);
13871 tree new_arg;
13873 if (!orig_arg)
13874 new_arg = NULL_TREE;
13875 else if (TREE_CODE (orig_arg) == TREE_VEC)
13876 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13877 else if (PACK_EXPANSION_P (orig_arg))
13879 /* Substitute into an expansion expression. */
13880 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13882 if (TREE_CODE (new_arg) == TREE_VEC)
13883 /* Add to the expanded length adjustment the number of
13884 expanded arguments. We subtract one from this
13885 measurement, because the argument pack expression
13886 itself is already counted as 1 in
13887 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13888 the argument pack is empty. */
13889 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13891 else if (ARGUMENT_PACK_P (orig_arg))
13892 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13893 else
13894 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13896 if (new_arg == error_mark_node)
13897 return error_mark_node;
13899 elts[i] = new_arg;
13900 if (new_arg != orig_arg)
13901 const_subst_p = false;
13904 if (const_subst_p)
13905 return t;
13907 tree maybe_reuse = NULL_TREE;
13909 /* If ARGS and T are both multi-level, the substituted result may be
13910 identical to ARGS. */
13911 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13912 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13913 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13914 maybe_reuse = args;
13915 /* If T appears to be a vector of generic template arguments, the
13916 substituted result may be identical to the corresponding level
13917 from ARGS. */
13918 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13920 int level, index;
13921 template_parm_level_and_index (parm, &level, &index);
13922 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13923 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13926 /* If the substituted result is identical to MAYBE_REUSE, return
13927 it and avoid allocating a new TREE_VEC, as an optimization. */
13928 if (maybe_reuse != NULL_TREE
13929 && TREE_VEC_LENGTH (maybe_reuse) == len
13930 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13931 return maybe_reuse;
13933 /* If T consists of only a pack expansion for which substitution yielded
13934 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13935 of effectively making a copy. */
13936 if (len == 1
13937 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13938 && TREE_CODE (elts[0]) == TREE_VEC)
13939 return elts[0];
13941 /* Make space for the expanded arguments coming from template
13942 argument packs. */
13943 tree r = make_tree_vec (len + expanded_len_adjust);
13944 /* T can contain TREE_VECs. That happens if T contains the
13945 arguments for a member template.
13946 In that case each TREE_VEC in T represents a level of template
13947 arguments, and T won't carry any non defaulted argument count.
13948 It will rather be the nested TREE_VECs that will carry one.
13949 In other words, T carries a non defaulted argument count only
13950 if it doesn't contain any nested TREE_VEC. */
13951 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13953 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13954 count += expanded_len_adjust;
13955 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13958 int out = 0;
13959 for (int i = 0; i < len; i++)
13961 tree orig_arg = TREE_VEC_ELT (t, i);
13962 if (orig_arg
13963 && PACK_EXPANSION_P (orig_arg)
13964 && TREE_CODE (elts[i]) == TREE_VEC)
13966 /* Now expand the template argument pack "in place". */
13967 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13968 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13970 else
13972 TREE_VEC_ELT (r, out) = elts[i];
13973 out++;
13976 gcc_assert (out == TREE_VEC_LENGTH (r));
13978 return r;
13981 /* Substitute ARGS into one level PARMS of template parameters. */
13983 static tree
13984 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13986 if (parms == error_mark_node)
13987 return error_mark_node;
13989 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13991 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13993 tree tuple = TREE_VEC_ELT (parms, i);
13995 if (tuple == error_mark_node)
13996 continue;
13998 TREE_VEC_ELT (new_vec, i) =
13999 tsubst_template_parm (tuple, args, complain);
14002 return new_vec;
14005 /* Return the result of substituting ARGS into the template parameters
14006 given by PARMS. If there are m levels of ARGS and m + n levels of
14007 PARMS, then the result will contain n levels of PARMS. For
14008 example, if PARMS is `template <class T> template <class U>
14009 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
14010 result will be `template <int*, double, class V>'. */
14012 static tree
14013 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
14015 tree r = NULL_TREE;
14016 tree* new_parms;
14018 /* When substituting into a template, we must set
14019 PROCESSING_TEMPLATE_DECL as the template parameters may be
14020 dependent if they are based on one-another, and the dependency
14021 predicates are short-circuit outside of templates. */
14022 ++processing_template_decl;
14024 for (new_parms = &r;
14025 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
14026 new_parms = &(TREE_CHAIN (*new_parms)),
14027 parms = TREE_CHAIN (parms))
14029 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
14030 args, complain);
14031 *new_parms =
14032 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
14033 - TMPL_ARGS_DEPTH (args)),
14034 new_vec, NULL_TREE);
14035 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
14036 = TEMPLATE_PARMS_CONSTRAINTS (parms);
14039 --processing_template_decl;
14041 return r;
14044 /* Return the result of substituting ARGS into one template parameter
14045 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
14046 parameter and which TREE_PURPOSE is the default argument of the
14047 template parameter. */
14049 static tree
14050 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
14052 tree default_value, parm_decl;
14054 if (args == NULL_TREE
14055 || t == NULL_TREE
14056 || t == error_mark_node)
14057 return t;
14059 gcc_assert (TREE_CODE (t) == TREE_LIST);
14061 default_value = TREE_PURPOSE (t);
14062 parm_decl = TREE_VALUE (t);
14064 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
14065 if (TREE_CODE (parm_decl) == PARM_DECL
14066 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
14067 parm_decl = error_mark_node;
14068 default_value = tsubst_template_arg (default_value, args,
14069 complain, NULL_TREE);
14071 tree r = build_tree_list (default_value, parm_decl);
14072 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
14073 return r;
14076 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
14077 parameter in PARMS for sake of declaration matching. */
14079 static void
14080 tsubst_each_template_parm_constraints (tree parms, tree args,
14081 tsubst_flags_t complain)
14083 ++processing_template_decl;
14084 for (; parms; parms = TREE_CHAIN (parms))
14086 tree level = TREE_VALUE (parms);
14087 for (tree parm : tree_vec_range (level))
14088 TEMPLATE_PARM_CONSTRAINTS (parm)
14089 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
14090 complain, NULL_TREE);
14092 --processing_template_decl;
14095 /* Substitute the ARGS into the indicated aggregate (or enumeration)
14096 type T. If T is not an aggregate or enumeration type, it is
14097 handled as if by tsubst. IN_DECL is as for tsubst. If
14098 ENTERING_SCOPE is nonzero, T is the context for a template which
14099 we are presently tsubst'ing. Return the substituted value. */
14101 static tree
14102 tsubst_aggr_type (tree t,
14103 tree args,
14104 tsubst_flags_t complain,
14105 tree in_decl,
14106 int entering_scope)
14108 if (t == NULL_TREE)
14109 return NULL_TREE;
14111 /* Handle typedefs via tsubst so that they get consistently reused. */
14112 if (typedef_variant_p (t))
14114 t = tsubst (t, args, complain, in_decl);
14115 if (t == error_mark_node)
14116 return error_mark_node;
14118 /* The effect of entering_scope is that for a dependent specialization
14119 A<T>, lookup_template_class prefers to return A's primary template
14120 type instead of the implicit instantiation. So when entering_scope,
14121 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
14122 taking advantage of the fact that lookup_template_class links the two
14123 types by setting TYPE_CANONICAL of the latter to the former. */
14124 if (entering_scope
14125 && CLASS_TYPE_P (t)
14126 && dependent_type_p (t)
14127 && TYPE_TEMPLATE_INFO (t)
14128 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
14129 t = TYPE_CANONICAL (t);
14131 return t;
14134 switch (TREE_CODE (t))
14136 case RECORD_TYPE:
14137 case ENUMERAL_TYPE:
14138 case UNION_TYPE:
14139 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
14141 default:
14142 return tsubst (t, args, complain, in_decl);
14146 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
14147 and ENUMERAL_TYPE cases of tsubst. */
14149 static tree
14150 tsubst_aggr_type_1 (tree t,
14151 tree args,
14152 tsubst_flags_t complain,
14153 tree in_decl,
14154 int entering_scope)
14156 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
14158 complain &= ~tf_qualifying_scope;
14160 /* Figure out what arguments are appropriate for the
14161 type we are trying to find. For example, given:
14163 template <class T> struct S;
14164 template <class T, class U> void f(T, U) { S<U> su; }
14166 and supposing that we are instantiating f<int, double>,
14167 then our ARGS will be {int, double}, but, when looking up
14168 S we only want {double}. */
14169 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14170 complain, in_decl);
14171 if (argvec == error_mark_node)
14172 return error_mark_node;
14174 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14175 entering_scope, complain);
14176 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14178 else
14179 /* This is not a template type, so there's nothing to do. */
14180 return t;
14183 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14184 indexed in reverse order of the parameters. */
14186 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14188 /* Return a reference to the vec* of defarg insts for FN. */
14190 static vec<tree,va_gc> *&
14191 defarg_insts_for (tree fn)
14193 if (!defarg_inst)
14194 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14195 tree_vec_map in = { { fn }, nullptr };
14196 tree_vec_map **slot
14197 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14198 if (!*slot)
14200 *slot = ggc_alloc<tree_vec_map> ();
14201 **slot = in;
14203 return (*slot)->to;
14206 /* Substitute into the default argument ARG (a default argument for
14207 FN), which has the indicated TYPE. */
14209 tree
14210 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14211 tsubst_flags_t complain)
14213 int errs = errorcount + sorrycount;
14215 /* This can happen in invalid code. */
14216 if (TREE_CODE (arg) == DEFERRED_PARSE)
14217 return arg;
14219 /* Shortcut {}. */
14220 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14221 && CONSTRUCTOR_NELTS (arg) == 0)
14222 return arg;
14224 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14225 parm = chain_index (parmnum, parm);
14226 tree parmtype = TREE_TYPE (parm);
14227 if (DECL_BY_REFERENCE (parm))
14228 parmtype = TREE_TYPE (parmtype);
14229 if (parmtype == error_mark_node)
14230 return error_mark_node;
14232 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14234 /* Remember the location of the pointer to the vec rather than the location
14235 of the particular element, in case the vec grows in tsubst_expr. */
14236 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14237 /* Index in reverse order to avoid allocating space for initial parameters
14238 that don't have default arguments. */
14239 unsigned ridx = list_length (parm);
14240 if (vec_safe_length (defs) < ridx)
14241 vec_safe_grow_cleared (defs, ridx);
14242 else if (tree inst = (*defs)[ridx - 1])
14243 return inst;
14245 /* This default argument came from a template. Instantiate the
14246 default argument here, not in tsubst. In the case of
14247 something like:
14249 template <class T>
14250 struct S {
14251 static T t();
14252 void f(T = t());
14255 we must be careful to do name lookup in the scope of S<T>,
14256 rather than in the current class. */
14257 push_to_top_level ();
14258 push_access_scope (fn);
14259 push_deferring_access_checks (dk_no_deferred);
14260 /* So in_immediate_context knows this is a default argument. */
14261 begin_scope (sk_function_parms, fn);
14262 start_lambda_scope (parm);
14264 /* The default argument expression may cause implicitly defined
14265 member functions to be synthesized, which will result in garbage
14266 collection. We must treat this situation as if we were within
14267 the body of function so as to avoid collecting live data on the
14268 stack. */
14269 ++function_depth;
14270 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14271 --function_depth;
14273 finish_lambda_scope ();
14275 /* Make sure the default argument is reasonable. */
14276 arg = check_default_argument (type, arg, complain);
14278 if (errorcount+sorrycount > errs
14279 && (complain & tf_warning_or_error))
14280 inform (input_location,
14281 " when instantiating default argument for call to %qD", fn);
14283 leave_scope ();
14284 pop_deferring_access_checks ();
14285 pop_access_scope (fn);
14286 pop_from_top_level ();
14288 if (arg != error_mark_node && !cp_unevaluated_operand)
14289 (*defs)[ridx - 1] = arg;
14291 return arg;
14294 /* Substitute into all the default arguments for FN. */
14296 static void
14297 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14299 tree arg;
14300 tree tmpl_args;
14302 tmpl_args = DECL_TI_ARGS (fn);
14304 /* If this function is not yet instantiated, we certainly don't need
14305 its default arguments. */
14306 if (uses_template_parms (tmpl_args))
14307 return;
14308 /* Don't do this again for clones. */
14309 if (DECL_CLONED_FUNCTION_P (fn))
14310 return;
14312 int i = 0;
14313 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14314 arg;
14315 arg = TREE_CHAIN (arg), ++i)
14316 if (TREE_PURPOSE (arg))
14317 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14318 TREE_VALUE (arg),
14319 TREE_PURPOSE (arg),
14320 complain);
14323 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14324 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14326 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14328 void
14329 store_explicit_specifier (tree v, tree t)
14331 if (!explicit_specifier_map)
14332 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14333 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14334 explicit_specifier_map->put (v, t);
14337 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14339 tree
14340 lookup_explicit_specifier (tree v)
14342 return *explicit_specifier_map->get (v);
14345 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14346 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14347 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14348 identical to T. */
14350 static tree
14351 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14352 tree raises, tsubst_flags_t complain)
14354 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14356 tree new_type;
14357 if (TREE_CODE (t) == FUNCTION_TYPE)
14359 new_type = build_function_type (return_type, arg_types);
14360 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14362 else
14364 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14365 /* Don't pick up extra function qualifiers from the basetype. */
14366 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14367 if (! MAYBE_CLASS_TYPE_P (r))
14369 /* [temp.deduct]
14371 Type deduction may fail for any of the following
14372 reasons:
14374 -- Attempting to create "pointer to member of T" when T
14375 is not a class type. */
14376 if (complain & tf_error)
14377 error ("creating pointer to member function of non-class type %qT",
14379 return error_mark_node;
14382 new_type = build_method_type_directly (r, return_type,
14383 TREE_CHAIN (arg_types));
14385 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14387 cp_ref_qualifier rqual = type_memfn_rqual (t);
14388 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14389 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14392 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14393 each of its formal parameters. If there is a disagreement then rebuild
14394 DECL's function type according to its formal parameter types, as part of a
14395 resolution for Core issues 1001/1322. */
14397 static void
14398 maybe_rebuild_function_decl_type (tree decl)
14400 bool function_type_needs_rebuilding = false;
14401 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14403 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14404 while (parm_type_list && parm_type_list != void_list_node)
14406 tree parm_type = TREE_VALUE (parm_type_list);
14407 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14408 if (!same_type_p (parm_type, formal_parm_type_unqual))
14410 function_type_needs_rebuilding = true;
14411 break;
14414 parm_list = DECL_CHAIN (parm_list);
14415 parm_type_list = TREE_CHAIN (parm_type_list);
14419 if (!function_type_needs_rebuilding)
14420 return;
14422 const tree fntype = TREE_TYPE (decl);
14423 tree parm_list = DECL_ARGUMENTS (decl);
14424 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14425 tree new_parm_type_list = NULL_TREE;
14426 tree *q = &new_parm_type_list;
14427 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14429 *q = copy_node (old_parm_type_list);
14430 parm_list = DECL_CHAIN (parm_list);
14431 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14432 q = &TREE_CHAIN (*q);
14434 while (old_parm_type_list && old_parm_type_list != void_list_node)
14436 *q = copy_node (old_parm_type_list);
14437 tree *new_parm_type = &TREE_VALUE (*q);
14438 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14439 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14440 *new_parm_type = formal_parm_type_unqual;
14442 parm_list = DECL_CHAIN (parm_list);
14443 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14444 q = &TREE_CHAIN (*q);
14446 if (old_parm_type_list == void_list_node)
14447 *q = void_list_node;
14449 TREE_TYPE (decl)
14450 = rebuild_function_or_method_type (fntype,
14451 TREE_TYPE (fntype), new_parm_type_list,
14452 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14455 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14457 static tree
14458 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14459 tree lambda_fntype, bool use_spec_table = true)
14461 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14462 hashval_t hash = 0;
14463 tree in_decl = t;
14465 /* Nobody should be tsubst'ing into non-template functions. */
14466 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14467 || DECL_LOCAL_DECL_P (t));
14469 if (DECL_LOCAL_DECL_P (t))
14471 if (tree spec = retrieve_local_specialization (t))
14472 return spec;
14474 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14476 /* If T is not dependent, just return it. */
14477 if (!uses_template_parms (DECL_TI_ARGS (t))
14478 && !LAMBDA_FUNCTION_P (t))
14479 return t;
14481 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14482 if (non_templated_friend_p (t))
14483 goto friend_case;
14485 /* Calculate the most general template of which R is a
14486 specialization. */
14487 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14489 /* We're substituting a lambda function under tsubst_lambda_expr but not
14490 directly from it; find the matching function we're already inside.
14491 But don't do this if T is a generic lambda with a single level of
14492 template parms, as in that case we're doing a normal instantiation. */
14493 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14494 && (!generic_lambda_fn_p (t)
14495 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14496 return enclosing_instantiation_of (t);
14498 /* Calculate the complete set of arguments used to
14499 specialize R. */
14500 if (use_spec_table && !lambda_fntype)
14502 argvec = tsubst_template_args (DECL_TI_ARGS
14503 (DECL_TEMPLATE_RESULT
14504 (DECL_TI_TEMPLATE (t))),
14505 args, complain, in_decl);
14506 if (argvec == error_mark_node)
14507 return error_mark_node;
14509 /* Check to see if we already have this specialization. */
14510 hash = spec_hasher::hash (gen_tmpl, argvec);
14511 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14512 /* The spec for these args might be a partial instantiation of the
14513 template, but here what we want is the FUNCTION_DECL. */
14514 return STRIP_TEMPLATE (spec);
14516 else
14517 argvec = args;
14519 else
14521 /* This special case arises when we have something like this:
14523 template <class T> struct S {
14524 friend void f<int>(int, double);
14527 Here, the DECL_TI_TEMPLATE for the friend declaration
14528 will be an IDENTIFIER_NODE. We are being called from
14529 tsubst_friend_function, and we want only to create a
14530 new decl (R) with appropriate types so that we can call
14531 determine_specialization. */
14532 friend_case:
14533 gen_tmpl = NULL_TREE;
14534 argvec = NULL_TREE;
14537 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14538 : NULL_TREE);
14539 tree ctx = closure ? closure : DECL_CONTEXT (t);
14540 bool member = ctx && TYPE_P (ctx);
14542 /* If this is a static or xobj lambda, remove the 'this' pointer added in
14543 tsubst_lambda_expr now that we know the closure type. */
14544 if (lambda_fntype && !DECL_IOBJ_MEMBER_FUNCTION_P (t))
14545 lambda_fntype = static_fn_type (lambda_fntype);
14547 if (member && !closure)
14548 ctx = tsubst_aggr_type (ctx, args,
14549 complain, t, /*entering_scope=*/1);
14551 tree type = (lambda_fntype ? lambda_fntype
14552 : tsubst (TREE_TYPE (t), args,
14553 complain | tf_fndecl_type, in_decl));
14554 if (type == error_mark_node)
14555 return error_mark_node;
14557 /* If we hit excessive deduction depth, the type is bogus even if
14558 it isn't error_mark_node, so don't build a decl. */
14559 if (excessive_deduction_depth)
14560 return error_mark_node;
14562 /* We do NOT check for matching decls pushed separately at this
14563 point, as they may not represent instantiations of this
14564 template, and in any case are considered separate under the
14565 discrete model. */
14566 tree r = copy_decl (t);
14567 DECL_USE_TEMPLATE (r) = 0;
14568 TREE_TYPE (r) = type;
14569 /* Clear out the mangled name and RTL for the instantiation. */
14570 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14571 SET_DECL_RTL (r, NULL);
14572 /* Leave DECL_INITIAL set on deleted instantiations. */
14573 if (!DECL_DELETED_FN (r))
14574 DECL_INITIAL (r) = NULL_TREE;
14575 DECL_CONTEXT (r) = ctx;
14576 set_instantiating_module (r);
14578 /* Handle explicit(dependent-expr). */
14579 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14581 tree spec = lookup_explicit_specifier (t);
14582 spec = tsubst_expr (spec, args, complain, in_decl);
14583 spec = build_explicit_specifier (spec, complain);
14584 if (spec == error_mark_node)
14585 return error_mark_node;
14586 if (instantiation_dependent_expression_p (spec))
14587 store_explicit_specifier (r, spec);
14588 else
14590 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14591 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14595 /* OpenMP UDRs have the only argument a reference to the declared
14596 type. We want to diagnose if the declared type is a reference,
14597 which is invalid, but as references to references are usually
14598 quietly merged, diagnose it here. */
14599 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14601 tree argtype
14602 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14603 argtype = tsubst (argtype, args, complain, in_decl);
14604 if (TYPE_REF_P (argtype))
14605 error_at (DECL_SOURCE_LOCATION (t),
14606 "reference type %qT in "
14607 "%<#pragma omp declare reduction%>", argtype);
14608 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14609 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14610 argtype);
14613 if (member && DECL_CONV_FN_P (r))
14614 /* Type-conversion operator. Reconstruct the name, in
14615 case it's the name of one of the template's parameters. */
14616 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14618 tree parms = DECL_ARGUMENTS (t);
14619 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14620 parms = DECL_CHAIN (parms);
14621 parms = tsubst (parms, args, complain, t);
14622 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14623 DECL_CONTEXT (parm) = r;
14624 if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
14626 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14627 DECL_NAME (tparm) = closure_identifier;
14628 DECL_CHAIN (tparm) = parms;
14629 parms = tparm;
14631 DECL_ARGUMENTS (r) = parms;
14632 DECL_RESULT (r) = NULL_TREE;
14634 maybe_rebuild_function_decl_type (r);
14636 TREE_STATIC (r) = 0;
14637 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14638 DECL_EXTERNAL (r) = 1;
14639 /* If this is an instantiation of a function with internal
14640 linkage, we already know what object file linkage will be
14641 assigned to the instantiation. */
14642 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14643 DECL_DEFER_OUTPUT (r) = 0;
14644 DECL_CHAIN (r) = NULL_TREE;
14645 DECL_PENDING_INLINE_INFO (r) = 0;
14646 DECL_PENDING_INLINE_P (r) = 0;
14647 DECL_SAVED_TREE (r) = NULL_TREE;
14648 DECL_STRUCT_FUNCTION (r) = NULL;
14649 TREE_USED (r) = 0;
14650 /* We'll re-clone as appropriate in instantiate_template. */
14651 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14653 /* If we aren't complaining now, return on error before we register
14654 the specialization so that we'll complain eventually. */
14655 if ((complain & tf_error) == 0
14656 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14657 && !grok_op_properties (r, /*complain=*/false))
14658 return error_mark_node;
14660 /* If we are looking at an xobj lambda, we might need to check the type of
14661 its xobj parameter. */
14662 if (LAMBDA_FUNCTION_P (r) && DECL_XOBJ_MEMBER_FUNCTION_P (r))
14664 tree closure_obj = DECL_CONTEXT (r);
14665 tree lambda_expr = CLASSTYPE_LAMBDA_EXPR (closure_obj);
14666 tree obj_param = TREE_TYPE (DECL_ARGUMENTS (r));
14668 if (!(LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr) != CPLD_NONE
14669 || LAMBDA_EXPR_CAPTURE_LIST (lambda_expr)))
14670 /* If a lambda has an empty capture clause, an xobj parameter of
14671 unrelated type is not an error. */;
14672 else if (dependent_type_p (obj_param))
14673 /* If we are coming from tsubst_lambda_expr we might not have
14674 substituted into our xobj parameter yet. We can't error out until
14675 we know what the type really is so do nothing...
14676 ...but if we are instantiating the call op for real and we don't
14677 have a real type then something has gone incredibly wrong. */
14678 gcc_assert (lambda_fntype);
14679 else
14681 /* We have a lambda with captures, and know the type of the xobj
14682 parameter, time to check it. */
14683 tree obj_param_type = TYPE_MAIN_VARIANT (non_reference (obj_param));
14684 if (!same_or_base_type_p (closure_obj, obj_param_type))
14686 /* This error does not emit when the lambda's call operator
14687 template is instantiated by taking its address, such as in
14688 the following case:
14690 auto f = [x = 0](this auto&&){};
14691 int (*fp)(int&) = &decltype(f)::operator();
14693 It only emits when explicitly calling the call operator with
14694 an explicit template parameter:
14696 template<typename T>
14697 struct S : T {
14698 using T::operator();
14699 operator int() const {return {};}
14702 auto s = S{[x = 0](this auto&&) {}};
14703 s.operator()<int>();
14705 This is due to resolve_address_of_overloaded_function being
14706 deficient at reporting candidates when overload resolution
14707 fails.
14709 This diagnostic will be active in the first case if/when
14710 resolve_address_of_overloaded_function is fixed to properly
14711 emit candidates upon failure to resolve to an overload. */
14712 if (complain & tf_error)
14713 error ("a lambda with captures may not have an explicit "
14714 "object parameter of an unrelated type");
14715 return error_mark_node;
14720 /* Associate the constraints directly with the instantiation. We
14721 don't substitute through the constraints; that's only done when
14722 they are checked. */
14723 if (tree ci = get_constraints (t))
14724 set_constraints (r, ci);
14726 if (DECL_FRIEND_CONTEXT (t))
14727 SET_DECL_FRIEND_CONTEXT (r,
14728 tsubst (DECL_FRIEND_CONTEXT (t),
14729 args, complain, in_decl));
14731 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14732 args, complain, in_decl))
14733 return error_mark_node;
14735 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14736 this in the special friend case mentioned above where
14737 GEN_TMPL is NULL. */
14738 if (gen_tmpl && !closure)
14740 DECL_TEMPLATE_INFO (r)
14741 = build_template_info (gen_tmpl, argvec);
14742 SET_DECL_IMPLICIT_INSTANTIATION (r);
14744 if (use_spec_table)
14746 tree new_r
14747 = register_specialization (r, gen_tmpl, argvec, false, hash);
14748 if (new_r != r)
14749 /* We instantiated this while substituting into
14750 the type earlier (template/friend54.C). */
14751 return new_r;
14754 /* We're not supposed to instantiate default arguments
14755 until they are called, for a template. But, for a
14756 declaration like:
14758 template <class T> void f ()
14759 { extern void g(int i = T()); }
14761 we should do the substitution when the template is
14762 instantiated. We handle the member function case in
14763 instantiate_class_template since the default arguments
14764 might refer to other members of the class. */
14765 if (!member
14766 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14767 && !uses_template_parms (argvec))
14768 tsubst_default_arguments (r, complain);
14770 else if (DECL_LOCAL_DECL_P (r))
14772 if (!cp_unevaluated_operand)
14773 register_local_specialization (r, t);
14775 else
14776 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14778 /* Copy the list of befriending classes. */
14779 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14780 *friends;
14781 friends = &TREE_CHAIN (*friends))
14783 *friends = copy_node (*friends);
14784 TREE_VALUE (*friends)
14785 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14788 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14790 maybe_retrofit_in_chrg (r);
14791 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14792 return error_mark_node;
14793 /* If this is an instantiation of a member template, clone it.
14794 If it isn't, that'll be handled by
14795 clone_constructors_and_destructors. */
14796 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14797 clone_cdtor (r, /*update_methods=*/false);
14799 else if ((complain & tf_error) != 0
14800 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14801 && !grok_op_properties (r, /*complain=*/true))
14802 return error_mark_node;
14804 /* Possibly limit visibility based on template args. */
14805 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14806 if (DECL_VISIBILITY_SPECIFIED (t))
14808 DECL_VISIBILITY_SPECIFIED (r) = 0;
14809 DECL_ATTRIBUTES (r)
14810 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14812 determine_visibility (r);
14813 if (DECL_SECTION_NAME (t))
14814 set_decl_section_name (r, t);
14815 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14816 && COMPLETE_TYPE_P (DECL_CONTEXT (r))
14817 && !processing_template_decl)
14818 defaulted_late_check (r);
14820 if (flag_openmp)
14821 if (tree attr = lookup_attribute ("omp declare variant base",
14822 DECL_ATTRIBUTES (r)))
14823 omp_declare_variant_finalize (r, attr);
14825 return r;
14828 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14830 static tree
14831 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14832 tree lambda_fntype, tree lambda_tparms)
14834 /* We can get here when processing a member function template,
14835 member class template, or template template parameter. */
14836 tree decl = DECL_TEMPLATE_RESULT (t);
14837 tree in_decl = t;
14838 tree spec;
14839 tree tmpl_args;
14840 tree full_args = NULL_TREE;
14841 tree r;
14842 hashval_t hash = 0;
14844 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14846 /* Template template parameter is treated here. */
14847 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14848 if (new_type == error_mark_node)
14849 r = error_mark_node;
14850 /* If we get a real template back, return it. This can happen in
14851 the context of most_specialized_partial_spec. */
14852 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14853 r = new_type;
14854 else
14855 /* The new TEMPLATE_DECL was built in
14856 reduce_template_parm_level. */
14857 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14858 return r;
14861 if (!lambda_fntype)
14863 /* We might already have an instance of this template.
14864 The ARGS are for the surrounding class type, so the
14865 full args contain the tsubst'd args for the context,
14866 plus the innermost args from the template decl. */
14867 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14868 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14869 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14870 /* Because this is a template, the arguments will still be
14871 dependent, even after substitution. If
14872 PROCESSING_TEMPLATE_DECL is not set, the dependency
14873 predicates will short-circuit. */
14874 ++processing_template_decl;
14875 full_args = tsubst_template_args (tmpl_args, args,
14876 complain, in_decl);
14877 --processing_template_decl;
14878 if (full_args == error_mark_node)
14879 return error_mark_node;
14881 /* If this is a default template template argument,
14882 tsubst might not have changed anything. */
14883 if (full_args == tmpl_args)
14884 return t;
14886 hash = spec_hasher::hash (t, full_args);
14887 spec = retrieve_specialization (t, full_args, hash);
14888 if (spec != NULL_TREE)
14890 if (TYPE_P (spec))
14891 /* Type partial instantiations are stored as the type by
14892 lookup_template_class_1, not here as the template. */
14893 spec = CLASSTYPE_TI_TEMPLATE (spec);
14894 else if (TREE_CODE (spec) != TEMPLATE_DECL)
14895 spec = DECL_TI_TEMPLATE (spec);
14896 return spec;
14900 /* Make a new template decl. It will be similar to the
14901 original, but will record the current template arguments.
14902 We also create a new function declaration, which is just
14903 like the old one, but points to this new template, rather
14904 than the old one. */
14905 r = copy_decl (t);
14906 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14907 DECL_CHAIN (r) = NULL_TREE;
14909 // Build new template info linking to the original template decl.
14910 if (!lambda_fntype)
14912 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14913 SET_DECL_IMPLICIT_INSTANTIATION (r);
14915 else
14916 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14918 /* The template parameters for this new template are all the
14919 template parameters for the old template, except the
14920 outermost level of parameters. */
14921 auto tparm_guard = make_temp_override (current_template_parms);
14922 DECL_TEMPLATE_PARMS (r)
14923 = current_template_parms
14924 = (lambda_tparms
14925 ? lambda_tparms
14926 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14927 complain));
14929 bool class_p = false;
14930 tree inner = decl;
14931 ++processing_template_decl;
14932 if (TREE_CODE (inner) == FUNCTION_DECL)
14933 inner = tsubst_function_decl (inner, args, complain, lambda_fntype,
14934 /*use_spec_table=*/false);
14935 else
14937 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14939 class_p = true;
14940 inner = TREE_TYPE (inner);
14942 if (class_p)
14943 inner = tsubst_aggr_type (inner, args, complain,
14944 in_decl, /*entering*/1);
14945 else
14946 inner = tsubst_decl (inner, args, complain, /*use_spec_table=*/false);
14948 --processing_template_decl;
14949 if (inner == error_mark_node)
14950 return error_mark_node;
14952 if (class_p)
14954 /* For a partial specialization, we need to keep pointing to
14955 the primary template. */
14956 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14958 CLASSTYPE_TI_TEMPLATE (inner) = r;
14959 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14962 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14963 inner = TYPE_MAIN_DECL (inner);
14965 else if (lambda_fntype)
14967 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14968 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14970 else
14972 DECL_TI_TEMPLATE (inner) = r;
14973 /* Set DECL_TI_ARGS to the full set of template arguments,
14974 which tsubst_function_decl / tsubst_decl didn't do due to
14975 use_spec_table=false. */
14976 DECL_TI_ARGS (inner) = full_args;
14977 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14980 DECL_TEMPLATE_RESULT (r) = inner;
14981 TREE_TYPE (r) = TREE_TYPE (inner);
14982 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14984 if (modules_p ())
14986 /* Propagate module information from the decl. */
14987 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14988 if (DECL_LANG_SPECIFIC (inner))
14989 /* If this is a constrained template, the above tsubst of
14990 inner can find the unconstrained template, which may have
14991 come from an import. This is ok, because we don't
14992 register this instantiation (see below). */
14993 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14994 || (TEMPLATE_PARMS_CONSTRAINTS
14995 (DECL_TEMPLATE_PARMS (t))));
14998 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14999 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
15001 if (PRIMARY_TEMPLATE_P (t))
15002 DECL_PRIMARY_TEMPLATE (r) = r;
15004 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (r) = false;
15006 if (!lambda_fntype && !class_p)
15008 /* Record this non-type partial instantiation. */
15009 /* FIXME we'd like to always register the TEMPLATE_DECL, or always
15010 the DECL_TEMPLATE_RESULT, but it seems the modules code relies
15011 on this current behavior. */
15012 if (TREE_CODE (inner) == FUNCTION_DECL)
15013 register_specialization (r, t, full_args, false, hash);
15014 else
15015 register_specialization (inner, t, full_args, false, hash);
15018 return r;
15021 /* True if FN is the op() for a lambda in an uninstantiated template. */
15023 bool
15024 lambda_fn_in_template_p (tree fn)
15026 if (!fn || !LAMBDA_FUNCTION_P (fn))
15027 return false;
15028 tree closure = DECL_CONTEXT (fn);
15029 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
15032 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
15033 which the above is true. */
15035 bool
15036 regenerated_lambda_fn_p (tree fn)
15038 if (!fn || !LAMBDA_FUNCTION_P (fn))
15039 return false;
15040 tree closure = DECL_CONTEXT (fn);
15041 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
15042 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
15045 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
15046 If T is not a regenerated LAMBDA_EXPR, return T. */
15048 tree
15049 most_general_lambda (tree t)
15051 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15052 t = TI_TEMPLATE (ti);
15053 return t;
15056 /* Return the set of template arguments used to regenerate the lambda T
15057 from its most general lambda. */
15059 tree
15060 lambda_regenerating_args (tree t)
15062 if (LAMBDA_FUNCTION_P (t))
15063 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
15064 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
15065 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
15066 return TI_ARGS (ti);
15067 else
15068 return NULL_TREE;
15071 /* We're instantiating a variable from template function TCTX. Return the
15072 corresponding current enclosing scope. We can match them up using
15073 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
15074 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
15075 the template definition in regenerate_decl_from_template. */
15077 static tree
15078 enclosing_instantiation_of (tree tctx)
15080 tree fn = current_function_decl;
15082 /* We shouldn't ever need to do this for other artificial functions. */
15083 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
15085 for (; fn; fn = decl_function_context (fn))
15086 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
15087 return fn;
15088 gcc_unreachable ();
15091 /* Substitute the ARGS into the T, which is a _DECL. Return the
15092 result of the substitution. Issue error and warning messages under
15093 control of COMPLAIN. The flag USE_SPEC_TABLE controls if we look up
15094 and insert into the specializations table or if we can assume it's
15095 the caller's responsibility; this is used by instantiate_template
15096 to avoid doing some redundant work. */
15098 static tree
15099 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
15100 bool use_spec_table /* = true */)
15102 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
15103 location_t saved_loc;
15104 tree r = NULL_TREE;
15105 tree in_decl = t;
15106 hashval_t hash = 0;
15108 if (t == error_mark_node)
15109 return error_mark_node;
15111 /* Set the filename and linenumber to improve error-reporting. */
15112 saved_loc = input_location;
15113 input_location = DECL_SOURCE_LOCATION (t);
15115 switch (TREE_CODE (t))
15117 case TEMPLATE_DECL:
15118 r = tsubst_template_decl (t, args, complain,
15119 /*lambda_fntype=*/NULL_TREE,
15120 /*lambda_tparms=*/NULL_TREE);
15121 break;
15123 case FUNCTION_DECL:
15124 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
15125 use_spec_table);
15126 break;
15128 case PARM_DECL:
15130 tree type = NULL_TREE;
15131 int i, len = 1;
15132 tree expanded_types = NULL_TREE;
15133 tree prev_r = NULL_TREE;
15134 tree first_r = NULL_TREE;
15136 if (DECL_PACK_P (t))
15138 /* If there is a local specialization that isn't a
15139 parameter pack, it means that we're doing a "simple"
15140 substitution from inside tsubst_pack_expansion. Just
15141 return the local specialization (which will be a single
15142 parm). */
15143 tree spec = retrieve_local_specialization (t);
15144 if (spec
15145 && TREE_CODE (spec) == PARM_DECL
15146 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
15147 RETURN (spec);
15149 /* Expand the TYPE_PACK_EXPANSION that provides the types for
15150 the parameters in this function parameter pack. */
15151 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15152 complain, in_decl);
15153 if (TREE_CODE (expanded_types) == TREE_VEC)
15155 len = TREE_VEC_LENGTH (expanded_types);
15157 /* Zero-length parameter packs are boring. Just substitute
15158 into the chain. */
15159 if (len == 0 && !cp_unevaluated_operand)
15160 RETURN (tsubst (TREE_CHAIN (t), args, complain,
15161 TREE_CHAIN (t)));
15163 else
15165 /* All we did was update the type. Make a note of that. */
15166 type = expanded_types;
15167 expanded_types = NULL_TREE;
15171 /* Loop through all of the parameters we'll build. When T is
15172 a function parameter pack, LEN is the number of expanded
15173 types in EXPANDED_TYPES; otherwise, LEN is 1. */
15174 r = NULL_TREE;
15175 for (i = 0; i < len; ++i)
15177 prev_r = r;
15178 r = copy_node (t);
15179 if (DECL_TEMPLATE_PARM_P (t))
15180 SET_DECL_TEMPLATE_PARM_P (r);
15182 if (expanded_types)
15183 /* We're on the Ith parameter of the function parameter
15184 pack. */
15186 /* Get the Ith type. */
15187 type = TREE_VEC_ELT (expanded_types, i);
15189 /* Rename the parameter to include the index. */
15190 DECL_NAME (r)
15191 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15193 else if (!type)
15194 /* We're dealing with a normal parameter. */
15195 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15197 type = type_decays_to (type);
15198 TREE_TYPE (r) = type;
15199 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15201 if (DECL_INITIAL (r))
15203 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
15204 DECL_INITIAL (r) = TREE_TYPE (r);
15205 else
15206 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
15207 complain, in_decl);
15210 DECL_CONTEXT (r) = NULL_TREE;
15212 if (!DECL_TEMPLATE_PARM_P (r))
15213 DECL_ARG_TYPE (r) = type_passed_as (type);
15215 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15216 args, complain, in_decl))
15217 return error_mark_node;
15219 /* Keep track of the first new parameter we
15220 generate. That's what will be returned to the
15221 caller. */
15222 if (!first_r)
15223 first_r = r;
15225 /* Build a proper chain of parameters when substituting
15226 into a function parameter pack. */
15227 if (prev_r)
15228 DECL_CHAIN (prev_r) = r;
15231 /* If cp_unevaluated_operand is set, we're just looking for a
15232 single dummy parameter, so don't keep going. */
15233 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
15234 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
15235 complain, DECL_CHAIN (t));
15237 /* FIRST_R contains the start of the chain we've built. */
15238 r = first_r;
15240 break;
15242 case FIELD_DECL:
15244 tree type = NULL_TREE;
15245 tree vec = NULL_TREE;
15246 tree expanded_types = NULL_TREE;
15247 int len = 1;
15249 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15251 /* This field is a lambda capture pack. Return a TREE_VEC of
15252 the expanded fields to instantiate_class_template_1. */
15253 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15254 complain, in_decl);
15255 if (TREE_CODE (expanded_types) == TREE_VEC)
15257 len = TREE_VEC_LENGTH (expanded_types);
15258 vec = make_tree_vec (len);
15260 else
15262 /* All we did was update the type. Make a note of that. */
15263 type = expanded_types;
15264 expanded_types = NULL_TREE;
15268 for (int i = 0; i < len; ++i)
15270 r = copy_decl (t);
15271 if (expanded_types)
15273 type = TREE_VEC_ELT (expanded_types, i);
15274 DECL_NAME (r)
15275 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15277 else if (!type)
15278 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15280 if (type == error_mark_node)
15281 RETURN (error_mark_node);
15282 TREE_TYPE (r) = type;
15283 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15285 if (DECL_C_BIT_FIELD (r))
15286 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15287 number of bits. */
15288 DECL_BIT_FIELD_REPRESENTATIVE (r)
15289 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15290 complain, in_decl);
15291 if (DECL_INITIAL (t))
15293 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15294 NSDMI in perform_member_init. Still set DECL_INITIAL
15295 so that we know there is one. */
15296 DECL_INITIAL (r) = void_node;
15297 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15298 retrofit_lang_decl (r);
15299 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15301 /* We don't have to set DECL_CONTEXT here; it is set by
15302 finish_member_declaration. */
15303 DECL_CHAIN (r) = NULL_TREE;
15305 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15306 args, complain, in_decl))
15307 return error_mark_node;
15309 if (vec)
15310 TREE_VEC_ELT (vec, i) = r;
15313 if (vec)
15314 r = vec;
15316 break;
15318 case USING_DECL:
15319 /* We reach here only for member using decls. We also need to check
15320 uses_template_parms because DECL_DEPENDENT_P is not set for a
15321 using-declaration that designates a member of the current
15322 instantiation (c++/53549). */
15323 if (DECL_DEPENDENT_P (t)
15324 || uses_template_parms (USING_DECL_SCOPE (t)))
15326 /* True iff this using-decl was written as a pack expansion
15327 (and a pack appeared in its scope or name). If a pack
15328 appeared in both, we expand the packs separately and
15329 manually merge them. */
15330 bool variadic_p = false;
15332 tree scope = USING_DECL_SCOPE (t);
15333 if (PACK_EXPANSION_P (scope))
15335 scope = tsubst_pack_expansion (scope, args,
15336 complain | tf_qualifying_scope,
15337 in_decl);
15338 variadic_p = true;
15340 else
15341 scope = tsubst_scope (scope, args, complain, in_decl);
15343 tree name = DECL_NAME (t);
15344 if (IDENTIFIER_CONV_OP_P (name)
15345 && PACK_EXPANSION_P (TREE_TYPE (name)))
15347 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15348 complain, in_decl);
15349 if (name == error_mark_node)
15351 r = error_mark_node;
15352 break;
15354 for (tree& elt : tree_vec_range (name))
15355 elt = make_conv_op_name (elt);
15356 variadic_p = true;
15358 else
15359 name = tsubst_name (name, args, complain, in_decl);
15361 int len;
15362 if (!variadic_p)
15363 len = 1;
15364 else if (TREE_CODE (scope) == TREE_VEC
15365 && TREE_CODE (name) == TREE_VEC)
15367 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15369 error ("mismatched argument pack lengths (%d vs %d)",
15370 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15371 r = error_mark_node;
15372 break;
15374 len = TREE_VEC_LENGTH (scope);
15376 else if (TREE_CODE (scope) == TREE_VEC)
15377 len = TREE_VEC_LENGTH (scope);
15378 else /* TREE_CODE (name) == TREE_VEC */
15379 len = TREE_VEC_LENGTH (name);
15381 r = make_tree_vec (len);
15382 for (int i = 0; i < len; ++i)
15384 tree escope = (TREE_CODE (scope) == TREE_VEC
15385 ? TREE_VEC_ELT (scope, i)
15386 : scope);
15387 tree ename = (TREE_CODE (name) == TREE_VEC
15388 ? TREE_VEC_ELT (name, i)
15389 : name);
15390 tree elt = do_class_using_decl (escope, ename);
15391 if (!elt)
15393 r = error_mark_node;
15394 break;
15396 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15397 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15398 TREE_VEC_ELT (r, i) = elt;
15401 if (!variadic_p && r != error_mark_node)
15402 r = TREE_VEC_ELT (r, 0);
15404 else
15406 r = copy_node (t);
15407 DECL_CHAIN (r) = NULL_TREE;
15409 break;
15411 case TYPE_DECL:
15412 case VAR_DECL:
15414 tree argvec = NULL_TREE;
15415 tree gen_tmpl = NULL_TREE;
15416 tree tmpl = NULL_TREE;
15417 tree type = NULL_TREE;
15419 if (TREE_TYPE (t) == error_mark_node)
15420 RETURN (error_mark_node);
15422 if (TREE_CODE (t) == TYPE_DECL
15423 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15425 /* If this is the canonical decl, we don't have to
15426 mess with instantiations, and often we can't (for
15427 typename, template type parms and such). Note that
15428 TYPE_NAME is not correct for the above test if
15429 we've copied the type for a typedef. */
15430 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15431 if (type == error_mark_node)
15432 RETURN (error_mark_node);
15433 r = TYPE_NAME (type);
15434 break;
15437 /* Check to see if we already have the specialization we
15438 need. */
15439 tree spec = NULL_TREE;
15440 bool local_p = false;
15441 tree ctx = DECL_CONTEXT (t);
15442 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15443 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15445 local_p = false;
15446 if (DECL_CLASS_SCOPE_P (t))
15448 ctx = tsubst_aggr_type (ctx, args,
15449 complain,
15450 in_decl, /*entering_scope=*/1);
15451 if (DECL_SELF_REFERENCE_P (t))
15452 /* The context and type of an injected-class-name are
15453 the same, so we don't need to substitute both. */
15454 type = ctx;
15455 /* If CTX is unchanged, then T is in fact the
15456 specialization we want. That situation occurs when
15457 referencing a static data member within in its own
15458 class. We can use pointer equality, rather than
15459 same_type_p, because DECL_CONTEXT is always
15460 canonical... */
15461 if (ctx == DECL_CONTEXT (t)
15462 /* ... unless T is a member template; in which
15463 case our caller can be willing to create a
15464 specialization of that template represented
15465 by T. */
15466 && !(DECL_TI_TEMPLATE (t)
15467 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15468 spec = t;
15471 if (!spec)
15473 tmpl = DECL_TI_TEMPLATE (t);
15474 if (use_spec_table)
15476 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15477 if (argvec == error_mark_node)
15478 RETURN (error_mark_node);
15479 gen_tmpl = most_general_template (tmpl);
15480 hash = spec_hasher::hash (gen_tmpl, argvec);
15481 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15483 else
15484 argvec = args;
15487 else
15489 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15490 /* Subsequent calls to pushdecl will fill this in. */
15491 ctx = NULL_TREE;
15492 /* A local variable. */
15493 local_p = true;
15494 /* Unless this is a reference to a static variable from an
15495 enclosing function, in which case we need to fill it in now. */
15496 if (TREE_STATIC (t))
15498 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15499 if (fn != current_function_decl)
15500 ctx = fn;
15502 spec = retrieve_local_specialization (t);
15504 /* If we already have the specialization we need, there is
15505 nothing more to do. */
15506 if (spec)
15508 r = spec;
15509 break;
15512 /* Create a new node for the specialization we need. */
15513 if (type == NULL_TREE)
15515 if (is_typedef_decl (t))
15516 type = DECL_ORIGINAL_TYPE (t);
15517 else
15518 type = TREE_TYPE (t);
15519 if (VAR_P (t)
15520 && VAR_HAD_UNKNOWN_BOUND (t)
15521 && type != error_mark_node)
15522 type = strip_array_domain (type);
15523 tsubst_flags_t tcomplain = complain;
15524 if (VAR_P (t))
15525 tcomplain |= tf_tst_ok;
15526 type = tsubst (type, args, tcomplain, in_decl);
15527 /* Substituting the type might have recursively instantiated this
15528 same alias (c++/86171). */
15529 if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15530 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15532 r = spec;
15533 break;
15536 if (type == error_mark_node && !(complain & tf_error))
15537 RETURN (error_mark_node);
15538 r = copy_decl (t);
15539 if (VAR_P (r))
15541 DECL_INITIALIZED_P (r) = 0;
15542 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15543 if (TREE_CODE (type) == FUNCTION_TYPE)
15545 /* It may seem that this case cannot occur, since:
15547 typedef void f();
15548 void g() { f x; }
15550 declares a function, not a variable. However:
15552 typedef void f();
15553 template <typename T> void g() { T t; }
15554 template void g<f>();
15556 is an attempt to declare a variable with function
15557 type. */
15558 error ("variable %qD has function type",
15559 /* R is not yet sufficiently initialized, so we
15560 just use its name. */
15561 DECL_NAME (r));
15562 RETURN (error_mark_node);
15564 type = complete_type (type);
15565 /* Wait until cp_finish_decl to set this again, to handle
15566 circular dependency (template/instantiate6.C). */
15567 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15568 type = check_var_type (DECL_NAME (r), type,
15569 DECL_SOURCE_LOCATION (r));
15570 if (DECL_HAS_VALUE_EXPR_P (t))
15572 tree ve = DECL_VALUE_EXPR (t);
15573 /* If the DECL_VALUE_EXPR is converted to the declared type,
15574 preserve the identity so that gimplify_type_sizes works. */
15575 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15576 if (nop)
15577 ve = TREE_OPERAND (ve, 0);
15578 ve = tsubst_expr (ve, args, complain, in_decl);
15579 if (REFERENCE_REF_P (ve))
15581 gcc_assert (TYPE_REF_P (type));
15582 ve = TREE_OPERAND (ve, 0);
15584 if (nop)
15585 ve = build_nop (type, ve);
15586 else if (DECL_LANG_SPECIFIC (t)
15587 && DECL_OMP_PRIVATIZED_MEMBER (t)
15588 && TREE_CODE (ve) == COMPONENT_REF
15589 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15590 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15591 type = TREE_TYPE (ve);
15592 else
15593 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15594 == TYPE_MAIN_VARIANT (type));
15595 SET_DECL_VALUE_EXPR (r, ve);
15597 if (CP_DECL_THREAD_LOCAL_P (r)
15598 && !processing_template_decl)
15599 set_decl_tls_model (r, decl_default_tls_model (r));
15601 else if (DECL_SELF_REFERENCE_P (t))
15602 SET_DECL_SELF_REFERENCE_P (r);
15603 TREE_TYPE (r) = type;
15604 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15605 DECL_CONTEXT (r) = ctx;
15606 /* Clear out the mangled name and RTL for the instantiation. */
15607 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15608 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15609 SET_DECL_RTL (r, NULL);
15610 set_instantiating_module (r);
15612 /* The initializer must not be expanded until it is required;
15613 see [temp.inst]. */
15614 DECL_INITIAL (r) = NULL_TREE;
15615 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15616 if (VAR_P (r))
15618 if (DECL_LANG_SPECIFIC (r))
15619 SET_DECL_DEPENDENT_INIT_P (r, false);
15621 SET_DECL_MODE (r, VOIDmode);
15623 /* Possibly limit visibility based on template args. */
15624 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15625 if (DECL_VISIBILITY_SPECIFIED (t))
15627 DECL_VISIBILITY_SPECIFIED (r) = 0;
15628 DECL_ATTRIBUTES (r)
15629 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15631 determine_visibility (r);
15632 if ((!local_p || TREE_STATIC (t)) && DECL_SECTION_NAME (t))
15633 set_decl_section_name (r, t);
15636 if (!local_p)
15638 /* A static data member declaration is always marked
15639 external when it is declared in-class, even if an
15640 initializer is present. We mimic the non-template
15641 processing here. */
15642 DECL_EXTERNAL (r) = 1;
15643 if (DECL_NAMESPACE_SCOPE_P (t))
15644 DECL_NOT_REALLY_EXTERN (r) = 1;
15646 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15647 SET_DECL_IMPLICIT_INSTANTIATION (r);
15648 if (use_spec_table)
15649 register_specialization (r, gen_tmpl, argvec, false, hash);
15651 else
15653 if (DECL_LANG_SPECIFIC (r))
15654 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15655 if (!cp_unevaluated_operand)
15656 register_local_specialization (r, t);
15659 DECL_CHAIN (r) = NULL_TREE;
15661 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15662 /*flags=*/0,
15663 args, complain, in_decl))
15664 return error_mark_node;
15666 /* Preserve a typedef that names a type. */
15667 if (is_typedef_decl (r) && type != error_mark_node)
15669 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15670 set_underlying_type (r);
15672 /* common_handle_aligned_attribute doesn't apply the alignment
15673 to DECL_ORIGINAL_TYPE. */
15674 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15675 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15676 TYPE_ALIGN (TREE_TYPE (t)));
15679 layout_decl (r, 0);
15681 break;
15683 default:
15684 gcc_unreachable ();
15686 #undef RETURN
15688 out:
15689 /* Restore the file and line information. */
15690 input_location = saved_loc;
15692 return r;
15695 /* Substitute into the complete parameter type list PARMS. */
15697 tree
15698 tsubst_function_parms (tree parms,
15699 tree args,
15700 tsubst_flags_t complain,
15701 tree in_decl)
15703 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15706 /* Substitute into the ARG_TYPES of a function type.
15707 If END is a TREE_CHAIN, leave it and any following types
15708 un-substituted. */
15710 static tree
15711 tsubst_arg_types (tree arg_types,
15712 tree args,
15713 tree end,
15714 tsubst_flags_t complain,
15715 tree in_decl)
15717 tree type = NULL_TREE;
15718 int len = 1;
15719 tree expanded_args = NULL_TREE;
15721 if (!arg_types || arg_types == void_list_node || arg_types == end)
15722 return arg_types;
15724 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15726 /* For a pack expansion, perform substitution on the
15727 entire expression. Later on, we'll handle the arguments
15728 one-by-one. */
15729 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15730 args, complain, in_decl);
15732 if (TREE_CODE (expanded_args) == TREE_VEC)
15733 /* So that we'll spin through the parameters, one by one. */
15734 len = TREE_VEC_LENGTH (expanded_args);
15735 else
15737 /* We only partially substituted into the parameter
15738 pack. Our type is TYPE_PACK_EXPANSION. */
15739 type = expanded_args;
15740 expanded_args = NULL_TREE;
15743 else
15744 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15746 /* Check if a substituted type is erroneous before substituting into
15747 the rest of the chain. */
15748 for (int i = 0; i < len; i++)
15750 if (expanded_args)
15751 type = TREE_VEC_ELT (expanded_args, i);
15753 if (type == error_mark_node)
15754 return error_mark_node;
15755 if (VOID_TYPE_P (type))
15757 if (complain & tf_error)
15759 error ("invalid parameter type %qT", type);
15760 if (in_decl)
15761 error ("in declaration %q+D", in_decl);
15763 return error_mark_node;
15767 /* We do not substitute into default arguments here. The standard
15768 mandates that they be instantiated only when needed, which is
15769 done in build_over_call. */
15770 tree default_arg = TREE_PURPOSE (arg_types);
15772 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15773 since the new op() won't have any associated template arguments for us
15774 to refer to later. */
15775 if (lambda_fn_in_template_p (in_decl)
15776 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15777 && DECL_LOCAL_DECL_P (in_decl)))
15778 default_arg = tsubst_expr (default_arg, args, complain, in_decl);
15780 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15781 args, end, complain, in_decl);
15782 if (remaining_arg_types == error_mark_node)
15783 return error_mark_node;
15785 for (int i = len-1; i >= 0; i--)
15787 if (expanded_args)
15788 type = TREE_VEC_ELT (expanded_args, i);
15790 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15791 top-level qualifiers as required. */
15792 type = cv_unqualified (type_decays_to (type));
15794 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15796 /* We've instantiated a template before its default arguments
15797 have been parsed. This can happen for a nested template
15798 class, and is not an error unless we require the default
15799 argument in a call of this function. */
15800 remaining_arg_types
15801 = tree_cons (default_arg, type, remaining_arg_types);
15802 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15803 remaining_arg_types);
15805 else
15806 remaining_arg_types
15807 = hash_tree_cons (default_arg, type, remaining_arg_types);
15810 return remaining_arg_types;
15813 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15814 *not* handle the exception-specification for FNTYPE, because the
15815 initial substitution of explicitly provided template parameters
15816 during argument deduction forbids substitution into the
15817 exception-specification:
15819 [temp.deduct]
15821 All references in the function type of the function template to the
15822 corresponding template parameters are replaced by the specified tem-
15823 plate argument values. If a substitution in a template parameter or
15824 in the function type of the function template results in an invalid
15825 type, type deduction fails. [Note: The equivalent substitution in
15826 exception specifications is done only when the function is instanti-
15827 ated, at which point a program is ill-formed if the substitution
15828 results in an invalid type.] */
15830 static tree
15831 tsubst_function_type (tree t,
15832 tree args,
15833 tsubst_flags_t complain,
15834 tree in_decl)
15836 tree return_type;
15837 tree arg_types = NULL_TREE;
15839 /* The TYPE_CONTEXT is not used for function/method types. */
15840 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15842 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15843 failure. */
15844 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15846 if (late_return_type_p)
15848 /* Substitute the argument types. */
15849 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15850 complain, in_decl);
15851 if (arg_types == error_mark_node)
15852 return error_mark_node;
15854 tree save_ccp = current_class_ptr;
15855 tree save_ccr = current_class_ref;
15856 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15857 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15858 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15859 if (do_inject)
15861 /* DR 1207: 'this' is in scope in the trailing return type. */
15862 inject_this_parameter (this_type, cp_type_quals (this_type));
15865 /* Substitute the return type. */
15866 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15868 if (do_inject)
15870 current_class_ptr = save_ccp;
15871 current_class_ref = save_ccr;
15874 else
15875 /* Substitute the return type. */
15876 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15878 if (return_type == error_mark_node)
15879 return error_mark_node;
15880 /* DR 486 clarifies that creation of a function type with an
15881 invalid return type is a deduction failure. */
15882 if (TREE_CODE (return_type) == ARRAY_TYPE
15883 || TREE_CODE (return_type) == FUNCTION_TYPE)
15885 if (complain & tf_error)
15887 if (TREE_CODE (return_type) == ARRAY_TYPE)
15888 error ("function returning an array");
15889 else
15890 error ("function returning a function");
15892 return error_mark_node;
15895 if (!late_return_type_p)
15897 /* Substitute the argument types. */
15898 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15899 complain, in_decl);
15900 if (arg_types == error_mark_node)
15901 return error_mark_node;
15904 /* Construct a new type node and return it. */
15905 return rebuild_function_or_method_type (t, return_type, arg_types,
15906 /*raises=*/NULL_TREE, complain);
15909 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15910 ARGS into that specification, and return the substituted
15911 specification. If there is no specification, return NULL_TREE. */
15913 static tree
15914 tsubst_exception_specification (tree fntype,
15915 tree args,
15916 tsubst_flags_t complain,
15917 tree in_decl,
15918 bool defer_ok)
15920 tree specs;
15921 tree new_specs;
15923 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15924 new_specs = NULL_TREE;
15925 if (specs && TREE_PURPOSE (specs))
15927 /* A noexcept-specifier. */
15928 tree expr = TREE_PURPOSE (specs);
15929 if (TREE_CODE (expr) == INTEGER_CST)
15930 new_specs = expr;
15931 else if (defer_ok)
15933 /* Defer instantiation of noexcept-specifiers to avoid
15934 excessive instantiations (c++/49107). */
15935 new_specs = make_node (DEFERRED_NOEXCEPT);
15936 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15938 /* We already partially instantiated this member template,
15939 so combine the new args with the old. */
15940 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15941 = DEFERRED_NOEXCEPT_PATTERN (expr);
15942 DEFERRED_NOEXCEPT_ARGS (new_specs)
15943 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15945 else
15947 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15948 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15951 else
15953 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15955 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15956 args);
15957 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15959 new_specs = tsubst_expr (expr, args, complain, in_decl);
15961 new_specs = build_noexcept_spec (new_specs, complain);
15962 /* We've instantiated a template before a noexcept-specifier
15963 contained therein has been parsed. This can happen for
15964 a nested template class:
15966 struct S {
15967 template<typename> struct B { B() noexcept(...); };
15968 struct A : B<int> { ... use B() ... };
15971 where completing B<int> will trigger instantiating the
15972 noexcept, even though we only parse it at the end of S. */
15973 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15975 gcc_checking_assert (defer_ok);
15976 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15979 else if (specs)
15981 if (! TREE_VALUE (specs))
15982 new_specs = specs;
15983 else
15984 while (specs)
15986 tree spec;
15987 int i, len = 1;
15988 tree expanded_specs = NULL_TREE;
15990 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15992 /* Expand the pack expansion type. */
15993 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15994 args, complain,
15995 in_decl);
15997 if (expanded_specs == error_mark_node)
15998 return error_mark_node;
15999 else if (TREE_CODE (expanded_specs) == TREE_VEC)
16000 len = TREE_VEC_LENGTH (expanded_specs);
16001 else
16003 /* We're substituting into a member template, so
16004 we got a TYPE_PACK_EXPANSION back. Add that
16005 expansion and move on. */
16006 gcc_assert (TREE_CODE (expanded_specs)
16007 == TYPE_PACK_EXPANSION);
16008 new_specs = add_exception_specifier (new_specs,
16009 expanded_specs,
16010 complain);
16011 specs = TREE_CHAIN (specs);
16012 continue;
16016 for (i = 0; i < len; ++i)
16018 if (expanded_specs)
16019 spec = TREE_VEC_ELT (expanded_specs, i);
16020 else
16021 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
16022 if (spec == error_mark_node)
16023 return spec;
16024 new_specs = add_exception_specifier (new_specs, spec,
16025 complain);
16028 specs = TREE_CHAIN (specs);
16031 return new_specs;
16034 /* Substitute through a TREE_LIST of types or expressions, handling pack
16035 expansions. */
16037 tree
16038 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16040 if (t == void_list_node)
16041 return t;
16043 tree purpose = TREE_PURPOSE (t);
16044 tree purposevec = NULL_TREE;
16045 if (!purpose)
16047 else if (PACK_EXPANSION_P (purpose))
16049 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
16050 if (TREE_CODE (purpose) == TREE_VEC)
16051 purposevec = purpose;
16053 else if (TYPE_P (purpose))
16054 purpose = tsubst (purpose, args, complain, in_decl);
16055 else
16056 purpose = tsubst_expr (purpose, args, complain, in_decl);
16057 if (purpose == error_mark_node || purposevec == error_mark_node)
16058 return error_mark_node;
16060 tree value = TREE_VALUE (t);
16061 tree valuevec = NULL_TREE;
16062 if (!value)
16064 else if (PACK_EXPANSION_P (value))
16066 value = tsubst_pack_expansion (value, args, complain, in_decl);
16067 if (TREE_CODE (value) == TREE_VEC)
16068 valuevec = value;
16070 else if (TYPE_P (value))
16071 value = tsubst (value, args, complain, in_decl);
16072 else
16073 value = tsubst_expr (value, args, complain, in_decl);
16074 if (value == error_mark_node || valuevec == error_mark_node)
16075 return error_mark_node;
16077 tree chain = TREE_CHAIN (t);
16078 if (!chain)
16080 else if (TREE_CODE (chain) == TREE_LIST)
16081 chain = tsubst_tree_list (chain, args, complain, in_decl);
16082 else if (TYPE_P (chain))
16083 chain = tsubst (chain, args, complain, in_decl);
16084 else
16085 chain = tsubst_expr (chain, args, complain, in_decl);
16086 if (chain == error_mark_node)
16087 return error_mark_node;
16089 if (purpose == TREE_PURPOSE (t)
16090 && value == TREE_VALUE (t)
16091 && chain == TREE_CHAIN (t))
16092 return t;
16094 int len;
16095 /* Determine the number of arguments. */
16096 if (purposevec)
16098 len = TREE_VEC_LENGTH (purposevec);
16099 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
16101 else if (valuevec)
16102 len = TREE_VEC_LENGTH (valuevec);
16103 else
16104 len = 1;
16106 for (int i = len; i-- > 0; )
16108 if (purposevec)
16109 purpose = TREE_VEC_ELT (purposevec, i);
16110 if (valuevec)
16111 value = TREE_VEC_ELT (valuevec, i);
16113 if (value && TYPE_P (value))
16114 chain = hash_tree_cons (purpose, value, chain);
16115 else
16116 chain = tree_cons (purpose, value, chain);
16119 return chain;
16122 /* Take the tree structure T and replace template parameters used
16123 therein with the argument vector ARGS. IN_DECL is an associated
16124 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
16125 Issue error and warning messages under control of COMPLAIN. Note
16126 that we must be relatively non-tolerant of extensions here, in
16127 order to preserve conformance; if we allow substitutions that
16128 should not be allowed, we may allow argument deductions that should
16129 not succeed, and therefore report ambiguous overload situations
16130 where there are none. In theory, we could allow the substitution,
16131 but indicate that it should have failed, and allow our caller to
16132 make sure that the right thing happens, but we don't try to do this
16133 yet.
16135 This function is used for dealing with types, decls and the like;
16136 for expressions, use tsubst_expr or tsubst_copy. */
16138 tree
16139 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16141 enum tree_code code;
16142 tree type, r = NULL_TREE;
16144 if (t == NULL_TREE || t == error_mark_node
16145 || t == integer_type_node
16146 || t == void_type_node
16147 || t == char_type_node
16148 || t == unknown_type_node
16149 || TREE_CODE (t) == NAMESPACE_DECL
16150 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
16151 return t;
16153 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
16154 complain &= ~tf_tst_ok;
16156 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
16157 complain &= ~tf_qualifying_scope;
16159 if (DECL_P (t))
16160 return tsubst_decl (t, args, complain);
16162 if (args == NULL_TREE)
16163 return t;
16165 code = TREE_CODE (t);
16167 gcc_assert (code != IDENTIFIER_NODE);
16168 type = TREE_TYPE (t);
16170 gcc_assert (type != unknown_type_node);
16172 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
16173 return d;
16175 /* Reuse typedefs. We need to do this to handle dependent attributes,
16176 such as attribute aligned. */
16177 if (TYPE_P (t)
16178 && typedef_variant_p (t))
16180 tree decl = TYPE_NAME (t);
16182 if (alias_template_specialization_p (t, nt_opaque))
16184 /* DECL represents an alias template and we want to
16185 instantiate it. */
16186 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16187 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16188 r = instantiate_alias_template (tmpl, gen_args, complain);
16190 else if (DECL_CLASS_SCOPE_P (decl)
16191 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
16192 && uses_template_parms (DECL_CONTEXT (decl)))
16194 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16195 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16196 r = retrieve_specialization (tmpl, gen_args, 0);
16198 else if (DECL_FUNCTION_SCOPE_P (decl)
16199 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
16200 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
16201 r = retrieve_local_specialization (decl);
16202 else
16203 /* The typedef is from a non-template context. */
16204 return t;
16206 if (r)
16208 r = TREE_TYPE (r);
16209 r = cp_build_qualified_type
16210 (r, cp_type_quals (t) | cp_type_quals (r),
16211 complain | tf_ignore_bad_quals);
16212 return r;
16214 else
16216 /* We don't have an instantiation yet, so drop the typedef. */
16217 int quals = cp_type_quals (t);
16218 t = DECL_ORIGINAL_TYPE (decl);
16219 t = cp_build_qualified_type (t, quals,
16220 complain | tf_ignore_bad_quals);
16224 bool fndecl_type = (complain & tf_fndecl_type);
16225 complain &= ~tf_fndecl_type;
16227 if (type
16228 && code != TYPENAME_TYPE
16229 && code != TEMPLATE_TYPE_PARM
16230 && code != TEMPLATE_PARM_INDEX
16231 && code != IDENTIFIER_NODE
16232 && code != FUNCTION_TYPE
16233 && code != METHOD_TYPE)
16234 type = tsubst (type, args, complain, in_decl);
16235 if (type == error_mark_node)
16236 return error_mark_node;
16238 switch (code)
16240 case RECORD_TYPE:
16241 if (TYPE_PTRMEMFUNC_P (t))
16242 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16243 /* Fall through. */
16244 case UNION_TYPE:
16245 case ENUMERAL_TYPE:
16246 return tsubst_aggr_type_1 (t, args, complain, in_decl,
16247 /*entering_scope=*/0);
16249 case ERROR_MARK:
16250 case IDENTIFIER_NODE:
16251 case VOID_TYPE:
16252 case OPAQUE_TYPE:
16253 case REAL_TYPE:
16254 case COMPLEX_TYPE:
16255 case VECTOR_TYPE:
16256 case BOOLEAN_TYPE:
16257 case NULLPTR_TYPE:
16258 case LANG_TYPE:
16259 return t;
16261 case INTEGER_TYPE:
16262 if (t == integer_type_node)
16263 return t;
16265 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16266 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16267 return t;
16270 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16272 max = tsubst_expr (omax, args, complain, in_decl);
16274 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16275 needed. */
16276 if (TREE_CODE (max) == NOP_EXPR
16277 && TREE_SIDE_EFFECTS (omax)
16278 && !TREE_TYPE (max))
16279 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16281 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16282 with TREE_SIDE_EFFECTS that indicates this is not an integral
16283 constant expression. */
16284 if (processing_template_decl
16285 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16287 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16288 TREE_SIDE_EFFECTS (max) = 1;
16291 return compute_array_index_type (NULL_TREE, max, complain);
16294 case TEMPLATE_TYPE_PARM:
16295 if (template_placeholder_p (t))
16297 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16298 tmpl = tsubst_expr (tmpl, args, complain, in_decl);
16299 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16300 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16302 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16303 return make_template_placeholder (tmpl);
16304 else
16305 return t;
16307 /* Fall through. */
16308 case TEMPLATE_TEMPLATE_PARM:
16309 case BOUND_TEMPLATE_TEMPLATE_PARM:
16310 case TEMPLATE_PARM_INDEX:
16312 int idx;
16313 int level;
16314 int levels;
16315 tree arg = NULL_TREE;
16317 r = NULL_TREE;
16319 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16320 template_parm_level_and_index (t, &level, &idx);
16322 levels = TMPL_ARGS_DEPTH (args);
16323 if (level <= levels
16324 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16326 arg = TMPL_ARG (args, level, idx);
16328 /* See through ARGUMENT_PACK_SELECT arguments. */
16329 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16330 arg = argument_pack_select_arg (arg);
16333 if (arg == error_mark_node)
16334 return error_mark_node;
16335 else if (arg != NULL_TREE)
16337 if (ARGUMENT_PACK_P (arg))
16338 /* If ARG is an argument pack, we don't actually want to
16339 perform a substitution here, because substitutions
16340 for argument packs are only done
16341 element-by-element. We can get to this point when
16342 substituting the type of a non-type template
16343 parameter pack, when that type actually contains
16344 template parameter packs from an outer template, e.g.,
16346 template<typename... Types> struct A {
16347 template<Types... Values> struct B { };
16348 }; */
16349 return t;
16351 if (code == TEMPLATE_TYPE_PARM)
16353 int quals;
16355 /* When building concept checks for the purpose of
16356 deducing placeholders, we can end up with wildcards
16357 where types are expected. Adjust this to the deduced
16358 value. */
16359 if (TREE_CODE (arg) == WILDCARD_DECL)
16360 arg = TREE_TYPE (TREE_TYPE (arg));
16362 gcc_assert (TYPE_P (arg));
16364 quals = cp_type_quals (arg) | cp_type_quals (t);
16366 return cp_build_qualified_type
16367 (arg, quals, complain | tf_ignore_bad_quals);
16369 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16371 /* We are processing a type constructed from a
16372 template template parameter. */
16373 tree argvec = tsubst (TYPE_TI_ARGS (t),
16374 args, complain, in_decl);
16375 if (argvec == error_mark_node)
16376 return error_mark_node;
16378 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16379 || TREE_CODE (arg) == TEMPLATE_DECL
16380 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16382 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16383 /* Consider this code:
16385 template <template <class> class Template>
16386 struct Internal {
16387 template <class Arg> using Bind = Template<Arg>;
16390 template <template <class> class Template, class Arg>
16391 using Instantiate = Template<Arg>; //#0
16393 template <template <class> class Template,
16394 class Argument>
16395 using Bind =
16396 Instantiate<Internal<Template>::template Bind,
16397 Argument>; //#1
16399 When #1 is parsed, the
16400 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16401 parameter `Template' in #0 matches the
16402 UNBOUND_CLASS_TEMPLATE representing the argument
16403 `Internal<Template>::template Bind'; We then want
16404 to assemble the type `Bind<Argument>' that can't
16405 be fully created right now, because
16406 `Internal<Template>' not being complete, the Bind
16407 template cannot be looked up in that context. So
16408 we need to "store" `Bind<Argument>' for later
16409 when the context of Bind becomes complete. Let's
16410 store that in a TYPENAME_TYPE. */
16411 return make_typename_type (TYPE_CONTEXT (arg),
16412 build_nt (TEMPLATE_ID_EXPR,
16413 TYPE_IDENTIFIER (arg),
16414 argvec),
16415 typename_type,
16416 complain);
16418 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16419 are resolving nested-types in the signature of a
16420 member function templates. Otherwise ARG is a
16421 TEMPLATE_DECL and is the real template to be
16422 instantiated. */
16423 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16424 arg = TYPE_NAME (arg);
16426 r = lookup_template_class (arg,
16427 argvec, in_decl,
16428 DECL_CONTEXT (arg),
16429 /*entering_scope=*/0,
16430 complain);
16431 return cp_build_qualified_type
16432 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16434 else if (code == TEMPLATE_TEMPLATE_PARM)
16435 return arg;
16436 else
16437 /* TEMPLATE_PARM_INDEX. */
16438 return convert_from_reference (unshare_expr (arg));
16441 if (level == 1)
16442 /* This can happen during the attempted tsubst'ing in
16443 unify. This means that we don't yet have any information
16444 about the template parameter in question. */
16445 return t;
16447 /* Early in template argument deduction substitution, we don't
16448 want to reduce the level of 'auto', or it will be confused
16449 with a normal template parm in subsequent deduction.
16450 Similarly, don't reduce the level of template parameters to
16451 avoid mismatches when deducing their types. */
16452 if (complain & tf_partial)
16453 return t;
16455 /* If we get here, we must have been looking at a parm for a
16456 more deeply nested template. Make a new version of this
16457 template parameter, but with a lower level. */
16458 int quals;
16459 switch (code)
16461 case TEMPLATE_TYPE_PARM:
16462 case TEMPLATE_TEMPLATE_PARM:
16463 quals = cp_type_quals (t);
16464 if (quals)
16466 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16467 t = TYPE_MAIN_VARIANT (t);
16470 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16471 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16472 && (code == TEMPLATE_TYPE_PARM
16473 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16474 /* Cache lowering a type parameter or a simple template
16475 template parameter. */
16476 r = TREE_TYPE (d);
16478 if (!r)
16480 r = copy_type (t);
16481 TEMPLATE_TYPE_PARM_INDEX (r)
16482 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16483 r, levels, args, complain);
16484 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16485 TYPE_MAIN_VARIANT (r) = r;
16486 TYPE_POINTER_TO (r) = NULL_TREE;
16487 TYPE_REFERENCE_TO (r) = NULL_TREE;
16489 if (code == TEMPLATE_TYPE_PARM)
16490 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16491 /* Propagate constraints on placeholders since they are
16492 only instantiated during satisfaction. */
16493 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16495 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16496 SET_TYPE_STRUCTURAL_EQUALITY (r);
16497 else
16498 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16501 if (quals)
16502 r = cp_build_qualified_type (r, quals,
16503 complain | tf_ignore_bad_quals);
16504 break;
16506 case BOUND_TEMPLATE_TEMPLATE_PARM:
16508 tree tinfo = TYPE_TEMPLATE_INFO (t);
16509 /* We might need to substitute into the types of non-type
16510 template parameters. This also lowers the level of
16511 the ttp appropriately. */
16512 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16513 complain, in_decl);
16514 if (tmpl == error_mark_node)
16515 return error_mark_node;
16516 tree argvec = tsubst (TI_ARGS (tinfo), args,
16517 complain, in_decl);
16518 if (argvec == error_mark_node)
16519 return error_mark_node;
16520 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16521 /*entering_scope=*/false, complain);
16522 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16523 break;
16526 case TEMPLATE_PARM_INDEX:
16527 /* OK, now substitute the type of the non-type parameter. We
16528 couldn't do it earlier because it might be an auto parameter,
16529 and we wouldn't need to if we had an argument. */
16530 type = tsubst (type, args, complain, in_decl);
16531 if (type == error_mark_node)
16532 return error_mark_node;
16533 r = reduce_template_parm_level (t, type, levels, args, complain);
16534 break;
16536 default:
16537 gcc_unreachable ();
16540 return r;
16543 case TREE_LIST:
16544 return tsubst_tree_list (t, args, complain, in_decl);
16546 case TREE_BINFO:
16547 /* We should never be tsubsting a binfo. */
16548 gcc_unreachable ();
16550 case TREE_VEC:
16551 /* A vector of template arguments. */
16552 gcc_assert (!type);
16553 return tsubst_template_args (t, args, complain, in_decl);
16555 case POINTER_TYPE:
16556 case REFERENCE_TYPE:
16558 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16559 return t;
16561 /* [temp.deduct]
16563 Type deduction may fail for any of the following
16564 reasons:
16566 -- Attempting to create a pointer to reference type.
16567 -- Attempting to create a reference to a reference type or
16568 a reference to void.
16570 Core issue 106 says that creating a reference to a reference
16571 during instantiation is no longer a cause for failure. We
16572 only enforce this check in strict C++98 mode. */
16573 if ((TYPE_REF_P (type)
16574 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16575 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16577 static location_t last_loc;
16579 /* We keep track of the last time we issued this error
16580 message to avoid spewing a ton of messages during a
16581 single bad template instantiation. */
16582 if (complain & tf_error
16583 && last_loc != input_location)
16585 if (VOID_TYPE_P (type))
16586 error ("forming reference to void");
16587 else if (code == POINTER_TYPE)
16588 error ("forming pointer to reference type %qT", type);
16589 else
16590 error ("forming reference to reference type %qT", type);
16591 last_loc = input_location;
16594 return error_mark_node;
16596 else if (TREE_CODE (type) == FUNCTION_TYPE
16597 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16598 || type_memfn_rqual (type) != REF_QUAL_NONE))
16600 if (complain & tf_error)
16602 if (code == POINTER_TYPE)
16603 error ("forming pointer to qualified function type %qT",
16604 type);
16605 else
16606 error ("forming reference to qualified function type %qT",
16607 type);
16609 return error_mark_node;
16611 else if (code == POINTER_TYPE)
16613 r = build_pointer_type (type);
16614 if (TREE_CODE (type) == METHOD_TYPE)
16615 r = build_ptrmemfunc_type (r);
16617 else if (TYPE_REF_P (type))
16618 /* In C++0x, during template argument substitution, when there is an
16619 attempt to create a reference to a reference type, reference
16620 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16622 "If a template-argument for a template-parameter T names a type
16623 that is a reference to a type A, an attempt to create the type
16624 'lvalue reference to cv T' creates the type 'lvalue reference to
16625 A,' while an attempt to create the type type rvalue reference to
16626 cv T' creates the type T"
16628 r = cp_build_reference_type
16629 (TREE_TYPE (type),
16630 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16631 else
16632 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16633 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16635 if (r != error_mark_node)
16636 /* Will this ever be needed for TYPE_..._TO values? */
16637 layout_type (r);
16639 return r;
16641 case OFFSET_TYPE:
16643 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16644 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16646 /* [temp.deduct]
16648 Type deduction may fail for any of the following
16649 reasons:
16651 -- Attempting to create "pointer to member of T" when T
16652 is not a class type. */
16653 if (complain & tf_error)
16654 error ("creating pointer to member of non-class type %qT", r);
16655 return error_mark_node;
16657 if (TYPE_REF_P (type))
16659 if (complain & tf_error)
16660 error ("creating pointer to member reference type %qT", type);
16661 return error_mark_node;
16663 if (VOID_TYPE_P (type))
16665 if (complain & tf_error)
16666 error ("creating pointer to member of type void");
16667 return error_mark_node;
16669 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16670 if (TREE_CODE (type) == FUNCTION_TYPE)
16672 /* The type of the implicit object parameter gets its
16673 cv-qualifiers from the FUNCTION_TYPE. */
16674 tree memptr;
16675 tree method_type
16676 = build_memfn_type (type, r, type_memfn_quals (type),
16677 type_memfn_rqual (type));
16678 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16679 return cp_build_qualified_type (memptr, cp_type_quals (t),
16680 complain);
16682 else
16683 return cp_build_qualified_type (build_ptrmem_type (r, type),
16684 cp_type_quals (t),
16685 complain);
16687 case FUNCTION_TYPE:
16688 case METHOD_TYPE:
16690 tree fntype;
16691 tree specs;
16692 fntype = tsubst_function_type (t, args, complain, in_decl);
16693 if (fntype == error_mark_node)
16694 return error_mark_node;
16696 /* Substitute the exception specification. */
16697 specs = tsubst_exception_specification (t, args, complain, in_decl,
16698 /*defer_ok*/fndecl_type);
16699 if (specs == error_mark_node)
16700 return error_mark_node;
16701 if (specs)
16702 fntype = build_exception_variant (fntype, specs);
16703 return fntype;
16705 case ARRAY_TYPE:
16707 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16708 if (domain == error_mark_node)
16709 return error_mark_node;
16711 /* As an optimization, we avoid regenerating the array type if
16712 it will obviously be the same as T. */
16713 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16714 return t;
16716 /* These checks should match the ones in create_array_type_for_decl.
16718 [temp.deduct]
16720 The deduction may fail for any of the following reasons:
16722 -- Attempting to create an array with an element type that
16723 is void, a function type, or a reference type, or [DR337]
16724 an abstract class type. */
16725 if (VOID_TYPE_P (type)
16726 || TREE_CODE (type) == FUNCTION_TYPE
16727 || (TREE_CODE (type) == ARRAY_TYPE
16728 && TYPE_DOMAIN (type) == NULL_TREE)
16729 || TYPE_REF_P (type))
16731 if (complain & tf_error)
16732 error ("creating array of %qT", type);
16733 return error_mark_node;
16736 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16737 !(complain & tf_error)))
16738 return error_mark_node;
16740 r = build_cplus_array_type (type, domain);
16742 if (!valid_array_size_p (input_location, r, in_decl,
16743 (complain & tf_error)))
16744 return error_mark_node;
16746 if (TYPE_USER_ALIGN (t))
16748 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16749 TYPE_USER_ALIGN (r) = 1;
16752 return r;
16755 case TYPENAME_TYPE:
16757 tree ctx = TYPE_CONTEXT (t);
16758 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16760 ctx = tsubst_pack_expansion (ctx, args,
16761 complain | tf_qualifying_scope,
16762 in_decl);
16763 if (ctx == error_mark_node
16764 || TREE_VEC_LENGTH (ctx) > 1)
16765 return error_mark_node;
16766 if (TREE_VEC_LENGTH (ctx) == 0)
16768 if (complain & tf_error)
16769 error ("%qD is instantiated for an empty pack",
16770 TYPENAME_TYPE_FULLNAME (t));
16771 return error_mark_node;
16773 ctx = TREE_VEC_ELT (ctx, 0);
16775 else
16776 ctx = tsubst_aggr_type (ctx, args,
16777 complain | tf_qualifying_scope,
16778 in_decl, /*entering_scope=*/1);
16779 if (ctx == error_mark_node)
16780 return error_mark_node;
16782 tree f = tsubst_name (TYPENAME_TYPE_FULLNAME (t), args,
16783 complain, in_decl);
16784 if (f == error_mark_node)
16785 return error_mark_node;
16787 if (!MAYBE_CLASS_TYPE_P (ctx))
16789 if (complain & tf_error)
16790 error ("%qT is not a class, struct, or union type", ctx);
16791 return error_mark_node;
16793 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16795 /* Normally, make_typename_type does not require that the CTX
16796 have complete type in order to allow things like:
16798 template <class T> struct S { typename S<T>::X Y; };
16800 But, such constructs have already been resolved by this
16801 point, so here CTX really should have complete type, unless
16802 it's a partial instantiation. */
16803 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16804 return error_mark_node;
16807 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16808 tags. TYPENAME_TYPE should probably remember the exact tag that
16809 was written. */
16810 enum tag_types tag_type
16811 = TYPENAME_IS_CLASS_P (t) ? class_type
16812 : TYPENAME_IS_ENUM_P (t) ? enum_type
16813 : typename_type;
16814 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16815 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16816 f = make_typename_type (ctx, f, tag_type, tcomplain);
16817 if (f == error_mark_node)
16818 return f;
16819 if (TREE_CODE (f) == TYPE_DECL)
16821 complain |= tf_ignore_bad_quals;
16822 f = TREE_TYPE (f);
16825 if (TREE_CODE (f) != TYPENAME_TYPE)
16827 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16829 if (complain & tf_error)
16830 error ("%qT resolves to %qT, which is not an enumeration type",
16831 t, f);
16832 else
16833 return error_mark_node;
16835 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16837 if (complain & tf_error)
16838 error ("%qT resolves to %qT, which is not a class type",
16839 t, f);
16840 else
16841 return error_mark_node;
16845 return cp_build_qualified_type
16846 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16849 case UNBOUND_CLASS_TEMPLATE:
16851 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16852 in_decl, /*entering_scope=*/1);
16853 tree name = TYPE_IDENTIFIER (t);
16854 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16856 if (ctx == error_mark_node || name == error_mark_node)
16857 return error_mark_node;
16859 if (parm_list)
16860 parm_list = tsubst_template_parms (parm_list, args, complain);
16861 return make_unbound_class_template (ctx, name, parm_list, complain);
16864 case TYPEOF_TYPE:
16866 tree type;
16868 ++cp_unevaluated_operand;
16869 ++c_inhibit_evaluation_warnings;
16871 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16873 --cp_unevaluated_operand;
16874 --c_inhibit_evaluation_warnings;
16876 type = finish_typeof (type);
16877 return cp_build_qualified_type (type,
16878 cp_type_quals (t)
16879 | cp_type_quals (type),
16880 complain);
16883 case DECLTYPE_TYPE:
16885 tree type;
16887 ++cp_unevaluated_operand;
16888 ++c_inhibit_evaluation_warnings;
16890 type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
16891 complain|tf_decltype, in_decl);
16893 --cp_unevaluated_operand;
16894 --c_inhibit_evaluation_warnings;
16896 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16897 type = lambda_capture_field_type (type,
16898 false /*explicit_init*/,
16899 DECLTYPE_FOR_REF_CAPTURE (t));
16900 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16901 type = lambda_proxy_type (type);
16902 else
16904 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16905 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16906 && EXPR_P (type))
16907 /* In a template ~id could be either a complement expression
16908 or an unqualified-id naming a destructor; if instantiating
16909 it produces an expression, it's not an id-expression or
16910 member access. */
16911 id = false;
16912 type = finish_decltype_type (type, id, complain);
16914 return cp_build_qualified_type (type,
16915 cp_type_quals (t)
16916 | cp_type_quals (type),
16917 complain | tf_ignore_bad_quals);
16920 case TRAIT_TYPE:
16922 tree type1 = TRAIT_TYPE_TYPE1 (t);
16923 if (TYPE_P (type1))
16924 type1 = tsubst (type1, args, complain, in_decl);
16925 else
16926 type1 = tsubst_expr (type1, args, complain, in_decl);
16927 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16928 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16929 return cp_build_qualified_type (type,
16930 cp_type_quals (t) | cp_type_quals (type),
16931 complain | tf_ignore_bad_quals);
16934 case TYPE_ARGUMENT_PACK:
16935 case NONTYPE_ARGUMENT_PACK:
16936 return tsubst_argument_pack (t, args, complain, in_decl);
16938 case VOID_CST:
16939 case INTEGER_CST:
16940 case REAL_CST:
16941 case STRING_CST:
16942 case PLUS_EXPR:
16943 case MINUS_EXPR:
16944 case NEGATE_EXPR:
16945 case NOP_EXPR:
16946 case INDIRECT_REF:
16947 case ADDR_EXPR:
16948 case CALL_EXPR:
16949 case ARRAY_REF:
16950 case SCOPE_REF:
16951 case OMP_ARRAY_SECTION:
16952 /* We should use one of the expression tsubsts for these codes. */
16953 gcc_unreachable ();
16955 default:
16956 sorry ("use of %qs in template", get_tree_code_name (code));
16957 return error_mark_node;
16961 /* Convenience wrapper over tsubst for substituting into the LHS
16962 of the :: scope resolution operator. */
16964 static tree
16965 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16967 gcc_checking_assert (TYPE_P (t));
16968 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16971 /* Convenience wrapper over tsubst for substituting into an id-expression
16972 without resolving its terminal name. */
16974 static tree
16975 tsubst_name (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16977 return tsubst_expr (t, args, complain | tf_no_name_lookup, in_decl);
16980 /* OLDFNS is a lookup set of member functions from some class template, and
16981 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16982 of that class template. Return the subset of NEWFNS which are
16983 specializations of a function from OLDFNS. */
16985 static tree
16986 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16988 /* Record all member functions from the old lookup set OLDFNS into
16989 VISIBLE_SET. */
16990 hash_set<tree> visible_set;
16991 bool seen_dep_using = false;
16992 for (tree fn : lkp_range (oldfns))
16994 if (TREE_CODE (fn) == USING_DECL)
16996 /* Imprecisely handle dependent using-decl by keeping all members
16997 in the new lookup set that are defined in a base class, i.e.
16998 members that could plausibly have been introduced by this
16999 dependent using-decl.
17000 FIXME: Track which members are introduced by a dependent
17001 using-decl precisely, perhaps by performing another lookup
17002 from the substituted USING_DECL_SCOPE. */
17003 gcc_checking_assert (DECL_DEPENDENT_P (fn));
17004 seen_dep_using = true;
17006 else
17007 visible_set.add (fn);
17010 /* Returns true iff (a less specialized version of) FN appeared in
17011 the old lookup set OLDFNS. */
17012 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
17013 if (DECL_CONTEXT (fn) != newtype)
17014 /* FN is a member function from a base class, introduced via a
17015 using-decl; if it might have been introduced by a dependent
17016 using-decl then just conservatively keep it, otherwise look
17017 in the old lookup set for FN exactly. */
17018 return seen_dep_using || visible_set.contains (fn);
17019 else if (TREE_CODE (fn) == TEMPLATE_DECL)
17020 /* FN is a member function template from the current class;
17021 look in the old lookup set for the TEMPLATE_DECL from which
17022 it was specialized. */
17023 return visible_set.contains (DECL_TI_TEMPLATE (fn));
17024 else
17025 /* FN is a non-template member function from the current class;
17026 look in the old lookup set for the FUNCTION_DECL from which
17027 it was specialized. */
17028 return visible_set.contains (DECL_TEMPLATE_RESULT
17029 (DECL_TI_TEMPLATE (fn)));
17032 bool lookup_changed_p = false;
17033 for (tree fn : lkp_range (newfns))
17034 if (!visible_p (fn))
17036 lookup_changed_p = true;
17037 break;
17039 if (!lookup_changed_p)
17040 return newfns;
17042 /* Filter out from NEWFNS the member functions that weren't
17043 previously visible according to OLDFNS. */
17044 tree filtered_fns = NULL_TREE;
17045 unsigned filtered_size = 0;
17046 for (tree fn : lkp_range (newfns))
17047 if (visible_p (fn))
17049 filtered_fns = lookup_add (fn, filtered_fns);
17050 filtered_size++;
17052 gcc_checking_assert (seen_dep_using
17053 ? filtered_size >= visible_set.elements ()
17054 : filtered_size == visible_set.elements ());
17056 return filtered_fns;
17059 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
17060 expression on the left-hand side of the "." or "->" operator. We
17061 only do the lookup if we had a dependent BASELINK. Otherwise we
17062 adjust it onto the instantiated heirarchy. */
17064 static tree
17065 tsubst_baselink (tree baselink, tree object_type,
17066 tree args, tsubst_flags_t complain, tree in_decl)
17068 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
17069 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
17070 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
17072 tree optype = BASELINK_OPTYPE (baselink);
17073 optype = tsubst (optype, args, complain, in_decl);
17075 tree template_args = NULL_TREE;
17076 bool template_id_p = false;
17077 tree fns = BASELINK_FUNCTIONS (baselink);
17078 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
17080 template_id_p = true;
17081 template_args = TREE_OPERAND (fns, 1);
17082 fns = TREE_OPERAND (fns, 0);
17083 if (template_args)
17084 template_args = tsubst_template_args (template_args, args,
17085 complain, in_decl);
17088 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
17089 binfo_type = tsubst (binfo_type, args, complain, in_decl);
17090 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
17091 || optype != BASELINK_OPTYPE (baselink));
17093 if (dependent_p)
17095 tree name = OVL_NAME (fns);
17096 if (IDENTIFIER_CONV_OP_P (name))
17097 name = make_conv_op_name (optype);
17099 /* See maybe_dependent_member_ref. */
17100 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
17102 if (template_id_p)
17103 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
17104 template_args);
17105 return build_qualified_name (NULL_TREE, qualifying_scope, name,
17106 /* ::template */false);
17109 if (name == complete_dtor_identifier)
17110 /* Treat as-if non-dependent below. */
17111 dependent_p = false;
17113 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
17114 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
17115 complain);
17116 if (maybe_incomplete)
17118 /* Filter out from the new lookup set those functions which didn't
17119 appear in the original lookup set (in a less specialized form).
17120 This is needed to preserve the consistency of member lookup
17121 performed in an incomplete-class context, within which
17122 later-declared members ought to remain invisible. */
17123 BASELINK_FUNCTIONS (baselink)
17124 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
17125 binfo_type);
17126 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
17129 if (!baselink)
17131 if ((complain & tf_error)
17132 && constructor_name_p (name, qualifying_scope))
17133 error ("cannot call constructor %<%T::%D%> directly",
17134 qualifying_scope, name);
17135 return error_mark_node;
17138 fns = BASELINK_FUNCTIONS (baselink);
17140 else
17142 /* We're going to overwrite pieces below, make a duplicate. */
17143 baselink = copy_node (baselink);
17145 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
17147 /* The decl we found was from non-dependent scope, but we still need
17148 to update the binfos for the instantiated qualifying_scope. */
17149 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
17150 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
17151 ba_unique, nullptr, complain);
17155 /* If lookup found a single function, mark it as used at this point.
17156 (If lookup found multiple functions the one selected later by
17157 overload resolution will be marked as used at that point.) */
17158 if (!template_id_p && !really_overloaded_fn (fns))
17160 tree fn = OVL_FIRST (fns);
17161 bool ok = mark_used (fn, complain);
17162 if (!ok && !(complain & tf_error))
17163 return error_mark_node;
17164 if (ok && BASELINK_P (baselink))
17165 /* We might have instantiated an auto function. */
17166 TREE_TYPE (baselink) = TREE_TYPE (fn);
17169 if (BASELINK_P (baselink))
17171 /* Add back the template arguments, if present. */
17172 if (template_id_p)
17173 BASELINK_FUNCTIONS (baselink)
17174 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
17176 /* Update the conversion operator type. */
17177 BASELINK_OPTYPE (baselink) = optype;
17180 if (!object_type)
17181 object_type = current_class_type;
17183 if (qualified_p || !dependent_p)
17185 baselink = adjust_result_of_qualified_name_lookup (baselink,
17186 qualifying_scope,
17187 object_type);
17188 if (!qualified_p)
17189 /* We need to call adjust_result_of_qualified_name_lookup in case the
17190 destructor names a base class, but we unset BASELINK_QUALIFIED_P
17191 so that we still get virtual function binding. */
17192 BASELINK_QUALIFIED_P (baselink) = false;
17195 return baselink;
17198 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
17199 true if the qualified-id will be a postfix-expression in-and-of
17200 itself; false if more of the postfix-expression follows the
17201 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
17202 of "&". */
17204 static tree
17205 tsubst_qualified_id (tree qualified_id, tree args,
17206 tsubst_flags_t complain, tree in_decl,
17207 bool done, bool address_p)
17209 tree expr;
17210 tree scope;
17211 tree name;
17212 bool is_template;
17213 tree template_args;
17214 location_t loc = EXPR_LOCATION (qualified_id);
17216 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
17218 /* Figure out what name to look up. */
17219 name = TREE_OPERAND (qualified_id, 1);
17220 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
17222 is_template = true;
17223 template_args = TREE_OPERAND (name, 1);
17224 if (template_args)
17225 template_args = tsubst_template_args (template_args, args,
17226 complain, in_decl);
17227 if (template_args == error_mark_node)
17228 return error_mark_node;
17229 name = TREE_OPERAND (name, 0);
17231 else
17233 is_template = false;
17234 template_args = NULL_TREE;
17237 /* Substitute into the qualifying scope. When there are no ARGS, we
17238 are just trying to simplify a non-dependent expression. In that
17239 case the qualifying scope may be dependent, and, in any case,
17240 substituting will not help. */
17241 scope = TREE_OPERAND (qualified_id, 0);
17242 if (args)
17244 scope = tsubst_scope (scope, args, complain, in_decl);
17245 expr = tsubst_name (name, args, complain, in_decl);
17247 else
17248 expr = name;
17250 if (dependent_scope_p (scope))
17252 if (TREE_CODE (expr) == SCOPE_REF)
17253 /* We built one in tsubst_baselink. */
17254 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17255 else
17257 if (is_template)
17258 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17259 template_args);
17260 expr = build_qualified_name (NULL_TREE, scope, expr,
17261 QUALIFIED_NAME_IS_TEMPLATE
17262 (qualified_id));
17264 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17265 return expr;
17268 if (!BASELINK_P (name) && !DECL_P (expr))
17270 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17272 /* A BIT_NOT_EXPR is used to represent a destructor. */
17273 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17275 error ("qualifying type %qT does not match destructor name ~%qT",
17276 scope, TREE_OPERAND (expr, 0));
17277 expr = error_mark_node;
17279 else
17280 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17281 LOOK_want::NORMAL, false);
17283 else
17284 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17285 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17286 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17288 if (complain & tf_error)
17290 error ("dependent-name %qE is parsed as a non-type, but "
17291 "instantiation yields a type", qualified_id);
17292 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17294 return error_mark_node;
17298 if (DECL_P (expr))
17300 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17301 scope, complain))
17302 return error_mark_node;
17303 /* Remember that there was a reference to this entity. */
17304 if (!mark_used (expr, complain) && !(complain & tf_error))
17305 return error_mark_node;
17308 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17310 if (complain & tf_error)
17311 qualified_name_lookup_error (scope,
17312 TREE_OPERAND (qualified_id, 1),
17313 expr, input_location);
17314 return error_mark_node;
17317 if (is_template)
17319 /* We may be repeating a check already done during parsing, but
17320 if it was well-formed and passed then, it will pass again
17321 now, and if it didn't, we wouldn't have got here. The case
17322 we want to catch is when we couldn't tell then, and can now,
17323 namely when templ prior to substitution was an
17324 identifier. */
17325 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17326 return error_mark_node;
17328 if (variable_template_p (expr))
17329 expr = lookup_and_finish_template_variable (expr, template_args,
17330 complain);
17331 else
17332 expr = lookup_template_function (expr, template_args);
17335 if (expr == error_mark_node && complain & tf_error)
17336 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17337 expr, input_location);
17338 else if (TYPE_P (scope))
17340 expr = (adjust_result_of_qualified_name_lookup
17341 (expr, scope, current_nonlambda_class_type ()));
17342 expr = (finish_qualified_id_expr
17343 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17344 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17345 /*template_arg_p=*/false, complain));
17348 /* Expressions do not generally have reference type. */
17349 if (TREE_CODE (expr) != SCOPE_REF
17350 /* However, if we're about to form a pointer-to-member, we just
17351 want the referenced member referenced. */
17352 && TREE_CODE (expr) != OFFSET_REF)
17353 expr = convert_from_reference (expr);
17355 if (REF_PARENTHESIZED_P (qualified_id))
17356 expr = force_paren_expr (expr);
17358 expr = maybe_wrap_with_location (expr, loc);
17360 return expr;
17363 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17364 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17365 for tsubst. */
17367 static tree
17368 tsubst_init (tree init, tree decl, tree args,
17369 tsubst_flags_t complain, tree in_decl)
17371 if (!init)
17372 return NULL_TREE;
17374 init = tsubst_expr (init, args, complain, in_decl);
17376 tree type = TREE_TYPE (decl);
17378 if (!init && type != error_mark_node)
17380 if (tree auto_node = type_uses_auto (type))
17382 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17384 if (complain & tf_error)
17385 error ("initializer for %q#D expands to an empty list "
17386 "of expressions", decl);
17387 return error_mark_node;
17390 else if (!dependent_type_p (type))
17392 /* If we had an initializer but it
17393 instantiated to nothing,
17394 value-initialize the object. This will
17395 only occur when the initializer was a
17396 pack expansion where the parameter packs
17397 used in that expansion were of length
17398 zero. */
17399 init = build_value_init (type, complain);
17400 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17401 init = get_target_expr (init, complain);
17402 if (TREE_CODE (init) == TARGET_EXPR)
17403 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17407 return init;
17410 /* If T is a reference to a dependent member of the current instantiation C and
17411 we are trying to refer to that member in a partial instantiation of C,
17412 return a SCOPE_REF; otherwise, return NULL_TREE.
17414 This can happen when forming a C++17 deduction guide, as in PR96199. */
17416 static tree
17417 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17418 tree in_decl)
17420 if (!(complain & tf_dguide))
17421 return NULL_TREE;
17423 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17424 if (!decl || !DECL_P (decl))
17425 return NULL_TREE;
17427 tree ctx = context_for_name_lookup (decl);
17428 if (!CLASS_TYPE_P (ctx))
17429 return NULL_TREE;
17431 ctx = tsubst (ctx, args, complain, in_decl);
17432 if (!dependent_scope_p (ctx))
17433 return NULL_TREE;
17435 if (TYPE_P (t))
17437 if (typedef_variant_p (t))
17438 t = strip_typedefs (t);
17439 tree decl = TYPE_NAME (t);
17440 if (decl)
17441 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17442 if (!decl)
17443 return NULL_TREE;
17444 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17445 complain);
17448 tree name = DECL_NAME (t);
17449 tree fullname = name;
17450 if (instantiates_primary_template_p (t))
17452 tree tinfo = get_template_info (t);
17453 name = DECL_NAME (TI_TEMPLATE (tinfo));
17454 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17455 targs = tsubst_template_args (targs, args, complain, in_decl);
17456 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17459 if (TREE_CODE (t) == TYPE_DECL)
17461 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17462 && TYPE_NAME (TREE_TYPE (t)) == t)
17463 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17464 scope, but it doesn't need to be rewritten again. */
17465 return NULL_TREE;
17466 tree type = build_typename_type (ctx, name, fullname, typename_type);
17467 return TYPE_NAME (type);
17469 else if (DECL_TYPE_TEMPLATE_P (t))
17470 return make_unbound_class_template (ctx, name,
17471 NULL_TREE, complain);
17472 else
17473 return build_qualified_name (NULL_TREE, ctx, fullname,
17474 TREE_CODE (t) == TEMPLATE_DECL);
17477 /* Helper function for tsubst_omp_clauses, used for instantiation of
17478 OMP_CLAUSE_DECL of clauses. */
17480 static tree
17481 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17482 tree in_decl, tree *iterator_cache)
17484 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17485 return decl;
17487 /* Handle OpenMP iterators. */
17488 if (TREE_CODE (decl) == TREE_LIST
17489 && TREE_PURPOSE (decl)
17490 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17492 tree ret;
17493 if (iterator_cache[0] == TREE_PURPOSE (decl))
17494 ret = iterator_cache[1];
17495 else
17497 tree *tp = &ret;
17498 begin_scope (sk_omp, NULL);
17499 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17501 *tp = copy_node (it);
17502 TREE_VEC_ELT (*tp, 0)
17503 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17504 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17505 pushdecl (TREE_VEC_ELT (*tp, 0));
17506 TREE_VEC_ELT (*tp, 1)
17507 = tsubst_stmt (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17508 TREE_VEC_ELT (*tp, 2)
17509 = tsubst_stmt (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17510 TREE_VEC_ELT (*tp, 3)
17511 = tsubst_stmt (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17512 TREE_CHAIN (*tp) = NULL_TREE;
17513 tp = &TREE_CHAIN (*tp);
17515 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17516 iterator_cache[0] = TREE_PURPOSE (decl);
17517 iterator_cache[1] = ret;
17519 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17520 args, complain,
17521 in_decl, NULL));
17524 /* Handle an OpenMP array section represented as a TREE_LIST (or
17525 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17526 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17527 TREE_LIST. We can handle it exactly the same as an array section
17528 (purpose, value, and a chain), even though the nomenclature
17529 (low_bound, length, etc) is different. */
17530 if (TREE_CODE (decl) == TREE_LIST)
17532 tree low_bound
17533 = tsubst_stmt (TREE_PURPOSE (decl), args, complain, in_decl);
17534 tree length = tsubst_stmt (TREE_VALUE (decl), args, complain, in_decl);
17535 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17536 in_decl, NULL);
17537 if (TREE_PURPOSE (decl) == low_bound
17538 && TREE_VALUE (decl) == length
17539 && TREE_CHAIN (decl) == chain)
17540 return decl;
17541 tree ret = tree_cons (low_bound, length, chain);
17542 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17543 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17544 return ret;
17546 else if (TREE_CODE (decl) == OMP_ARRAY_SECTION)
17548 tree low_bound
17549 = tsubst_stmt (TREE_OPERAND (decl, 1), args, complain, in_decl);
17550 tree length = tsubst_stmt (TREE_OPERAND (decl, 2), args, complain,
17551 in_decl);
17552 tree base = tsubst_omp_clause_decl (TREE_OPERAND (decl, 0), args,
17553 complain, in_decl, NULL);
17554 if (TREE_OPERAND (decl, 0) == base
17555 && TREE_OPERAND (decl, 1) == low_bound
17556 && TREE_OPERAND (decl, 2) == length)
17557 return decl;
17558 return build3 (OMP_ARRAY_SECTION, TREE_TYPE (base), base, low_bound,
17559 length);
17561 tree ret = tsubst_stmt (decl, args, complain, in_decl);
17562 /* Undo convert_from_reference tsubst_expr could have called. */
17563 if (decl
17564 && REFERENCE_REF_P (ret)
17565 && !REFERENCE_REF_P (decl))
17566 ret = TREE_OPERAND (ret, 0);
17567 return ret;
17570 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17572 static tree
17573 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17574 tree args, tsubst_flags_t complain, tree in_decl)
17576 tree new_clauses = NULL_TREE, nc, oc;
17577 tree linear_no_step = NULL_TREE;
17578 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17580 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17582 nc = copy_node (oc);
17583 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17584 new_clauses = nc;
17586 switch (OMP_CLAUSE_CODE (nc))
17588 case OMP_CLAUSE_LASTPRIVATE:
17589 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17591 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17592 tsubst_stmt (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
17593 complain, in_decl);
17594 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17595 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17597 /* FALLTHRU */
17598 case OMP_CLAUSE_PRIVATE:
17599 case OMP_CLAUSE_SHARED:
17600 case OMP_CLAUSE_FIRSTPRIVATE:
17601 case OMP_CLAUSE_COPYIN:
17602 case OMP_CLAUSE_COPYPRIVATE:
17603 case OMP_CLAUSE_UNIFORM:
17604 case OMP_CLAUSE_DEPEND:
17605 case OMP_CLAUSE_DOACROSS:
17606 case OMP_CLAUSE_AFFINITY:
17607 case OMP_CLAUSE_FROM:
17608 case OMP_CLAUSE_TO:
17609 case OMP_CLAUSE_MAP:
17610 case OMP_CLAUSE__CACHE_:
17611 case OMP_CLAUSE_NONTEMPORAL:
17612 case OMP_CLAUSE_USE_DEVICE_PTR:
17613 case OMP_CLAUSE_USE_DEVICE_ADDR:
17614 case OMP_CLAUSE_IS_DEVICE_PTR:
17615 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17616 case OMP_CLAUSE_INCLUSIVE:
17617 case OMP_CLAUSE_EXCLUSIVE:
17618 OMP_CLAUSE_DECL (nc)
17619 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17620 in_decl, iterator_cache);
17621 break;
17622 case OMP_CLAUSE_NUM_TEAMS:
17623 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17624 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17625 = tsubst_stmt (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17626 complain, in_decl);
17627 /* FALLTHRU */
17628 case OMP_CLAUSE_TILE:
17629 case OMP_CLAUSE_IF:
17630 case OMP_CLAUSE_SELF:
17631 case OMP_CLAUSE_NUM_THREADS:
17632 case OMP_CLAUSE_SCHEDULE:
17633 case OMP_CLAUSE_COLLAPSE:
17634 case OMP_CLAUSE_FINAL:
17635 case OMP_CLAUSE_DEVICE:
17636 case OMP_CLAUSE_DIST_SCHEDULE:
17637 case OMP_CLAUSE_THREAD_LIMIT:
17638 case OMP_CLAUSE_SAFELEN:
17639 case OMP_CLAUSE_SIMDLEN:
17640 case OMP_CLAUSE_NUM_TASKS:
17641 case OMP_CLAUSE_GRAINSIZE:
17642 case OMP_CLAUSE_PRIORITY:
17643 case OMP_CLAUSE_ORDERED:
17644 case OMP_CLAUSE_HINT:
17645 case OMP_CLAUSE_FILTER:
17646 case OMP_CLAUSE_NUM_GANGS:
17647 case OMP_CLAUSE_NUM_WORKERS:
17648 case OMP_CLAUSE_VECTOR_LENGTH:
17649 case OMP_CLAUSE_WORKER:
17650 case OMP_CLAUSE_VECTOR:
17651 case OMP_CLAUSE_ASYNC:
17652 case OMP_CLAUSE_WAIT:
17653 case OMP_CLAUSE_DETACH:
17654 OMP_CLAUSE_OPERAND (nc, 0)
17655 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
17656 break;
17657 case OMP_CLAUSE_REDUCTION:
17658 case OMP_CLAUSE_IN_REDUCTION:
17659 case OMP_CLAUSE_TASK_REDUCTION:
17660 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17662 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17663 if (TREE_CODE (placeholder) == SCOPE_REF)
17665 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17666 complain, in_decl);
17667 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17668 = build_qualified_name (NULL_TREE, scope,
17669 TREE_OPERAND (placeholder, 1),
17670 false);
17672 else
17673 gcc_assert (identifier_p (placeholder));
17675 OMP_CLAUSE_DECL (nc)
17676 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17677 in_decl, NULL);
17678 break;
17679 case OMP_CLAUSE_GANG:
17680 case OMP_CLAUSE_ALIGNED:
17681 OMP_CLAUSE_DECL (nc)
17682 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17683 in_decl, NULL);
17684 OMP_CLAUSE_OPERAND (nc, 1)
17685 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17686 break;
17687 case OMP_CLAUSE_ALLOCATE:
17688 OMP_CLAUSE_DECL (nc)
17689 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17690 in_decl, NULL);
17691 OMP_CLAUSE_OPERAND (nc, 1)
17692 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
17693 OMP_CLAUSE_OPERAND (nc, 2)
17694 = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
17695 break;
17696 case OMP_CLAUSE_LINEAR:
17697 OMP_CLAUSE_DECL (nc)
17698 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17699 in_decl, NULL);
17700 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17702 gcc_assert (!linear_no_step);
17703 linear_no_step = nc;
17705 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17706 OMP_CLAUSE_LINEAR_STEP (nc)
17707 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17708 complain, in_decl, NULL);
17709 else
17710 OMP_CLAUSE_LINEAR_STEP (nc)
17711 = tsubst_stmt (OMP_CLAUSE_LINEAR_STEP (oc), args,
17712 complain, in_decl);
17713 break;
17714 case OMP_CLAUSE_NOWAIT:
17715 case OMP_CLAUSE_DEFAULT:
17716 case OMP_CLAUSE_UNTIED:
17717 case OMP_CLAUSE_MERGEABLE:
17718 case OMP_CLAUSE_INBRANCH:
17719 case OMP_CLAUSE_NOTINBRANCH:
17720 case OMP_CLAUSE_PROC_BIND:
17721 case OMP_CLAUSE_FOR:
17722 case OMP_CLAUSE_PARALLEL:
17723 case OMP_CLAUSE_SECTIONS:
17724 case OMP_CLAUSE_TASKGROUP:
17725 case OMP_CLAUSE_NOGROUP:
17726 case OMP_CLAUSE_THREADS:
17727 case OMP_CLAUSE_SIMD:
17728 case OMP_CLAUSE_DEFAULTMAP:
17729 case OMP_CLAUSE_ORDER:
17730 case OMP_CLAUSE_BIND:
17731 case OMP_CLAUSE_INDEPENDENT:
17732 case OMP_CLAUSE_AUTO:
17733 case OMP_CLAUSE_SEQ:
17734 case OMP_CLAUSE_IF_PRESENT:
17735 case OMP_CLAUSE_FINALIZE:
17736 case OMP_CLAUSE_NOHOST:
17737 break;
17738 default:
17739 gcc_unreachable ();
17741 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17742 switch (OMP_CLAUSE_CODE (nc))
17744 case OMP_CLAUSE_SHARED:
17745 case OMP_CLAUSE_PRIVATE:
17746 case OMP_CLAUSE_FIRSTPRIVATE:
17747 case OMP_CLAUSE_LASTPRIVATE:
17748 case OMP_CLAUSE_COPYPRIVATE:
17749 case OMP_CLAUSE_LINEAR:
17750 case OMP_CLAUSE_REDUCTION:
17751 case OMP_CLAUSE_IN_REDUCTION:
17752 case OMP_CLAUSE_TASK_REDUCTION:
17753 case OMP_CLAUSE_USE_DEVICE_PTR:
17754 case OMP_CLAUSE_USE_DEVICE_ADDR:
17755 case OMP_CLAUSE_IS_DEVICE_PTR:
17756 case OMP_CLAUSE_HAS_DEVICE_ADDR:
17757 case OMP_CLAUSE_INCLUSIVE:
17758 case OMP_CLAUSE_EXCLUSIVE:
17759 case OMP_CLAUSE_ALLOCATE:
17760 /* tsubst_expr on SCOPE_REF results in returning
17761 finish_non_static_data_member result. Undo that here. */
17762 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17763 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17764 == IDENTIFIER_NODE))
17766 tree t = OMP_CLAUSE_DECL (nc);
17767 tree v = t;
17768 while (v)
17769 switch (TREE_CODE (v))
17771 case COMPONENT_REF:
17772 case MEM_REF:
17773 case INDIRECT_REF:
17774 CASE_CONVERT:
17775 case POINTER_PLUS_EXPR:
17776 v = TREE_OPERAND (v, 0);
17777 continue;
17778 case PARM_DECL:
17779 if (DECL_CONTEXT (v) == current_function_decl
17780 && DECL_ARTIFICIAL (v)
17781 && DECL_NAME (v) == this_identifier)
17782 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17783 /* FALLTHRU */
17784 default:
17785 v = NULL_TREE;
17786 break;
17789 else if (VAR_P (OMP_CLAUSE_DECL (oc))
17790 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17791 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17792 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17793 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17795 tree decl = OMP_CLAUSE_DECL (nc);
17796 if (VAR_P (decl))
17798 retrofit_lang_decl (decl);
17799 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17802 break;
17803 default:
17804 break;
17808 new_clauses = nreverse (new_clauses);
17809 if (ort != C_ORT_OMP_DECLARE_SIMD)
17811 new_clauses = finish_omp_clauses (new_clauses, ort);
17812 if (linear_no_step)
17813 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17814 if (nc == linear_no_step)
17816 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17817 break;
17820 return new_clauses;
17823 /* Like tsubst_expr, but unshare TREE_LIST nodes. */
17825 static tree
17826 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17827 tree in_decl)
17829 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17831 tree purpose, value, chain;
17833 if (t == NULL)
17834 return t;
17836 if (TREE_CODE (t) != TREE_LIST)
17837 return tsubst_expr (t, args, complain, in_decl);
17839 if (t == void_list_node)
17840 return t;
17842 purpose = TREE_PURPOSE (t);
17843 if (purpose)
17844 purpose = RECUR (purpose);
17845 value = TREE_VALUE (t);
17846 if (value)
17848 if (TREE_CODE (value) != LABEL_DECL)
17849 value = RECUR (value);
17850 else
17852 value = lookup_label (DECL_NAME (value));
17853 gcc_assert (TREE_CODE (value) == LABEL_DECL);
17854 TREE_USED (value) = 1;
17857 chain = TREE_CHAIN (t);
17858 if (chain && chain != void_type_node)
17859 chain = RECUR (chain);
17860 return tree_cons (purpose, value, chain);
17861 #undef RECUR
17864 /* Used to temporarily communicate the list of #pragma omp parallel
17865 clauses to #pragma omp for instantiation if they are combined
17866 together. */
17868 static tree *omp_parallel_combined_clauses;
17870 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17871 cp_decomp *);
17873 /* Substitute one OMP_FOR iterator. */
17875 static bool
17876 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17877 tree initv, tree condv, tree incrv, tree *clauses,
17878 tree args, tsubst_flags_t complain, tree in_decl)
17880 #define RECUR(NODE) \
17881 tsubst_stmt ((NODE), args, complain, in_decl)
17882 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17883 bool ret = false;
17885 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17886 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17888 decl = TREE_OPERAND (init, 0);
17889 init = TREE_OPERAND (init, 1);
17890 tree decl_expr = NULL_TREE;
17891 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17892 if (range_for)
17894 bool decomp = false;
17895 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17897 tree v = DECL_VALUE_EXPR (decl);
17898 if (TREE_CODE (v) == ARRAY_REF
17899 && VAR_P (TREE_OPERAND (v, 0))
17900 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17902 cp_decomp decomp_d = { NULL_TREE, 0 };
17903 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17904 maybe_push_decl (d);
17905 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17906 in_decl, &decomp_d);
17907 decomp = true;
17908 if (d == error_mark_node)
17909 decl = error_mark_node;
17910 else
17911 for (unsigned int i = 0; i < decomp_d.count; i++)
17913 if (!DECL_HAS_VALUE_EXPR_P (decomp_d.decl))
17915 tree v = build_nt (ARRAY_REF, d,
17916 size_int (decomp_d.count - i - 1),
17917 NULL_TREE, NULL_TREE);
17918 SET_DECL_VALUE_EXPR (decomp_d.decl, v);
17919 DECL_HAS_VALUE_EXPR_P (decomp_d.decl) = 1;
17921 fit_decomposition_lang_decl (decomp_d.decl, d);
17922 decomp_d.decl = DECL_CHAIN (decomp_d.decl);
17926 decl = tsubst_decl (decl, args, complain);
17927 if (!decomp)
17928 maybe_push_decl (decl);
17930 else if (init && TREE_CODE (init) == DECL_EXPR)
17932 /* We need to jump through some hoops to handle declarations in the
17933 init-statement, since we might need to handle auto deduction,
17934 but we need to keep control of initialization. */
17935 decl_expr = init;
17936 init = DECL_INITIAL (DECL_EXPR_DECL (init));
17937 decl = tsubst_decl (decl, args, complain);
17939 else
17941 if (TREE_CODE (decl) == SCOPE_REF)
17943 decl = RECUR (decl);
17944 if (TREE_CODE (decl) == COMPONENT_REF)
17946 tree v = decl;
17947 while (v)
17948 switch (TREE_CODE (v))
17950 case COMPONENT_REF:
17951 case MEM_REF:
17952 case INDIRECT_REF:
17953 CASE_CONVERT:
17954 case POINTER_PLUS_EXPR:
17955 v = TREE_OPERAND (v, 0);
17956 continue;
17957 case PARM_DECL:
17958 if (DECL_CONTEXT (v) == current_function_decl
17959 && DECL_ARTIFICIAL (v)
17960 && DECL_NAME (v) == this_identifier)
17962 decl = TREE_OPERAND (decl, 1);
17963 decl = omp_privatize_field (decl, false);
17965 /* FALLTHRU */
17966 default:
17967 v = NULL_TREE;
17968 break;
17972 else
17973 decl = RECUR (decl);
17975 if (init && TREE_CODE (init) == TREE_VEC)
17977 init = copy_node (init);
17978 TREE_VEC_ELT (init, 0)
17979 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
17980 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
17981 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
17983 else
17984 init = RECUR (init);
17986 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17988 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17989 if (TREE_CODE (o) == TREE_LIST)
17990 TREE_VEC_ELT (orig_declv, i)
17991 = tree_cons (RECUR (TREE_PURPOSE (o)),
17992 RECUR (TREE_VALUE (o)),
17993 NULL_TREE);
17994 else
17995 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17998 if (range_for)
18000 tree this_pre_body = NULL_TREE;
18001 tree orig_init = NULL_TREE;
18002 tree orig_decl = NULL_TREE;
18003 tree init_sl = NULL_TREE;
18004 cp_convert_omp_range_for (this_pre_body, init_sl, decl, orig_decl, init,
18005 orig_init, cond, incr);
18006 if (orig_decl)
18008 if (orig_declv == NULL_TREE)
18009 orig_declv = copy_node (declv);
18010 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18011 ret = true;
18013 else if (orig_declv)
18014 TREE_VEC_ELT (orig_declv, i) = decl;
18017 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18018 if (!range_for && auto_node && init)
18019 TREE_TYPE (decl)
18020 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18022 gcc_assert (!type_dependent_expression_p (decl));
18024 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18026 if (decl_expr)
18028 /* Declare the variable, but don't let that initialize it. */
18029 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18030 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18031 RECUR (decl_expr);
18032 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18035 if (!range_for)
18037 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18038 if (COMPARISON_CLASS_P (cond)
18039 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18041 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18042 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18043 TREE_VEC_ELT (rhs, 0)
18044 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18045 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18046 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18047 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18048 lhs, rhs);
18050 else
18051 cond = RECUR (cond);
18052 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18053 if (TREE_CODE (incr) == MODIFY_EXPR)
18055 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18056 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18057 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18058 NOP_EXPR, rhs, NULL_TREE, complain);
18060 else
18061 incr = RECUR (incr);
18062 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18063 TREE_VEC_ELT (orig_declv, i) = decl;
18065 TREE_VEC_ELT (declv, i) = decl;
18066 TREE_VEC_ELT (initv, i) = init;
18067 TREE_VEC_ELT (condv, i) = cond;
18068 TREE_VEC_ELT (incrv, i) = incr;
18069 return ret;
18072 if (decl_expr)
18074 /* Declare and initialize the variable. */
18075 RECUR (decl_expr);
18076 init = NULL_TREE;
18078 else if (init)
18080 tree *pc;
18081 int j;
18082 for (j = ((omp_parallel_combined_clauses == NULL
18083 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18085 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18087 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18088 && OMP_CLAUSE_DECL (*pc) == decl)
18089 break;
18090 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18091 && OMP_CLAUSE_DECL (*pc) == decl)
18093 if (j)
18094 break;
18095 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18096 tree c = *pc;
18097 *pc = OMP_CLAUSE_CHAIN (c);
18098 OMP_CLAUSE_CHAIN (c) = *clauses;
18099 *clauses = c;
18101 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18102 && OMP_CLAUSE_DECL (*pc) == decl)
18104 error ("iteration variable %qD should not be firstprivate",
18105 decl);
18106 *pc = OMP_CLAUSE_CHAIN (*pc);
18108 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18109 && OMP_CLAUSE_DECL (*pc) == decl)
18111 error ("iteration variable %qD should not be reduction",
18112 decl);
18113 *pc = OMP_CLAUSE_CHAIN (*pc);
18115 else
18116 pc = &OMP_CLAUSE_CHAIN (*pc);
18118 if (*pc)
18119 break;
18121 if (*pc == NULL_TREE)
18123 tree c = build_omp_clause (input_location,
18124 TREE_CODE (t) == OMP_LOOP
18125 ? OMP_CLAUSE_LASTPRIVATE
18126 : OMP_CLAUSE_PRIVATE);
18127 OMP_CLAUSE_DECL (c) = decl;
18128 c = finish_omp_clauses (c, C_ORT_OMP);
18129 if (c)
18131 OMP_CLAUSE_CHAIN (c) = *clauses;
18132 *clauses = c;
18136 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18137 if (COMPARISON_CLASS_P (cond))
18139 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18140 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18141 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18143 else
18144 cond = RECUR (cond);
18145 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18146 switch (TREE_CODE (incr))
18148 case PREINCREMENT_EXPR:
18149 case PREDECREMENT_EXPR:
18150 case POSTINCREMENT_EXPR:
18151 case POSTDECREMENT_EXPR:
18152 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18153 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18154 break;
18155 case MODIFY_EXPR:
18156 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18157 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18159 tree rhs = TREE_OPERAND (incr, 1);
18160 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18161 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18162 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18163 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18164 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18165 rhs0, rhs1));
18167 else
18168 incr = RECUR (incr);
18169 break;
18170 case MODOP_EXPR:
18171 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18172 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18174 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18175 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18176 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18177 TREE_TYPE (decl), lhs,
18178 RECUR (TREE_OPERAND (incr, 2))));
18180 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18181 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18182 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18184 tree rhs = TREE_OPERAND (incr, 2);
18185 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18186 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18187 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18188 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18189 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18190 rhs0, rhs1));
18192 else
18193 incr = RECUR (incr);
18194 break;
18195 default:
18196 incr = RECUR (incr);
18197 break;
18200 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18201 TREE_VEC_ELT (orig_declv, i) = decl;
18202 TREE_VEC_ELT (declv, i) = decl;
18203 TREE_VEC_ELT (initv, i) = init;
18204 TREE_VEC_ELT (condv, i) = cond;
18205 TREE_VEC_ELT (incrv, i) = incr;
18206 return false;
18207 #undef RECUR
18210 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18211 of OMP_TARGET's body. */
18213 static tree
18214 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18216 *walk_subtrees = 0;
18217 switch (TREE_CODE (*tp))
18219 case OMP_TEAMS:
18220 return *tp;
18221 case BIND_EXPR:
18222 case STATEMENT_LIST:
18223 *walk_subtrees = 1;
18224 break;
18225 default:
18226 break;
18228 return NULL_TREE;
18231 /* Helper function for tsubst_expr. For decomposition declaration
18232 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18233 also the corresponding decls representing the identifiers
18234 of the decomposition declaration. Return DECL if successful
18235 or error_mark_node otherwise, set *FIRST to the first decl
18236 in the list chained through DECL_CHAIN and *CNT to the number
18237 of such decls. */
18239 static tree
18240 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18241 tsubst_flags_t complain, tree in_decl, cp_decomp *decomp)
18243 tree decl2, decl3, prev = decl;
18244 decomp->count = 0;
18245 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18246 for (decl2 = DECL_CHAIN (pattern_decl);
18247 decl2
18248 && VAR_P (decl2)
18249 && DECL_DECOMPOSITION_P (decl2)
18250 && DECL_NAME (decl2);
18251 decl2 = DECL_CHAIN (decl2))
18253 if (TREE_TYPE (decl2) == error_mark_node && decomp->count == 0)
18255 gcc_assert (errorcount);
18256 return error_mark_node;
18258 decomp->count++;
18259 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18260 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18261 tree v = DECL_VALUE_EXPR (decl2);
18262 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18263 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18264 decl3 = tsubst (decl2, args, complain, in_decl);
18265 SET_DECL_VALUE_EXPR (decl2, v);
18266 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18267 if (VAR_P (decl3))
18268 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18269 else
18271 gcc_assert (errorcount);
18272 decl = error_mark_node;
18273 continue;
18275 maybe_push_decl (decl3);
18276 if (error_operand_p (decl3))
18277 decl = error_mark_node;
18278 else if (decl != error_mark_node
18279 && DECL_CHAIN (decl3) != prev
18280 && decl != prev)
18282 gcc_assert (errorcount);
18283 decl = error_mark_node;
18285 else
18286 prev = decl3;
18288 decomp->decl = prev;
18289 return decl;
18292 /* Return the proper local_specialization for init-capture pack DECL. */
18294 static tree
18295 lookup_init_capture_pack (tree decl)
18297 /* We handle normal pack captures by forwarding to the specialization of the
18298 captured parameter. We can't do that for pack init-captures; we need them
18299 to have their own local_specialization. We created the individual
18300 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18301 when we process the DECL_EXPR for the pack init-capture in the template.
18302 So, how do we find them? We don't know the capture proxy pack when
18303 building the individual resulting proxies, and we don't know the
18304 individual proxies when instantiating the pack. What we have in common is
18305 the FIELD_DECL.
18307 So...when we instantiate the FIELD_DECL, we stick the result in
18308 local_specializations. Then at the DECL_EXPR we look up that result, see
18309 how many elements it has, synthesize the names, and look them up. */
18311 tree cname = DECL_NAME (decl);
18312 tree val = DECL_VALUE_EXPR (decl);
18313 tree field = TREE_OPERAND (val, 1);
18314 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18315 tree fpack = retrieve_local_specialization (field);
18316 if (fpack == error_mark_node)
18317 return error_mark_node;
18319 int len = 1;
18320 tree vec = NULL_TREE;
18321 tree r = NULL_TREE;
18322 if (TREE_CODE (fpack) == TREE_VEC)
18324 len = TREE_VEC_LENGTH (fpack);
18325 vec = make_tree_vec (len);
18326 r = make_node (NONTYPE_ARGUMENT_PACK);
18327 ARGUMENT_PACK_ARGS (r) = vec;
18329 for (int i = 0; i < len; ++i)
18331 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18332 tree elt = lookup_name (ename);
18333 if (vec)
18334 TREE_VEC_ELT (vec, i) = elt;
18335 else
18336 r = elt;
18338 return r;
18341 /* T is an operand of a template tree being substituted. Return whether
18342 T is dependent such that we should suppress some warnings that would
18343 make sense if the substituted expression were written directly, like
18344 template <int I> bool f() { return I == 2; }
18345 We don't want to warn when instantiating f that comparing two constants
18346 always has the same value.
18348 This is a more limited concept of dependence than instantiation-dependent;
18349 here we don't care whether substitution could fail. */
18351 static bool
18352 dependent_operand_p (tree t)
18354 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18355 t = TREE_OPERAND (t, 0);
18356 ++processing_template_decl;
18357 bool r = (potential_constant_expression (t)
18358 ? value_dependent_expression_p (t)
18359 : type_dependent_expression_p (t));
18360 --processing_template_decl;
18361 return r;
18364 /* A superset of tsubst_expr that also handles statement trees. */
18366 static tree
18367 tsubst_stmt (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18369 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18370 #define RECUR(NODE) \
18371 tsubst_stmt ((NODE), args, complain, in_decl)
18373 tree stmt, tmp;
18374 tree r;
18375 location_t loc;
18377 if (t == NULL_TREE || t == error_mark_node)
18378 return t;
18380 loc = input_location;
18381 if (location_t eloc = cp_expr_location (t))
18382 input_location = eloc;
18383 if (STATEMENT_CODE_P (TREE_CODE (t)))
18384 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18386 switch (TREE_CODE (t))
18388 case STATEMENT_LIST:
18390 for (tree stmt : tsi_range (t))
18391 RECUR (stmt);
18392 break;
18395 case CTOR_INITIALIZER:
18396 finish_mem_initializers (tsubst_initializer_list
18397 (TREE_OPERAND (t, 0), args));
18398 break;
18400 case RETURN_EXPR:
18401 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18402 break;
18404 case CO_RETURN_EXPR:
18405 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18406 break;
18408 case EXPR_STMT:
18409 tmp = RECUR (EXPR_STMT_EXPR (t));
18410 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18411 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18412 else
18413 finish_expr_stmt (tmp);
18414 break;
18416 case USING_STMT:
18417 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18418 break;
18420 case PRECONDITION_STMT:
18421 case POSTCONDITION_STMT:
18422 gcc_unreachable ();
18424 case ASSERTION_STMT:
18426 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18427 if (r != error_mark_node)
18428 add_stmt (r);
18429 RETURN (r);
18431 break;
18433 case DECL_EXPR:
18435 tree decl, pattern_decl;
18436 tree init;
18438 pattern_decl = decl = DECL_EXPR_DECL (t);
18439 if (TREE_CODE (decl) == LABEL_DECL)
18440 finish_label_decl (DECL_NAME (decl));
18441 else if (TREE_CODE (decl) == USING_DECL)
18443 tree scope = USING_DECL_SCOPE (decl);
18444 if (DECL_DEPENDENT_P (decl))
18446 scope = tsubst (scope, args, complain, in_decl);
18447 if (!MAYBE_CLASS_TYPE_P (scope)
18448 && TREE_CODE (scope) != ENUMERAL_TYPE)
18450 if (complain & tf_error)
18451 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18452 "class, namespace, or enumeration", scope);
18453 return error_mark_node;
18455 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18457 else
18459 /* This is a non-dependent using-decl, and we'll have
18460 used the names it found during template parsing. We do
18461 not want to do the lookup again, because we might not
18462 find the things we found then. */
18463 gcc_checking_assert (scope == tsubst (scope, args,
18464 complain, in_decl));
18465 /* We still need to push the bindings so that we can look up
18466 this name later. */
18467 push_using_decl_bindings (DECL_NAME (decl),
18468 USING_DECL_DECLS (decl));
18471 else if (is_capture_proxy (decl)
18472 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18474 /* We're in tsubst_lambda_expr, we've already inserted a new
18475 capture proxy, so look it up and register it. */
18476 tree inst;
18477 if (!DECL_PACK_P (decl))
18479 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18480 LOOK_want::HIDDEN_LAMBDA);
18481 gcc_assert (inst != decl && is_capture_proxy (inst));
18483 else if (is_normal_capture_proxy (decl))
18485 inst = (retrieve_local_specialization
18486 (DECL_CAPTURED_VARIABLE (decl)));
18487 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18488 || DECL_PACK_P (inst));
18490 else
18491 inst = lookup_init_capture_pack (decl);
18493 register_local_specialization (inst, decl);
18494 break;
18496 else if (DECL_PRETTY_FUNCTION_P (decl))
18497 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18498 DECL_NAME (decl),
18499 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18500 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18501 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18502 /* Don't copy the old closure; we'll create a new one in
18503 tsubst_lambda_expr. */
18504 break;
18505 else
18507 init = DECL_INITIAL (decl);
18508 decl = tsubst (decl, args, complain, in_decl);
18509 if (decl != error_mark_node)
18511 /* By marking the declaration as instantiated, we avoid
18512 trying to instantiate it. Since instantiate_decl can't
18513 handle local variables, and since we've already done
18514 all that needs to be done, that's the right thing to
18515 do. */
18516 if (VAR_P (decl))
18517 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18518 if (VAR_P (decl) && !DECL_NAME (decl)
18519 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18520 /* Anonymous aggregates are a special case. */
18521 finish_anon_union (decl);
18522 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18524 DECL_CONTEXT (decl) = current_function_decl;
18525 if (DECL_NAME (decl) == this_identifier)
18527 tree lam = DECL_CONTEXT (current_function_decl);
18528 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18529 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18531 insert_capture_proxy (decl);
18533 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18534 /* We already did a pushtag. */;
18535 else if (VAR_OR_FUNCTION_DECL_P (decl)
18536 && DECL_LOCAL_DECL_P (decl))
18538 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18539 DECL_CONTEXT (decl) = NULL_TREE;
18540 decl = pushdecl (decl);
18541 if (TREE_CODE (decl) == FUNCTION_DECL
18542 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18543 && cp_check_omp_declare_reduction (decl))
18544 instantiate_body (pattern_decl, args, decl, true);
18546 else
18548 bool const_init = false;
18549 cp_decomp decomp_d, *decomp = NULL;
18550 tree ndecl = error_mark_node;
18551 tree asmspec_tree = NULL_TREE;
18552 maybe_push_decl (decl);
18554 if (VAR_P (decl)
18555 && DECL_LANG_SPECIFIC (decl)
18556 && DECL_OMP_PRIVATIZED_MEMBER (decl))
18557 break;
18559 if (VAR_P (decl)
18560 && DECL_DECOMPOSITION_P (decl)
18561 && TREE_TYPE (pattern_decl) != error_mark_node)
18563 decomp = &decomp_d;
18564 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18565 complain, in_decl, decomp);
18568 init = tsubst_init (init, decl, args, complain, in_decl);
18570 if (VAR_P (decl))
18571 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18572 (pattern_decl));
18574 /* In a non-template function, VLA type declarations are
18575 handled in grokdeclarator; for templates, handle them
18576 now. */
18577 predeclare_vla (decl);
18579 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18581 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18582 const char *asmspec = IDENTIFIER_POINTER (id);
18583 gcc_assert (asmspec[0] == '*');
18584 asmspec_tree
18585 = build_string (IDENTIFIER_LENGTH (id) - 1,
18586 asmspec + 1);
18587 TREE_TYPE (asmspec_tree) = char_array_type_node;
18590 cp_finish_decl (decl, init, const_init, asmspec_tree, 0,
18591 decomp);
18593 if (ndecl != error_mark_node)
18594 cp_finish_decomp (ndecl, decomp);
18599 break;
18602 case FOR_STMT:
18603 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18604 RECUR (FOR_INIT_STMT (t));
18605 finish_init_stmt (stmt);
18606 tmp = RECUR (FOR_COND (t));
18607 finish_for_cond (tmp, stmt, false, 0, false);
18608 tmp = RECUR (FOR_EXPR (t));
18609 finish_for_expr (tmp, stmt);
18611 bool prev = note_iteration_stmt_body_start ();
18612 RECUR (FOR_BODY (t));
18613 note_iteration_stmt_body_end (prev);
18615 finish_for_stmt (stmt);
18616 break;
18618 case RANGE_FOR_STMT:
18620 /* Construct another range_for, if this is not a final
18621 substitution (for inside a generic lambda of a
18622 template). Otherwise convert to a regular for. */
18623 tree decl, expr;
18624 stmt = (processing_template_decl
18625 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18626 : begin_for_stmt (NULL_TREE, NULL_TREE));
18627 RECUR (RANGE_FOR_INIT_STMT (t));
18628 decl = RANGE_FOR_DECL (t);
18629 decl = tsubst (decl, args, complain, in_decl);
18630 maybe_push_decl (decl);
18631 expr = RECUR (RANGE_FOR_EXPR (t));
18633 cp_decomp decomp_d, *decomp = NULL;
18634 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18636 decomp = &decomp_d;
18637 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18638 complain, in_decl, decomp);
18641 tree unroll = RECUR (RANGE_FOR_UNROLL (t));
18642 if (unroll)
18643 unroll
18644 = cp_check_pragma_unroll (EXPR_LOCATION (RANGE_FOR_UNROLL (t)),
18645 unroll);
18646 if (processing_template_decl)
18648 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18649 RANGE_FOR_UNROLL (stmt) = unroll;
18650 RANGE_FOR_NOVECTOR (stmt) = RANGE_FOR_NOVECTOR (t);
18651 finish_range_for_decl (stmt, decl, expr);
18652 if (decomp && decl != error_mark_node)
18653 cp_finish_decomp (decl, decomp);
18655 else
18656 stmt = cp_convert_range_for (stmt, decl, expr, decomp,
18657 RANGE_FOR_IVDEP (t), unroll,
18658 RANGE_FOR_NOVECTOR (t));
18660 bool prev = note_iteration_stmt_body_start ();
18661 RECUR (RANGE_FOR_BODY (t));
18662 note_iteration_stmt_body_end (prev);
18663 finish_for_stmt (stmt);
18665 break;
18667 case WHILE_STMT:
18668 stmt = begin_while_stmt ();
18669 tmp = RECUR (WHILE_COND (t));
18670 finish_while_stmt_cond (tmp, stmt, false, 0, false);
18672 bool prev = note_iteration_stmt_body_start ();
18673 RECUR (WHILE_BODY (t));
18674 note_iteration_stmt_body_end (prev);
18676 finish_while_stmt (stmt);
18677 break;
18679 case DO_STMT:
18680 stmt = begin_do_stmt ();
18682 bool prev = note_iteration_stmt_body_start ();
18683 RECUR (DO_BODY (t));
18684 note_iteration_stmt_body_end (prev);
18686 finish_do_body (stmt);
18687 tmp = RECUR (DO_COND (t));
18688 finish_do_stmt (tmp, stmt, false, 0, false);
18689 break;
18691 case IF_STMT:
18692 stmt = begin_if_stmt ();
18693 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18694 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18695 if (IF_STMT_CONSTEXPR_P (t))
18696 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18698 tree cond = IF_COND (t);
18699 bool was_dep = dependent_operand_p (cond);
18700 cond = RECUR (cond);
18701 warning_sentinel s1(warn_address, was_dep);
18702 tmp = finish_if_stmt_cond (cond, stmt);
18704 if (IF_STMT_CONSTEXPR_P (t)
18705 && instantiation_dependent_expression_p (tmp))
18707 /* We're partially instantiating a generic lambda, but the condition
18708 of the constexpr if is still dependent. Don't substitute into the
18709 branches now, just remember the template arguments. */
18710 do_poplevel (IF_SCOPE (stmt));
18711 IF_COND (stmt) = IF_COND (t);
18712 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18713 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18714 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18715 add_stmt (stmt);
18716 break;
18718 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18719 /* Don't instantiate the THEN_CLAUSE. */;
18720 else if (IF_STMT_CONSTEVAL_P (t))
18722 bool save_in_consteval_if_p = in_consteval_if_p;
18723 in_consteval_if_p = true;
18724 RECUR (THEN_CLAUSE (t));
18725 in_consteval_if_p = save_in_consteval_if_p;
18727 else
18729 tree folded = fold_non_dependent_expr (tmp, complain);
18730 bool inhibit = integer_zerop (folded);
18731 if (inhibit)
18732 ++c_inhibit_evaluation_warnings;
18733 RECUR (THEN_CLAUSE (t));
18734 if (inhibit)
18735 --c_inhibit_evaluation_warnings;
18737 finish_then_clause (stmt);
18739 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18740 /* Don't instantiate the ELSE_CLAUSE. */;
18741 else if (ELSE_CLAUSE (t))
18743 tree folded = fold_non_dependent_expr (tmp, complain);
18744 bool inhibit = integer_nonzerop (folded);
18745 begin_else_clause (stmt);
18746 if (inhibit)
18747 ++c_inhibit_evaluation_warnings;
18748 RECUR (ELSE_CLAUSE (t));
18749 if (inhibit)
18750 --c_inhibit_evaluation_warnings;
18751 finish_else_clause (stmt);
18754 finish_if_stmt (stmt);
18755 break;
18757 case BIND_EXPR:
18758 if (BIND_EXPR_BODY_BLOCK (t))
18759 stmt = begin_function_body ();
18760 else
18761 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18762 ? BCS_TRY_BLOCK : 0);
18764 RECUR (BIND_EXPR_BODY (t));
18766 if (BIND_EXPR_BODY_BLOCK (t))
18767 finish_function_body (stmt);
18768 else
18769 finish_compound_stmt (stmt);
18770 break;
18772 case BREAK_STMT:
18773 finish_break_stmt ();
18774 break;
18776 case CONTINUE_STMT:
18777 finish_continue_stmt ();
18778 break;
18780 case SWITCH_STMT:
18781 stmt = begin_switch_stmt ();
18782 tmp = RECUR (SWITCH_STMT_COND (t));
18783 finish_switch_cond (tmp, stmt);
18784 RECUR (SWITCH_STMT_BODY (t));
18785 finish_switch_stmt (stmt);
18786 break;
18788 case CASE_LABEL_EXPR:
18790 tree decl = CASE_LABEL (t);
18791 tree low = RECUR (CASE_LOW (t));
18792 tree high = RECUR (CASE_HIGH (t));
18793 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18794 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18796 tree label = CASE_LABEL (l);
18797 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18798 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18799 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18802 break;
18804 case LABEL_EXPR:
18806 tree decl = LABEL_EXPR_LABEL (t);
18807 tree label;
18809 label = finish_label_stmt (DECL_NAME (decl));
18810 if (TREE_CODE (label) == LABEL_DECL)
18811 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18812 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18813 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18815 break;
18817 case GOTO_EXPR:
18818 tmp = GOTO_DESTINATION (t);
18819 if (TREE_CODE (tmp) != LABEL_DECL)
18820 /* Computed goto's must be tsubst'd into. On the other hand,
18821 non-computed gotos must not be; the identifier in question
18822 will have no binding. */
18823 tmp = RECUR (tmp);
18824 else
18825 tmp = DECL_NAME (tmp);
18826 finish_goto_stmt (tmp);
18827 break;
18829 case ASM_EXPR:
18831 tree string = RECUR (ASM_STRING (t));
18832 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18833 complain, in_decl);
18834 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18835 complain, in_decl);
18836 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18837 complain, in_decl);
18838 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18839 complain, in_decl);
18840 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18841 outputs, inputs, clobbers, labels,
18842 ASM_INLINE_P (t));
18843 tree asm_expr = tmp;
18844 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18845 asm_expr = TREE_OPERAND (asm_expr, 0);
18846 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18848 break;
18850 case TRY_BLOCK:
18851 if (CLEANUP_P (t))
18853 stmt = begin_try_block ();
18854 RECUR (TRY_STMTS (t));
18855 finish_cleanup_try_block (stmt);
18856 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18858 else
18860 tree compound_stmt = NULL_TREE;
18862 if (FN_TRY_BLOCK_P (t))
18863 stmt = begin_function_try_block (&compound_stmt);
18864 else
18865 stmt = begin_try_block ();
18867 RECUR (TRY_STMTS (t));
18869 if (FN_TRY_BLOCK_P (t))
18870 finish_function_try_block (stmt);
18871 else
18872 finish_try_block (stmt);
18874 RECUR (TRY_HANDLERS (t));
18875 if (FN_TRY_BLOCK_P (t))
18876 finish_function_handler_sequence (stmt, compound_stmt);
18877 else
18878 finish_handler_sequence (stmt);
18880 break;
18882 case HANDLER:
18884 tree decl = HANDLER_PARMS (t);
18886 if (decl)
18888 decl = tsubst (decl, args, complain, in_decl);
18889 /* Prevent instantiate_decl from trying to instantiate
18890 this variable. We've already done all that needs to be
18891 done. */
18892 if (decl != error_mark_node)
18893 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18895 stmt = begin_handler ();
18896 finish_handler_parms (decl, stmt);
18897 RECUR (HANDLER_BODY (t));
18898 finish_handler (stmt);
18900 break;
18902 case TAG_DEFN:
18903 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18904 if (dependent_type_p (tmp))
18905 /* This is a partial instantiation, try again when full. */
18906 add_stmt (build_min (TAG_DEFN, tmp));
18907 else if (CLASS_TYPE_P (tmp))
18909 /* Local classes are not independent templates; they are
18910 instantiated along with their containing function. And this
18911 way we don't have to deal with pushing out of one local class
18912 to instantiate a member of another local class. */
18913 /* Closures are handled by the LAMBDA_EXPR. */
18914 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18915 complete_type (tmp);
18916 tree save_ccp = current_class_ptr;
18917 tree save_ccr = current_class_ref;
18918 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18919 if ((VAR_P (fld)
18920 || (TREE_CODE (fld) == FUNCTION_DECL
18921 && !DECL_ARTIFICIAL (fld)))
18922 && DECL_TEMPLATE_INSTANTIATION (fld))
18923 instantiate_decl (fld, /*defer_ok=*/false,
18924 /*expl_inst_class=*/false);
18925 else if (TREE_CODE (fld) == FIELD_DECL)
18926 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
18927 current_class_ptr = save_ccp;
18928 current_class_ref = save_ccr;
18930 break;
18932 case STATIC_ASSERT:
18934 tree condition, message;
18936 ++c_inhibit_evaluation_warnings;
18937 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
18938 complain, in_decl);
18939 message = tsubst_expr (STATIC_ASSERT_MESSAGE (t), args,
18940 complain, in_decl);
18941 if (TREE_CODE (STATIC_ASSERT_MESSAGE (t)) != STRING_CST
18942 && TREE_CODE (message) == STRING_CST)
18943 message = build1_loc (STATIC_ASSERT_SOURCE_LOCATION (t),
18944 PAREN_EXPR, TREE_TYPE (message), message);
18945 --c_inhibit_evaluation_warnings;
18947 finish_static_assert (condition, message,
18948 STATIC_ASSERT_SOURCE_LOCATION (t),
18949 /*member_p=*/false, /*show_expr_p=*/true);
18951 break;
18953 case OACC_KERNELS:
18954 case OACC_PARALLEL:
18955 case OACC_SERIAL:
18956 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC_TARGET, args,
18957 complain, in_decl);
18958 stmt = begin_omp_parallel ();
18959 RECUR (OMP_BODY (t));
18960 finish_omp_construct (TREE_CODE (t), stmt, tmp);
18961 break;
18963 case OMP_PARALLEL:
18964 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18965 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18966 complain, in_decl);
18967 if (OMP_PARALLEL_COMBINED (t))
18968 omp_parallel_combined_clauses = &tmp;
18969 stmt = begin_omp_parallel ();
18970 RECUR (OMP_PARALLEL_BODY (t));
18971 gcc_assert (omp_parallel_combined_clauses == NULL);
18972 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18973 = OMP_PARALLEL_COMBINED (t);
18974 pop_omp_privatization_clauses (r);
18975 break;
18977 case OMP_TASK:
18978 if (OMP_TASK_BODY (t) == NULL_TREE)
18980 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18981 complain, in_decl);
18982 t = copy_node (t);
18983 OMP_TASK_CLAUSES (t) = tmp;
18984 add_stmt (t);
18985 break;
18987 r = push_omp_privatization_clauses (false);
18988 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18989 complain, in_decl);
18990 stmt = begin_omp_task ();
18991 RECUR (OMP_TASK_BODY (t));
18992 finish_omp_task (tmp, stmt);
18993 pop_omp_privatization_clauses (r);
18994 break;
18996 case OMP_FOR:
18997 case OMP_LOOP:
18998 case OMP_SIMD:
18999 case OMP_DISTRIBUTE:
19000 case OMP_TASKLOOP:
19001 case OACC_LOOP:
19003 tree clauses, body, pre_body;
19004 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19005 tree orig_declv = NULL_TREE;
19006 tree incrv = NULL_TREE;
19007 enum c_omp_region_type ort = C_ORT_OMP;
19008 bool any_range_for = false;
19009 int i;
19011 if (TREE_CODE (t) == OACC_LOOP)
19012 ort = C_ORT_ACC;
19014 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19015 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19016 in_decl);
19017 if (OMP_FOR_INIT (t) != NULL_TREE)
19019 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19020 if (OMP_FOR_ORIG_DECLS (t))
19021 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19022 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19023 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19024 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19027 keep_next_level (true);
19028 stmt = begin_omp_structured_block ();
19030 pre_body = push_stmt_list ();
19031 RECUR (OMP_FOR_PRE_BODY (t));
19032 pre_body = pop_stmt_list (pre_body);
19034 if (OMP_FOR_INIT (t) != NULL_TREE)
19035 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19036 any_range_for
19037 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19038 condv, incrv, &clauses, args,
19039 complain, in_decl);
19040 omp_parallel_combined_clauses = NULL;
19042 if (any_range_for)
19044 gcc_assert (orig_declv);
19045 body = begin_omp_structured_block ();
19046 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19047 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19048 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19049 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19050 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19051 TREE_VEC_ELT (declv, i));
19053 else
19054 body = push_stmt_list ();
19055 RECUR (OMP_FOR_BODY (t));
19056 if (any_range_for)
19057 body = finish_omp_structured_block (body);
19058 else
19059 body = pop_stmt_list (body);
19061 if (OMP_FOR_INIT (t) != NULL_TREE)
19062 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19063 orig_declv, initv, condv, incrv, body, pre_body,
19064 NULL, clauses);
19065 else
19067 t = make_node (TREE_CODE (t));
19068 TREE_TYPE (t) = void_type_node;
19069 OMP_FOR_BODY (t) = body;
19070 OMP_FOR_PRE_BODY (t) = pre_body;
19071 OMP_FOR_CLAUSES (t) = clauses;
19072 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19073 add_stmt (t);
19076 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19077 t));
19078 pop_omp_privatization_clauses (r);
19080 break;
19082 case OMP_SECTIONS:
19083 case OMP_MASKED:
19084 omp_parallel_combined_clauses = NULL;
19085 /* FALLTHRU */
19086 case OMP_SINGLE:
19087 case OMP_SCOPE:
19088 case OMP_TEAMS:
19089 case OMP_CRITICAL:
19090 case OMP_TASKGROUP:
19091 case OMP_SCAN:
19092 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19093 && OMP_TEAMS_COMBINED (t));
19094 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19095 in_decl);
19096 if (TREE_CODE (t) == OMP_TEAMS)
19098 keep_next_level (true);
19099 stmt = begin_omp_structured_block ();
19100 RECUR (OMP_BODY (t));
19101 stmt = finish_omp_structured_block (stmt);
19103 else
19105 stmt = push_stmt_list ();
19106 RECUR (OMP_BODY (t));
19107 stmt = pop_stmt_list (stmt);
19110 if (TREE_CODE (t) == OMP_CRITICAL
19111 && tmp != NULL_TREE
19112 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19114 error_at (OMP_CLAUSE_LOCATION (tmp),
19115 "%<#pragma omp critical%> with %<hint%> clause requires "
19116 "a name, except when %<omp_sync_hint_none%> is used");
19117 RETURN (error_mark_node);
19119 t = copy_node (t);
19120 OMP_BODY (t) = stmt;
19121 OMP_CLAUSES (t) = tmp;
19122 add_stmt (t);
19123 pop_omp_privatization_clauses (r);
19124 break;
19126 case OMP_DEPOBJ:
19127 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19128 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19130 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19131 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19133 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19134 args, complain, in_decl);
19135 if (tmp == NULL_TREE)
19136 tmp = error_mark_node;
19138 else
19140 kind = (enum omp_clause_depend_kind)
19141 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19142 tmp = NULL_TREE;
19144 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19146 else
19147 finish_omp_depobj (EXPR_LOCATION (t), r,
19148 OMP_CLAUSE_DEPEND_INVALID,
19149 OMP_DEPOBJ_CLAUSES (t));
19150 break;
19152 case OACC_DATA:
19153 case OMP_TARGET_DATA:
19154 case OMP_TARGET:
19155 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19156 TREE_CODE (t) == OACC_DATA
19157 ? C_ORT_ACC
19158 : TREE_CODE (t) == OMP_TARGET
19159 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19160 args, complain, in_decl);
19161 keep_next_level (true);
19162 stmt = begin_omp_structured_block ();
19164 RECUR (OMP_BODY (t));
19165 stmt = finish_omp_structured_block (stmt);
19167 t = copy_node (t);
19168 OMP_BODY (t) = stmt;
19169 OMP_CLAUSES (t) = tmp;
19171 if (TREE_CODE (t) == OMP_TARGET)
19172 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19173 &OMP_CLAUSES (t));
19175 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19177 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19178 if (teams)
19179 /* For combined target teams, ensure the num_teams and
19180 thread_limit clause expressions are evaluated on the host,
19181 before entering the target construct. */
19182 for (tree c = OMP_TEAMS_CLAUSES (teams);
19183 c; c = OMP_CLAUSE_CHAIN (c))
19184 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19185 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19186 for (int i = 0;
19187 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19188 if (OMP_CLAUSE_OPERAND (c, i)
19189 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19191 tree expr = OMP_CLAUSE_OPERAND (c, i);
19192 expr = force_target_expr (TREE_TYPE (expr), expr,
19193 tf_none);
19194 if (expr == error_mark_node)
19195 continue;
19196 tmp = TARGET_EXPR_SLOT (expr);
19197 add_stmt (expr);
19198 OMP_CLAUSE_OPERAND (c, i) = expr;
19199 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19200 OMP_CLAUSE_FIRSTPRIVATE);
19201 OMP_CLAUSE_DECL (tc) = tmp;
19202 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19203 OMP_TARGET_CLAUSES (t) = tc;
19206 add_stmt (t);
19207 break;
19209 case OACC_DECLARE:
19210 t = copy_node (t);
19211 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19212 complain, in_decl);
19213 OACC_DECLARE_CLAUSES (t) = tmp;
19214 add_stmt (t);
19215 break;
19217 case OMP_TARGET_UPDATE:
19218 case OMP_TARGET_ENTER_DATA:
19219 case OMP_TARGET_EXIT_DATA:
19220 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19221 complain, in_decl);
19222 t = copy_node (t);
19223 OMP_STANDALONE_CLAUSES (t) = tmp;
19224 add_stmt (t);
19225 break;
19227 case OACC_CACHE:
19228 case OACC_ENTER_DATA:
19229 case OACC_EXIT_DATA:
19230 case OACC_UPDATE:
19231 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19232 complain, in_decl);
19233 t = copy_node (t);
19234 OMP_STANDALONE_CLAUSES (t) = tmp;
19235 add_stmt (t);
19236 break;
19238 case OMP_ORDERED:
19239 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19240 complain, in_decl);
19241 if (OMP_BODY (t))
19243 stmt = push_stmt_list ();
19244 RECUR (OMP_BODY (t));
19245 stmt = pop_stmt_list (stmt);
19247 else
19248 stmt = NULL_TREE;
19250 t = copy_node (t);
19251 OMP_BODY (t) = stmt;
19252 OMP_ORDERED_CLAUSES (t) = tmp;
19253 add_stmt (t);
19254 break;
19256 case OMP_MASTER:
19257 case OMP_STRUCTURED_BLOCK:
19258 omp_parallel_combined_clauses = NULL;
19259 /* FALLTHRU */
19260 case OMP_SECTION:
19261 stmt = push_stmt_list ();
19262 RECUR (OMP_BODY (t));
19263 stmt = pop_stmt_list (stmt);
19265 t = copy_node (t);
19266 OMP_BODY (t) = stmt;
19267 add_stmt (t);
19268 break;
19270 case OMP_ATOMIC:
19271 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19272 tmp = NULL_TREE;
19273 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19274 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19275 complain, in_decl);
19276 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19278 tree op1 = TREE_OPERAND (t, 1);
19279 tree rhs1 = NULL_TREE;
19280 tree r = NULL_TREE;
19281 tree lhs, rhs;
19282 if (TREE_CODE (op1) == COMPOUND_EXPR)
19284 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19285 op1 = TREE_OPERAND (op1, 1);
19287 if (TREE_CODE (op1) == COND_EXPR)
19289 gcc_assert (rhs1 == NULL_TREE);
19290 tree c = TREE_OPERAND (op1, 0);
19291 if (TREE_CODE (c) == MODIFY_EXPR)
19293 r = RECUR (TREE_OPERAND (c, 0));
19294 c = TREE_OPERAND (c, 1);
19296 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19297 rhs = RECUR (TREE_OPERAND (c, 1));
19298 lhs = RECUR (TREE_OPERAND (op1, 2));
19299 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19301 else
19303 lhs = RECUR (TREE_OPERAND (op1, 0));
19304 rhs = RECUR (TREE_OPERAND (op1, 1));
19306 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19307 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19308 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19309 OMP_ATOMIC_WEAK (t));
19311 else
19313 tree op1 = TREE_OPERAND (t, 1);
19314 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19315 tree rhs1 = NULL_TREE, r = NULL_TREE;
19316 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19317 enum tree_code opcode = NOP_EXPR;
19318 if (code == OMP_ATOMIC_READ)
19320 v = RECUR (TREE_OPERAND (op1, 0));
19321 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19323 else if (code == OMP_ATOMIC_CAPTURE_OLD
19324 || code == OMP_ATOMIC_CAPTURE_NEW)
19326 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19327 v = RECUR (TREE_OPERAND (op1, 0));
19328 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19329 if (TREE_CODE (op11) == COMPOUND_EXPR)
19331 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19332 op11 = TREE_OPERAND (op11, 1);
19334 if (TREE_CODE (op11) == COND_EXPR)
19336 gcc_assert (rhs1 == NULL_TREE);
19337 tree c = TREE_OPERAND (op11, 0);
19338 if (TREE_CODE (c) == MODIFY_EXPR)
19340 r = RECUR (TREE_OPERAND (c, 0));
19341 c = TREE_OPERAND (c, 1);
19343 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19344 rhs = RECUR (TREE_OPERAND (c, 1));
19345 lhs = RECUR (TREE_OPERAND (op11, 2));
19346 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19348 else
19350 lhs = RECUR (TREE_OPERAND (op11, 0));
19351 rhs = RECUR (TREE_OPERAND (op11, 1));
19353 opcode = TREE_CODE (op11);
19354 if (opcode == MODIFY_EXPR)
19355 opcode = NOP_EXPR;
19357 else
19359 code = OMP_ATOMIC;
19360 lhs = RECUR (TREE_OPERAND (op1, 0));
19361 rhs = RECUR (TREE_OPERAND (op1, 1));
19363 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19364 lhs1, rhs1, r, tmp,
19365 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19367 break;
19369 case TRANSACTION_EXPR:
19371 int flags = 0;
19372 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19373 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19375 if (TRANSACTION_EXPR_IS_STMT (t))
19377 tree body = TRANSACTION_EXPR_BODY (t);
19378 tree noex = NULL_TREE;
19379 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19381 noex = MUST_NOT_THROW_COND (body);
19382 if (noex == NULL_TREE)
19383 noex = boolean_true_node;
19384 body = TREE_OPERAND (body, 0);
19386 stmt = begin_transaction_stmt (input_location, NULL, flags);
19387 RECUR (body);
19388 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19390 else
19392 stmt = build_transaction_expr (EXPR_LOCATION (t),
19393 RECUR (TRANSACTION_EXPR_BODY (t)),
19394 flags, NULL_TREE);
19395 RETURN (stmt);
19398 break;
19400 case MUST_NOT_THROW_EXPR:
19402 tree op0 = RECUR (TREE_OPERAND (t, 0));
19403 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19404 RETURN (build_must_not_throw_expr (op0, cond));
19407 case EXPR_PACK_EXPANSION:
19408 error ("invalid use of pack expansion expression");
19409 RETURN (error_mark_node);
19411 case NONTYPE_ARGUMENT_PACK:
19412 error ("use %<...%> to expand argument pack");
19413 RETURN (error_mark_node);
19415 case COMPOUND_EXPR:
19416 tmp = RECUR (TREE_OPERAND (t, 0));
19417 if (tmp == NULL_TREE)
19418 /* If the first operand was a statement, we're done with it. */
19419 RETURN (RECUR (TREE_OPERAND (t, 1)));
19420 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19421 RECUR (TREE_OPERAND (t, 1)),
19422 templated_operator_saved_lookups (t),
19423 complain));
19425 case PREDICT_EXPR:
19426 RETURN (add_stmt (copy_node (t)));
19428 default:
19429 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19431 RETURN (tsubst_expr (t, args, complain, in_decl));
19434 RETURN (NULL_TREE);
19435 out:
19436 input_location = loc;
19437 return r;
19438 #undef RECUR
19439 #undef RETURN
19442 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19443 function. For description of the body see comment above
19444 cp_parser_omp_declare_reduction_exprs. */
19446 static void
19447 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19449 if (t == NULL_TREE || t == error_mark_node)
19450 return;
19452 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19454 tree_stmt_iterator tsi;
19455 int i;
19456 tree stmts[7];
19457 memset (stmts, 0, sizeof stmts);
19458 for (i = 0, tsi = tsi_start (t);
19459 i < 7 && !tsi_end_p (tsi);
19460 i++, tsi_next (&tsi))
19461 stmts[i] = tsi_stmt (tsi);
19462 gcc_assert (tsi_end_p (tsi));
19464 if (i >= 3)
19466 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19467 && TREE_CODE (stmts[1]) == DECL_EXPR);
19468 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19469 args, complain, in_decl);
19470 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19471 args, complain, in_decl);
19472 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19473 expect to be pushing it. */
19474 DECL_CONTEXT (omp_out) = current_function_decl;
19475 DECL_CONTEXT (omp_in) = current_function_decl;
19476 keep_next_level (true);
19477 tree block = begin_omp_structured_block ();
19478 tsubst_stmt (stmts[2], args, complain, in_decl);
19479 block = finish_omp_structured_block (block);
19480 block = maybe_cleanup_point_expr_void (block);
19481 add_decl_expr (omp_out);
19482 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19483 add_decl_expr (omp_in);
19484 finish_expr_stmt (block);
19486 if (i >= 6)
19488 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19489 && TREE_CODE (stmts[4]) == DECL_EXPR);
19490 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19491 args, complain, in_decl);
19492 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19493 args, complain, in_decl);
19494 DECL_CONTEXT (omp_priv) = current_function_decl;
19495 DECL_CONTEXT (omp_orig) = current_function_decl;
19496 keep_next_level (true);
19497 tree block = begin_omp_structured_block ();
19498 tsubst_stmt (stmts[5], args, complain, in_decl);
19499 block = finish_omp_structured_block (block);
19500 block = maybe_cleanup_point_expr_void (block);
19501 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19502 add_decl_expr (omp_priv);
19503 add_decl_expr (omp_orig);
19504 finish_expr_stmt (block);
19505 if (i == 7)
19506 add_decl_expr (omp_orig);
19510 /* T is a postfix-expression that is not being used in a function
19511 call. Return the substituted version of T. */
19513 static tree
19514 tsubst_non_call_postfix_expression (tree t, tree args,
19515 tsubst_flags_t complain,
19516 tree in_decl)
19518 if (TREE_CODE (t) == SCOPE_REF)
19519 t = tsubst_qualified_id (t, args, complain, in_decl,
19520 /*done=*/false, /*address_p=*/false);
19521 else
19522 t = tsubst_expr (t, args, complain, in_decl);
19524 return t;
19527 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19528 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19529 dependent init-capture. EXPLICIT_P is true if the original list had
19530 explicit captures. */
19532 static void
19533 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19534 tsubst_flags_t complain)
19536 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19538 tree type = NULL_TREE;
19539 if (!init)
19541 if (complain & tf_error)
19542 error ("empty initializer in lambda init-capture");
19543 init = error_mark_node;
19545 else if (TREE_CODE (init) == TREE_LIST)
19546 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19547 if (!type)
19548 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19549 TREE_TYPE (field) = type;
19550 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19552 list = tree_cons (field, init, list);
19553 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19556 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19557 instantiation context. Instantiating a pack expansion containing a lambda
19558 might result in multiple lambdas all based on the same lambda in the
19559 template. */
19561 tree
19562 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19564 tree oldfn = lambda_function (t);
19565 in_decl = oldfn;
19567 tree r = build_lambda_expr ();
19569 LAMBDA_EXPR_LOCATION (r)
19570 = LAMBDA_EXPR_LOCATION (t);
19571 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19572 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19573 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19574 LAMBDA_EXPR_REGEN_INFO (r)
19575 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19576 preserve_args (args)));
19577 else
19578 LAMBDA_EXPR_REGEN_INFO (r)
19579 = build_template_info (t, preserve_args (args));
19581 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19582 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19584 vec<tree,va_gc>* field_packs = NULL;
19585 unsigned name_independent_cnt = 0;
19586 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19587 cap = TREE_CHAIN (cap))
19589 tree ofield = TREE_PURPOSE (cap);
19590 tree init = TREE_VALUE (cap);
19591 if (PACK_EXPANSION_P (init))
19592 init = tsubst_pack_expansion (init, args, complain, in_decl);
19593 else
19594 init = tsubst_expr (init, args, complain, in_decl);
19596 if (init == error_mark_node)
19597 return error_mark_node;
19599 if (init && TREE_CODE (init) == TREE_LIST)
19600 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19602 if (!processing_template_decl
19603 && init && TREE_CODE (init) != TREE_VEC
19604 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19606 /* For a VLA, simply tsubsting the field type won't work, we need to
19607 go through add_capture again. XXX do we want to do this for all
19608 captures? */
19609 tree name = (get_identifier
19610 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19611 tree ftype = TREE_TYPE (ofield);
19612 bool by_ref = (TYPE_REF_P (ftype)
19613 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19614 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19615 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield),
19616 &name_independent_cnt);
19617 continue;
19620 if (PACK_EXPANSION_P (ofield))
19621 ofield = PACK_EXPANSION_PATTERN (ofield);
19622 tree field = tsubst_decl (ofield, args, complain);
19624 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19626 /* Remember these for when we've pushed local_specializations. */
19627 vec_safe_push (field_packs, ofield);
19628 vec_safe_push (field_packs, field);
19631 if (field == error_mark_node)
19632 return error_mark_node;
19634 if (TREE_CODE (field) == TREE_VEC)
19636 int len = TREE_VEC_LENGTH (field);
19637 gcc_assert (TREE_CODE (init) == TREE_VEC
19638 && TREE_VEC_LENGTH (init) == len);
19639 for (int i = 0; i < len; ++i)
19640 prepend_one_capture (TREE_VEC_ELT (field, i),
19641 TREE_VEC_ELT (init, i),
19642 LAMBDA_EXPR_CAPTURE_LIST (r),
19643 LAMBDA_CAPTURE_EXPLICIT_P (cap),
19644 complain);
19646 else
19648 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19649 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
19651 if (id_equal (DECL_NAME (field), "__this"))
19652 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19656 tree type = begin_lambda_type (r);
19657 if (type == error_mark_node)
19658 return error_mark_node;
19660 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
19661 record_lambda_scope (r);
19662 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19663 /* If we're pushed into another scope (PR105652), fix it. */
19664 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19665 = TYPE_CONTEXT (TREE_TYPE (t));
19666 record_lambda_scope_discriminator (r);
19668 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
19669 determine_visibility (TYPE_NAME (type));
19671 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19673 tree oldtmpl = (generic_lambda_fn_p (oldfn)
19674 ? DECL_TI_TEMPLATE (oldfn)
19675 : NULL_TREE);
19677 tree tparms = NULL_TREE;
19678 if (oldtmpl)
19679 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
19681 tree fntype = static_fn_type (oldfn);
19683 tree saved_ctp = current_template_parms;
19684 if (oldtmpl)
19686 ++processing_template_decl;
19687 current_template_parms = tparms;
19689 fntype = tsubst (fntype, args, complain, in_decl);
19690 if (oldtmpl)
19692 current_template_parms = saved_ctp;
19693 --processing_template_decl;
19696 if (fntype == error_mark_node)
19697 r = error_mark_node;
19698 else
19700 /* The body of a lambda-expression is not a subexpression of the
19701 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
19702 which would be skipped if cp_unevaluated_operand. */
19703 cp_evaluated ev;
19705 /* Fix the type of 'this'.
19706 For static and xobj member functions we use this to transport the
19707 lambda's closure type. It appears that in the regular case the
19708 object parameter is still pulled off, and then re-added again anyway.
19709 So perhaps we could do something better here? */
19710 fntype = build_memfn_type (fntype, type,
19711 type_memfn_quals (fntype),
19712 type_memfn_rqual (fntype));
19713 tree inst = (oldtmpl
19714 ? tsubst_template_decl (oldtmpl, args, complain,
19715 fntype, tparms)
19716 : tsubst_function_decl (oldfn, args, complain, fntype));
19717 if (inst == error_mark_node)
19719 r = error_mark_node;
19720 goto out;
19722 finish_member_declaration (inst);
19723 record_lambda_scope_sig_discriminator (r, inst);
19725 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
19727 /* Let finish_function set this. */
19728 DECL_DECLARED_CONSTEXPR_P (fn) = false;
19730 bool nested = cfun;
19731 if (nested)
19732 push_function_context ();
19733 else
19734 /* Still increment function_depth so that we don't GC in the
19735 middle of an expression. */
19736 ++function_depth;
19738 local_specialization_stack s (lss_copy);
19740 bool save_in_consteval_if_p = in_consteval_if_p;
19741 in_consteval_if_p = false;
19743 tree body = start_lambda_function (fn, r);
19745 /* Now record them for lookup_init_capture_pack. */
19746 int fplen = vec_safe_length (field_packs);
19747 for (int i = 0; i < fplen; )
19749 tree pack = (*field_packs)[i++];
19750 tree inst = (*field_packs)[i++];
19751 register_local_specialization (inst, pack);
19753 release_tree_vector (field_packs);
19755 register_parameter_specializations (oldfn, fn);
19757 if (oldtmpl)
19759 /* We might not partially instantiate some parts of the function, so
19760 copy these flags from the original template. */
19761 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19762 current_function_returns_value = ol->returns_value;
19763 current_function_returns_null = ol->returns_null;
19764 current_function_returns_abnormally = ol->returns_abnormally;
19765 current_function_infinite_loop = ol->infinite_loop;
19768 /* [temp.deduct] A lambda-expression appearing in a function type or a
19769 template parameter is not considered part of the immediate context for
19770 the purposes of template argument deduction. */
19771 complain = tf_warning_or_error;
19773 tree saved = DECL_SAVED_TREE (oldfn);
19774 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19775 /* We already have a body block from start_lambda_function, we don't
19776 need another to confuse NRV (91217). */
19777 saved = BIND_EXPR_BODY (saved);
19779 tsubst_stmt (saved, args, complain, r);
19781 finish_lambda_function (body);
19783 in_consteval_if_p = save_in_consteval_if_p;
19785 if (nested)
19786 pop_function_context ();
19787 else
19788 --function_depth;
19790 /* The capture list was built up in reverse order; fix that now. */
19791 LAMBDA_EXPR_CAPTURE_LIST (r)
19792 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19794 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19796 maybe_add_lambda_conv_op (type);
19799 out:
19800 finish_struct (type, /*attr*/NULL_TREE);
19802 insert_pending_capture_proxies ();
19804 return r;
19807 /* Subroutine of maybe_fold_fn_template_args. */
19809 static bool
19810 fold_targs_r (tree targs, tsubst_flags_t complain)
19812 int len = TREE_VEC_LENGTH (targs);
19813 for (int i = 0; i < len; ++i)
19815 tree &elt = TREE_VEC_ELT (targs, i);
19816 if (!elt || TYPE_P (elt)
19817 || TREE_CODE (elt) == TEMPLATE_DECL)
19818 continue;
19819 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
19821 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
19822 return false;
19824 else if (/* We can only safely preevaluate scalar prvalues. */
19825 SCALAR_TYPE_P (TREE_TYPE (elt))
19826 && !glvalue_p (elt)
19827 && !TREE_CONSTANT (elt))
19829 elt = cxx_constant_value (elt, complain);
19830 if (elt == error_mark_node)
19831 return false;
19835 return true;
19838 /* Try to do constant evaluation of any explicit template arguments in FN
19839 before overload resolution, to get any errors only once. Return true iff
19840 we didn't have any problems folding. */
19842 static bool
19843 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
19845 if (processing_template_decl || fn == NULL_TREE)
19846 return true;
19847 if (fn == error_mark_node)
19848 return false;
19849 if (TREE_CODE (fn) == OFFSET_REF
19850 || TREE_CODE (fn) == COMPONENT_REF)
19851 fn = TREE_OPERAND (fn, 1);
19852 if (BASELINK_P (fn))
19853 fn = BASELINK_FUNCTIONS (fn);
19854 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
19855 return true;
19856 tree targs = TREE_OPERAND (fn, 1);
19857 if (targs == NULL_TREE)
19858 return true;
19859 if (targs == error_mark_node)
19860 return false;
19861 return fold_targs_r (targs, complain);
19864 /* Helper function for tsubst_expr CALL_EXPR and ARRAY_REF handling. */
19866 static void
19867 tsubst_call_args (tree t, tree args, tsubst_flags_t complain,
19868 tree in_decl, releasing_vec &call_args)
19870 unsigned int nargs = call_expr_nargs (t);
19871 for (unsigned int i = 0; i < nargs; ++i)
19873 tree arg = CALL_EXPR_ARG (t, i);
19875 if (!PACK_EXPANSION_P (arg))
19876 vec_safe_push (call_args, tsubst_expr (arg, args, complain, in_decl));
19877 else
19879 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
19880 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19881 if (TREE_CODE (arg) == TREE_VEC)
19883 unsigned int len, j;
19885 len = TREE_VEC_LENGTH (arg);
19886 for (j = 0; j < len; ++j)
19888 tree value = TREE_VEC_ELT (arg, j);
19889 if (value != NULL_TREE)
19890 value = convert_from_reference (value);
19891 vec_safe_push (call_args, value);
19894 else
19895 /* A partial substitution. Add one entry. */
19896 vec_safe_push (call_args, arg);
19901 /* Like tsubst but deals with expressions and performs semantic
19902 analysis. */
19904 tree
19905 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19907 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19908 #define RECUR(NODE) \
19909 tsubst_expr (NODE, args, complain, in_decl)
19911 tree retval, op1;
19912 location_t save_loc;
19914 if (t == NULL_TREE || t == error_mark_node)
19915 return t;
19917 save_loc = input_location;
19918 if (location_t eloc = cp_expr_location (t))
19919 input_location = eloc;
19921 /* N3276 decltype magic only applies to calls at the top level or on the
19922 right side of a comma. */
19923 tsubst_flags_t decltype_flag = (complain & tf_decltype);
19924 complain &= ~tf_decltype;
19926 /* This flag only applies to id-expressions at the top level, and
19927 controls resolution thereof. */
19928 tsubst_flags_t no_name_lookup_flag = (complain & tf_no_name_lookup);
19929 complain &= ~tf_no_name_lookup;
19931 if (!no_name_lookup_flag)
19932 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
19933 return d;
19935 switch (TREE_CODE (t))
19937 case USING_DECL:
19938 t = DECL_NAME (t);
19939 /* Fall through. */
19940 case IDENTIFIER_NODE:
19942 tree decl;
19943 cp_id_kind idk;
19944 const char *error_msg;
19946 if (IDENTIFIER_CONV_OP_P (t))
19948 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19949 t = make_conv_op_name (new_type);
19952 if (no_name_lookup_flag)
19953 RETURN (t);
19955 /* Look up the name. */
19956 decl = lookup_name (t);
19958 /* By convention, expressions use ERROR_MARK_NODE to indicate
19959 failure, not NULL_TREE. */
19960 if (decl == NULL_TREE)
19961 decl = error_mark_node;
19963 decl = finish_id_expression (t, decl, NULL_TREE,
19964 &idk,
19965 /*i_c_e_p=*/false,
19966 /*allow_i_c_e_p=*/true,
19967 /*non_i_c_e_p=*/nullptr,
19968 /*template_p=*/false,
19969 /*done=*/true,
19970 /*address_p=*/false,
19971 /*template_arg_p=*/false,
19972 &error_msg,
19973 input_location);
19974 if (error_msg)
19975 error (error_msg);
19976 if (identifier_p (decl))
19978 if (complain & tf_error)
19979 unqualified_name_lookup_error (decl);
19980 decl = error_mark_node;
19982 RETURN (decl);
19985 case TEMPLATE_ID_EXPR:
19987 tree object;
19988 tree templ = TREE_OPERAND (t, 0);
19989 tree targs = TREE_OPERAND (t, 1);
19991 if (no_name_lookup_flag)
19992 templ = tsubst_name (templ, args, complain, in_decl);
19993 else
19994 templ = tsubst_expr (templ, args, complain, in_decl);
19996 if (targs)
19997 targs = tsubst_template_args (targs, args, complain, in_decl);
19998 if (targs == error_mark_node)
19999 RETURN (error_mark_node);
20001 if (TREE_CODE (templ) == SCOPE_REF)
20003 tree name = TREE_OPERAND (templ, 1);
20004 tree tid = lookup_template_function (name, targs);
20005 TREE_OPERAND (templ, 1) = tid;
20006 RETURN (templ);
20009 if (concept_definition_p (templ))
20011 tree check = build_concept_check (templ, targs, complain);
20012 if (check == error_mark_node)
20013 RETURN (error_mark_node);
20015 tree id = unpack_concept_check (check);
20017 /* If we built a function concept check, return the underlying
20018 template-id. So we can evaluate it as a function call. */
20019 if (function_concept_p (TREE_OPERAND (id, 0)))
20020 RETURN (id);
20022 RETURN (check);
20025 if (variable_template_p (templ))
20027 if (no_name_lookup_flag)
20028 RETURN (lookup_template_variable (templ, targs, complain));
20030 tree r = lookup_and_finish_template_variable (templ, targs,
20031 complain);
20032 r = convert_from_reference (r);
20033 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20034 RETURN (r);
20037 if (TREE_CODE (templ) == COMPONENT_REF)
20039 object = TREE_OPERAND (templ, 0);
20040 templ = TREE_OPERAND (templ, 1);
20042 else
20043 object = NULL_TREE;
20045 tree tid = lookup_template_function (templ, targs);
20046 protected_set_expr_location (tid, EXPR_LOCATION (t));
20048 if (object)
20049 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20050 object, tid, NULL_TREE));
20051 else if (no_name_lookup_flag)
20052 RETURN (tid);
20053 else if (identifier_p (templ))
20055 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20056 name lookup found nothing when parsing the template name. */
20057 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20058 RETURN (tid);
20060 else
20061 RETURN (baselink_for_fns (tid));
20064 case INDIRECT_REF:
20066 tree r = RECUR (TREE_OPERAND (t, 0));
20068 if (REFERENCE_REF_P (t))
20070 /* A type conversion to reference type will be enclosed in
20071 such an indirect ref, but the substitution of the cast
20072 will have also added such an indirect ref. */
20073 r = convert_from_reference (r);
20075 else
20076 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20077 templated_operator_saved_lookups (t),
20078 complain|decltype_flag);
20080 if (REF_PARENTHESIZED_P (t))
20081 r = force_paren_expr (r);
20083 RETURN (r);
20086 case NOP_EXPR:
20088 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20089 tree op0 = RECUR (TREE_OPERAND (t, 0));
20090 RETURN (build_nop (type, op0));
20093 case IMPLICIT_CONV_EXPR:
20095 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20096 tree expr = RECUR (TREE_OPERAND (t, 0));
20097 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20099 retval = copy_node (t);
20100 TREE_TYPE (retval) = type;
20101 TREE_OPERAND (retval, 0) = expr;
20102 RETURN (retval);
20104 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20106 tree r = convert_nontype_argument (type, expr, complain);
20107 if (r == NULL_TREE)
20108 r = error_mark_node;
20109 RETURN (r);
20111 int flags = LOOKUP_IMPLICIT;
20112 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20113 flags = LOOKUP_NORMAL;
20114 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20115 flags |= LOOKUP_NO_NARROWING;
20116 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20117 flags));
20120 case CONVERT_EXPR:
20122 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20123 tree op0 = RECUR (TREE_OPERAND (t, 0));
20124 if (op0 == error_mark_node)
20125 RETURN (error_mark_node);
20126 RETURN (build1 (CONVERT_EXPR, type, op0));
20129 case CAST_EXPR:
20130 case REINTERPRET_CAST_EXPR:
20131 case CONST_CAST_EXPR:
20132 case DYNAMIC_CAST_EXPR:
20133 case STATIC_CAST_EXPR:
20135 tree type;
20136 tree op, r = NULL_TREE;
20138 tsubst_flags_t tcomplain = complain;
20139 if (TREE_CODE (t) == CAST_EXPR)
20140 tcomplain |= tf_tst_ok;
20141 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20143 op = RECUR (TREE_OPERAND (t, 0));
20145 warning_sentinel s(warn_useless_cast);
20146 warning_sentinel s2(warn_ignored_qualifiers);
20147 warning_sentinel s3(warn_int_in_bool_context);
20148 switch (TREE_CODE (t))
20150 case CAST_EXPR:
20151 r = build_functional_cast (input_location, type, op, complain);
20152 break;
20153 case REINTERPRET_CAST_EXPR:
20154 r = build_reinterpret_cast (input_location, type, op, complain);
20155 break;
20156 case CONST_CAST_EXPR:
20157 r = build_const_cast (input_location, type, op, complain);
20158 break;
20159 case DYNAMIC_CAST_EXPR:
20160 r = build_dynamic_cast (input_location, type, op, complain);
20161 break;
20162 case STATIC_CAST_EXPR:
20163 r = build_static_cast (input_location, type, op, complain);
20164 if (IMPLICIT_RVALUE_P (t))
20165 set_implicit_rvalue_p (r);
20166 break;
20167 default:
20168 gcc_unreachable ();
20171 RETURN (r);
20174 case BIT_CAST_EXPR:
20176 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20177 tree op0 = RECUR (TREE_OPERAND (t, 0));
20178 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20181 case POSTDECREMENT_EXPR:
20182 case POSTINCREMENT_EXPR:
20183 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20184 args, complain, in_decl);
20185 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20186 templated_operator_saved_lookups (t),
20187 complain|decltype_flag));
20189 case BIT_NOT_EXPR:
20190 if (identifier_p (TREE_OPERAND (t, 0)))
20192 gcc_checking_assert (no_name_lookup_flag);
20193 RETURN (t);
20195 else if (TYPE_P (TREE_OPERAND (t, 0)))
20197 gcc_checking_assert (no_name_lookup_flag);
20198 tree op0 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
20199 RETURN (build_min_nt_loc (EXPR_LOCATION (t), BIT_NOT_EXPR, op0));
20201 /* Fall through. */
20202 case PREDECREMENT_EXPR:
20203 case PREINCREMENT_EXPR:
20204 case NEGATE_EXPR:
20205 case ABS_EXPR:
20206 case TRUTH_NOT_EXPR:
20207 case UNARY_PLUS_EXPR: /* Unary + */
20208 case REALPART_EXPR:
20209 case IMAGPART_EXPR:
20210 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20211 RECUR (TREE_OPERAND (t, 0)),
20212 templated_operator_saved_lookups (t),
20213 complain|decltype_flag));
20215 case EXCESS_PRECISION_EXPR:
20217 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20218 tree op0 = RECUR (TREE_OPERAND (t, 0));
20219 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20220 RETURN (op0);
20221 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20222 type, op0));
20225 case FIX_TRUNC_EXPR:
20226 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20227 gcc_unreachable ();
20229 case ADDR_EXPR:
20230 op1 = TREE_OPERAND (t, 0);
20231 if (TREE_CODE (op1) == LABEL_DECL)
20232 RETURN (finish_label_address_expr (DECL_NAME (op1),
20233 EXPR_LOCATION (op1)));
20234 if (TREE_CODE (op1) == SCOPE_REF)
20235 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20236 /*done=*/true, /*address_p=*/true);
20237 else
20238 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20239 in_decl);
20240 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20241 templated_operator_saved_lookups (t),
20242 complain|decltype_flag));
20244 case PLUS_EXPR:
20245 case MINUS_EXPR:
20246 case MULT_EXPR:
20247 case TRUNC_DIV_EXPR:
20248 case CEIL_DIV_EXPR:
20249 case FLOOR_DIV_EXPR:
20250 case ROUND_DIV_EXPR:
20251 case EXACT_DIV_EXPR:
20252 case BIT_AND_EXPR:
20253 case BIT_IOR_EXPR:
20254 case BIT_XOR_EXPR:
20255 case TRUNC_MOD_EXPR:
20256 case FLOOR_MOD_EXPR:
20257 case TRUTH_ANDIF_EXPR:
20258 case TRUTH_ORIF_EXPR:
20259 case TRUTH_AND_EXPR:
20260 case TRUTH_OR_EXPR:
20261 case RSHIFT_EXPR:
20262 case LSHIFT_EXPR:
20263 case EQ_EXPR:
20264 case NE_EXPR:
20265 case MAX_EXPR:
20266 case MIN_EXPR:
20267 case LE_EXPR:
20268 case GE_EXPR:
20269 case LT_EXPR:
20270 case GT_EXPR:
20271 case SPACESHIP_EXPR:
20272 case MEMBER_REF:
20273 case DOTSTAR_EXPR:
20275 /* If either OP0 or OP1 was value- or type-dependent, suppress
20276 warnings that depend on the range of the types involved. */
20277 tree op0 = TREE_OPERAND (t, 0);
20278 tree op1 = TREE_OPERAND (t, 1);
20279 const bool was_dep = (dependent_operand_p (op0)
20280 || dependent_operand_p (op1));
20281 op0 = RECUR (op0);
20282 op1 = RECUR (op1);
20284 warning_sentinel s1(warn_type_limits, was_dep);
20285 warning_sentinel s2(warn_div_by_zero, was_dep);
20286 warning_sentinel s3(warn_logical_op, was_dep);
20287 warning_sentinel s4(warn_tautological_compare, was_dep);
20288 warning_sentinel s5(warn_address, was_dep);
20290 tree r = build_x_binary_op
20291 (input_location, TREE_CODE (t),
20292 op0,
20293 (warning_suppressed_p (TREE_OPERAND (t, 0))
20294 ? ERROR_MARK
20295 : TREE_CODE (TREE_OPERAND (t, 0))),
20296 op1,
20297 (warning_suppressed_p (TREE_OPERAND (t, 1))
20298 ? ERROR_MARK
20299 : TREE_CODE (TREE_OPERAND (t, 1))),
20300 templated_operator_saved_lookups (t),
20301 /*overload=*/NULL,
20302 complain|decltype_flag);
20303 if (EXPR_P (r))
20304 copy_warning (r, t);
20306 RETURN (r);
20309 case POINTER_PLUS_EXPR:
20311 tree op0 = RECUR (TREE_OPERAND (t, 0));
20312 if (op0 == error_mark_node)
20313 RETURN (error_mark_node);
20314 tree op1 = RECUR (TREE_OPERAND (t, 1));
20315 if (op1 == error_mark_node)
20316 RETURN (error_mark_node);
20317 RETURN (fold_build_pointer_plus (op0, op1));
20320 case SCOPE_REF:
20321 if (no_name_lookup_flag)
20323 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
20324 tree op1 = tsubst_name (TREE_OPERAND (t, 1), args, complain, in_decl);
20325 RETURN (build_qualified_name (/*type=*/NULL_TREE, op0, op1,
20326 QUALIFIED_NAME_IS_TEMPLATE (t)));
20328 else
20329 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20330 /*address_p=*/false));
20332 case BASELINK:
20333 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20334 args, complain, in_decl));
20336 case ARRAY_REF:
20337 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20338 args, complain, in_decl);
20339 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20340 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20341 == ovl_op_identifier (ARRAY_REF)))
20343 tree c = TREE_OPERAND (t, 1);
20344 releasing_vec index_exp_list;
20345 tsubst_call_args (c, args, complain, in_decl, index_exp_list);
20347 tree r;
20348 if (vec_safe_length (index_exp_list) == 1
20349 && !PACK_EXPANSION_P (index_exp_list[0]))
20350 r = grok_array_decl (EXPR_LOCATION (t), op1,
20351 index_exp_list[0], NULL,
20352 complain | decltype_flag);
20353 else
20354 r = grok_array_decl (EXPR_LOCATION (t), op1,
20355 NULL_TREE, &index_exp_list,
20356 complain | decltype_flag);
20357 RETURN (r);
20359 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20360 RECUR (TREE_OPERAND (t, 1)),
20361 complain|decltype_flag));
20363 case OMP_ARRAY_SECTION:
20365 tree op0 = RECUR (TREE_OPERAND (t, 0));
20366 tree op1 = NULL_TREE, op2 = NULL_TREE;
20367 if (op0 == error_mark_node)
20368 RETURN (error_mark_node);
20369 if (TREE_OPERAND (t, 1))
20371 op1 = RECUR (TREE_OPERAND (t, 1));
20372 if (op1 == error_mark_node)
20373 RETURN (error_mark_node);
20375 if (TREE_OPERAND (t, 2))
20377 op2 = RECUR (TREE_OPERAND (t, 2));
20378 if (op2 == error_mark_node)
20379 RETURN (error_mark_node);
20381 RETURN (build_omp_array_section (EXPR_LOCATION (t), op0, op1, op2));
20384 case SIZEOF_EXPR:
20385 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20386 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20388 tree expanded, op = TREE_OPERAND (t, 0);
20389 int len = 0;
20391 if (SIZEOF_EXPR_TYPE_P (t))
20392 op = TREE_TYPE (op);
20394 ++cp_unevaluated_operand;
20395 ++c_inhibit_evaluation_warnings;
20396 /* We only want to compute the number of arguments. */
20397 if (PACK_EXPANSION_P (op))
20398 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
20399 else
20400 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
20401 args, complain, in_decl);
20402 --cp_unevaluated_operand;
20403 --c_inhibit_evaluation_warnings;
20405 if (TREE_CODE (expanded) == TREE_VEC)
20407 len = TREE_VEC_LENGTH (expanded);
20408 /* Set TREE_USED for the benefit of -Wunused. */
20409 for (int i = 0; i < len; i++)
20410 if (DECL_P (TREE_VEC_ELT (expanded, i)))
20411 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
20414 if (expanded == error_mark_node)
20415 RETURN (error_mark_node);
20416 else if (PACK_EXPANSION_P (expanded)
20417 || (TREE_CODE (expanded) == TREE_VEC
20418 && pack_expansion_args_count (expanded)))
20421 if (PACK_EXPANSION_P (expanded))
20422 /* OK. */;
20423 else
20424 expanded = make_argument_pack (expanded);
20426 if (TYPE_P (expanded))
20427 RETURN (cxx_sizeof_or_alignof_type (input_location,
20428 expanded, SIZEOF_EXPR,
20429 false,
20430 complain & tf_error));
20431 else
20432 RETURN (cxx_sizeof_or_alignof_expr (input_location,
20433 expanded, SIZEOF_EXPR,
20434 false,
20435 complain & tf_error));
20437 else
20438 RETURN (build_int_cst (size_type_node, len));
20440 /* Fall through */
20442 case ALIGNOF_EXPR:
20444 tree r;
20446 op1 = TREE_OPERAND (t, 0);
20447 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20448 op1 = TREE_TYPE (op1);
20449 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20450 && ALIGNOF_EXPR_STD_P (t));
20451 if (!args)
20453 /* When there are no ARGS, we are trying to evaluate a
20454 non-dependent expression from the parser. Trying to do
20455 the substitutions may not work. */
20456 if (!TYPE_P (op1))
20457 op1 = TREE_TYPE (op1);
20459 else
20461 ++cp_unevaluated_operand;
20462 ++c_inhibit_evaluation_warnings;
20463 if (TYPE_P (op1))
20464 op1 = tsubst (op1, args, complain, in_decl);
20465 else
20466 op1 = tsubst_expr (op1, args, complain, in_decl);
20467 --cp_unevaluated_operand;
20468 --c_inhibit_evaluation_warnings;
20470 if (TYPE_P (op1))
20471 r = cxx_sizeof_or_alignof_type (input_location,
20472 op1, TREE_CODE (t), std_alignof,
20473 complain & tf_error);
20474 else
20475 r = cxx_sizeof_or_alignof_expr (input_location,
20476 op1, TREE_CODE (t), std_alignof,
20477 complain & tf_error);
20478 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20480 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20482 if (!processing_template_decl && TYPE_P (op1))
20484 r = build_min (SIZEOF_EXPR, size_type_node,
20485 build1 (NOP_EXPR, op1, error_mark_node));
20486 SIZEOF_EXPR_TYPE_P (r) = 1;
20488 else
20489 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20490 TREE_SIDE_EFFECTS (r) = 0;
20491 TREE_READONLY (r) = 1;
20493 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20495 RETURN (r);
20498 case AT_ENCODE_EXPR:
20500 op1 = TREE_OPERAND (t, 0);
20501 ++cp_unevaluated_operand;
20502 ++c_inhibit_evaluation_warnings;
20503 op1 = tsubst (op1, args, complain, in_decl);
20504 --cp_unevaluated_operand;
20505 --c_inhibit_evaluation_warnings;
20506 RETURN (objc_build_encode_expr (op1));
20509 case NOEXCEPT_EXPR:
20510 op1 = TREE_OPERAND (t, 0);
20511 ++cp_unevaluated_operand;
20512 ++c_inhibit_evaluation_warnings;
20513 ++cp_noexcept_operand;
20514 op1 = tsubst_expr (op1, args, complain, in_decl);
20515 --cp_unevaluated_operand;
20516 --c_inhibit_evaluation_warnings;
20517 --cp_noexcept_operand;
20518 RETURN (finish_noexcept_expr (op1, complain));
20520 case MODOP_EXPR:
20522 warning_sentinel s(warn_div_by_zero);
20523 tree lhs = RECUR (TREE_OPERAND (t, 0));
20524 tree rhs = RECUR (TREE_OPERAND (t, 2));
20526 tree r = build_x_modify_expr
20527 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20528 templated_operator_saved_lookups (t),
20529 complain|decltype_flag);
20530 /* TREE_NO_WARNING must be set if either the expression was
20531 parenthesized or it uses an operator such as >>= rather
20532 than plain assignment. In the former case, it was already
20533 set and must be copied. In the latter case,
20534 build_x_modify_expr sets it and it must not be reset
20535 here. */
20536 if (warning_suppressed_p (t, OPT_Wparentheses))
20537 suppress_warning (STRIP_REFERENCE_REF (r), OPT_Wparentheses);
20539 RETURN (r);
20542 case ARROW_EXPR:
20543 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20544 args, complain, in_decl);
20545 /* Remember that there was a reference to this entity. */
20546 if (DECL_P (op1)
20547 && !mark_used (op1, complain) && !(complain & tf_error))
20548 RETURN (error_mark_node);
20549 RETURN (build_x_arrow (input_location, op1, complain));
20551 case NEW_EXPR:
20553 tree placement = RECUR (TREE_OPERAND (t, 0));
20554 tree init = RECUR (TREE_OPERAND (t, 3));
20555 vec<tree, va_gc> *placement_vec;
20556 vec<tree, va_gc> *init_vec;
20557 tree ret;
20558 location_t loc = EXPR_LOCATION (t);
20560 if (placement == NULL_TREE)
20561 placement_vec = NULL;
20562 else if (placement == error_mark_node)
20563 RETURN (error_mark_node);
20564 else
20566 placement_vec = make_tree_vector ();
20567 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20568 vec_safe_push (placement_vec, TREE_VALUE (placement));
20571 /* If there was an initializer in the original tree, but it
20572 instantiated to an empty list, then we should pass a
20573 non-NULL empty vector to tell build_new that it was an
20574 empty initializer() rather than no initializer. This can
20575 only happen when the initializer is a pack expansion whose
20576 parameter packs are of length zero. */
20577 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20578 init_vec = NULL;
20579 else if (init == error_mark_node)
20580 RETURN (error_mark_node);
20581 else
20583 init_vec = make_tree_vector ();
20584 if (init == void_node)
20585 gcc_assert (init_vec != NULL);
20586 else
20588 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20589 vec_safe_push (init_vec, TREE_VALUE (init));
20593 /* Avoid passing an enclosing decl to valid_array_size_p. */
20594 in_decl = NULL_TREE;
20596 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20597 tree op2 = RECUR (TREE_OPERAND (t, 2));
20598 ret = build_new (loc, &placement_vec, op1, op2,
20599 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20600 complain);
20602 if (placement_vec != NULL)
20603 release_tree_vector (placement_vec);
20604 if (init_vec != NULL)
20605 release_tree_vector (init_vec);
20607 RETURN (ret);
20610 case DELETE_EXPR:
20612 tree op0 = RECUR (TREE_OPERAND (t, 0));
20613 tree op1 = RECUR (TREE_OPERAND (t, 1));
20614 RETURN (delete_sanity (input_location, op0, op1,
20615 DELETE_EXPR_USE_VEC (t),
20616 DELETE_EXPR_USE_GLOBAL (t),
20617 complain));
20620 case COMPOUND_EXPR:
20622 tree op0 = tsubst_expr (TREE_OPERAND (t, 0), args,
20623 complain & ~tf_decltype, in_decl);
20624 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20625 op0,
20626 RECUR (TREE_OPERAND (t, 1)),
20627 templated_operator_saved_lookups (t),
20628 complain|decltype_flag));
20631 case CALL_EXPR:
20633 tree function;
20634 unsigned int nargs;
20635 bool qualified_p;
20636 bool koenig_p;
20637 tree ret;
20639 function = CALL_EXPR_FN (t);
20640 /* Internal function with no arguments. */
20641 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20642 RETURN (t);
20644 /* When we parsed the expression, we determined whether or
20645 not Koenig lookup should be performed. */
20646 koenig_p = KOENIG_LOOKUP_P (t);
20647 if (function == NULL_TREE)
20649 koenig_p = false;
20650 qualified_p = false;
20652 else if (TREE_CODE (function) == SCOPE_REF)
20654 qualified_p = true;
20655 function = tsubst_qualified_id (function, args, complain, in_decl,
20656 /*done=*/false,
20657 /*address_p=*/false);
20659 else if (CALL_EXPR_STATIC_CHAIN (t)
20660 && TREE_CODE (function) == FUNCTION_DECL
20661 && fndecl_built_in_p (function, BUILT_IN_CLASSIFY_TYPE))
20663 tree type = tsubst (CALL_EXPR_STATIC_CHAIN (t), args, complain,
20664 in_decl);
20665 if (dependent_type_p (type))
20667 ret = build_vl_exp (CALL_EXPR, 4);
20668 CALL_EXPR_FN (ret) = function;
20669 CALL_EXPR_STATIC_CHAIN (ret) = type;
20670 CALL_EXPR_ARG (ret, 0)
20671 = build_min (SIZEOF_EXPR, size_type_node, type);
20672 TREE_TYPE (ret) = integer_type_node;
20674 else
20675 ret = build_int_cst (integer_type_node, type_to_class (type));
20676 RETURN (ret);
20678 else if (koenig_p
20679 && (identifier_p (function)
20680 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20681 && identifier_p (TREE_OPERAND (function, 0)))))
20683 /* Do nothing; calling tsubst_expr on an identifier
20684 would incorrectly perform unqualified lookup again.
20686 Note that we can also have an IDENTIFIER_NODE if the earlier
20687 unqualified lookup found a dependent local extern declaration
20688 (as per finish_call_expr); in that case koenig_p will be false
20689 and we do want to do the lookup again to find the substituted
20690 declaration. */
20691 qualified_p = false;
20693 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20694 function = tsubst_name (function, args, complain, in_decl);
20696 else
20698 if (TREE_CODE (function) == COMPONENT_REF)
20700 tree op = TREE_OPERAND (function, 1);
20702 qualified_p = (TREE_CODE (op) == SCOPE_REF
20703 || (BASELINK_P (op)
20704 && BASELINK_QUALIFIED_P (op)));
20706 else
20707 qualified_p = false;
20709 if (TREE_CODE (function) == ADDR_EXPR
20710 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20711 /* Avoid error about taking the address of a constructor. */
20712 function = TREE_OPERAND (function, 0);
20714 tsubst_flags_t subcomplain = complain;
20715 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20716 /* When KOENIG_P, we don't want to mark_used the callee before
20717 augmenting the overload set via ADL, so during this initial
20718 substitution we disable mark_used by setting tf_conv (68942). */
20719 subcomplain |= tf_conv;
20720 function = tsubst_expr (function, args, subcomplain, in_decl);
20722 if (BASELINK_P (function))
20723 qualified_p = true;
20726 nargs = call_expr_nargs (t);
20727 releasing_vec call_args;
20728 tsubst_call_args (t, args, complain, in_decl, call_args);
20730 /* Stripped-down processing for a call in a thunk. Specifically, in
20731 the thunk template for a generic lambda. */
20732 if (call_from_lambda_thunk_p (t))
20734 /* Now that we've expanded any packs, the number of call args
20735 might be different. */
20736 unsigned int cargs = call_args->length ();
20737 tree thisarg = NULL_TREE;
20738 if (TREE_CODE (function) == COMPONENT_REF)
20740 thisarg = TREE_OPERAND (function, 0);
20741 if (TREE_CODE (thisarg) == INDIRECT_REF)
20742 thisarg = TREE_OPERAND (thisarg, 0);
20743 function = TREE_OPERAND (function, 1);
20744 if (TREE_CODE (function) == BASELINK)
20745 function = BASELINK_FUNCTIONS (function);
20747 /* We aren't going to do normal overload resolution, so force the
20748 template-id to resolve. */
20749 function = resolve_nondeduced_context (function, complain);
20750 for (unsigned i = 0; i < cargs; ++i)
20752 /* In a thunk, pass through args directly, without any
20753 conversions. */
20754 tree arg = (*call_args)[i];
20755 while (TREE_CODE (arg) != PARM_DECL)
20756 arg = TREE_OPERAND (arg, 0);
20757 (*call_args)[i] = arg;
20759 if (thisarg)
20761 /* If there are no other args, just push 'this'. */
20762 if (cargs == 0)
20763 vec_safe_push (call_args, thisarg);
20764 else
20766 /* Otherwise, shift the other args over to make room. */
20767 tree last = (*call_args)[cargs - 1];
20768 vec_safe_push (call_args, last);
20769 for (int i = cargs - 1; i > 0; --i)
20770 (*call_args)[i] = (*call_args)[i - 1];
20771 (*call_args)[0] = thisarg;
20774 ret = build_call_a (function, call_args->length (),
20775 call_args->address ());
20776 /* The thunk location is not interesting. */
20777 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20778 CALL_FROM_THUNK_P (ret) = true;
20779 if (CLASS_TYPE_P (TREE_TYPE (ret)))
20780 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20782 RETURN (ret);
20785 /* We do not perform argument-dependent lookup if normal
20786 lookup finds a non-function, in accordance with the
20787 resolution of DR 218. */
20788 if (koenig_p
20789 && ((is_overloaded_fn (function)
20790 /* If lookup found a member function, the Koenig lookup is
20791 not appropriate, even if an unqualified-name was used
20792 to denote the function. */
20793 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20794 || identifier_p (function)
20795 /* C++20 P0846: Lookup found nothing. */
20796 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20797 && identifier_p (TREE_OPERAND (function, 0))))
20798 /* Only do this when substitution turns a dependent call
20799 into a non-dependent call. */
20800 && type_dependent_expression_p_push (t)
20801 && !any_type_dependent_arguments_p (call_args))
20802 function = perform_koenig_lookup (function, call_args, tf_none);
20804 if (function != NULL_TREE
20805 && (identifier_p (function)
20806 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20807 && identifier_p (TREE_OPERAND (function, 0))
20808 && !any_dependent_template_arguments_p (TREE_OPERAND
20809 (function, 1))))
20810 && !any_type_dependent_arguments_p (call_args))
20812 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
20813 if (template_id_p)
20814 function = TREE_OPERAND (function, 0);
20815 if (koenig_p && (complain & tf_warning_or_error))
20817 /* For backwards compatibility and good diagnostics, try
20818 the unqualified lookup again if we aren't in SFINAE
20819 context. */
20820 tree unq = tsubst_expr (function, args, complain, in_decl);
20821 if (unq == error_mark_node)
20822 RETURN (error_mark_node);
20824 if (unq != function)
20826 char const *const msg
20827 = G_("%qD was not declared in this scope, "
20828 "and no declarations were found by "
20829 "argument-dependent lookup at the point "
20830 "of instantiation");
20832 bool in_lambda = (current_class_type
20833 && LAMBDA_TYPE_P (current_class_type));
20834 /* In a lambda fn, we have to be careful to not
20835 introduce new this captures. Legacy code can't
20836 be using lambdas anyway, so it's ok to be
20837 stricter. Be strict with C++20 template-id ADL too.
20838 And be strict if we're already failing anyway. */
20839 bool strict = in_lambda || template_id_p || seen_error();
20840 bool diag = true;
20841 if (strict)
20842 error_at (cp_expr_loc_or_input_loc (t),
20843 msg, function);
20844 else
20845 diag = permerror (cp_expr_loc_or_input_loc (t),
20846 msg, function);
20847 if (diag)
20849 tree fn = unq;
20851 if (INDIRECT_REF_P (fn))
20852 fn = TREE_OPERAND (fn, 0);
20853 if (is_overloaded_fn (fn))
20854 fn = get_first_fn (fn);
20856 if (!DECL_P (fn))
20857 /* Can't say anything more. */;
20858 else if (DECL_CLASS_SCOPE_P (fn))
20860 location_t loc = cp_expr_loc_or_input_loc (t);
20861 inform (loc,
20862 "declarations in dependent base %qT are "
20863 "not found by unqualified lookup",
20864 DECL_CLASS_CONTEXT (fn));
20865 if (current_class_ptr)
20866 inform (loc,
20867 "use %<this->%D%> instead", function);
20868 else
20869 inform (loc,
20870 "use %<%T::%D%> instead",
20871 current_class_name, function);
20873 else
20874 inform (DECL_SOURCE_LOCATION (fn),
20875 "%qD declared here, later in the "
20876 "translation unit", fn);
20877 if (strict)
20878 RETURN (error_mark_node);
20881 function = unq;
20884 if (identifier_p (function))
20886 if (complain & tf_error)
20887 unqualified_name_lookup_error (function);
20888 RETURN (error_mark_node);
20892 /* Remember that there was a reference to this entity. */
20893 if (function != NULL_TREE
20894 && DECL_P (function)
20895 && !mark_used (function, complain) && !(complain & tf_error))
20896 RETURN (error_mark_node);
20898 if (!maybe_fold_fn_template_args (function, complain))
20899 return error_mark_node;
20901 /* Put back tf_decltype for the actual call. */
20902 complain |= decltype_flag;
20904 if (function == NULL_TREE)
20905 switch (CALL_EXPR_IFN (t))
20907 case IFN_LAUNDER:
20908 gcc_assert (nargs == 1);
20909 if (vec_safe_length (call_args) != 1)
20911 error_at (cp_expr_loc_or_input_loc (t),
20912 "wrong number of arguments to "
20913 "%<__builtin_launder%>");
20914 ret = error_mark_node;
20916 else
20917 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20918 (*call_args)[0], complain);
20919 break;
20921 case IFN_VEC_CONVERT:
20922 gcc_assert (nargs == 1);
20923 if (vec_safe_length (call_args) != 1)
20925 error_at (cp_expr_loc_or_input_loc (t),
20926 "wrong number of arguments to "
20927 "%<__builtin_convertvector%>");
20928 ret = error_mark_node;
20929 break;
20931 ret = cp_build_vec_convert ((*call_args)[0], input_location,
20932 tsubst (TREE_TYPE (t), args,
20933 complain, in_decl),
20934 complain);
20935 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20936 RETURN (ret);
20937 break;
20939 case IFN_SHUFFLEVECTOR:
20941 ret = build_x_shufflevector (input_location, call_args,
20942 complain);
20943 if (ret != error_mark_node)
20944 RETURN (ret);
20945 break;
20948 case IFN_ASSUME:
20949 gcc_assert (nargs == 1);
20950 if (vec_safe_length (call_args) != 1)
20952 error_at (cp_expr_loc_or_input_loc (t),
20953 "wrong number of arguments to "
20954 "%<assume%> attribute");
20955 ret = error_mark_node;
20957 else
20959 tree &arg = (*call_args)[0];
20960 if (!type_dependent_expression_p (arg))
20961 arg = contextual_conv_bool (arg, tf_warning_or_error);
20962 if (error_operand_p (arg))
20964 ret = error_mark_node;
20965 break;
20967 ret = build_assume_call (EXPR_LOCATION (t), arg);
20968 RETURN (ret);
20970 break;
20972 default:
20973 /* Unsupported internal function with arguments. */
20974 gcc_unreachable ();
20976 else if (TREE_CODE (function) == OFFSET_REF
20977 || TREE_CODE (function) == DOTSTAR_EXPR
20978 || TREE_CODE (function) == MEMBER_REF)
20979 ret = build_offset_ref_call_from_tree (function, &call_args,
20980 complain);
20981 else if (concept_check_p (function))
20983 /* FUNCTION is a template-id referring to a concept definition. */
20984 tree id = unpack_concept_check (function);
20985 tree tmpl = TREE_OPERAND (id, 0);
20986 tree args = TREE_OPERAND (id, 1);
20988 /* Calls to standard and variable concepts should have been
20989 previously diagnosed. */
20990 gcc_assert (function_concept_p (tmpl));
20992 /* Ensure the result is wrapped as a call expression. */
20993 ret = build_concept_check (tmpl, args, tf_warning_or_error);
20995 else
20996 ret = finish_call_expr (function, &call_args,
20997 /*disallow_virtual=*/qualified_p,
20998 koenig_p,
20999 complain);
21001 if (ret != error_mark_node)
21003 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21004 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21005 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21006 if (op || ord || rev)
21007 if (tree call = extract_call_expr (ret))
21009 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21010 CALL_EXPR_ORDERED_ARGS (call) = ord;
21011 CALL_EXPR_REVERSE_ARGS (call) = rev;
21013 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21014 /* This also suppresses -Wredundant-move. */
21015 suppress_warning (ret, OPT_Wpessimizing_move);
21018 RETURN (ret);
21021 case COND_EXPR:
21023 tree cond = RECUR (TREE_OPERAND (t, 0));
21024 cond = mark_rvalue_use (cond);
21025 tree folded_cond = fold_non_dependent_expr (cond, complain);
21026 tree exp1, exp2;
21028 if (TREE_CODE (folded_cond) == INTEGER_CST)
21030 if (integer_zerop (folded_cond))
21032 ++c_inhibit_evaluation_warnings;
21033 exp1 = RECUR (TREE_OPERAND (t, 1));
21034 --c_inhibit_evaluation_warnings;
21035 exp2 = RECUR (TREE_OPERAND (t, 2));
21037 else
21039 exp1 = RECUR (TREE_OPERAND (t, 1));
21040 ++c_inhibit_evaluation_warnings;
21041 exp2 = RECUR (TREE_OPERAND (t, 2));
21042 --c_inhibit_evaluation_warnings;
21044 cond = folded_cond;
21046 else
21048 exp1 = RECUR (TREE_OPERAND (t, 1));
21049 exp2 = RECUR (TREE_OPERAND (t, 2));
21052 warning_sentinel s(warn_duplicated_branches);
21053 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21054 cond, exp1, exp2, complain));
21057 case PSEUDO_DTOR_EXPR:
21059 tree op0 = RECUR (TREE_OPERAND (t, 0));
21060 tree op1 = RECUR (TREE_OPERAND (t, 1));
21061 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21062 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21063 input_location));
21066 case TREE_LIST:
21067 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21069 case COMPONENT_REF:
21071 tree object;
21072 tree object_type;
21073 tree member;
21074 tree r;
21076 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21077 args, complain, in_decl);
21078 /* Remember that there was a reference to this entity. */
21079 if (DECL_P (object)
21080 && !mark_used (object, complain) && !(complain & tf_error))
21081 RETURN (error_mark_node);
21082 object_type = TREE_TYPE (object);
21084 member = TREE_OPERAND (t, 1);
21085 if (BASELINK_P (member))
21086 member = tsubst_baselink (member,
21087 non_reference (TREE_TYPE (object)),
21088 args, complain, in_decl);
21089 else
21090 member = tsubst_name (member, args, complain, in_decl);
21091 if (member == error_mark_node)
21092 RETURN (error_mark_node);
21094 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21095 && TREE_CODE (member) == FIELD_DECL)
21097 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21098 RETURN (r);
21100 else if (TREE_CODE (member) == FIELD_DECL)
21102 r = finish_non_static_data_member (member, object, NULL_TREE,
21103 complain);
21104 if (TREE_CODE (r) == COMPONENT_REF)
21105 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21106 RETURN (r);
21108 else if (type_dependent_expression_p (object))
21109 /* We can't do much here. */;
21110 else if (!CLASS_TYPE_P (object_type))
21112 if (scalarish_type_p (object_type))
21114 tree s = NULL_TREE;
21115 tree dtor = member;
21117 if (TREE_CODE (dtor) == SCOPE_REF)
21119 s = TREE_OPERAND (dtor, 0);
21120 dtor = TREE_OPERAND (dtor, 1);
21122 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21124 dtor = TREE_OPERAND (dtor, 0);
21125 if (TYPE_P (dtor))
21126 RETURN (finish_pseudo_destructor_expr
21127 (object, s, dtor, input_location));
21131 else if (TREE_CODE (member) == SCOPE_REF
21132 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21134 /* Lookup the template functions now that we know what the
21135 scope is. */
21136 tree scope = TREE_OPERAND (member, 0);
21137 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21138 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21139 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21140 /*complain=*/false);
21141 if (BASELINK_P (member))
21143 BASELINK_FUNCTIONS (member)
21144 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21145 args);
21146 member = (adjust_result_of_qualified_name_lookup
21147 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21148 object_type));
21150 else
21152 qualified_name_lookup_error (scope, tmpl, member,
21153 input_location);
21154 RETURN (error_mark_node);
21157 else if (TREE_CODE (member) == SCOPE_REF
21158 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21159 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21161 if (complain & tf_error)
21163 if (TYPE_P (TREE_OPERAND (member, 0)))
21164 error ("%qT is not a class or namespace",
21165 TREE_OPERAND (member, 0));
21166 else
21167 error ("%qD is not a class or namespace",
21168 TREE_OPERAND (member, 0));
21170 RETURN (error_mark_node);
21173 r = finish_class_member_access_expr (object, member,
21174 /*template_p=*/false,
21175 complain);
21176 if (REF_PARENTHESIZED_P (t))
21177 r = force_paren_expr (r);
21178 RETURN (r);
21181 case THROW_EXPR:
21182 RETURN (build_throw
21183 (input_location, RECUR (TREE_OPERAND (t, 0)), complain));
21185 case CONSTRUCTOR:
21187 vec<constructor_elt, va_gc> *n;
21188 constructor_elt *ce;
21189 unsigned HOST_WIDE_INT idx;
21190 bool process_index_p;
21191 int newlen;
21192 bool need_copy_p = false;
21193 tree r;
21195 tsubst_flags_t tcomplain = complain;
21196 if (COMPOUND_LITERAL_P (t))
21197 tcomplain |= tf_tst_ok;
21198 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21199 if (type == error_mark_node)
21200 RETURN (error_mark_node);
21202 /* We do not want to process the index of aggregate
21203 initializers as they are identifier nodes which will be
21204 looked up by digest_init. */
21205 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21207 if (null_member_pointer_value_p (t))
21209 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21210 RETURN (t);
21213 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21214 newlen = vec_safe_length (n);
21215 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21217 if (ce->index && process_index_p
21218 /* An identifier index is looked up in the type
21219 being initialized, not the current scope. */
21220 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21221 ce->index = RECUR (ce->index);
21223 if (PACK_EXPANSION_P (ce->value))
21225 /* Substitute into the pack expansion. */
21226 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21227 in_decl);
21229 if (ce->value == error_mark_node
21230 || PACK_EXPANSION_P (ce->value))
21232 else if (TREE_VEC_LENGTH (ce->value) == 1)
21233 /* Just move the argument into place. */
21234 ce->value = TREE_VEC_ELT (ce->value, 0);
21235 else
21237 /* Update the length of the final CONSTRUCTOR
21238 arguments vector, and note that we will need to
21239 copy.*/
21240 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21241 need_copy_p = true;
21244 else
21245 ce->value = RECUR (ce->value);
21248 if (need_copy_p)
21250 vec<constructor_elt, va_gc> *old_n = n;
21252 vec_alloc (n, newlen);
21253 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21255 if (TREE_CODE (ce->value) == TREE_VEC)
21257 int i, len = TREE_VEC_LENGTH (ce->value);
21258 for (i = 0; i < len; ++i)
21259 CONSTRUCTOR_APPEND_ELT (n, 0,
21260 TREE_VEC_ELT (ce->value, i));
21262 else
21263 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21267 r = build_constructor (init_list_type_node, n);
21268 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21269 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21270 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21272 if (TREE_HAS_CONSTRUCTOR (t))
21274 fcl_t cl = fcl_functional;
21275 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21276 cl = fcl_c99;
21277 RETURN (finish_compound_literal (type, r, complain, cl));
21280 TREE_TYPE (r) = type;
21281 RETURN (r);
21284 case TYPEID_EXPR:
21286 tree operand_0 = TREE_OPERAND (t, 0);
21287 if (TYPE_P (operand_0))
21289 operand_0 = tsubst (operand_0, args, complain, in_decl);
21290 RETURN (get_typeid (operand_0, complain));
21292 else
21294 operand_0 = RECUR (operand_0);
21295 RETURN (build_typeid (operand_0, complain));
21299 case FUNCTION_DECL:
21300 case PARM_DECL:
21301 case VAR_DECL:
21302 if (!args)
21303 RETURN (t);
21304 tree r;
21305 if (VAR_OR_FUNCTION_DECL_P (t)
21306 && DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
21307 r = tsubst_decl (t, args, complain);
21308 else if (VAR_OR_FUNCTION_DECL_P (t) && DECL_LOCAL_DECL_P (t))
21310 /* Local specialization will usually have been created when
21311 we instantiated the DECL_EXPR_DECL. */
21312 r = retrieve_local_specialization (t);
21313 if (!r)
21315 /* We're in a generic lambda referencing a local extern
21316 from an outer block-scope of a non-template. */
21317 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
21318 r = t;
21321 else if (local_variable_p (t)
21322 && ((r = retrieve_local_specialization (t))
21323 || TREE_CODE (t) == PARM_DECL
21324 || uses_template_parms (DECL_CONTEXT (t))))
21326 if (r == NULL_TREE && TREE_CODE (t) == PARM_DECL)
21328 /* We get here for a use of 'this' in an NSDMI. */
21329 if (DECL_NAME (t) == this_identifier && current_class_ptr)
21330 RETURN (current_class_ptr);
21332 /* This can happen for a parameter name used later in a function
21333 declaration (such as in a late-specified return type). Just
21334 make a dummy decl, since it's only used for its type. */
21335 gcc_assert (cp_unevaluated_operand);
21336 r = tsubst_decl (t, args, complain);
21337 /* Give it the template pattern as its context; its true context
21338 hasn't been instantiated yet and this is good enough for
21339 mangling. */
21340 DECL_CONTEXT (r) = DECL_CONTEXT (t);
21342 else if (r == NULL_TREE)
21344 /* First try name lookup to find the instantiation. */
21345 r = lookup_name (DECL_NAME (t));
21346 if (r)
21348 if (!VAR_P (r))
21350 /* During error-recovery we may find a non-variable,
21351 even an OVERLOAD: just bail out and avoid ICEs and
21352 duplicate diagnostics (c++/62207). */
21353 gcc_assert (seen_error ());
21354 RETURN (error_mark_node);
21356 if (!is_capture_proxy (r))
21358 /* Make sure the one we found is the one we want. */
21359 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
21360 if (ctx != DECL_CONTEXT (r))
21361 r = NULL_TREE;
21365 if (r)
21366 /* OK */;
21367 else
21369 /* This can happen for a variable used in a
21370 late-specified return type of a local lambda, or for a
21371 local static or constant. Building a new VAR_DECL
21372 should be OK in all those cases. */
21373 r = tsubst_decl (t, args, complain);
21374 if (local_specializations)
21375 /* Avoid infinite recursion (79640). */
21376 register_local_specialization (r, t);
21377 if (decl_maybe_constant_var_p (r))
21379 /* We can't call cp_finish_decl, so handle the
21380 initializer by hand. */
21381 tree init = tsubst_init (DECL_INITIAL (t), r, args,
21382 complain, in_decl);
21383 if (!processing_template_decl)
21384 init = maybe_constant_init (init);
21385 if (processing_template_decl
21386 ? potential_constant_expression (init)
21387 : reduced_constant_expression_p (init))
21388 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
21389 = TREE_CONSTANT (r) = true;
21390 DECL_INITIAL (r) = init;
21391 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
21392 TREE_TYPE (r)
21393 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
21394 complain, adc_variable_type);
21396 gcc_assert (cp_unevaluated_operand
21397 || processing_contract_condition
21398 || TREE_STATIC (r)
21399 || decl_constant_var_p (r)
21400 || seen_error ());
21401 if (!processing_template_decl
21402 && !TREE_STATIC (r))
21403 r = process_outer_var_ref (r, complain);
21405 /* Remember this for subsequent uses. */
21406 if (local_specializations)
21407 register_local_specialization (r, t);
21409 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
21410 r = argument_pack_select_arg (r);
21412 else
21413 r = t;
21414 if (!mark_used (r, complain))
21415 RETURN (error_mark_node);
21417 if (!no_name_lookup_flag
21418 && (TREE_CODE (t) == PARM_DECL || TREE_CODE (t) == VAR_DECL))
21420 /* ??? We're doing a subset of finish_id_expression here. */
21421 if (tree wrap = maybe_get_tls_wrapper_call (r))
21422 /* Replace an evaluated use of the thread_local variable with
21423 a call to its wrapper. */
21424 r = wrap;
21425 else if (outer_automatic_var_p (r))
21426 r = process_outer_var_ref (r, complain);
21428 if (!TYPE_REF_P (TREE_TYPE (t)))
21429 /* If the original type was a reference, we'll be wrapped in
21430 the appropriate INDIRECT_REF. */
21431 r = convert_from_reference (r);
21433 RETURN (r);
21435 case CONST_DECL:
21437 tree enum_type;
21438 tree v;
21440 if (DECL_TEMPLATE_PARM_P (t))
21441 RETURN (RECUR (DECL_INITIAL (t)));
21442 if (!uses_template_parms (DECL_CONTEXT (t)))
21443 RETURN (t);
21445 /* Unfortunately, we cannot just call lookup_name here.
21446 Consider:
21448 template <int I> int f() {
21449 enum E { a = I };
21450 struct S { void g() { E e = a; } };
21453 When we instantiate f<7>::S::g(), say, lookup_name is not
21454 clever enough to find f<7>::a. */
21455 enum_type
21456 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21457 /*entering_scope=*/0);
21459 for (v = TYPE_VALUES (enum_type);
21460 v != NULL_TREE;
21461 v = TREE_CHAIN (v))
21462 if (TREE_PURPOSE (v) == DECL_NAME (t))
21463 RETURN (TREE_VALUE (v));
21465 /* We didn't find the name. That should never happen; if
21466 name-lookup found it during preliminary parsing, we
21467 should find it again here during instantiation. */
21468 gcc_unreachable ();
21469 RETURN (t);
21472 case FIELD_DECL:
21473 if (DECL_CONTEXT (t))
21475 tree ctx;
21477 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
21478 /*entering_scope=*/1);
21479 if (ctx != DECL_CONTEXT (t))
21481 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
21482 if (!r)
21484 if (complain & tf_error)
21485 error ("using invalid field %qD", t);
21486 RETURN (error_mark_node);
21488 RETURN (r);
21491 RETURN (t);
21493 case NAMESPACE_DECL:
21494 case OVERLOAD:
21495 RETURN (t);
21497 case TEMPLATE_DECL:
21498 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
21499 RETURN (tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
21500 args, complain, in_decl));
21501 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
21502 RETURN (tsubst (t, args, complain, in_decl));
21503 else if (DECL_CLASS_SCOPE_P (t)
21504 && uses_template_parms (DECL_CONTEXT (t)))
21506 /* Template template argument like the following example need
21507 special treatment:
21509 template <template <class> class TT> struct C {};
21510 template <class T> struct D {
21511 template <class U> struct E {};
21512 C<E> c; // #1
21514 D<int> d; // #2
21516 We are processing the template argument `E' in #1 for
21517 the template instantiation #2. Originally, `E' is a
21518 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
21519 have to substitute this with one having context `D<int>'. */
21521 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
21522 in_decl, /*entering_scope=*/true);
21523 RETURN (lookup_field (context, DECL_NAME(t), 0, false));
21525 else
21526 /* Ordinary template template argument. */
21527 RETURN (t);
21529 case TEMPLATE_PARM_INDEX:
21530 case TYPE_DECL:
21531 RETURN (tsubst (t, args, complain, in_decl));
21533 case CLEANUP_POINT_EXPR:
21534 /* We shouldn't have built any of these during initial template
21535 generation. Instead, they should be built during instantiation
21536 in response to the saved STMT_IS_FULL_EXPR_P setting. */
21537 gcc_unreachable ();
21539 case OFFSET_REF:
21541 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21542 tree op0 = RECUR (TREE_OPERAND (t, 0));
21543 tree op1 = RECUR (TREE_OPERAND (t, 1));
21544 r = build2 (OFFSET_REF, type, op0, op1);
21545 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
21546 if (!mark_used (TREE_OPERAND (r, 1), complain)
21547 && !(complain & tf_error))
21548 RETURN (error_mark_node);
21549 RETURN (r);
21552 case EXPR_PACK_EXPANSION:
21553 error ("invalid use of pack expansion expression");
21554 RETURN (error_mark_node);
21556 case NONTYPE_ARGUMENT_PACK:
21557 error ("use %<...%> to expand argument pack");
21558 RETURN (error_mark_node);
21560 case VOID_CST:
21561 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
21562 RETURN (t);
21564 case INTEGER_CST:
21565 case REAL_CST:
21566 case COMPLEX_CST:
21567 case VECTOR_CST:
21569 /* Instantiate any typedefs in the type. */
21570 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21571 r = fold_convert (type, t);
21572 gcc_assert (TREE_CODE (r) == TREE_CODE (t));
21573 RETURN (r);
21576 case STRING_CST:
21578 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21579 r = t;
21580 if (type != TREE_TYPE (t))
21582 r = copy_node (t);
21583 TREE_TYPE (r) = type;
21585 RETURN (r);
21588 case PTRMEM_CST:
21589 /* These can sometimes show up in a partial instantiation, but never
21590 involve template parms. */
21591 gcc_assert (!uses_template_parms (t));
21592 RETURN (t);
21594 case UNARY_LEFT_FOLD_EXPR:
21595 RETURN (tsubst_unary_left_fold (t, args, complain, in_decl));
21596 case UNARY_RIGHT_FOLD_EXPR:
21597 RETURN (tsubst_unary_right_fold (t, args, complain, in_decl));
21598 case BINARY_LEFT_FOLD_EXPR:
21599 RETURN (tsubst_binary_left_fold (t, args, complain, in_decl));
21600 case BINARY_RIGHT_FOLD_EXPR:
21601 RETURN (tsubst_binary_right_fold (t, args, complain, in_decl));
21602 case PREDICT_EXPR:
21603 RETURN (t);
21605 case DEBUG_BEGIN_STMT:
21606 /* ??? There's no point in copying it for now, but maybe some
21607 day it will contain more information, such as a pointer back
21608 to the containing function, inlined copy or so. */
21609 RETURN (t);
21611 case CO_YIELD_EXPR:
21612 RETURN (finish_co_yield_expr (input_location,
21613 RECUR (TREE_OPERAND (t, 0))));
21615 case CO_AWAIT_EXPR:
21616 RETURN (finish_co_await_expr (input_location,
21617 RECUR (TREE_OPERAND (t, 0))));
21619 case VA_ARG_EXPR:
21621 tree op0 = RECUR (TREE_OPERAND (t, 0));
21622 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21623 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21626 case OFFSETOF_EXPR:
21628 tree object_ptr
21629 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
21630 RETURN (finish_offsetof (object_ptr,
21631 RECUR (TREE_OPERAND (t, 0)),
21632 EXPR_LOCATION (t)));
21635 case ADDRESSOF_EXPR:
21636 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21637 RECUR (TREE_OPERAND (t, 0)), complain));
21639 case TRAIT_EXPR:
21641 tree type1 = TRAIT_EXPR_TYPE1 (t);
21642 if (TYPE_P (type1))
21643 type1 = tsubst (type1, args, complain, in_decl);
21644 else
21645 type1 = tsubst_expr (type1, args, complain, in_decl);
21646 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21647 complain, in_decl);
21648 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21649 TRAIT_EXPR_KIND (t), type1, type2));
21652 case STMT_EXPR:
21654 tree old_stmt_expr = cur_stmt_expr;
21655 tree stmt_expr = begin_stmt_expr ();
21657 cur_stmt_expr = stmt_expr;
21658 tsubst_stmt (STMT_EXPR_STMT (t), args, complain, in_decl);
21659 stmt_expr = finish_stmt_expr (stmt_expr, false);
21660 cur_stmt_expr = old_stmt_expr;
21662 /* If the resulting list of expression statement is empty,
21663 fold it further into void_node. */
21664 if (empty_expr_stmt_p (stmt_expr))
21665 stmt_expr = void_node;
21667 RETURN (stmt_expr);
21670 case LAMBDA_EXPR:
21672 if (complain & tf_partial)
21674 /* We don't have a full set of template arguments yet; don't touch
21675 the lambda at all. */
21676 gcc_assert (processing_template_decl);
21677 return t;
21679 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21681 RETURN (build_lambda_object (r));
21684 case TRANSACTION_EXPR:
21685 gcc_checking_assert (!TRANSACTION_EXPR_IS_STMT (t));
21686 RETURN (tsubst_stmt (t, args, complain, in_decl));
21688 case PAREN_EXPR:
21689 if (REF_PARENTHESIZED_P (t))
21690 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21691 else
21692 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21694 tree op0 = RECUR (TREE_OPERAND (t, 0));
21695 RETURN (build1_loc (input_location, PAREN_EXPR,
21696 TREE_TYPE (op0), op0));
21699 case VEC_PERM_EXPR:
21701 tree op0 = RECUR (TREE_OPERAND (t, 0));
21702 tree op1 = RECUR (TREE_OPERAND (t, 1));
21703 tree op2 = RECUR (TREE_OPERAND (t, 2));
21704 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21705 complain));
21708 case REQUIRES_EXPR:
21710 complain &= ~tf_warning_or_error;
21711 tree r = tsubst_requires_expr (t, args, complain, in_decl);
21712 RETURN (r);
21715 case RANGE_EXPR:
21716 /* No need to substitute further, a RANGE_EXPR will always be built
21717 with constant operands. */
21718 RETURN (t);
21720 case NON_LVALUE_EXPR:
21721 case VIEW_CONVERT_EXPR:
21723 tree op = RECUR (TREE_OPERAND (t, 0));
21725 if (location_wrapper_p (t))
21726 /* We need to do this here as well as in tsubst_copy so we get the
21727 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21728 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21730 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21731 if (REF_PARENTHESIZED_P (t))
21732 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21733 RETURN (finish_parenthesized_expr (op));
21735 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21736 parameter object const. */
21737 if (TREE_TYPE (op) == NULL_TREE
21738 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21740 /* The template argument is not const, presumably because
21741 it is still dependent, and so not the const template parm
21742 object. */
21743 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21744 if (TREE_CODE (op) == CONSTRUCTOR
21745 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21747 /* Don't add a wrapper to these. */
21748 op = copy_node (op);
21749 TREE_TYPE (op) = type;
21751 else
21752 /* Do add a wrapper otherwise (in particular, if op is
21753 another TEMPLATE_PARM_INDEX). */
21754 op = build1 (VIEW_CONVERT_EXPR, type, op);
21756 RETURN (op);
21759 case ANNOTATE_EXPR:
21761 op1 = RECUR (TREE_OPERAND (t, 0));
21762 tree op2 = RECUR (TREE_OPERAND (t, 1));
21763 tree op3 = RECUR (TREE_OPERAND (t, 2));
21764 if (TREE_CODE (op2) == INTEGER_CST
21765 && wi::to_widest (op2) == (int) annot_expr_unroll_kind)
21766 op3 = cp_check_pragma_unroll (EXPR_LOCATION (TREE_OPERAND (t, 2)),
21767 op3);
21768 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
21769 TREE_TYPE (op1), op1, op2, op3));
21772 default:
21773 /* Handle Objective-C++ constructs, if appropriate. */
21774 if (tree subst = objcp_tsubst_expr (t, args, complain, in_decl))
21775 RETURN (subst);
21777 /* We shouldn't get here, but keep going if !flag_checking. */
21778 if (flag_checking)
21779 gcc_unreachable ();
21780 RETURN (t);
21783 #undef RECUR
21784 #undef RETURN
21785 out:
21786 input_location = save_loc;
21787 return retval;
21790 /* Verify that the instantiated ARGS are valid. For type arguments,
21791 make sure that the type's linkage is ok. For non-type arguments,
21792 make sure they are constants if they are integral or enumerations.
21793 Emit an error under control of COMPLAIN, and return TRUE on error. */
21795 static bool
21796 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21798 if (dependent_template_arg_p (t))
21799 return false;
21800 if (ARGUMENT_PACK_P (t))
21802 tree vec = ARGUMENT_PACK_ARGS (t);
21803 int len = TREE_VEC_LENGTH (vec);
21804 bool result = false;
21805 int i;
21807 for (i = 0; i < len; ++i)
21808 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21809 result = true;
21810 return result;
21812 else if (TYPE_P (t))
21814 /* [basic.link]: A name with no linkage (notably, the name
21815 of a class or enumeration declared in a local scope)
21816 shall not be used to declare an entity with linkage.
21817 This implies that names with no linkage cannot be used as
21818 template arguments
21820 DR 757 relaxes this restriction for C++0x. */
21821 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21822 : no_linkage_check (t, /*relaxed_p=*/false));
21824 if (nt)
21826 /* DR 488 makes use of a type with no linkage cause
21827 type deduction to fail. */
21828 if (complain & tf_error)
21830 if (TYPE_UNNAMED_P (nt))
21831 error ("%qT is/uses unnamed type", t);
21832 else
21833 error ("template argument for %qD uses local type %qT",
21834 tmpl, t);
21836 return true;
21838 /* In order to avoid all sorts of complications, we do not
21839 allow variably-modified types as template arguments. */
21840 else if (variably_modified_type_p (t, NULL_TREE))
21842 if (complain & tf_error)
21843 error ("%qT is a variably modified type", t);
21844 return true;
21847 /* Class template and alias template arguments should be OK. */
21848 else if (DECL_TYPE_TEMPLATE_P (t))
21850 /* A non-type argument of integral or enumerated type must be a
21851 constant. */
21852 else if (TREE_TYPE (t)
21853 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21854 && !REFERENCE_REF_P (t)
21855 && !TREE_CONSTANT (t))
21857 if (complain & tf_error)
21858 error ("integral expression %qE is not constant", t);
21859 return true;
21861 return false;
21864 static bool
21865 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21867 int ix, len = DECL_NTPARMS (tmpl);
21868 bool result = false;
21870 for (ix = 0; ix != len; ix++)
21872 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21873 result = true;
21875 if (result && (complain & tf_error))
21876 error (" trying to instantiate %qD", tmpl);
21877 return result;
21880 /* Call mark_used on each entity within the non-type template arguments in
21881 ARGS for an instantiation of TMPL, to ensure that each such entity is
21882 considered odr-used (and therefore marked for instantiation) regardless of
21883 whether the specialization was first formed in a template context (which
21884 inhibits mark_used).
21886 This function assumes push_to_top_level has been called beforehand. */
21888 static void
21889 mark_template_arguments_used (tree tmpl, tree args)
21891 /* It suffices to do this only when instantiating a primary template. */
21892 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21893 return;
21895 /* We already marked outer arguments when specializing the context. */
21896 args = INNERMOST_TEMPLATE_ARGS (args);
21898 for (tree arg : tree_vec_range (args))
21900 /* A (pointer/reference to) function or variable NTTP argument. */
21901 if (TREE_CODE (arg) == ADDR_EXPR
21902 || TREE_CODE (arg) == INDIRECT_REF)
21904 while (TREE_CODE (arg) == ADDR_EXPR
21905 || REFERENCE_REF_P (arg)
21906 || CONVERT_EXPR_P (arg))
21907 arg = TREE_OPERAND (arg, 0);
21908 if (VAR_OR_FUNCTION_DECL_P (arg))
21910 /* Pass tf_none to avoid duplicate diagnostics: if this call
21911 fails then an earlier call to mark_used for this argument
21912 must have also failed and emitted a diagnostic. */
21913 bool ok = mark_used (arg, tf_none);
21914 gcc_checking_assert (ok || seen_error ());
21917 /* A class NTTP argument. */
21918 else if (VAR_P (arg)
21919 && DECL_NTTP_OBJECT_P (arg))
21921 auto mark_used_r = [](tree *tp, int *, void *) {
21922 if (VAR_OR_FUNCTION_DECL_P (*tp))
21924 bool ok = mark_used (*tp, tf_none);
21925 gcc_checking_assert (ok || seen_error ());
21927 return NULL_TREE;
21929 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21930 mark_used_r, nullptr);
21935 /* We're out of SFINAE context now, so generate diagnostics for the access
21936 errors we saw earlier when instantiating D from TMPL and ARGS. */
21938 static void
21939 recheck_decl_substitution (tree d, tree tmpl, tree args)
21941 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21942 tree type = TREE_TYPE (pattern);
21943 location_t loc = input_location;
21945 push_access_scope (d);
21946 push_deferring_access_checks (dk_no_deferred);
21947 input_location = DECL_SOURCE_LOCATION (pattern);
21948 tsubst (type, args, tf_warning_or_error, d);
21949 input_location = loc;
21950 pop_deferring_access_checks ();
21951 pop_access_scope (d);
21954 /* Instantiate the indicated variable, function, or alias template TMPL with
21955 the template arguments in TARG_PTR. */
21957 tree
21958 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21960 auto_timevar tv (TV_TEMPLATE_INST);
21962 tree targ_ptr = orig_args;
21963 tree fndecl;
21964 tree gen_tmpl;
21965 bool access_ok = true;
21967 if (tmpl == error_mark_node)
21968 return error_mark_node;
21970 /* The other flags are not relevant anymore here, especially tf_partial
21971 shouldn't be set. For instance, we may be called while doing a partial
21972 substitution of a template variable, but the type of the variable
21973 template may be auto, in which case we will call do_auto_deduction
21974 in mark_used (which clears tf_partial) and the auto must be properly
21975 reduced at that time for the deduction to work. */
21976 complain &= tf_warning_or_error;
21978 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21980 if (modules_p ())
21981 lazy_load_pendings (tmpl);
21983 /* If this function is a clone, handle it specially. */
21984 if (DECL_CLONED_FUNCTION_P (tmpl))
21986 tree spec;
21987 tree clone;
21989 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21990 DECL_CLONED_FUNCTION. */
21991 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21992 targ_ptr, complain);
21993 if (spec == error_mark_node)
21994 return error_mark_node;
21996 /* Look for the clone. */
21997 FOR_EACH_CLONE (clone, spec)
21998 if (DECL_NAME (clone) == DECL_NAME (tmpl))
21999 return clone;
22000 /* We should always have found the clone by now. */
22001 gcc_unreachable ();
22002 return NULL_TREE;
22005 if (targ_ptr == error_mark_node)
22006 return error_mark_node;
22008 /* Check to see if we already have this specialization. */
22009 gen_tmpl = most_general_template (tmpl);
22010 if (TMPL_ARGS_DEPTH (targ_ptr)
22011 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22012 /* targ_ptr only has the innermost template args, so add the outer ones
22013 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22014 the case of a non-dependent call within a template definition). */
22015 targ_ptr = (add_outermost_template_args
22016 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22017 targ_ptr));
22019 hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
22020 tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
22022 gcc_checking_assert (tmpl == gen_tmpl
22023 || ((fndecl
22024 = retrieve_specialization (tmpl, orig_args, 0))
22025 == spec)
22026 || fndecl == NULL_TREE);
22028 if (spec != NULL_TREE)
22030 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22032 if (complain & tf_error)
22033 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22034 return error_mark_node;
22036 return spec;
22039 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22040 complain))
22041 return error_mark_node;
22043 /* We are building a FUNCTION_DECL, during which the access of its
22044 parameters and return types have to be checked. However this
22045 FUNCTION_DECL which is the desired context for access checking
22046 is not built yet. We solve this chicken-and-egg problem by
22047 deferring all checks until we have the FUNCTION_DECL. */
22048 push_deferring_access_checks (dk_deferred);
22050 /* Instantiation of the function happens in the context of the function
22051 template, not the context of the overload resolution we're doing. */
22052 push_to_top_level ();
22053 /* If there are dependent arguments, e.g. because we're doing partial
22054 ordering, make sure processing_template_decl stays set. */
22055 if (uses_template_parms (targ_ptr))
22056 ++processing_template_decl;
22057 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22059 tree ctx;
22060 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22061 /* If the context of the partially instantiated template is
22062 already non-dependent, then we might as well use it. */
22063 ctx = DECL_CONTEXT (tmpl);
22064 else
22065 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22066 complain, gen_tmpl, true);
22067 push_nested_class (ctx);
22070 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22072 tree partial_ti = NULL_TREE;
22073 fndecl = NULL_TREE;
22074 if (VAR_P (pattern))
22076 /* We need to determine if we're using a partial or explicit
22077 specialization now, because the type of the variable could be
22078 different. */
22079 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
22080 partial_ti = most_specialized_partial_spec (tid, complain);
22081 if (partial_ti == error_mark_node)
22082 pattern = error_mark_node;
22083 else if (partial_ti)
22085 tree partial_tmpl = TI_TEMPLATE (partial_ti);
22086 tree partial_args = TI_ARGS (partial_ti);
22087 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22088 fndecl = tsubst_decl (partial_pat, partial_args, complain,
22089 /*use_spec_table=*/false);
22093 /* Substitute template parameters to obtain the specialization. */
22094 if (fndecl == NULL_TREE)
22095 fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
22096 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22097 pop_nested_class ();
22098 pop_from_top_level ();
22100 if (fndecl == error_mark_node)
22102 pop_deferring_access_checks ();
22103 return error_mark_node;
22106 /* The DECL_TI_TEMPLATE should always be the immediate parent
22107 template, not the most general template. */
22108 DECL_TI_TEMPLATE (fndecl) = tmpl;
22109 DECL_TI_ARGS (fndecl) = targ_ptr;
22110 if (VAR_P (pattern))
22112 /* Now that we we've formed this variable template specialization,
22113 remember the result of most_specialized_partial_spec for it. */
22114 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
22116 /* And remember if the variable was declared with []. */
22117 if (TREE_CODE (TREE_TYPE (fndecl)) == ARRAY_TYPE
22118 && TYPE_DOMAIN (TREE_TYPE (fndecl)) == NULL_TREE)
22119 SET_VAR_HAD_UNKNOWN_BOUND (fndecl);
22122 fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
22123 if (fndecl == error_mark_node)
22124 return error_mark_node;
22126 set_instantiating_module (fndecl);
22128 /* Now we know the specialization, compute access previously
22129 deferred. Do no access control for inheriting constructors,
22130 as we already checked access for the inherited constructor. */
22131 if (!(flag_new_inheriting_ctors
22132 && DECL_INHERITED_CTOR (fndecl)))
22134 push_access_scope (fndecl);
22135 if (!perform_deferred_access_checks (complain))
22136 access_ok = false;
22137 pop_access_scope (fndecl);
22139 pop_deferring_access_checks ();
22141 /* If we've just instantiated the main entry point for a function,
22142 instantiate all the alternate entry points as well. We do this
22143 by cloning the instantiation of the main entry point, not by
22144 instantiating the template clones. */
22145 if (tree chain = DECL_CHAIN (gen_tmpl))
22146 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22147 clone_cdtor (fndecl, /*update_methods=*/false);
22149 if (!access_ok)
22151 if (!(complain & tf_error))
22153 /* Remember to reinstantiate when we're out of SFINAE so the user
22154 can see the errors. */
22155 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22157 return error_mark_node;
22160 return fndecl;
22163 /* Instantiate the alias template TMPL with ARGS. Also push a template
22164 instantiation level, which instantiate_template doesn't do because
22165 functions and variables have sufficient context established by the
22166 callers. */
22168 static tree
22169 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22171 if (tmpl == error_mark_node || args == error_mark_node)
22172 return error_mark_node;
22174 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22175 args, tmpl, complain);
22176 if (args == error_mark_node)
22177 return error_mark_node;
22179 /* FIXME check for satisfaction in check_instantiated_args. */
22180 if (!constraints_satisfied_p (tmpl, args))
22182 if (complain & tf_error)
22184 auto_diagnostic_group d;
22185 error ("template constraint failure for %qD", tmpl);
22186 diagnose_constraints (input_location, tmpl, args);
22188 return error_mark_node;
22191 if (!push_tinst_level (tmpl, args))
22192 return error_mark_node;
22193 tree r = instantiate_template (tmpl, args, complain);
22194 pop_tinst_level ();
22196 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22198 /* An alias template specialization can be dependent
22199 even if its underlying type is not. */
22200 TYPE_DEPENDENT_P (d) = true;
22201 TYPE_DEPENDENT_P_VALID (d) = true;
22202 /* Sometimes a dependent alias spec is equivalent to its expansion,
22203 sometimes not. So always use structural_comptypes. */
22204 SET_TYPE_STRUCTURAL_EQUALITY (d);
22207 return r;
22210 /* PARM is a template parameter pack for FN. Returns true iff
22211 PARM is used in a deducible way in the argument list of FN. */
22213 static bool
22214 pack_deducible_p (tree parm, tree fn)
22216 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22217 for (; t; t = TREE_CHAIN (t))
22219 tree type = TREE_VALUE (t);
22220 tree packs;
22221 if (!PACK_EXPANSION_P (type))
22222 continue;
22223 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22224 packs; packs = TREE_CHAIN (packs))
22225 if (template_args_equal (TREE_VALUE (packs), parm))
22227 /* The template parameter pack is used in a function parameter
22228 pack. If this is the end of the parameter list, the
22229 template parameter pack is deducible. */
22230 if (TREE_CHAIN (t) == void_list_node)
22231 return true;
22232 else
22233 /* Otherwise, not. Well, it could be deduced from
22234 a non-pack parameter, but doing so would end up with
22235 a deduction mismatch, so don't bother. */
22236 return false;
22239 /* The template parameter pack isn't used in any function parameter
22240 packs, but it might be used deeper, e.g. tuple<Args...>. */
22241 return true;
22244 /* Subroutine of fn_type_unification: check non-dependent parms for
22245 convertibility. */
22247 static int
22248 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22249 tree fn, unification_kind_t strict, int flags,
22250 struct conversion **convs, bool explain_p,
22251 bool noninst_only_p)
22253 /* Non-constructor methods need to leave a conversion for 'this', which
22254 isn't included in nargs here. */
22255 unsigned offset = (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
22256 && !DECL_CONSTRUCTOR_P (fn));
22258 for (unsigned ia = 0;
22259 parms && parms != void_list_node && ia < nargs; )
22261 tree parm = TREE_VALUE (parms);
22263 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22264 && (!TREE_CHAIN (parms)
22265 || TREE_CHAIN (parms) == void_list_node))
22266 /* For a function parameter pack that occurs at the end of the
22267 parameter-declaration-list, the type A of each remaining
22268 argument of the call is compared with the type P of the
22269 declarator-id of the function parameter pack. */
22270 break;
22272 parms = TREE_CHAIN (parms);
22274 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22275 /* For a function parameter pack that does not occur at the
22276 end of the parameter-declaration-list, the type of the
22277 parameter pack is a non-deduced context. */
22278 continue;
22280 if (!uses_template_parms (parm))
22282 tree arg = args[ia];
22283 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22284 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22286 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22287 conv_p, explain_p, noninst_only_p))
22288 return 1;
22291 ++ia;
22294 return 0;
22297 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22298 NARGS elements of the arguments that are being used when calling
22299 it. TARGS is a vector into which the deduced template arguments
22300 are placed.
22302 Returns either a FUNCTION_DECL for the matching specialization of FN or
22303 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22304 true, diagnostics will be printed to explain why it failed.
22306 If FN is a conversion operator, or we are trying to produce a specific
22307 specialization, RETURN_TYPE is the return type desired.
22309 The EXPLICIT_TARGS are explicit template arguments provided via a
22310 template-id.
22312 The parameter STRICT is one of:
22314 DEDUCE_CALL:
22315 We are deducing arguments for a function call, as in
22316 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22317 deducing arguments for a call to the result of a conversion
22318 function template, as in [over.call.object].
22320 DEDUCE_CONV:
22321 We are deducing arguments for a conversion function, as in
22322 [temp.deduct.conv].
22324 DEDUCE_EXACT:
22325 We are deducing arguments when doing an explicit instantiation
22326 as in [temp.explicit], when determining an explicit specialization
22327 as in [temp.expl.spec], or when taking the address of a function
22328 template, as in [temp.deduct.funcaddr]. */
22330 tree
22331 fn_type_unification (tree fn,
22332 tree explicit_targs,
22333 tree targs,
22334 const tree *args,
22335 unsigned int nargs,
22336 tree return_type,
22337 unification_kind_t strict,
22338 int flags,
22339 struct conversion **convs,
22340 bool explain_p,
22341 bool decltype_p)
22343 tree parms;
22344 tree fntype;
22345 tree decl = NULL_TREE;
22346 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22347 bool ok;
22348 static int deduction_depth;
22349 /* type_unification_real will pass back any access checks from default
22350 template argument substitution. */
22351 vec<deferred_access_check, va_gc> *checks = NULL;
22352 /* We don't have all the template args yet. */
22353 bool incomplete = true;
22355 tree orig_fn = fn;
22356 if (flag_new_inheriting_ctors)
22357 fn = strip_inheriting_ctors (fn);
22359 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22360 tree r = error_mark_node;
22362 tree full_targs = targs;
22363 if (TMPL_ARGS_DEPTH (targs)
22364 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22365 full_targs = (add_outermost_template_args
22366 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22367 targs));
22369 if (decltype_p)
22370 complain |= tf_decltype;
22372 /* In C++0x, it's possible to have a function template whose type depends
22373 on itself recursively. This is most obvious with decltype, but can also
22374 occur with enumeration scope (c++/48969). So we need to catch infinite
22375 recursion and reject the substitution at deduction time; this function
22376 will return error_mark_node for any repeated substitution.
22378 This also catches excessive recursion such as when f<N> depends on
22379 f<N-1> across all integers, and returns error_mark_node for all the
22380 substitutions back up to the initial one.
22382 This is, of course, not reentrant. */
22383 if (excessive_deduction_depth)
22384 return error_mark_node;
22385 ++deduction_depth;
22387 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22389 fntype = TREE_TYPE (fn);
22390 if (explicit_targs)
22392 /* [temp.deduct]
22394 The specified template arguments must match the template
22395 parameters in kind (i.e., type, nontype, template), and there
22396 must not be more arguments than there are parameters;
22397 otherwise type deduction fails.
22399 Nontype arguments must match the types of the corresponding
22400 nontype template parameters, or must be convertible to the
22401 types of the corresponding nontype parameters as specified in
22402 _temp.arg.nontype_, otherwise type deduction fails.
22404 All references in the function type of the function template
22405 to the corresponding template parameters are replaced by the
22406 specified template argument values. If a substitution in a
22407 template parameter or in the function type of the function
22408 template results in an invalid type, type deduction fails. */
22409 int i, len = TREE_VEC_LENGTH (tparms);
22410 location_t loc = input_location;
22411 incomplete = false;
22413 if (explicit_targs == error_mark_node)
22414 goto fail;
22416 if (TMPL_ARGS_DEPTH (explicit_targs)
22417 < TMPL_ARGS_DEPTH (full_targs))
22418 explicit_targs = add_outermost_template_args (full_targs,
22419 explicit_targs);
22421 /* Adjust any explicit template arguments before entering the
22422 substitution context. */
22423 explicit_targs
22424 = (coerce_template_parms (tparms, explicit_targs, fn,
22425 complain|tf_partial,
22426 /*require_all_args=*/false));
22427 if (explicit_targs == error_mark_node)
22428 goto fail;
22430 /* Substitute the explicit args into the function type. This is
22431 necessary so that, for instance, explicitly declared function
22432 arguments can match null pointed constants. If we were given
22433 an incomplete set of explicit args, we must not do semantic
22434 processing during substitution as we could create partial
22435 instantiations. */
22436 for (i = 0; i < len; i++)
22438 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22439 bool parameter_pack = false;
22440 tree targ = TREE_VEC_ELT (explicit_targs, i);
22442 /* Dig out the actual parm. */
22443 if (TREE_CODE (parm) == TYPE_DECL
22444 || TREE_CODE (parm) == TEMPLATE_DECL)
22446 parm = TREE_TYPE (parm);
22447 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22449 else if (TREE_CODE (parm) == PARM_DECL)
22451 parm = DECL_INITIAL (parm);
22452 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22455 if (targ == NULL_TREE)
22456 /* No explicit argument for this template parameter. */
22457 incomplete = true;
22458 else if (parameter_pack && pack_deducible_p (parm, fn))
22460 /* Mark the argument pack as "incomplete". We could
22461 still deduce more arguments during unification.
22462 We remove this mark in type_unification_real. */
22463 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22464 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22465 = ARGUMENT_PACK_ARGS (targ);
22467 /* We have some incomplete argument packs. */
22468 incomplete = true;
22472 if (incomplete)
22474 if (!push_tinst_level (fn, explicit_targs))
22476 excessive_deduction_depth = true;
22477 goto fail;
22479 ++processing_template_decl;
22480 input_location = DECL_SOURCE_LOCATION (fn);
22481 /* Ignore any access checks; we'll see them again in
22482 instantiate_template and they might have the wrong
22483 access path at this point. */
22484 push_deferring_access_checks (dk_deferred);
22485 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22486 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22487 pop_deferring_access_checks ();
22488 input_location = loc;
22489 --processing_template_decl;
22490 pop_tinst_level ();
22492 if (fntype == error_mark_node)
22493 goto fail;
22496 /* Place the explicitly specified arguments in TARGS. */
22497 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22498 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22499 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22500 if (!incomplete && CHECKING_P
22501 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22502 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22503 (targs, NUM_TMPL_ARGS (explicit_targs));
22506 if (return_type && strict != DEDUCE_CALL)
22508 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22509 new_args[0] = return_type;
22510 memcpy (new_args + 1, args, nargs * sizeof (tree));
22511 args = new_args;
22512 ++nargs;
22515 if (!incomplete)
22516 goto deduced;
22518 /* Never do unification on the 'this' parameter. */
22519 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22521 if (return_type && strict == DEDUCE_CALL)
22523 /* We're deducing for a call to the result of a template conversion
22524 function. The parms we really want are in return_type. */
22525 if (INDIRECT_TYPE_P (return_type))
22526 return_type = TREE_TYPE (return_type);
22527 parms = TYPE_ARG_TYPES (return_type);
22529 else if (return_type)
22531 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22534 /* We allow incomplete unification without an error message here
22535 because the standard doesn't seem to explicitly prohibit it. Our
22536 callers must be ready to deal with unification failures in any
22537 event. */
22539 /* If we aren't explaining yet, push tinst context so we can see where
22540 any errors (e.g. from class instantiations triggered by instantiation
22541 of default template arguments) come from. If we are explaining, this
22542 context is redundant. */
22543 if (!explain_p && !push_tinst_level (fn, targs))
22545 excessive_deduction_depth = true;
22546 goto fail;
22549 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22550 full_targs, parms, args, nargs, /*subr=*/0,
22551 strict, &checks, explain_p);
22552 if (!explain_p)
22553 pop_tinst_level ();
22554 if (!ok)
22555 goto fail;
22557 /* Now that we have bindings for all of the template arguments,
22558 ensure that the arguments deduced for the template template
22559 parameters have compatible template parameter lists. We cannot
22560 check this property before we have deduced all template
22561 arguments, because the template parameter types of a template
22562 template parameter might depend on prior template parameters
22563 deduced after the template template parameter. The following
22564 ill-formed example illustrates this issue:
22566 template<typename T, template<T> class C> void f(C<5>, T);
22568 template<int N> struct X {};
22570 void g() {
22571 f(X<5>(), 5l); // error: template argument deduction fails
22574 The template parameter list of 'C' depends on the template type
22575 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22576 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22577 time that we deduce 'C'. */
22578 if (!template_template_parm_bindings_ok_p
22579 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22581 unify_inconsistent_template_template_parameters (explain_p);
22582 goto fail;
22585 deduced:
22587 /* As a refinement of CWG2369, check first and foremost non-dependent
22588 conversions that we know are not going to induce template instantiation
22589 (PR99599). */
22590 if (strict == DEDUCE_CALL
22591 && incomplete
22592 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22593 convs, explain_p,
22594 /*noninst_only_p=*/true))
22595 goto fail;
22597 /* CWG2369: Check satisfaction before non-deducible conversions. */
22598 if (!constraints_satisfied_p (fn, targs))
22600 if (explain_p)
22601 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22602 goto fail;
22605 /* DR 1391: All parameters have args, now check non-dependent parms for
22606 convertibility. We don't do this if all args were explicitly specified,
22607 as the standard says that we substitute explicit args immediately. */
22608 if (incomplete
22609 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22610 convs, explain_p,
22611 /*noninst_only_p=*/false))
22612 goto fail;
22614 /* All is well so far. Now, check:
22616 [temp.deduct]
22618 When all template arguments have been deduced, all uses of
22619 template parameters in nondeduced contexts are replaced with
22620 the corresponding deduced argument values. If the
22621 substitution results in an invalid type, as described above,
22622 type deduction fails. */
22623 if (!push_tinst_level (fn, targs))
22625 excessive_deduction_depth = true;
22626 goto fail;
22629 /* Also collect access checks from the instantiation. */
22630 reopen_deferring_access_checks (checks);
22632 decl = instantiate_template (fn, targs, complain);
22634 checks = get_deferred_access_checks ();
22635 pop_deferring_access_checks ();
22637 pop_tinst_level ();
22639 if (decl == error_mark_node)
22640 goto fail;
22642 /* Now perform any access checks encountered during substitution. */
22643 push_access_scope (decl);
22644 ok = perform_access_checks (checks, complain);
22645 pop_access_scope (decl);
22646 if (!ok)
22647 goto fail;
22649 /* If we're looking for an exact match, check that what we got
22650 is indeed an exact match. It might not be if some template
22651 parameters are used in non-deduced contexts. But don't check
22652 for an exact match if we have dependent template arguments;
22653 in that case we're doing partial ordering, and we already know
22654 that we have two candidates that will provide the actual type. */
22655 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22657 tree substed = TREE_TYPE (decl);
22658 unsigned int i;
22660 tree sarg
22661 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22662 if (return_type)
22663 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22664 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22665 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22667 unify_type_mismatch (explain_p, args[i],
22668 TREE_VALUE (sarg));
22669 goto fail;
22671 if ((i < nargs || sarg)
22672 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22673 doesn't contain the trailing void, and conv fns are always (). */
22674 && !DECL_CONV_FN_P (decl))
22676 unsigned nsargs = i + list_length (sarg);
22677 unify_arity (explain_p, nargs, nsargs);
22678 goto fail;
22682 /* After doing deduction with the inherited constructor, actually return an
22683 instantiation of the inheriting constructor. */
22684 if (orig_fn != fn)
22685 decl = instantiate_template (orig_fn, targs, complain);
22687 r = decl;
22689 fail:
22690 --deduction_depth;
22691 if (excessive_deduction_depth)
22693 if (deduction_depth == 0)
22694 /* Reset once we're all the way out. */
22695 excessive_deduction_depth = false;
22698 return r;
22701 /* Returns true iff PARM is a forwarding reference in the context of
22702 template argument deduction for TMPL. */
22704 static bool
22705 forwarding_reference_p (tree parm, tree tmpl)
22707 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22708 cv-unqualified template parameter ..." */
22709 if (TYPE_REF_P (parm)
22710 && TYPE_REF_IS_RVALUE (parm)
22711 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22712 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22714 parm = TREE_TYPE (parm);
22715 /* [temp.deduct.call], "... that does not represent a template parameter
22716 of a class template (during class template argument deduction)." */
22717 if (tmpl
22718 && deduction_guide_p (tmpl)
22719 && DECL_ARTIFICIAL (tmpl))
22721 /* Since the template parameters of a synthesized guide consist of
22722 the template parameters of the class template followed by those of
22723 the constructor (if any), we can tell if PARM represents a template
22724 parameter of the class template by comparing its index with the
22725 arity of the class template. */
22726 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22727 if (TEMPLATE_TYPE_IDX (parm)
22728 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22729 return false;
22731 return true;
22733 return false;
22736 /* Adjust types before performing type deduction, as described in
22737 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22738 sections are symmetric. PARM is the type of a function parameter
22739 or the return type of the conversion function. ARG is the type of
22740 the argument passed to the call, or the type of the value
22741 initialized with the result of the conversion function.
22742 ARG_EXPR is the original argument expression, which may be null. */
22744 static int
22745 maybe_adjust_types_for_deduction (tree tparms,
22746 unification_kind_t strict,
22747 tree* parm,
22748 tree* arg,
22749 tree arg_expr)
22751 int result = 0;
22753 switch (strict)
22755 case DEDUCE_CALL:
22756 break;
22758 case DEDUCE_CONV:
22759 /* [temp.deduct.conv] First remove a reference type on parm.
22760 DRs 322 & 976 affected this. */
22761 if (TYPE_REF_P (*parm))
22762 *parm = TREE_TYPE (*parm);
22764 /* Swap PARM and ARG throughout the remainder of this
22765 function; the handling is precisely symmetric since PARM
22766 will initialize ARG rather than vice versa. */
22767 std::swap (parm, arg);
22769 break;
22771 case DEDUCE_EXACT:
22772 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22773 too, but here handle it by stripping the reference from PARM
22774 rather than by adding it to ARG. */
22775 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22776 && TYPE_REF_P (*arg)
22777 && !TYPE_REF_IS_RVALUE (*arg))
22778 *parm = TREE_TYPE (*parm);
22779 /* Nothing else to do in this case. */
22780 return 0;
22782 default:
22783 gcc_unreachable ();
22786 if (!TYPE_REF_P (*parm))
22788 /* [temp.deduct.call]
22790 If P is not a reference type:
22792 --If A is an array type, the pointer type produced by the
22793 array-to-pointer standard conversion (_conv.array_) is
22794 used in place of A for type deduction; otherwise,
22796 --If A is a function type, the pointer type produced by
22797 the function-to-pointer standard conversion
22798 (_conv.func_) is used in place of A for type deduction;
22799 otherwise,
22801 --If A is a cv-qualified type, the top level
22802 cv-qualifiers of A's type are ignored for type
22803 deduction. */
22804 if (TREE_CODE (*arg) == ARRAY_TYPE)
22805 *arg = build_pointer_type (TREE_TYPE (*arg));
22806 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22807 *arg = build_pointer_type (*arg);
22808 else
22809 *arg = TYPE_MAIN_VARIANT (*arg);
22812 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22813 an lvalue, the type 'lvalue reference to A' is used in place of A for
22814 type deduction." */
22815 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22816 && (arg_expr ? lvalue_p (arg_expr)
22817 /* try_one_overload doesn't provide an arg_expr, but
22818 functions are always lvalues. */
22819 : TREE_CODE (*arg) == FUNCTION_TYPE))
22820 *arg = build_reference_type (*arg);
22822 /* [temp.deduct.call]
22824 If P is a cv-qualified type, the top level cv-qualifiers
22825 of P's type are ignored for type deduction. If P is a
22826 reference type, the type referred to by P is used for
22827 type deduction. */
22828 *parm = TYPE_MAIN_VARIANT (*parm);
22829 if (TYPE_REF_P (*parm))
22831 *parm = TREE_TYPE (*parm);
22832 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22835 return result;
22838 /* Return true if computing a conversion from FROM to TO might induce template
22839 instantiation. Conversely, if this predicate returns false then computing
22840 the conversion definitely won't induce template instantiation. */
22842 static bool
22843 conversion_may_instantiate_p (tree to, tree from)
22845 to = non_reference (to);
22846 from = non_reference (from);
22848 bool ptr_conv_p = false;
22849 if (TYPE_PTR_P (to)
22850 && TYPE_PTR_P (from))
22852 to = TREE_TYPE (to);
22853 from = TREE_TYPE (from);
22854 ptr_conv_p = true;
22857 /* If one of the types is a not-yet-instantiated class template
22858 specialization, then computing the conversion might instantiate
22859 it in order to inspect bases, conversion functions and/or
22860 converting constructors. */
22861 if ((CLASS_TYPE_P (to)
22862 && !COMPLETE_TYPE_P (to)
22863 && CLASSTYPE_TEMPLATE_INSTANTIATION (to))
22864 || (CLASS_TYPE_P (from)
22865 && !COMPLETE_TYPE_P (from)
22866 && CLASSTYPE_TEMPLATE_INSTANTIATION (from)))
22867 return true;
22869 /* Converting from one pointer type to another, or between
22870 reference-related types, always yields a standard conversion. */
22871 if (ptr_conv_p || reference_related_p (to, from))
22872 return false;
22874 /* Converting to a non-aggregate class type will consider its
22875 user-declared constructors, which might induce instantiation. */
22876 if (CLASS_TYPE_P (to)
22877 && CLASSTYPE_NON_AGGREGATE (to))
22878 return true;
22880 /* Similarly, converting from a class type will consider its conversion
22881 functions. */
22882 if (CLASS_TYPE_P (from)
22883 && TYPE_HAS_CONVERSION (from))
22884 return true;
22886 /* Otherwise, computing this conversion definitely won't induce
22887 template instantiation. */
22888 return false;
22891 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22892 template which doesn't contain any deducible template parameters; check if
22893 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22894 unify_one_argument. */
22896 static int
22897 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22898 int flags, struct conversion **conv_p,
22899 bool explain_p, bool noninst_only_p)
22901 tree type;
22903 if (!TYPE_P (arg))
22904 type = TREE_TYPE (arg);
22905 else
22906 type = arg;
22908 if (same_type_p (parm, type))
22909 return unify_success (explain_p);
22911 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22912 if (strict == DEDUCE_CONV)
22914 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22915 return unify_success (explain_p);
22917 else if (strict == DEDUCE_CALL)
22919 if (conv_p && *conv_p)
22921 /* This conversion was already computed earlier (when
22922 computing only non-instantiating conversions). */
22923 gcc_checking_assert (!noninst_only_p);
22924 return unify_success (explain_p);
22927 if (noninst_only_p
22928 && conversion_may_instantiate_p (parm, type))
22929 return unify_success (explain_p);
22931 bool ok = false;
22932 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22933 if (conv_p)
22934 /* Avoid recalculating this in add_function_candidate. */
22935 ok = (*conv_p
22936 = good_conversion (parm, type, conv_arg, flags, complain));
22937 else
22938 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22939 if (ok)
22940 return unify_success (explain_p);
22943 if (strict == DEDUCE_EXACT)
22944 return unify_type_mismatch (explain_p, parm, arg);
22945 else
22946 return unify_arg_conversion (explain_p, parm, type, arg);
22949 static bool uses_deducible_template_parms (tree type);
22951 /* Returns true iff the expression EXPR is one from which a template
22952 argument can be deduced. In other words, if it's an undecorated
22953 use of a template non-type parameter. */
22955 static bool
22956 deducible_expression (tree expr)
22958 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22959 while (CONVERT_EXPR_P (expr)
22960 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22961 || REFERENCE_REF_P (expr))
22962 expr = TREE_OPERAND (expr, 0);
22963 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22966 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22967 deducible way; that is, if it has a max value of <PARM> - 1. */
22969 static bool
22970 deducible_array_bound (tree domain)
22972 if (domain == NULL_TREE)
22973 return false;
22975 tree max = TYPE_MAX_VALUE (domain);
22976 if (TREE_CODE (max) != MINUS_EXPR)
22977 return false;
22979 return deducible_expression (TREE_OPERAND (max, 0));
22982 /* Returns true iff the template arguments ARGS use a template parameter
22983 in a deducible way. */
22985 static bool
22986 deducible_template_args (tree args)
22988 for (tree elt : tree_vec_range (args))
22990 bool deducible;
22991 if (ARGUMENT_PACK_P (elt))
22992 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22993 else
22995 if (PACK_EXPANSION_P (elt))
22996 elt = PACK_EXPANSION_PATTERN (elt);
22997 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22998 deducible = true;
22999 else if (TYPE_P (elt))
23000 deducible = uses_deducible_template_parms (elt);
23001 else
23002 deducible = deducible_expression (elt);
23004 if (deducible)
23005 return true;
23007 return false;
23010 /* Returns true iff TYPE contains any deducible references to template
23011 parameters, as per 14.8.2.5. */
23013 static bool
23014 uses_deducible_template_parms (tree type)
23016 if (PACK_EXPANSION_P (type))
23017 type = PACK_EXPANSION_PATTERN (type);
23019 /* T
23020 cv-list T
23021 TT<T>
23022 TT<i>
23023 TT<> */
23024 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
23025 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
23026 return true;
23028 /* T*
23030 T&& */
23031 if (INDIRECT_TYPE_P (type))
23032 return uses_deducible_template_parms (TREE_TYPE (type));
23034 /* T[integer-constant ]
23035 type [i] */
23036 if (TREE_CODE (type) == ARRAY_TYPE)
23037 return (uses_deducible_template_parms (TREE_TYPE (type))
23038 || deducible_array_bound (TYPE_DOMAIN (type)));
23040 /* T type ::*
23041 type T::*
23042 T T::*
23043 T (type ::*)()
23044 type (T::*)()
23045 type (type ::*)(T)
23046 type (T::*)(T)
23047 T (type ::*)(T)
23048 T (T::*)()
23049 T (T::*)(T) */
23050 if (TYPE_PTRMEM_P (type))
23051 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
23052 || (uses_deducible_template_parms
23053 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
23055 /* template-name <T> (where template-name refers to a class template)
23056 template-name <i> (where template-name refers to a class template) */
23057 if (CLASS_TYPE_P (type)
23058 && CLASSTYPE_TEMPLATE_INFO (type)
23059 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
23060 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
23061 (CLASSTYPE_TI_ARGS (type)));
23063 /* type (T)
23065 T(T) */
23066 if (FUNC_OR_METHOD_TYPE_P (type))
23068 if (uses_deducible_template_parms (TREE_TYPE (type)))
23069 return true;
23070 tree parm = TYPE_ARG_TYPES (type);
23071 if (TREE_CODE (type) == METHOD_TYPE)
23072 parm = TREE_CHAIN (parm);
23073 for (; parm; parm = TREE_CHAIN (parm))
23074 if (uses_deducible_template_parms (TREE_VALUE (parm)))
23075 return true;
23076 if (flag_noexcept_type
23077 && TYPE_RAISES_EXCEPTIONS (type)
23078 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
23079 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
23080 return true;
23083 return false;
23086 /* Subroutine of type_unification_real and unify_pack_expansion to
23087 handle unification of a single P/A pair. Parameters are as
23088 for those functions. */
23090 static int
23091 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23092 int subr, unification_kind_t strict,
23093 bool explain_p)
23095 tree arg_expr = NULL_TREE;
23096 int arg_strict;
23098 if (arg == error_mark_node || parm == error_mark_node)
23099 return unify_invalid (explain_p);
23100 if (arg == unknown_type_node)
23101 /* We can't deduce anything from this, but we might get all the
23102 template args from other function args. */
23103 return unify_success (explain_p);
23105 /* Implicit conversions (Clause 4) will be performed on a function
23106 argument to convert it to the type of the corresponding function
23107 parameter if the parameter type contains no template-parameters that
23108 participate in template argument deduction. */
23109 if (strict != DEDUCE_EXACT
23110 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23111 /* For function parameters with no deducible template parameters,
23112 just return. We'll check non-dependent conversions later. */
23113 return unify_success (explain_p);
23115 switch (strict)
23117 case DEDUCE_CALL:
23118 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23119 | UNIFY_ALLOW_MORE_CV_QUAL
23120 | UNIFY_ALLOW_DERIVED);
23121 break;
23123 case DEDUCE_CONV:
23124 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23125 break;
23127 case DEDUCE_EXACT:
23128 arg_strict = UNIFY_ALLOW_NONE;
23129 break;
23131 default:
23132 gcc_unreachable ();
23135 /* We only do these transformations if this is the top-level
23136 parameter_type_list in a call or declaration matching; in other
23137 situations (nested function declarators, template argument lists) we
23138 won't be comparing a type to an expression, and we don't do any type
23139 adjustments. */
23140 if (!subr)
23142 if (!TYPE_P (arg))
23144 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23145 if (type_unknown_p (arg))
23147 /* [temp.deduct.type] A template-argument can be
23148 deduced from a pointer to function or pointer
23149 to member function argument if the set of
23150 overloaded functions does not contain function
23151 templates and at most one of a set of
23152 overloaded functions provides a unique
23153 match. */
23154 resolve_overloaded_unification (tparms, targs, parm,
23155 arg, strict,
23156 arg_strict, explain_p);
23157 /* If a unique match was not found, this is a
23158 non-deduced context, so we still succeed. */
23159 return unify_success (explain_p);
23162 arg_expr = arg;
23163 arg = unlowered_expr_type (arg);
23164 if (arg == error_mark_node)
23165 return unify_invalid (explain_p);
23168 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23169 &parm, &arg, arg_expr);
23171 else
23172 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23173 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23174 return unify_template_argument_mismatch (explain_p, parm, arg);
23176 /* For deduction from an init-list we need the actual list. */
23177 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23178 arg = arg_expr;
23179 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23182 /* for_each_template_parm callback that always returns 0. */
23184 static int
23185 zero_r (tree, void *)
23187 return 0;
23190 /* for_each_template_parm any_fn callback to handle deduction of a template
23191 type argument from the type of an array bound. */
23193 static int
23194 array_deduction_r (tree t, void *data)
23196 tree_pair_p d = (tree_pair_p)data;
23197 tree &tparms = d->purpose;
23198 tree &targs = d->value;
23200 if (TREE_CODE (t) == ARRAY_TYPE)
23201 if (tree dom = TYPE_DOMAIN (t))
23202 if (tree max = TYPE_MAX_VALUE (dom))
23204 if (TREE_CODE (max) == MINUS_EXPR)
23205 max = TREE_OPERAND (max, 0);
23206 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23207 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23208 UNIFY_ALLOW_NONE, /*explain*/false);
23211 /* Keep walking. */
23212 return 0;
23215 /* Try to deduce any not-yet-deduced template type arguments from the type of
23216 an array bound. This is handled separately from unify because 14.8.2.5 says
23217 "The type of a type parameter is only deduced from an array bound if it is
23218 not otherwise deduced." */
23220 static void
23221 try_array_deduction (tree tparms, tree targs, tree parm)
23223 tree_pair_s data = { tparms, targs };
23224 hash_set<tree> visited;
23225 for_each_template_parm (parm, zero_r, &data, &visited,
23226 /*nondeduced*/false, array_deduction_r);
23229 /* Most parms like fn_type_unification.
23231 If SUBR is 1, we're being called recursively (to unify the
23232 arguments of a function or method parameter of a function
23233 template).
23235 CHECKS is a pointer to a vector of access checks encountered while
23236 substituting default template arguments. */
23238 static int
23239 type_unification_real (tree tparms,
23240 tree full_targs,
23241 tree xparms,
23242 const tree *xargs,
23243 unsigned int xnargs,
23244 int subr,
23245 unification_kind_t strict,
23246 vec<deferred_access_check, va_gc> **checks,
23247 bool explain_p)
23249 tree parm, arg;
23250 int i;
23251 int ntparms = TREE_VEC_LENGTH (tparms);
23252 int saw_undeduced = 0;
23253 tree parms;
23254 const tree *args;
23255 unsigned int nargs;
23256 unsigned int ia;
23258 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23259 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23260 gcc_assert (ntparms > 0);
23262 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23264 /* Reset the number of non-defaulted template arguments contained
23265 in TARGS. */
23266 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23268 again:
23269 parms = xparms;
23270 args = xargs;
23271 nargs = xnargs;
23273 /* Only fn_type_unification cares about terminal void. */
23274 if (nargs && args[nargs-1] == void_type_node)
23275 --nargs;
23277 ia = 0;
23278 while (parms && parms != void_list_node
23279 && ia < nargs)
23281 parm = TREE_VALUE (parms);
23283 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23284 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23285 /* For a function parameter pack that occurs at the end of the
23286 parameter-declaration-list, the type A of each remaining
23287 argument of the call is compared with the type P of the
23288 declarator-id of the function parameter pack. */
23289 break;
23291 parms = TREE_CHAIN (parms);
23293 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23294 /* For a function parameter pack that does not occur at the
23295 end of the parameter-declaration-list, the type of the
23296 parameter pack is a non-deduced context. */
23297 continue;
23299 arg = args[ia];
23300 ++ia;
23302 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23303 explain_p))
23304 return 1;
23307 if (parms
23308 && parms != void_list_node
23309 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23311 /* Unify the remaining arguments with the pack expansion type. */
23312 tree argvec;
23313 tree parmvec = make_tree_vec (1);
23315 /* Allocate a TREE_VEC and copy in all of the arguments */
23316 argvec = make_tree_vec (nargs - ia);
23317 for (i = 0; ia < nargs; ++ia, ++i)
23318 TREE_VEC_ELT (argvec, i) = args[ia];
23320 /* Copy the parameter into parmvec. */
23321 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23322 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23323 /*subr=*/subr, explain_p))
23324 return 1;
23326 /* Advance to the end of the list of parameters. */
23327 parms = TREE_CHAIN (parms);
23330 /* Fail if we've reached the end of the parm list, and more args
23331 are present, and the parm list isn't variadic. */
23332 if (ia < nargs && parms == void_list_node)
23333 return unify_too_many_arguments (explain_p, nargs, ia);
23334 /* Fail if parms are left and they don't have default values and
23335 they aren't all deduced as empty packs (c++/57397). This is
23336 consistent with sufficient_parms_p. */
23337 if (parms && parms != void_list_node
23338 && TREE_PURPOSE (parms) == NULL_TREE)
23340 unsigned int count = nargs;
23341 tree p = parms;
23342 bool type_pack_p;
23345 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23346 if (!type_pack_p)
23347 count++;
23348 p = TREE_CHAIN (p);
23350 while (p && p != void_list_node);
23351 if (count != nargs)
23352 return unify_too_few_arguments (explain_p, ia, count,
23353 type_pack_p);
23356 if (!subr)
23358 tsubst_flags_t complain = (explain_p
23359 ? tf_warning_or_error
23360 : tf_none);
23361 bool tried_array_deduction = (cxx_dialect < cxx17);
23363 for (i = 0; i < ntparms; i++)
23365 tree targ = TREE_VEC_ELT (targs, i);
23366 tree tparm = TREE_VEC_ELT (tparms, i);
23368 /* Clear the "incomplete" flags on all argument packs now so that
23369 substituting them into later default arguments works. */
23370 if (targ && ARGUMENT_PACK_P (targ))
23372 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23373 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23376 if (targ || tparm == error_mark_node)
23377 continue;
23378 tparm = TREE_VALUE (tparm);
23380 if (TREE_CODE (tparm) == TYPE_DECL
23381 && !tried_array_deduction)
23383 try_array_deduction (tparms, targs, xparms);
23384 tried_array_deduction = true;
23385 if (TREE_VEC_ELT (targs, i))
23386 continue;
23389 /* If this is an undeduced nontype parameter that depends on
23390 a type parameter, try another pass; its type may have been
23391 deduced from a later argument than the one from which
23392 this parameter can be deduced. */
23393 if (TREE_CODE (tparm) == PARM_DECL
23394 && !is_auto (TREE_TYPE (tparm))
23395 && uses_template_parms (TREE_TYPE (tparm))
23396 && saw_undeduced < 2)
23398 saw_undeduced = 1;
23399 continue;
23402 /* Core issue #226 (C++0x) [temp.deduct]:
23404 If a template argument has not been deduced, its
23405 default template argument, if any, is used.
23407 When we are in C++98 mode, TREE_PURPOSE will either
23408 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23409 to explicitly check cxx_dialect here. */
23410 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23411 /* OK, there is a default argument. Wait until after the
23412 conversion check to do substitution. */
23413 continue;
23415 /* If the type parameter is a parameter pack, then it will
23416 be deduced to an empty parameter pack. */
23417 if (template_parameter_pack_p (tparm))
23419 tree arg;
23421 if (TREE_CODE (tparm) == PARM_DECL)
23423 arg = make_node (NONTYPE_ARGUMENT_PACK);
23424 TREE_CONSTANT (arg) = 1;
23426 else
23427 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23429 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23431 TREE_VEC_ELT (targs, i) = arg;
23432 continue;
23435 return unify_parameter_deduction_failure (explain_p, tparm);
23438 /* During partial ordering, we deduce dependent template args. */
23439 bool any_dependent_targs = false;
23441 /* Now substitute into the default template arguments. */
23442 for (i = 0; i < ntparms; i++)
23444 tree targ = TREE_VEC_ELT (targs, i);
23445 tree tparm = TREE_VEC_ELT (tparms, i);
23447 if (targ)
23449 if (!any_dependent_targs && dependent_template_arg_p (targ))
23450 any_dependent_targs = true;
23451 continue;
23453 if (tparm == error_mark_node)
23454 continue;
23456 tree parm = TREE_VALUE (tparm);
23457 tree arg = TREE_PURPOSE (tparm);
23458 reopen_deferring_access_checks (*checks);
23459 location_t save_loc = input_location;
23460 if (DECL_P (parm))
23461 input_location = DECL_SOURCE_LOCATION (parm);
23463 if (saw_undeduced == 1
23464 && TREE_CODE (parm) == PARM_DECL
23465 && !is_auto (TREE_TYPE (parm))
23466 && uses_template_parms (TREE_TYPE (parm)))
23468 /* The type of this non-type parameter depends on undeduced
23469 parameters. Don't try to use its default argument yet,
23470 since we might deduce an argument for it on the next pass,
23471 but do check whether the arguments we already have cause
23472 substitution failure, so that that happens before we try
23473 later default arguments (78489). */
23474 ++processing_template_decl;
23475 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23476 NULL_TREE);
23477 --processing_template_decl;
23478 if (type == error_mark_node)
23479 arg = error_mark_node;
23480 else
23481 arg = NULL_TREE;
23483 else
23485 /* Even if the call is happening in template context, getting
23486 here means it's non-dependent, and a default argument is
23487 considered a separate definition under [temp.decls], so we can
23488 do this substitution without processing_template_decl. This
23489 is important if the default argument contains something that
23490 might be instantiation-dependent like access (87480). */
23491 processing_template_decl_sentinel s (!any_dependent_targs);
23492 tree substed = NULL_TREE;
23493 if (saw_undeduced == 1 && !any_dependent_targs)
23495 /* First instatiate in template context, in case we still
23496 depend on undeduced template parameters. */
23497 ++processing_template_decl;
23498 substed = tsubst_template_arg (arg, full_targs, complain,
23499 NULL_TREE);
23500 --processing_template_decl;
23501 if (substed != error_mark_node
23502 && !uses_template_parms (substed))
23503 /* We replaced all the tparms, substitute again out of
23504 template context. */
23505 substed = NULL_TREE;
23507 if (!substed)
23508 substed = tsubst_template_arg (arg, full_targs, complain,
23509 NULL_TREE);
23511 if (!uses_template_parms (substed))
23512 arg = convert_template_argument (parm, substed, full_targs,
23513 complain, i, NULL_TREE);
23514 else if (saw_undeduced == 1)
23515 arg = NULL_TREE;
23516 else if (!any_dependent_targs)
23517 arg = error_mark_node;
23520 input_location = save_loc;
23521 *checks = get_deferred_access_checks ();
23522 pop_deferring_access_checks ();
23524 if (arg == error_mark_node)
23525 return 1;
23526 else if (arg)
23528 TREE_VEC_ELT (targs, i) = arg;
23529 /* The position of the first default template argument,
23530 is also the number of non-defaulted arguments in TARGS.
23531 Record that. */
23532 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23533 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23537 if (saw_undeduced++ == 1)
23538 goto again;
23541 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23542 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23544 return unify_success (explain_p);
23547 /* Subroutine of type_unification_real. Args are like the variables
23548 at the call site. ARG is an overloaded function (or template-id);
23549 we try deducing template args from each of the overloads, and if
23550 only one succeeds, we go with that. Modifies TARGS and returns
23551 true on success. */
23553 static bool
23554 resolve_overloaded_unification (tree tparms,
23555 tree targs,
23556 tree parm,
23557 tree arg,
23558 unification_kind_t strict,
23559 int sub_strict,
23560 bool explain_p)
23562 tree tempargs = copy_node (targs);
23563 int good = 0;
23564 tree goodfn = NULL_TREE;
23565 bool addr_p;
23567 if (TREE_CODE (arg) == ADDR_EXPR)
23569 arg = TREE_OPERAND (arg, 0);
23570 addr_p = true;
23572 else
23573 addr_p = false;
23575 if (TREE_CODE (arg) == COMPONENT_REF)
23576 /* Handle `&x' where `x' is some static or non-static member
23577 function name. */
23578 arg = TREE_OPERAND (arg, 1);
23580 if (TREE_CODE (arg) == OFFSET_REF)
23581 arg = TREE_OPERAND (arg, 1);
23583 /* Strip baselink information. */
23584 if (BASELINK_P (arg))
23585 arg = BASELINK_FUNCTIONS (arg);
23587 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23589 /* If we got some explicit template args, we need to plug them into
23590 the affected templates before we try to unify, in case the
23591 explicit args will completely resolve the templates in question. */
23593 int ok = 0;
23594 tree expl_subargs = TREE_OPERAND (arg, 1);
23595 arg = TREE_OPERAND (arg, 0);
23597 for (lkp_iterator iter (arg); iter; ++iter)
23599 tree fn = *iter;
23600 tree subargs, elem;
23602 if (TREE_CODE (fn) != TEMPLATE_DECL)
23603 continue;
23605 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23606 expl_subargs, NULL_TREE, tf_none);
23607 if (subargs != error_mark_node
23608 && !any_dependent_template_arguments_p (subargs))
23610 fn = instantiate_template (fn, subargs, tf_none);
23611 if (!constraints_satisfied_p (fn))
23612 continue;
23613 if (undeduced_auto_decl (fn))
23615 /* Instantiate the function to deduce its return type. */
23616 ++function_depth;
23617 instantiate_decl (fn, /*defer*/false, /*class*/false);
23618 --function_depth;
23621 if (flag_noexcept_type)
23622 maybe_instantiate_noexcept (fn, tf_none);
23624 elem = TREE_TYPE (fn);
23625 if (try_one_overload (tparms, targs, tempargs, parm,
23626 elem, strict, sub_strict, addr_p, explain_p)
23627 && (!goodfn || !same_type_p (goodfn, elem)))
23629 goodfn = elem;
23630 ++good;
23633 else if (subargs)
23634 ++ok;
23636 /* If no templates (or more than one) are fully resolved by the
23637 explicit arguments, this template-id is a non-deduced context; it
23638 could still be OK if we deduce all template arguments for the
23639 enclosing call through other arguments. */
23640 if (good != 1)
23641 good = ok;
23643 else if (!OVL_P (arg))
23644 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23645 -- but the deduction does not succeed because the expression is
23646 not just the function on its own. */
23647 return false;
23648 else
23649 for (lkp_iterator iter (arg); iter; ++iter)
23651 tree fn = *iter;
23652 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23653 strict, sub_strict, addr_p, explain_p)
23654 && (!goodfn || !decls_match (goodfn, fn)))
23656 goodfn = fn;
23657 ++good;
23661 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23662 to function or pointer to member function argument if the set of
23663 overloaded functions does not contain function templates and at most
23664 one of a set of overloaded functions provides a unique match.
23666 So if we found multiple possibilities, we return success but don't
23667 deduce anything. */
23669 if (good == 1)
23671 int i = TREE_VEC_LENGTH (targs);
23672 for (; i--; )
23673 if (TREE_VEC_ELT (tempargs, i))
23675 tree old = TREE_VEC_ELT (targs, i);
23676 tree new_ = TREE_VEC_ELT (tempargs, i);
23677 if (new_ && old && ARGUMENT_PACK_P (old)
23678 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23679 /* Don't forget explicit template arguments in a pack. */
23680 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23681 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23682 TREE_VEC_ELT (targs, i) = new_;
23685 if (good)
23686 return true;
23688 return false;
23691 /* Core DR 115: In contexts where deduction is done and fails, or in
23692 contexts where deduction is not done, if a template argument list is
23693 specified and it, along with any default template arguments, identifies
23694 a single function template specialization, then the template-id is an
23695 lvalue for the function template specialization. */
23697 tree
23698 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23700 tree expr, offset, baselink;
23701 bool addr;
23703 if (!type_unknown_p (orig_expr))
23704 return orig_expr;
23706 expr = orig_expr;
23707 addr = false;
23708 offset = NULL_TREE;
23709 baselink = NULL_TREE;
23711 if (TREE_CODE (expr) == ADDR_EXPR)
23713 expr = TREE_OPERAND (expr, 0);
23714 addr = true;
23716 if (TREE_CODE (expr) == OFFSET_REF)
23718 offset = expr;
23719 expr = TREE_OPERAND (expr, 1);
23721 if (BASELINK_P (expr))
23723 baselink = expr;
23724 expr = BASELINK_FUNCTIONS (expr);
23727 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23729 int good = 0;
23730 tree goodfn = NULL_TREE;
23732 /* If we got some explicit template args, we need to plug them into
23733 the affected templates before we try to unify, in case the
23734 explicit args will completely resolve the templates in question. */
23736 tree expl_subargs = TREE_OPERAND (expr, 1);
23737 tree arg = TREE_OPERAND (expr, 0);
23738 tree badfn = NULL_TREE;
23739 tree badargs = NULL_TREE;
23741 for (lkp_iterator iter (arg); iter; ++iter)
23743 tree fn = *iter;
23744 tree subargs, elem;
23746 if (TREE_CODE (fn) != TEMPLATE_DECL)
23747 continue;
23749 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23750 expl_subargs, NULL_TREE, tf_none);
23751 if (subargs != error_mark_node
23752 && !any_dependent_template_arguments_p (subargs))
23754 elem = instantiate_template (fn, subargs, tf_none);
23755 if (elem == error_mark_node)
23757 badfn = fn;
23758 badargs = subargs;
23760 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23761 && constraints_satisfied_p (elem))
23763 goodfn = elem;
23764 ++good;
23768 if (good == 1)
23770 mark_used (goodfn);
23771 expr = goodfn;
23772 if (baselink)
23773 expr = build_baselink (BASELINK_BINFO (baselink),
23774 BASELINK_ACCESS_BINFO (baselink),
23775 expr, BASELINK_OPTYPE (baselink));
23776 if (offset)
23778 tree base
23779 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23780 expr = build_offset_ref (base, expr, addr, complain);
23782 if (addr)
23783 expr = cp_build_addr_expr (expr, complain);
23784 return expr;
23786 else if (good == 0 && badargs && (complain & tf_error))
23787 /* There were no good options and at least one bad one, so let the
23788 user know what the problem is. */
23789 instantiate_template (badfn, badargs, complain);
23791 return orig_expr;
23794 /* As above, but error out if the expression remains overloaded. */
23796 tree
23797 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23799 exp = resolve_nondeduced_context (exp, complain);
23800 if (type_unknown_p (exp))
23802 if (complain & tf_error)
23803 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23804 return error_mark_node;
23806 return exp;
23809 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23810 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23811 different overloads deduce different arguments for a given parm.
23812 ADDR_P is true if the expression for which deduction is being
23813 performed was of the form "& fn" rather than simply "fn".
23815 Returns 1 on success. */
23817 static int
23818 try_one_overload (tree tparms,
23819 tree orig_targs,
23820 tree targs,
23821 tree parm,
23822 tree arg,
23823 unification_kind_t strict,
23824 int sub_strict,
23825 bool addr_p,
23826 bool explain_p)
23828 int nargs;
23829 tree tempargs;
23830 int i;
23832 if (arg == error_mark_node)
23833 return 0;
23835 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23836 to function or pointer to member function argument if the set of
23837 overloaded functions does not contain function templates and at most
23838 one of a set of overloaded functions provides a unique match.
23840 So if this is a template, just return success. */
23842 if (uses_template_parms (arg))
23843 return 1;
23845 if (TREE_CODE (arg) == METHOD_TYPE)
23846 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23847 else if (addr_p)
23848 arg = build_pointer_type (arg);
23850 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23851 &parm, &arg, NULL_TREE);
23853 /* We don't copy orig_targs for this because if we have already deduced
23854 some template args from previous args, unify would complain when we
23855 try to deduce a template parameter for the same argument, even though
23856 there isn't really a conflict. */
23857 nargs = TREE_VEC_LENGTH (targs);
23858 tempargs = make_tree_vec (nargs);
23860 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23861 return 0;
23863 /* First make sure we didn't deduce anything that conflicts with
23864 explicitly specified args. */
23865 for (i = nargs; i--; )
23867 tree elt = TREE_VEC_ELT (tempargs, i);
23868 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23870 if (!elt)
23871 /*NOP*/;
23872 else if (uses_template_parms (elt))
23873 /* Since we're unifying against ourselves, we will fill in
23874 template args used in the function parm list with our own
23875 template parms. Discard them. */
23876 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23877 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23879 /* Check that the argument at each index of the deduced argument pack
23880 is equivalent to the corresponding explicitly specified argument.
23881 We may have deduced more arguments than were explicitly specified,
23882 and that's OK. */
23884 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23885 that's wrong if we deduce the same argument pack from multiple
23886 function arguments: it's only incomplete the first time. */
23888 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23889 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23891 if (TREE_VEC_LENGTH (deduced_pack)
23892 < TREE_VEC_LENGTH (explicit_pack))
23893 return 0;
23895 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23896 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23897 TREE_VEC_ELT (deduced_pack, j)))
23898 return 0;
23900 else if (oldelt && !template_args_equal (oldelt, elt))
23901 return 0;
23904 for (i = nargs; i--; )
23906 tree elt = TREE_VEC_ELT (tempargs, i);
23908 if (elt)
23909 TREE_VEC_ELT (targs, i) = elt;
23912 return 1;
23915 /* PARM is a template class (perhaps with unbound template
23916 parameters). ARG is a fully instantiated type. If ARG can be
23917 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23918 TARGS are as for unify. */
23920 static tree
23921 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23922 bool explain_p)
23924 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23925 return NULL_TREE;
23926 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23927 /* Matches anything. */;
23928 else if (CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
23929 return NULL_TREE;
23931 /* We need to make a new template argument vector for the call to
23932 unify. If we used TARGS, we'd clutter it up with the result of
23933 the attempted unification, even if this class didn't work out.
23934 We also don't want to commit ourselves to all the unifications
23935 we've already done, since unification is supposed to be done on
23936 an argument-by-argument basis. In other words, consider the
23937 following pathological case:
23939 template <int I, int J, int K>
23940 struct S {};
23942 template <int I, int J>
23943 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23945 template <int I, int J, int K>
23946 void f(S<I, J, K>, S<I, I, I>);
23948 void g() {
23949 S<0, 0, 0> s0;
23950 S<0, 1, 2> s2;
23952 f(s0, s2);
23955 Now, by the time we consider the unification involving `s2', we
23956 already know that we must have `f<0, 0, 0>'. But, even though
23957 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23958 because there are two ways to unify base classes of S<0, 1, 2>
23959 with S<I, I, I>. If we kept the already deduced knowledge, we
23960 would reject the possibility I=1. */
23961 targs = copy_template_args (targs);
23962 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23963 targ = NULL_TREE;
23965 int err;
23966 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23967 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23968 else
23969 err = unify (tparms, targs,
23970 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
23971 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (arg)),
23972 UNIFY_ALLOW_NONE, explain_p);
23974 return err ? NULL_TREE : arg;
23977 /* Given a template type PARM and a class type ARG, find the unique
23978 base type in ARG that is an instance of PARM. We do not examine
23979 ARG itself; only its base-classes. If there is not exactly one
23980 appropriate base class, return NULL_TREE. PARM may be the type of
23981 a partial specialization, as well as a plain template type. Used
23982 by unify. */
23984 static enum template_base_result
23985 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23986 bool explain_p, tree *result)
23988 tree rval = NULL_TREE;
23989 tree binfo;
23991 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23993 binfo = TYPE_BINFO (complete_type (arg));
23994 if (!binfo)
23996 /* The type could not be completed. */
23997 *result = NULL_TREE;
23998 return tbr_incomplete_type;
24001 /* Walk in inheritance graph order. The search order is not
24002 important, and this avoids multiple walks of virtual bases. */
24003 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
24005 tree r = try_class_unification (tparms, targs, parm,
24006 BINFO_TYPE (binfo), explain_p);
24008 if (r)
24010 /* If there is more than one satisfactory baseclass, then:
24012 [temp.deduct.call]
24014 If they yield more than one possible deduced A, the type
24015 deduction fails.
24017 applies. */
24018 if (rval && !same_type_p (r, rval))
24020 /* [temp.deduct.call]/4.3: If there is a class C that is a
24021 (direct or indirect) base class of D and derived (directly or
24022 indirectly) from a class B and that would be a valid deduced
24023 A, the deduced A cannot be B or pointer to B, respectively. */
24024 if (DERIVED_FROM_P (r, rval))
24025 /* Ignore r. */
24026 continue;
24027 else if (DERIVED_FROM_P (rval, r))
24028 /* Ignore rval. */;
24029 else
24031 *result = NULL_TREE;
24032 return tbr_ambiguous_baseclass;
24036 rval = r;
24040 *result = rval;
24041 return tbr_success;
24044 /* Returns the level of DECL, which declares a template parameter. */
24046 static int
24047 template_decl_level (tree decl)
24049 switch (TREE_CODE (decl))
24051 case TYPE_DECL:
24052 case TEMPLATE_DECL:
24053 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
24055 case PARM_DECL:
24056 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
24058 default:
24059 gcc_unreachable ();
24061 return 0;
24064 /* Decide whether ARG can be unified with PARM, considering only the
24065 cv-qualifiers of each type, given STRICT as documented for unify.
24066 Returns nonzero iff the unification is OK on that basis. */
24068 static int
24069 check_cv_quals_for_unify (int strict, tree arg, tree parm)
24071 int arg_quals = cp_type_quals (arg);
24072 int parm_quals = cp_type_quals (parm);
24074 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24075 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24077 /* Although a CVR qualifier is ignored when being applied to a
24078 substituted template parameter ([8.3.2]/1 for example), that
24079 does not allow us to unify "const T" with "int&" because both
24080 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
24081 It is ok when we're allowing additional CV qualifiers
24082 at the outer level [14.8.2.1]/3,1st bullet. */
24083 if ((TYPE_REF_P (arg)
24084 || FUNC_OR_METHOD_TYPE_P (arg))
24085 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24086 return 0;
24088 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24089 && (parm_quals & TYPE_QUAL_RESTRICT))
24090 return 0;
24093 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24094 && (arg_quals & parm_quals) != parm_quals)
24095 return 0;
24097 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24098 && (parm_quals & arg_quals) != arg_quals)
24099 return 0;
24101 return 1;
24104 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24105 void
24106 template_parm_level_and_index (tree parm, int* level, int* index)
24108 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24109 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24110 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24112 *index = TEMPLATE_TYPE_IDX (parm);
24113 *level = TEMPLATE_TYPE_LEVEL (parm);
24115 else
24117 *index = TEMPLATE_PARM_IDX (parm);
24118 *level = TEMPLATE_PARM_LEVEL (parm);
24122 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24123 do { \
24124 if (unify (TP, TA, P, A, S, EP)) \
24125 return 1; \
24126 } while (0)
24128 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24129 expansion at the end of PACKED_PARMS. Returns 0 if the type
24130 deduction succeeds, 1 otherwise. STRICT is the same as in
24131 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24132 function call argument list. We'll need to adjust the arguments to make them
24133 types. SUBR tells us if this is from a recursive call to
24134 type_unification_real, or for comparing two template argument
24135 lists. */
24137 static int
24138 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24139 tree packed_args, unification_kind_t strict,
24140 bool subr, bool explain_p)
24142 tree parm
24143 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24144 tree pattern = PACK_EXPANSION_PATTERN (parm);
24145 tree pack, packs = NULL_TREE;
24146 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24148 /* Add in any args remembered from an earlier partial instantiation. */
24149 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24150 int levels = TMPL_ARGS_DEPTH (targs);
24152 packed_args = expand_template_argument_pack (packed_args);
24154 int len = TREE_VEC_LENGTH (packed_args);
24156 /* Determine the parameter packs we will be deducing from the
24157 pattern, and record their current deductions. */
24158 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24159 pack; pack = TREE_CHAIN (pack))
24161 tree parm_pack = TREE_VALUE (pack);
24162 int idx, level;
24164 /* Only template parameter packs can be deduced, not e.g. function
24165 parameter packs or __bases or __integer_pack. */
24166 if (!TEMPLATE_PARM_P (parm_pack))
24167 continue;
24169 /* Determine the index and level of this parameter pack. */
24170 template_parm_level_and_index (parm_pack, &level, &idx);
24171 if (level > levels)
24172 continue;
24174 /* Keep track of the parameter packs and their corresponding
24175 argument packs. */
24176 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24177 TREE_TYPE (packs) = make_tree_vec (len - start);
24180 /* Loop through all of the arguments that have not yet been
24181 unified and unify each with the pattern. */
24182 for (i = start; i < len; i++)
24184 tree parm;
24185 bool any_explicit = false;
24186 tree arg = TREE_VEC_ELT (packed_args, i);
24188 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24189 or the element of its argument pack at the current index if
24190 this argument was explicitly specified. */
24191 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24193 int idx, level;
24194 tree arg, pargs;
24195 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24197 arg = NULL_TREE;
24198 if (TREE_VALUE (pack)
24199 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24200 && (i - start < TREE_VEC_LENGTH (pargs)))
24202 any_explicit = true;
24203 arg = TREE_VEC_ELT (pargs, i - start);
24205 TMPL_ARG (targs, level, idx) = arg;
24208 /* If we had explicit template arguments, substitute them into the
24209 pattern before deduction. */
24210 if (any_explicit)
24212 /* Some arguments might still be unspecified or dependent. */
24213 bool dependent;
24214 ++processing_template_decl;
24215 dependent = any_dependent_template_arguments_p (targs);
24216 if (!dependent)
24217 --processing_template_decl;
24218 parm = tsubst (pattern, targs,
24219 explain_p ? tf_warning_or_error : tf_none,
24220 NULL_TREE);
24221 if (dependent)
24222 --processing_template_decl;
24223 if (parm == error_mark_node)
24224 return 1;
24226 else
24227 parm = pattern;
24229 /* Unify the pattern with the current argument. */
24230 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24231 explain_p))
24232 return 1;
24234 /* For each parameter pack, collect the deduced value. */
24235 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24237 int idx, level;
24238 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24240 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24241 TMPL_ARG (targs, level, idx);
24245 /* Verify that the results of unification with the parameter packs
24246 produce results consistent with what we've seen before, and make
24247 the deduced argument packs available. */
24248 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24250 tree old_pack = TREE_VALUE (pack);
24251 tree new_args = TREE_TYPE (pack);
24252 int i, len = TREE_VEC_LENGTH (new_args);
24253 int idx, level;
24254 bool nondeduced_p = false;
24256 /* By default keep the original deduced argument pack.
24257 If necessary, more specific code is going to update the
24258 resulting deduced argument later down in this function. */
24259 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24260 TMPL_ARG (targs, level, idx) = old_pack;
24262 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24263 actually deduce anything. */
24264 for (i = 0; i < len && !nondeduced_p; ++i)
24265 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24266 nondeduced_p = true;
24267 if (nondeduced_p)
24268 continue;
24270 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24272 /* If we had fewer function args than explicit template args,
24273 just use the explicits. */
24274 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24275 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24276 if (len < explicit_len)
24277 new_args = explicit_args;
24280 if (!old_pack)
24282 tree result;
24283 /* Build the deduced *_ARGUMENT_PACK. */
24284 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24286 result = make_node (NONTYPE_ARGUMENT_PACK);
24287 TREE_CONSTANT (result) = 1;
24289 else
24290 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24292 ARGUMENT_PACK_ARGS (result) = new_args;
24294 /* Note the deduced argument packs for this parameter
24295 pack. */
24296 TMPL_ARG (targs, level, idx) = result;
24298 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24299 && (ARGUMENT_PACK_ARGS (old_pack)
24300 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24302 /* We only had the explicitly-provided arguments before, but
24303 now we have a complete set of arguments. */
24304 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24306 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24307 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24308 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24310 else
24312 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24313 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24314 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24315 /* During template argument deduction for the aggregate deduction
24316 candidate, the number of elements in a trailing parameter pack
24317 is only deduced from the number of remaining function
24318 arguments if it is not otherwise deduced. */
24319 if (cxx_dialect >= cxx20
24320 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24321 /* FIXME This isn't set properly for partial instantiations. */
24322 && TPARMS_PRIMARY_TEMPLATE (tparms)
24323 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24324 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24325 if (!comp_template_args (old_args, new_args,
24326 &bad_old_arg, &bad_new_arg))
24327 /* Inconsistent unification of this parameter pack. */
24328 return unify_parameter_pack_inconsistent (explain_p,
24329 bad_old_arg,
24330 bad_new_arg);
24334 return unify_success (explain_p);
24337 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24338 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24339 parameters and return value are as for unify. */
24341 static int
24342 unify_array_domain (tree tparms, tree targs,
24343 tree parm_dom, tree arg_dom,
24344 bool explain_p)
24346 tree parm_max;
24347 tree arg_max;
24348 bool parm_cst;
24349 bool arg_cst;
24351 /* Our representation of array types uses "N - 1" as the
24352 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24353 not an integer constant. We cannot unify arbitrarily
24354 complex expressions, so we eliminate the MINUS_EXPRs
24355 here. */
24356 parm_max = TYPE_MAX_VALUE (parm_dom);
24357 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24358 if (!parm_cst)
24360 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24361 parm_max = TREE_OPERAND (parm_max, 0);
24363 arg_max = TYPE_MAX_VALUE (arg_dom);
24364 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24365 if (!arg_cst)
24367 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24368 trying to unify the type of a variable with the type
24369 of a template parameter. For example:
24371 template <unsigned int N>
24372 void f (char (&) [N]);
24373 int g();
24374 void h(int i) {
24375 char a[g(i)];
24376 f(a);
24379 Here, the type of the ARG will be "int [g(i)]", and
24380 may be a SAVE_EXPR, etc. */
24381 if (TREE_CODE (arg_max) != MINUS_EXPR)
24382 return unify_vla_arg (explain_p, arg_dom);
24383 arg_max = TREE_OPERAND (arg_max, 0);
24386 /* If only one of the bounds used a MINUS_EXPR, compensate
24387 by adding one to the other bound. */
24388 if (parm_cst && !arg_cst)
24389 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24390 integer_type_node,
24391 parm_max,
24392 integer_one_node);
24393 else if (arg_cst && !parm_cst)
24394 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24395 integer_type_node,
24396 arg_max,
24397 integer_one_node);
24399 return unify (tparms, targs, parm_max, arg_max,
24400 UNIFY_ALLOW_INTEGER, explain_p);
24403 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24405 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24407 static pa_kind_t
24408 pa_kind (tree t)
24410 if (PACK_EXPANSION_P (t))
24411 t = PACK_EXPANSION_PATTERN (t);
24412 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24413 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24414 || DECL_TYPE_TEMPLATE_P (t))
24415 return pa_tmpl;
24416 else if (TYPE_P (t))
24417 return pa_type;
24418 else
24419 return pa_expr;
24422 /* Deduce the value of template parameters. TPARMS is the (innermost)
24423 set of template parameters to a template. TARGS is the bindings
24424 for those template parameters, as determined thus far; TARGS may
24425 include template arguments for outer levels of template parameters
24426 as well. PARM is a parameter to a template function, or a
24427 subcomponent of that parameter; ARG is the corresponding argument.
24428 This function attempts to match PARM with ARG in a manner
24429 consistent with the existing assignments in TARGS. If more values
24430 are deduced, then TARGS is updated.
24432 Returns 0 if the type deduction succeeds, 1 otherwise. The
24433 parameter STRICT is a bitwise or of the following flags:
24435 UNIFY_ALLOW_NONE:
24436 Require an exact match between PARM and ARG.
24437 UNIFY_ALLOW_MORE_CV_QUAL:
24438 Allow the deduced ARG to be more cv-qualified (by qualification
24439 conversion) than ARG.
24440 UNIFY_ALLOW_LESS_CV_QUAL:
24441 Allow the deduced ARG to be less cv-qualified than ARG.
24442 UNIFY_ALLOW_DERIVED:
24443 Allow the deduced ARG to be a template base class of ARG,
24444 or a pointer to a template base class of the type pointed to by
24445 ARG.
24446 UNIFY_ALLOW_INTEGER:
24447 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24448 case for more information.
24449 UNIFY_ALLOW_OUTER_LEVEL:
24450 This is the outermost level of a deduction. Used to determine validity
24451 of qualification conversions. A valid qualification conversion must
24452 have const qualified pointers leading up to the inner type which
24453 requires additional CV quals, except at the outer level, where const
24454 is not required [conv.qual]. It would be normal to set this flag in
24455 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24456 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24457 This is the outermost level of a deduction, and PARM can be more CV
24458 qualified at this point.
24459 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24460 This is the outermost level of a deduction, and PARM can be less CV
24461 qualified at this point. */
24463 static int
24464 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24465 bool explain_p)
24467 int idx;
24468 tree targ;
24469 tree tparm;
24470 int strict_in = strict;
24471 tsubst_flags_t complain = (explain_p
24472 ? tf_warning_or_error
24473 : tf_none);
24475 /* I don't think this will do the right thing with respect to types.
24476 But the only case I've seen it in so far has been array bounds, where
24477 signedness is the only information lost, and I think that will be
24478 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24479 finish_id_expression_1, and are also OK. */
24480 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24481 parm = TREE_OPERAND (parm, 0);
24483 if (arg == error_mark_node)
24484 return unify_invalid (explain_p);
24485 if (arg == unknown_type_node
24486 || arg == init_list_type_node)
24487 /* We can't deduce anything from this, but we might get all the
24488 template args from other function args. */
24489 return unify_success (explain_p);
24491 if (parm == any_targ_node || arg == any_targ_node)
24492 return unify_success (explain_p);
24494 /* If PARM uses template parameters, then we can't bail out here,
24495 even if ARG == PARM, since we won't record unifications for the
24496 template parameters. We might need them if we're trying to
24497 figure out which of two things is more specialized. */
24498 if (arg == parm
24499 && (DECL_P (parm) || !uses_template_parms (parm)))
24500 return unify_success (explain_p);
24502 /* Handle init lists early, so the rest of the function can assume
24503 we're dealing with a type. */
24504 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24506 tree elttype;
24507 tree orig_parm = parm;
24509 if (!is_std_init_list (parm)
24510 && TREE_CODE (parm) != ARRAY_TYPE)
24511 /* We can only deduce from an initializer list argument if the
24512 parameter is std::initializer_list or an array; otherwise this
24513 is a non-deduced context. */
24514 return unify_success (explain_p);
24516 if (TREE_CODE (parm) == ARRAY_TYPE)
24517 elttype = TREE_TYPE (parm);
24518 else
24520 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24521 /* Deduction is defined in terms of a single type, so just punt
24522 on the (bizarre) std::initializer_list<T...>. */
24523 if (PACK_EXPANSION_P (elttype))
24524 return unify_success (explain_p);
24527 if (strict != DEDUCE_EXACT
24528 && TYPE_P (elttype)
24529 && !uses_deducible_template_parms (elttype))
24530 /* If ELTTYPE has no deducible template parms, skip deduction from
24531 the list elements. */;
24532 else
24533 for (auto &e: CONSTRUCTOR_ELTS (arg))
24535 tree elt = e.value;
24536 int elt_strict = strict;
24538 if (elt == error_mark_node)
24539 return unify_invalid (explain_p);
24541 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24543 tree type = TREE_TYPE (elt);
24544 if (type == error_mark_node)
24545 return unify_invalid (explain_p);
24546 /* It should only be possible to get here for a call. */
24547 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24548 elt_strict |= maybe_adjust_types_for_deduction
24549 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24550 elt = type;
24553 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24554 explain_p);
24557 if (TREE_CODE (parm) == ARRAY_TYPE
24558 && deducible_array_bound (TYPE_DOMAIN (parm)))
24560 /* Also deduce from the length of the initializer list. */
24561 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24562 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24563 if (idx == error_mark_node)
24564 return unify_invalid (explain_p);
24565 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24566 idx, explain_p);
24569 /* If the std::initializer_list<T> deduction worked, replace the
24570 deduced A with std::initializer_list<A>. */
24571 if (orig_parm != parm)
24573 idx = TEMPLATE_TYPE_IDX (orig_parm);
24574 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24575 targ = listify (targ);
24576 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24578 return unify_success (explain_p);
24581 /* If parm and arg aren't the same kind of thing (template, type, or
24582 expression), fail early. */
24583 if (pa_kind (parm) != pa_kind (arg))
24584 return unify_invalid (explain_p);
24586 /* Immediately reject some pairs that won't unify because of
24587 cv-qualification mismatches. */
24588 if (TREE_CODE (arg) == TREE_CODE (parm)
24589 && TYPE_P (arg)
24590 /* It is the elements of the array which hold the cv quals of an array
24591 type, and the elements might be template type parms. We'll check
24592 when we recurse. */
24593 && TREE_CODE (arg) != ARRAY_TYPE
24594 /* We check the cv-qualifiers when unifying with template type
24595 parameters below. We want to allow ARG `const T' to unify with
24596 PARM `T' for example, when computing which of two templates
24597 is more specialized, for example. */
24598 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24599 && !check_cv_quals_for_unify (strict_in, arg, parm))
24600 return unify_cv_qual_mismatch (explain_p, parm, arg);
24602 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24603 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24604 && !FUNC_OR_METHOD_TYPE_P (parm))
24605 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24606 /* PMFs recurse at the same level, so don't strip this yet. */
24607 if (!TYPE_PTRMEMFUNC_P (parm))
24608 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24609 strict &= ~UNIFY_ALLOW_DERIVED;
24610 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24611 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24613 switch (TREE_CODE (parm))
24615 case TYPENAME_TYPE:
24616 case SCOPE_REF:
24617 case UNBOUND_CLASS_TEMPLATE:
24618 /* In a type which contains a nested-name-specifier, template
24619 argument values cannot be deduced for template parameters used
24620 within the nested-name-specifier. */
24621 return unify_success (explain_p);
24623 case TEMPLATE_TYPE_PARM:
24624 case TEMPLATE_TEMPLATE_PARM:
24625 case BOUND_TEMPLATE_TEMPLATE_PARM:
24626 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24627 if (error_operand_p (tparm))
24628 return unify_invalid (explain_p);
24630 if (TEMPLATE_TYPE_LEVEL (parm)
24631 != template_decl_level (tparm))
24632 /* The PARM is not one we're trying to unify. Just check
24633 to see if it matches ARG. */
24635 if (TREE_CODE (arg) == TREE_CODE (parm)
24636 && (is_auto (parm) ? is_auto (arg)
24637 : same_type_p (parm, arg)))
24638 return unify_success (explain_p);
24639 else
24640 return unify_type_mismatch (explain_p, parm, arg);
24642 idx = TEMPLATE_TYPE_IDX (parm);
24643 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24644 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24645 if (error_operand_p (tparm))
24646 return unify_invalid (explain_p);
24648 /* Check for mixed types and values. */
24649 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24650 && TREE_CODE (tparm) != TYPE_DECL)
24651 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24652 && TREE_CODE (tparm) != TEMPLATE_DECL))
24653 gcc_unreachable ();
24655 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24657 if ((strict_in & UNIFY_ALLOW_DERIVED)
24658 && CLASS_TYPE_P (arg))
24660 /* First try to match ARG directly. */
24661 tree t = try_class_unification (tparms, targs, parm, arg,
24662 explain_p);
24663 if (!t)
24665 /* Otherwise, look for a suitable base of ARG, as below. */
24666 enum template_base_result r;
24667 r = get_template_base (tparms, targs, parm, arg,
24668 explain_p, &t);
24669 if (!t)
24670 return unify_no_common_base (explain_p, r, parm, arg);
24671 arg = t;
24674 /* ARG must be constructed from a template class or a template
24675 template parameter. */
24676 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24677 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24678 return unify_template_deduction_failure (explain_p, parm, arg);
24680 /* Deduce arguments T, i from TT<T> or TT<i>. */
24681 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24682 return 1;
24684 arg = TYPE_TI_TEMPLATE (arg);
24685 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24686 /* If the template is a template template parameter, use the
24687 TEMPLATE_TEMPLATE_PARM for matching. */
24688 arg = TREE_TYPE (arg);
24690 /* Fall through to deduce template name. */
24693 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24694 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24696 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24698 /* Simple cases: Value already set, does match or doesn't. */
24699 if (targ != NULL_TREE && template_args_equal (targ, arg))
24700 return unify_success (explain_p);
24701 else if (targ)
24702 return unify_inconsistency (explain_p, parm, targ, arg);
24704 else
24706 /* If PARM is `const T' and ARG is only `int', we don't have
24707 a match unless we are allowing additional qualification.
24708 If ARG is `const int' and PARM is just `T' that's OK;
24709 that binds `const int' to `T'. */
24710 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24711 arg, parm))
24712 return unify_cv_qual_mismatch (explain_p, parm, arg);
24714 /* Consider the case where ARG is `const volatile int' and
24715 PARM is `const T'. Then, T should be `volatile int'. */
24716 arg = cp_build_qualified_type
24717 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24718 if (arg == error_mark_node)
24719 return unify_invalid (explain_p);
24721 /* Simple cases: Value already set, does match or doesn't. */
24722 if (targ != NULL_TREE && same_type_p (targ, arg))
24723 return unify_success (explain_p);
24724 else if (targ)
24725 return unify_inconsistency (explain_p, parm, targ, arg);
24727 /* Make sure that ARG is not a variable-sized array. (Note
24728 that were talking about variable-sized arrays (like
24729 `int[n]'), rather than arrays of unknown size (like
24730 `int[]').) We'll get very confused by such a type since
24731 the bound of the array is not constant, and therefore
24732 not mangleable. Besides, such types are not allowed in
24733 ISO C++, so we can do as we please here. We do allow
24734 them for 'auto' deduction, since that isn't ABI-exposed. */
24735 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24736 return unify_vla_arg (explain_p, arg);
24738 /* Strip typedefs as in convert_template_argument. */
24739 arg = canonicalize_type_argument (arg, tf_none);
24742 /* If ARG is a parameter pack or an expansion, we cannot unify
24743 against it unless PARM is also a parameter pack. */
24744 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24745 && !template_parameter_pack_p (parm))
24746 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24748 /* If the argument deduction results is a METHOD_TYPE,
24749 then there is a problem.
24750 METHOD_TYPE doesn't map to any real C++ type the result of
24751 the deduction cannot be of that type. */
24752 if (TREE_CODE (arg) == METHOD_TYPE)
24753 return unify_method_type_error (explain_p, arg);
24755 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24756 return unify_success (explain_p);
24758 case TEMPLATE_PARM_INDEX:
24759 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24760 if (error_operand_p (tparm))
24761 return unify_invalid (explain_p);
24763 if (TEMPLATE_PARM_LEVEL (parm)
24764 != template_decl_level (tparm))
24766 /* The PARM is not one we're trying to unify. Just check
24767 to see if it matches ARG. */
24768 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24769 && cp_tree_equal (parm, arg));
24770 if (result)
24771 unify_expression_unequal (explain_p, parm, arg);
24772 return result;
24775 idx = TEMPLATE_PARM_IDX (parm);
24776 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24778 if (targ)
24780 if ((strict & UNIFY_ALLOW_INTEGER)
24781 && TREE_TYPE (targ) && TREE_TYPE (arg)
24782 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24783 /* We're deducing from an array bound, the type doesn't matter.
24784 This conversion should match the one below. */
24785 arg = fold (build_nop (TREE_TYPE (targ), arg));
24786 int x = !cp_tree_equal (targ, arg);
24787 if (x)
24788 unify_inconsistency (explain_p, parm, targ, arg);
24789 return x;
24792 /* [temp.deduct.type] If, in the declaration of a function template
24793 with a non-type template-parameter, the non-type
24794 template-parameter is used in an expression in the function
24795 parameter-list and, if the corresponding template-argument is
24796 deduced, the template-argument type shall match the type of the
24797 template-parameter exactly, except that a template-argument
24798 deduced from an array bound may be of any integral type.
24799 The non-type parameter might use already deduced type parameters. */
24800 tparm = TREE_TYPE (parm);
24801 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24802 /* We don't have enough levels of args to do any substitution. This
24803 can happen in the context of -fnew-ttp-matching. */;
24804 else
24806 ++processing_template_decl;
24807 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24808 --processing_template_decl;
24810 if (tree a = type_uses_auto (tparm))
24812 tparm = do_auto_deduction (tparm, arg, a,
24813 complain, adc_unify, targs,
24814 LOOKUP_NORMAL,
24815 TPARMS_PRIMARY_TEMPLATE (tparms));
24816 if (tparm == error_mark_node)
24817 return 1;
24821 if (!TREE_TYPE (arg)
24822 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24823 /* Template-parameter dependent expression. Just accept it for now.
24824 It will later be processed in convert_template_argument. */
24826 else if (same_type_ignoring_top_level_qualifiers_p
24827 (non_reference (TREE_TYPE (arg)),
24828 non_reference (tparm)))
24829 /* OK. Ignore top-level quals here because a class-type template
24830 parameter object is const. */;
24831 else if ((strict & UNIFY_ALLOW_INTEGER)
24832 && CP_INTEGRAL_TYPE_P (tparm))
24833 /* Convert the ARG to the type of PARM; the deduced non-type
24834 template argument must exactly match the types of the
24835 corresponding parameter. This conversion should match the
24836 one above. */
24837 arg = fold (build_nop (tparm, arg));
24838 else if (uses_template_parms (tparm))
24840 /* We haven't deduced the type of this parameter yet. */
24841 if (cxx_dialect >= cxx17
24842 /* We deduce from array bounds in try_array_deduction. */
24843 && !(strict & UNIFY_ALLOW_INTEGER)
24844 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24846 /* Deduce it from the non-type argument. As above, ignore
24847 top-level quals here too. */
24848 tree atype = cv_unqualified (TREE_TYPE (arg));
24849 RECUR_AND_CHECK_FAILURE (tparms, targs,
24850 tparm, atype,
24851 UNIFY_ALLOW_NONE, explain_p);
24852 /* Now check whether the type of this parameter is still
24853 dependent, and give up if so. */
24854 ++processing_template_decl;
24855 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24856 --processing_template_decl;
24857 if (uses_template_parms (tparm))
24858 return unify_success (explain_p);
24860 else
24861 /* Try again later. */
24862 return unify_success (explain_p);
24864 else
24865 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24867 /* If ARG is a parameter pack or an expansion, we cannot unify
24868 against it unless PARM is also a parameter pack. */
24869 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24870 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24871 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24874 bool removed_attr = false;
24875 arg = strip_typedefs_expr (arg, &removed_attr);
24877 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24878 return unify_success (explain_p);
24880 case PTRMEM_CST:
24882 /* A pointer-to-member constant can be unified only with
24883 another constant. */
24884 if (TREE_CODE (arg) != PTRMEM_CST)
24885 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24887 /* Just unify the class member. It would be useless (and possibly
24888 wrong, depending on the strict flags) to unify also
24889 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24890 arg refer to the same variable, even if through different
24891 classes. For instance:
24893 struct A { int x; };
24894 struct B : A { };
24896 Unification of &A::x and &B::x must succeed. */
24897 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24898 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24901 case POINTER_TYPE:
24903 if (!TYPE_PTR_P (arg))
24904 return unify_type_mismatch (explain_p, parm, arg);
24906 /* [temp.deduct.call]
24908 A can be another pointer or pointer to member type that can
24909 be converted to the deduced A via a qualification
24910 conversion (_conv.qual_).
24912 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24913 This will allow for additional cv-qualification of the
24914 pointed-to types if appropriate. */
24916 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24917 /* The derived-to-base conversion only persists through one
24918 level of pointers. */
24919 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24921 return unify (tparms, targs, TREE_TYPE (parm),
24922 TREE_TYPE (arg), strict, explain_p);
24925 case REFERENCE_TYPE:
24926 if (!TYPE_REF_P (arg))
24927 return unify_type_mismatch (explain_p, parm, arg);
24928 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24929 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24931 case ARRAY_TYPE:
24932 if (TREE_CODE (arg) != ARRAY_TYPE)
24933 return unify_type_mismatch (explain_p, parm, arg);
24934 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24935 != (TYPE_DOMAIN (arg) == NULL_TREE))
24936 return unify_type_mismatch (explain_p, parm, arg);
24937 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24938 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24939 if (TYPE_DOMAIN (parm) != NULL_TREE)
24940 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24941 TYPE_DOMAIN (arg), explain_p);
24942 return unify_success (explain_p);
24944 case REAL_TYPE:
24945 case COMPLEX_TYPE:
24946 case VECTOR_TYPE:
24947 case INTEGER_TYPE:
24948 case BOOLEAN_TYPE:
24949 case ENUMERAL_TYPE:
24950 case VOID_TYPE:
24951 case OPAQUE_TYPE:
24952 case NULLPTR_TYPE:
24953 if (TREE_CODE (arg) != TREE_CODE (parm))
24954 return unify_type_mismatch (explain_p, parm, arg);
24956 /* We have already checked cv-qualification at the top of the
24957 function. */
24958 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24959 return unify_type_mismatch (explain_p, parm, arg);
24961 /* As far as unification is concerned, this wins. Later checks
24962 will invalidate it if necessary. */
24963 return unify_success (explain_p);
24965 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24966 /* Type INTEGER_CST can come from ordinary constant template args. */
24967 case INTEGER_CST:
24968 case REAL_CST:
24969 if (TREE_TYPE (arg) == NULL_TREE
24970 || !same_type_p (TREE_TYPE (parm), TREE_TYPE (arg)))
24971 return unify_template_argument_mismatch (explain_p, parm, arg);
24972 while (CONVERT_EXPR_P (arg))
24973 arg = TREE_OPERAND (arg, 0);
24975 if (TREE_CODE (arg) != TREE_CODE (parm))
24976 return unify_template_argument_mismatch (explain_p, parm, arg);
24977 return (simple_cst_equal (parm, arg)
24978 ? unify_success (explain_p)
24979 : unify_template_argument_mismatch (explain_p, parm, arg));
24981 case TREE_VEC:
24983 int i, len, argslen;
24984 int parm_variadic_p = 0;
24986 if (TREE_CODE (arg) != TREE_VEC)
24987 return unify_template_argument_mismatch (explain_p, parm, arg);
24989 len = TREE_VEC_LENGTH (parm);
24990 argslen = TREE_VEC_LENGTH (arg);
24992 /* Check for pack expansions in the parameters. */
24993 for (i = 0; i < len; ++i)
24995 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24997 if (i == len - 1)
24998 /* We can unify against something with a trailing
24999 parameter pack. */
25000 parm_variadic_p = 1;
25001 else
25002 /* [temp.deduct.type]/9: If the template argument list of
25003 P contains a pack expansion that is not the last
25004 template argument, the entire template argument list
25005 is a non-deduced context. */
25006 return unify_success (explain_p);
25010 /* If we don't have enough arguments to satisfy the parameters
25011 (not counting the pack expression at the end), or we have
25012 too many arguments for a parameter list that doesn't end in
25013 a pack expression, we can't unify. */
25014 if (parm_variadic_p
25015 ? argslen < len - parm_variadic_p
25016 : argslen != len)
25017 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
25019 /* Unify all of the parameters that precede the (optional)
25020 pack expression. */
25021 for (i = 0; i < len - parm_variadic_p; ++i)
25023 RECUR_AND_CHECK_FAILURE (tparms, targs,
25024 TREE_VEC_ELT (parm, i),
25025 TREE_VEC_ELT (arg, i),
25026 UNIFY_ALLOW_NONE, explain_p);
25028 if (parm_variadic_p)
25029 return unify_pack_expansion (tparms, targs, parm, arg,
25030 DEDUCE_EXACT,
25031 /*subr=*/true, explain_p);
25032 return unify_success (explain_p);
25035 case RECORD_TYPE:
25036 case UNION_TYPE:
25037 if (TREE_CODE (arg) != TREE_CODE (parm))
25038 return unify_type_mismatch (explain_p, parm, arg);
25040 if (TYPE_PTRMEMFUNC_P (parm))
25042 if (!TYPE_PTRMEMFUNC_P (arg))
25043 return unify_type_mismatch (explain_p, parm, arg);
25045 return unify (tparms, targs,
25046 TYPE_PTRMEMFUNC_FN_TYPE (parm),
25047 TYPE_PTRMEMFUNC_FN_TYPE (arg),
25048 strict, explain_p);
25050 else if (TYPE_PTRMEMFUNC_P (arg))
25051 return unify_type_mismatch (explain_p, parm, arg);
25053 if (CLASSTYPE_TEMPLATE_INFO (parm))
25055 tree t = NULL_TREE;
25057 if (strict_in & UNIFY_ALLOW_DERIVED)
25059 /* First, we try to unify the PARM and ARG directly. */
25060 t = try_class_unification (tparms, targs,
25061 parm, arg, explain_p);
25063 if (!t)
25065 /* Fallback to the special case allowed in
25066 [temp.deduct.call]:
25068 If P is a class, and P has the form
25069 template-id, then A can be a derived class of
25070 the deduced A. Likewise, if P is a pointer to
25071 a class of the form template-id, A can be a
25072 pointer to a derived class pointed to by the
25073 deduced A. */
25074 enum template_base_result r;
25075 r = get_template_base (tparms, targs, parm, arg,
25076 explain_p, &t);
25078 if (!t)
25080 /* Don't give the derived diagnostic if we're
25081 already dealing with the same template. */
25082 bool same_template
25083 = (CLASSTYPE_TEMPLATE_INFO (arg)
25084 && (CLASSTYPE_TI_TEMPLATE (parm)
25085 == CLASSTYPE_TI_TEMPLATE (arg)));
25086 return unify_no_common_base (explain_p && !same_template,
25087 r, parm, arg);
25091 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25092 && (CLASSTYPE_TI_TEMPLATE (parm)
25093 == CLASSTYPE_TI_TEMPLATE (arg)))
25094 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25095 Then, we should unify `int' and `U'. */
25096 t = arg;
25097 else
25098 /* There's no chance of unification succeeding. */
25099 return unify_type_mismatch (explain_p, parm, arg);
25101 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))
25102 return unify (tparms, targs,
25103 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
25104 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (t)),
25105 UNIFY_ALLOW_NONE, explain_p);
25106 else
25107 return unify_success (explain_p);
25109 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25110 return unify_type_mismatch (explain_p, parm, arg);
25111 return unify_success (explain_p);
25113 case METHOD_TYPE:
25114 case FUNCTION_TYPE:
25116 unsigned int nargs;
25117 tree *args;
25118 tree a;
25119 unsigned int i;
25121 if (TREE_CODE (arg) != TREE_CODE (parm))
25122 return unify_type_mismatch (explain_p, parm, arg);
25124 /* CV qualifications for methods can never be deduced, they must
25125 match exactly. We need to check them explicitly here,
25126 because type_unification_real treats them as any other
25127 cv-qualified parameter. */
25128 if (TREE_CODE (parm) == METHOD_TYPE
25129 && (!check_cv_quals_for_unify
25130 (UNIFY_ALLOW_NONE,
25131 class_of_this_parm (arg),
25132 class_of_this_parm (parm))))
25133 return unify_cv_qual_mismatch (explain_p, parm, arg);
25134 if (TREE_CODE (arg) == FUNCTION_TYPE
25135 && type_memfn_quals (parm) != type_memfn_quals (arg))
25136 return unify_cv_qual_mismatch (explain_p, parm, arg);
25137 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25138 return unify_type_mismatch (explain_p, parm, arg);
25140 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25141 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25143 nargs = list_length (TYPE_ARG_TYPES (arg));
25144 args = XALLOCAVEC (tree, nargs);
25145 for (a = TYPE_ARG_TYPES (arg), i = 0;
25146 a != NULL_TREE && a != void_list_node;
25147 a = TREE_CHAIN (a), ++i)
25148 args[i] = TREE_VALUE (a);
25149 nargs = i;
25151 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25152 args, nargs, 1, DEDUCE_EXACT,
25153 NULL, explain_p))
25154 return 1;
25156 if (flag_noexcept_type)
25158 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25159 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25160 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25161 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25162 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25163 && uses_template_parms (TREE_PURPOSE (pspec)))
25164 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25165 TREE_PURPOSE (aspec),
25166 UNIFY_ALLOW_NONE, explain_p);
25167 else
25169 bool pn = nothrow_spec_p (pspec);
25170 bool an = nothrow_spec_p (aspec);
25171 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25172 /more/ noexcept, since function pointer conversions are the
25173 reverse of qualification conversions. */
25174 if (an == pn
25175 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25176 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25177 /* OK. */;
25178 else
25179 return unify_type_mismatch (explain_p, parm, arg);
25182 if (flag_tm)
25184 /* As for noexcept. */
25185 bool pn = tx_safe_fn_type_p (parm);
25186 bool an = tx_safe_fn_type_p (arg);
25187 if (an == pn
25188 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25189 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25190 /* OK. */;
25191 else
25192 return unify_type_mismatch (explain_p, parm, arg);
25195 return 0;
25198 case OFFSET_TYPE:
25199 /* Unify a pointer to member with a pointer to member function, which
25200 deduces the type of the member as a function type. */
25201 if (TYPE_PTRMEMFUNC_P (arg))
25203 /* Check top-level cv qualifiers */
25204 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25205 return unify_cv_qual_mismatch (explain_p, parm, arg);
25207 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25208 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25209 UNIFY_ALLOW_NONE, explain_p);
25211 /* Determine the type of the function we are unifying against. */
25212 tree fntype = static_fn_type (arg);
25214 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25217 if (TREE_CODE (arg) != OFFSET_TYPE)
25218 return unify_type_mismatch (explain_p, parm, arg);
25219 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25220 TYPE_OFFSET_BASETYPE (arg),
25221 UNIFY_ALLOW_NONE, explain_p);
25222 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25223 strict, explain_p);
25225 case CONST_DECL:
25226 /* CONST_DECL should already have been folded to its DECL_INITIAL. */
25227 gcc_unreachable ();
25229 case FIELD_DECL:
25230 case FUNCTION_DECL:
25231 case TEMPLATE_DECL:
25232 /* Matched cases are handled by the ARG == PARM test above. */
25233 return unify_template_argument_mismatch (explain_p, parm, arg);
25235 case VAR_DECL:
25236 /* We might get a variable as a non-type template argument in parm if the
25237 corresponding parameter is type-dependent. Make any necessary
25238 adjustments based on whether arg is a reference. */
25239 if (CONSTANT_CLASS_P (arg))
25240 parm = fold_non_dependent_expr (parm, complain);
25241 else if (REFERENCE_REF_P (arg))
25243 tree sub = TREE_OPERAND (arg, 0);
25244 STRIP_NOPS (sub);
25245 if (TREE_CODE (sub) == ADDR_EXPR)
25246 arg = TREE_OPERAND (sub, 0);
25248 /* Now use the normal expression code to check whether they match. */
25249 goto expr;
25251 case TYPE_ARGUMENT_PACK:
25252 case NONTYPE_ARGUMENT_PACK:
25253 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25254 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25256 case TYPEOF_TYPE:
25257 case DECLTYPE_TYPE:
25258 case TRAIT_TYPE:
25259 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25260 or TRAIT_TYPE nodes. */
25261 return unify_success (explain_p);
25263 case ERROR_MARK:
25264 /* Unification fails if we hit an error node. */
25265 return unify_invalid (explain_p);
25267 case INDIRECT_REF:
25268 if (REFERENCE_REF_P (parm))
25270 bool pexp = PACK_EXPANSION_P (arg);
25271 if (pexp)
25272 arg = PACK_EXPANSION_PATTERN (arg);
25273 if (REFERENCE_REF_P (arg))
25274 arg = TREE_OPERAND (arg, 0);
25275 if (pexp)
25276 arg = make_pack_expansion (arg, complain);
25277 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25278 strict, explain_p);
25280 /* FALLTHRU */
25282 default:
25283 /* An unresolved overload is a nondeduced context. */
25284 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25285 return unify_success (explain_p);
25286 gcc_assert (EXPR_P (parm)
25287 || TREE_CODE (parm) == CONSTRUCTOR
25288 || TREE_CODE (parm) == TRAIT_EXPR);
25289 expr:
25290 /* We must be looking at an expression. This can happen with
25291 something like:
25293 template <int I>
25294 void foo(S<I>, S<I + 2>);
25298 template<typename T>
25299 void foo(A<T, T{}>);
25301 This is a "non-deduced context":
25303 [deduct.type]
25305 The non-deduced contexts are:
25307 --A non-type template argument or an array bound in which
25308 a subexpression references a template parameter.
25310 In these cases, we assume deduction succeeded, but don't
25311 actually infer any unifications. */
25313 if (!uses_template_parms (parm)
25314 && !template_args_equal (parm, arg))
25315 return unify_expression_unequal (explain_p, parm, arg);
25316 else
25317 return unify_success (explain_p);
25320 #undef RECUR_AND_CHECK_FAILURE
25322 /* Note that DECL can be defined in this translation unit, if
25323 required. */
25325 static void
25326 mark_definable (tree decl)
25328 tree clone;
25329 DECL_NOT_REALLY_EXTERN (decl) = 1;
25330 FOR_EACH_CLONE (clone, decl)
25331 DECL_NOT_REALLY_EXTERN (clone) = 1;
25334 /* Called if RESULT is explicitly instantiated, or is a member of an
25335 explicitly instantiated class. */
25337 void
25338 mark_decl_instantiated (tree result, int extern_p)
25340 SET_DECL_EXPLICIT_INSTANTIATION (result);
25342 /* If this entity has already been written out, it's too late to
25343 make any modifications. */
25344 if (TREE_ASM_WRITTEN (result))
25345 return;
25347 /* consteval functions are never emitted. */
25348 if (TREE_CODE (result) == FUNCTION_DECL
25349 && DECL_IMMEDIATE_FUNCTION_P (result))
25350 return;
25352 /* For anonymous namespace we don't need to do anything. */
25353 if (decl_internal_context_p (result))
25355 gcc_assert (!TREE_PUBLIC (result));
25356 return;
25359 if (TREE_CODE (result) != FUNCTION_DECL)
25360 /* The TREE_PUBLIC flag for function declarations will have been
25361 set correctly by tsubst. */
25362 TREE_PUBLIC (result) = 1;
25364 if (extern_p)
25366 DECL_EXTERNAL (result) = 1;
25367 DECL_NOT_REALLY_EXTERN (result) = 0;
25369 else
25371 mark_definable (result);
25372 mark_needed (result);
25373 /* Always make artificials weak. */
25374 if (DECL_ARTIFICIAL (result) && flag_weak)
25375 comdat_linkage (result);
25376 /* For WIN32 we also want to put explicit instantiations in
25377 linkonce sections. */
25378 else if (TREE_PUBLIC (result))
25379 maybe_make_one_only (result);
25380 if (TREE_CODE (result) == FUNCTION_DECL
25381 && DECL_TEMPLATE_INSTANTIATED (result))
25382 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25383 since start_preparsed_function wouldn't have if we had an earlier
25384 extern explicit instantiation. */
25385 DECL_EXTERNAL (result) = 0;
25388 /* If EXTERN_P, then this function will not be emitted -- unless
25389 followed by an explicit instantiation, at which point its linkage
25390 will be adjusted. If !EXTERN_P, then this function will be
25391 emitted here. In neither circumstance do we want
25392 import_export_decl to adjust the linkage. */
25393 DECL_INTERFACE_KNOWN (result) = 1;
25396 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25397 important template arguments. If any are missing, we check whether
25398 they're important by using error_mark_node for substituting into any
25399 args that were used for partial ordering (the ones between ARGS and END)
25400 and seeing if it bubbles up. */
25402 static bool
25403 check_undeduced_parms (tree targs, tree args, tree end)
25405 bool found = false;
25406 for (tree& targ : tree_vec_range (targs))
25407 if (targ == NULL_TREE)
25409 found = true;
25410 targ = error_mark_node;
25412 if (found)
25414 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25415 if (substed == error_mark_node)
25416 return true;
25418 return false;
25421 /* Given two function templates PAT1 and PAT2, return:
25423 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25424 -1 if PAT2 is more specialized than PAT1.
25425 0 if neither is more specialized.
25427 LEN indicates the number of parameters we should consider
25428 (defaulted parameters should not be considered).
25430 The 1998 std underspecified function template partial ordering, and
25431 DR214 addresses the issue. We take pairs of arguments, one from
25432 each of the templates, and deduce them against each other. One of
25433 the templates will be more specialized if all the *other*
25434 template's arguments deduce against its arguments and at least one
25435 of its arguments *does* *not* deduce against the other template's
25436 corresponding argument. Deduction is done as for class templates.
25437 The arguments used in deduction have reference and top level cv
25438 qualifiers removed. Iff both arguments were originally reference
25439 types *and* deduction succeeds in both directions, an lvalue reference
25440 wins against an rvalue reference and otherwise the template
25441 with the more cv-qualified argument wins for that pairing (if
25442 neither is more cv-qualified, they both are equal). Unlike regular
25443 deduction, after all the arguments have been deduced in this way,
25444 we do *not* verify the deduced template argument values can be
25445 substituted into non-deduced contexts.
25447 The logic can be a bit confusing here, because we look at deduce1 and
25448 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25449 can find template arguments for pat1 to make arg1 look like arg2, that
25450 means that arg2 is at least as specialized as arg1. */
25453 more_specialized_fn (tree pat1, tree pat2, int len)
25455 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25456 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25457 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25458 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25459 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25460 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25461 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25462 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25463 tree origs1, origs2;
25464 bool lose1 = false;
25465 bool lose2 = false;
25467 /* C++17 [temp.func.order]/3 (CWG532)
25469 If only one of the function templates M is a non-static member of some
25470 class A, M is considered to have a new first parameter inserted in its
25471 function parameter list. Given cv as the cv-qualifiers of M (if any), the
25472 new parameter is of type "rvalue reference to cv A" if the optional
25473 ref-qualifier of M is && or if M has no ref-qualifier and the first
25474 parameter of the other template has rvalue reference type. Otherwise, the
25475 new parameter is of type "lvalue reference to cv A". */
25477 if (DECL_STATIC_FUNCTION_P (decl1) || DECL_STATIC_FUNCTION_P (decl2))
25479 /* Note C++20 DR2445 extended the above to static member functions, but
25480 I think think the old G++ behavior of just skipping the object
25481 parameter when comparing to a static member function was better, so
25482 let's stick with that for now. This is CWG2834. --jason 2023-12 */
25483 if (DECL_OBJECT_MEMBER_FUNCTION_P (decl1))
25485 len--; /* LEN is the number of significant arguments for DECL1 */
25486 args1 = TREE_CHAIN (args1);
25488 else if (DECL_OBJECT_MEMBER_FUNCTION_P (decl2))
25489 args2 = TREE_CHAIN (args2);
25491 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25492 && DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25494 /* Note DR2445 also (IMO wrongly) removed the "only one" above, which
25495 would break e.g. cpp1y/lambda-generic-variadic5.C. */
25496 len--;
25497 args1 = TREE_CHAIN (args1);
25498 args2 = TREE_CHAIN (args2);
25500 else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
25501 || DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
25503 /* The other is a non-member or explicit object member function;
25504 rewrite the implicit object parameter to a reference. */
25505 tree ns = DECL_IOBJ_MEMBER_FUNCTION_P (decl2) ? decl2 : decl1;
25506 tree &nsargs = ns == decl2 ? args2 : args1;
25507 tree obtype = TREE_TYPE (TREE_VALUE (nsargs));
25509 nsargs = TREE_CHAIN (nsargs);
25511 cp_ref_qualifier rqual = type_memfn_rqual (TREE_TYPE (ns));
25512 if (rqual == REF_QUAL_NONE)
25514 tree otherfirst = ns == decl1 ? args2 : args1;
25515 otherfirst = TREE_VALUE (otherfirst);
25516 if (TREE_CODE (otherfirst) == REFERENCE_TYPE
25517 && TYPE_REF_IS_RVALUE (otherfirst))
25518 rqual = REF_QUAL_RVALUE;
25520 obtype = cp_build_reference_type (obtype, rqual == REF_QUAL_RVALUE);
25521 nsargs = tree_cons (NULL_TREE, obtype, nsargs);
25524 /* If only one is a conversion operator, they are unordered. */
25525 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25526 return 0;
25528 /* Consider the return type for a conversion function */
25529 if (DECL_CONV_FN_P (decl1))
25531 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25532 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25533 len++;
25536 processing_template_decl++;
25538 origs1 = args1;
25539 origs2 = args2;
25541 while (len--
25542 /* Stop when an ellipsis is seen. */
25543 && args1 != NULL_TREE && args2 != NULL_TREE)
25545 tree arg1 = TREE_VALUE (args1);
25546 tree arg2 = TREE_VALUE (args2);
25547 int deduce1, deduce2;
25548 int quals1 = -1;
25549 int quals2 = -1;
25550 int ref1 = 0;
25551 int ref2 = 0;
25553 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25554 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25556 /* When both arguments are pack expansions, we need only
25557 unify the patterns themselves. */
25558 arg1 = PACK_EXPANSION_PATTERN (arg1);
25559 arg2 = PACK_EXPANSION_PATTERN (arg2);
25561 /* This is the last comparison we need to do. */
25562 len = 0;
25565 if (TYPE_REF_P (arg1))
25567 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25568 arg1 = TREE_TYPE (arg1);
25569 quals1 = cp_type_quals (arg1);
25572 if (TYPE_REF_P (arg2))
25574 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25575 arg2 = TREE_TYPE (arg2);
25576 quals2 = cp_type_quals (arg2);
25579 arg1 = TYPE_MAIN_VARIANT (arg1);
25580 arg2 = TYPE_MAIN_VARIANT (arg2);
25582 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25584 int i, len2 = remaining_arguments (args2);
25585 tree parmvec = make_tree_vec (1);
25586 tree argvec = make_tree_vec (len2);
25587 tree ta = args2;
25589 /* Setup the parameter vector, which contains only ARG1. */
25590 TREE_VEC_ELT (parmvec, 0) = arg1;
25592 /* Setup the argument vector, which contains the remaining
25593 arguments. */
25594 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25595 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25597 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25598 argvec, DEDUCE_EXACT,
25599 /*subr=*/true, /*explain_p=*/false)
25600 == 0);
25602 /* We cannot deduce in the other direction, because ARG1 is
25603 a pack expansion but ARG2 is not. */
25604 deduce2 = 0;
25606 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25608 int i, len1 = remaining_arguments (args1);
25609 tree parmvec = make_tree_vec (1);
25610 tree argvec = make_tree_vec (len1);
25611 tree ta = args1;
25613 /* Setup the parameter vector, which contains only ARG1. */
25614 TREE_VEC_ELT (parmvec, 0) = arg2;
25616 /* Setup the argument vector, which contains the remaining
25617 arguments. */
25618 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25619 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25621 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25622 argvec, DEDUCE_EXACT,
25623 /*subr=*/true, /*explain_p=*/false)
25624 == 0);
25626 /* We cannot deduce in the other direction, because ARG2 is
25627 a pack expansion but ARG1 is not.*/
25628 deduce1 = 0;
25631 else
25633 /* The normal case, where neither argument is a pack
25634 expansion. */
25635 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25636 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25637 == 0);
25638 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25639 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25640 == 0);
25643 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25644 arg2, then arg2 is not as specialized as arg1. */
25645 if (!deduce1)
25646 lose2 = true;
25647 if (!deduce2)
25648 lose1 = true;
25650 /* "If, for a given type, deduction succeeds in both directions
25651 (i.e., the types are identical after the transformations above)
25652 and both P and A were reference types (before being replaced with
25653 the type referred to above):
25654 - if the type from the argument template was an lvalue reference and
25655 the type from the parameter template was not, the argument type is
25656 considered to be more specialized than the other; otherwise,
25657 - if the type from the argument template is more cv-qualified
25658 than the type from the parameter template (as described above),
25659 the argument type is considered to be more specialized than the other;
25660 otherwise,
25661 - neither type is more specialized than the other." */
25663 if (deduce1 && deduce2)
25665 if (ref1 && ref2 && ref1 != ref2)
25667 if (ref1 > ref2)
25668 lose1 = true;
25669 else
25670 lose2 = true;
25672 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25674 if ((quals1 & quals2) == quals2)
25675 lose2 = true;
25676 if ((quals1 & quals2) == quals1)
25677 lose1 = true;
25681 if (lose1 && lose2)
25682 /* We've failed to deduce something in either direction.
25683 These must be unordered. */
25684 break;
25686 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25687 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25688 /* We have already processed all of the arguments in our
25689 handing of the pack expansion type. */
25690 len = 0;
25692 args1 = TREE_CHAIN (args1);
25693 args2 = TREE_CHAIN (args2);
25696 /* "In most cases, all template parameters must have values in order for
25697 deduction to succeed, but for partial ordering purposes a template
25698 parameter may remain without a value provided it is not used in the
25699 types being used for partial ordering."
25701 Thus, if we are missing any of the targs1 we need to substitute into
25702 origs1, then pat2 is not as specialized as pat1. This can happen when
25703 there is a nondeduced context. */
25704 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25705 lose2 = true;
25706 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25707 lose1 = true;
25709 processing_template_decl--;
25711 /* If both deductions succeed, the partial ordering selects the more
25712 constrained template. */
25713 /* P2113: If the corresponding template-parameters of the
25714 template-parameter-lists are not equivalent ([temp.over.link]) or if
25715 the function parameters that positionally correspond between the two
25716 templates are not of the same type, neither template is more
25717 specialized than the other. */
25718 if (!lose1 && !lose2
25719 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25720 DECL_TEMPLATE_PARMS (pat2))
25721 && compparms (origs1, origs2))
25723 int winner = more_constrained (decl1, decl2);
25724 if (winner > 0)
25725 lose2 = true;
25726 else if (winner < 0)
25727 lose1 = true;
25730 /* All things being equal, if the next argument is a pack expansion
25731 for one function but not for the other, prefer the
25732 non-variadic function. FIXME this is bogus; see c++/41958. */
25733 if (lose1 == lose2
25734 && args1 && TREE_VALUE (args1)
25735 && args2 && TREE_VALUE (args2))
25737 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25738 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25741 if (lose1 == lose2)
25742 return 0;
25743 else if (!lose1)
25744 return 1;
25745 else
25746 return -1;
25749 /* Determine which of two partial specializations of TMPL is more
25750 specialized.
25752 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25753 to the first partial specialization. The TREE_PURPOSE is the
25754 innermost set of template parameters for the partial
25755 specialization. PAT2 is similar, but for the second template.
25757 Return 1 if the first partial specialization is more specialized;
25758 -1 if the second is more specialized; 0 if neither is more
25759 specialized.
25761 See [temp.class.order] for information about determining which of
25762 two templates is more specialized. */
25764 static int
25765 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25767 tree targs;
25768 int winner = 0;
25769 bool any_deductions = false;
25771 tree tmpl1 = TREE_VALUE (pat1);
25772 tree tmpl2 = TREE_VALUE (pat2);
25773 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25774 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25776 /* Just like what happens for functions, if we are ordering between
25777 different template specializations, we may encounter dependent
25778 types in the arguments, and we need our dependency check functions
25779 to behave correctly. */
25780 ++processing_template_decl;
25781 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25782 if (targs)
25784 --winner;
25785 any_deductions = true;
25788 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25789 if (targs)
25791 ++winner;
25792 any_deductions = true;
25794 --processing_template_decl;
25796 /* If both deductions succeed, the partial ordering selects the more
25797 constrained template. */
25798 if (!winner && any_deductions)
25799 winner = more_constrained (tmpl1, tmpl2);
25801 /* In the case of a tie where at least one of the templates
25802 has a parameter pack at the end, the template with the most
25803 non-packed parameters wins. */
25804 if (winner == 0
25805 && any_deductions
25806 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25807 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25809 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25810 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25811 int len1 = TREE_VEC_LENGTH (args1);
25812 int len2 = TREE_VEC_LENGTH (args2);
25814 /* We don't count the pack expansion at the end. */
25815 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25816 --len1;
25817 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25818 --len2;
25820 if (len1 > len2)
25821 return 1;
25822 else if (len1 < len2)
25823 return -1;
25826 return winner;
25829 /* Return the template arguments that will produce the function signature
25830 DECL from the function template FN, with the explicit template
25831 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25832 also match. Return NULL_TREE if no satisfactory arguments could be
25833 found. */
25835 static tree
25836 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25838 int ntparms = DECL_NTPARMS (fn);
25839 tree targs = make_tree_vec (ntparms);
25840 tree decl_type = TREE_TYPE (decl);
25841 tree decl_arg_types;
25842 tree *args;
25843 unsigned int nargs, ix;
25844 tree arg;
25846 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25848 /* Never do unification on the 'this' parameter. */
25849 decl_arg_types = skip_artificial_parms_for (decl,
25850 TYPE_ARG_TYPES (decl_type));
25852 nargs = list_length (decl_arg_types);
25853 args = XALLOCAVEC (tree, nargs);
25854 for (arg = decl_arg_types, ix = 0;
25855 arg != NULL_TREE;
25856 arg = TREE_CHAIN (arg), ++ix)
25857 args[ix] = TREE_VALUE (arg);
25859 if (fn_type_unification (fn, explicit_args, targs,
25860 args, ix,
25861 (check_rettype || DECL_CONV_FN_P (fn)
25862 ? TREE_TYPE (decl_type) : NULL_TREE),
25863 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25864 /*explain_p=*/false,
25865 /*decltype*/false)
25866 == error_mark_node)
25867 return NULL_TREE;
25869 return targs;
25872 /* Return the innermost template arguments that, when applied to a partial
25873 specialization SPEC_TMPL of TMPL, yield the ARGS.
25875 For example, suppose we have:
25877 template <class T, class U> struct S {};
25878 template <class T> struct S<T*, int> {};
25880 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25881 partial specialization and the ARGS will be {double*, int}. The resulting
25882 vector will be {double}, indicating that `T' is bound to `double'. */
25884 static tree
25885 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25887 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25888 tree spec_args
25889 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25890 int i, ntparms = TREE_VEC_LENGTH (tparms);
25891 tree deduced_args;
25892 tree innermost_deduced_args;
25894 innermost_deduced_args = make_tree_vec (ntparms);
25895 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25897 deduced_args = copy_node (args);
25898 SET_TMPL_ARGS_LEVEL (deduced_args,
25899 TMPL_ARGS_DEPTH (deduced_args),
25900 innermost_deduced_args);
25902 else
25903 deduced_args = innermost_deduced_args;
25905 bool tried_array_deduction = (cxx_dialect < cxx17);
25906 again:
25907 if (unify (tparms, deduced_args,
25908 INNERMOST_TEMPLATE_ARGS (spec_args),
25909 INNERMOST_TEMPLATE_ARGS (args),
25910 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25911 return NULL_TREE;
25913 for (i = 0; i < ntparms; ++i)
25914 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25916 if (!tried_array_deduction)
25918 try_array_deduction (tparms, innermost_deduced_args,
25919 INNERMOST_TEMPLATE_ARGS (spec_args));
25920 tried_array_deduction = true;
25921 if (TREE_VEC_ELT (innermost_deduced_args, i))
25922 goto again;
25924 return NULL_TREE;
25927 if (!push_tinst_level (spec_tmpl, deduced_args))
25929 excessive_deduction_depth = true;
25930 return NULL_TREE;
25933 /* Verify that nondeduced template arguments agree with the type
25934 obtained from argument deduction.
25936 For example:
25938 struct A { typedef int X; };
25939 template <class T, class U> struct C {};
25940 template <class T> struct C<T, typename T::X> {};
25942 Then with the instantiation `C<A, int>', we can deduce that
25943 `T' is `A' but unify () does not check whether `typename T::X'
25944 is `int'. */
25945 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25947 if (spec_args != error_mark_node)
25948 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25949 INNERMOST_TEMPLATE_ARGS (spec_args),
25950 tmpl, tf_none, false);
25952 pop_tinst_level ();
25954 if (spec_args == error_mark_node
25955 /* We only need to check the innermost arguments; the other
25956 arguments will always agree. */
25957 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25958 INNERMOST_TEMPLATE_ARGS (args)))
25959 return NULL_TREE;
25961 /* Now that we have bindings for all of the template arguments,
25962 ensure that the arguments deduced for the template template
25963 parameters have compatible template parameter lists. See the use
25964 of template_template_parm_bindings_ok_p in fn_type_unification
25965 for more information. */
25966 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25967 return NULL_TREE;
25969 return deduced_args;
25972 // Compare two function templates T1 and T2 by deducing bindings
25973 // from one against the other. If both deductions succeed, compare
25974 // constraints to see which is more constrained.
25975 static int
25976 more_specialized_inst (tree t1, tree t2)
25978 int fate = 0;
25979 int count = 0;
25981 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25983 --fate;
25984 ++count;
25987 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25989 ++fate;
25990 ++count;
25993 // If both deductions succeed, then one may be more constrained.
25994 if (count == 2 && fate == 0)
25995 fate = more_constrained (t1, t2);
25997 return fate;
26000 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
26001 Return the TREE_LIST node with the most specialized template, if
26002 any. If there is no most specialized template, the error_mark_node
26003 is returned.
26005 Note that this function does not look at, or modify, the
26006 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
26007 returned is one of the elements of INSTANTIATIONS, callers may
26008 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
26009 and retrieve it from the value returned. */
26011 tree
26012 most_specialized_instantiation (tree templates)
26014 tree fn, champ;
26016 ++processing_template_decl;
26018 champ = templates;
26019 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
26021 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
26022 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
26023 if (fate == -1)
26024 champ = fn;
26025 else if (!fate)
26027 /* Equally specialized, move to next function. If there
26028 is no next function, nothing's most specialized. */
26029 fn = TREE_CHAIN (fn);
26030 champ = fn;
26031 if (!fn)
26032 break;
26036 if (champ)
26037 /* Now verify that champ is better than everything earlier in the
26038 instantiation list. */
26039 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
26040 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
26042 champ = NULL_TREE;
26043 break;
26047 processing_template_decl--;
26049 if (!champ)
26050 return error_mark_node;
26052 return champ;
26055 /* If DECL is a specialization of some template, return the most
26056 general such template. Otherwise, returns NULL_TREE.
26058 For example, given:
26060 template <class T> struct S { template <class U> void f(U); };
26062 if TMPL is `template <class U> void S<int>::f(U)' this will return
26063 the full template. This function will not trace past partial
26064 specializations, however. For example, given in addition:
26066 template <class T> struct S<T*> { template <class U> void f(U); };
26068 if TMPL is `template <class U> void S<int*>::f(U)' this will return
26069 `template <class T> template <class U> S<T*>::f(U)'. */
26071 tree
26072 most_general_template (const_tree decl)
26074 if (TREE_CODE (decl) != TEMPLATE_DECL)
26076 if (tree tinfo = get_template_info (decl))
26077 decl = TI_TEMPLATE (tinfo);
26078 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
26079 template friend, or a FIELD_DECL for a capture pack. */
26080 if (TREE_CODE (decl) != TEMPLATE_DECL)
26081 return NULL_TREE;
26084 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
26085 return DECL_TI_TEMPLATE (DECL_TEMPLATE_RESULT (decl));
26087 /* Look for more and more general templates. */
26088 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
26090 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
26091 (See cp-tree.h for details.) */
26092 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
26093 break;
26095 if (CLASS_TYPE_P (TREE_TYPE (decl))
26096 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
26097 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
26098 break;
26100 /* Stop if we run into an explicitly specialized class template. */
26101 if (!DECL_NAMESPACE_SCOPE_P (decl)
26102 && DECL_CONTEXT (decl)
26103 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
26104 break;
26106 decl = DECL_TI_TEMPLATE (decl);
26109 return CONST_CAST_TREE (decl);
26112 /* Return the most specialized of the template partial specializations
26113 which can produce TARGET, a specialization of some class or variable
26114 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
26115 TEMPLATE_DECL node corresponding to the partial specialization, while
26116 the TI_ARGS is the set of template arguments that must be substituted
26117 into the template pattern in order to generate TARGET. The result is
26118 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
26119 RECHECKING is true.
26121 If the choice of partial specialization is ambiguous, a diagnostic
26122 is issued, and the error_mark_node is returned. If there are no
26123 partial specializations matching TARGET, then NULL_TREE is
26124 returned, indicating that the primary template should be used. */
26126 tree
26127 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
26128 bool rechecking /* = false */)
26130 tree tinfo = NULL_TREE;
26131 tree tmpl, args, decl;
26132 if (TYPE_P (target))
26134 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26135 tmpl = TI_TEMPLATE (tinfo);
26136 args = TI_ARGS (tinfo);
26137 decl = TYPE_NAME (target);
26139 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26141 tmpl = TREE_OPERAND (target, 0);
26142 args = TREE_OPERAND (target, 1);
26143 decl = DECL_TEMPLATE_RESULT (tmpl);
26145 else if (VAR_P (target))
26147 tinfo = DECL_TEMPLATE_INFO (target);
26148 tmpl = TI_TEMPLATE (tinfo);
26149 args = TI_ARGS (tinfo);
26150 decl = target;
26152 else
26153 gcc_unreachable ();
26155 if (!PRIMARY_TEMPLATE_P (tmpl))
26156 return NULL_TREE;
26158 if (!rechecking
26159 && tinfo
26160 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
26161 return TI_PARTIAL_INFO (tinfo);
26163 tree main_tmpl = most_general_template (tmpl);
26164 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26165 if (!specs)
26166 /* There are no partial specializations of this template. */
26167 return NULL_TREE;
26169 push_access_scope_guard pas (decl);
26170 deferring_access_check_sentinel acs (dk_no_deferred);
26172 /* For determining which partial specialization to use, only the
26173 innermost args are interesting. */
26174 tree outer_args = NULL_TREE;
26175 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26177 outer_args = strip_innermost_template_args (args, 1);
26178 args = INNERMOST_TEMPLATE_ARGS (args);
26181 /* The caller hasn't called push_to_top_level yet, but we need
26182 get_partial_spec_bindings to be done in non-template context so that we'll
26183 fully resolve everything. */
26184 processing_template_decl_sentinel ptds;
26186 tree list = NULL_TREE;
26187 for (tree t = specs; t; t = TREE_CHAIN (t))
26189 const tree ospec_tmpl = TREE_VALUE (t);
26191 tree spec_tmpl;
26192 if (outer_args)
26194 /* Substitute in the template args from the enclosing class. */
26195 ++processing_template_decl;
26196 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26197 --processing_template_decl;
26198 if (spec_tmpl == error_mark_node)
26199 return error_mark_node;
26201 else
26202 spec_tmpl = ospec_tmpl;
26204 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26205 if (spec_args)
26207 if (outer_args)
26208 spec_args = add_to_template_args (outer_args, spec_args);
26210 /* Keep the candidate only if its constraints are satisfied. */
26211 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26212 list = tree_cons (spec_args, ospec_tmpl, list);
26216 if (! list)
26217 return NULL_TREE;
26219 tree champ = list;
26220 bool ambiguous_p = false;
26221 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26223 int fate = more_specialized_partial_spec (tmpl, champ, t);
26224 if (fate == 1)
26226 else
26228 if (fate == 0)
26230 t = TREE_CHAIN (t);
26231 if (! t)
26233 ambiguous_p = true;
26234 break;
26237 champ = t;
26241 if (!ambiguous_p)
26242 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26244 int fate = more_specialized_partial_spec (tmpl, champ, t);
26245 if (fate != 1)
26247 ambiguous_p = true;
26248 break;
26252 if (ambiguous_p)
26254 const char *str;
26255 char *spaces = NULL;
26256 if (!(complain & tf_error))
26257 return error_mark_node;
26258 if (TYPE_P (target))
26259 error ("ambiguous template instantiation for %q#T", target);
26260 else
26261 error ("ambiguous template instantiation for %q#D", target);
26262 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26263 for (tree t = list; t; t = TREE_CHAIN (t))
26265 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26266 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26267 "%s %#qS", spaces ? spaces : str, subst);
26268 spaces = spaces ? spaces : get_spaces (str);
26270 free (spaces);
26271 return error_mark_node;
26274 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
26275 if (!rechecking && tinfo)
26276 TI_PARTIAL_INFO (tinfo) = result;
26277 return result;
26280 /* Explicitly instantiate DECL. */
26282 void
26283 do_decl_instantiation (tree decl, tree storage)
26285 tree result = NULL_TREE;
26286 int extern_p = 0;
26288 if (!decl || decl == error_mark_node)
26289 /* An error occurred, for which grokdeclarator has already issued
26290 an appropriate message. */
26291 return;
26292 else if (! DECL_LANG_SPECIFIC (decl))
26294 error ("explicit instantiation of non-template %q#D", decl);
26295 return;
26297 else if (DECL_DECLARED_CONCEPT_P (decl))
26299 if (VAR_P (decl))
26300 error ("explicit instantiation of variable concept %q#D", decl);
26301 else
26302 error ("explicit instantiation of function concept %q#D", decl);
26303 return;
26306 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26307 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26309 if (VAR_P (decl) && !var_templ)
26311 /* There is an asymmetry here in the way VAR_DECLs and
26312 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26313 the latter, the DECL we get back will be marked as a
26314 template instantiation, and the appropriate
26315 DECL_TEMPLATE_INFO will be set up. This does not happen for
26316 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26317 should handle VAR_DECLs as it currently handles
26318 FUNCTION_DECLs. */
26319 if (!DECL_CLASS_SCOPE_P (decl))
26321 error ("%qD is not a static data member of a class template", decl);
26322 return;
26324 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26325 if (!result || !VAR_P (result))
26327 error ("no matching template for %qD found", decl);
26328 return;
26330 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26332 error ("type %qT for explicit instantiation %qD does not match "
26333 "declared type %qT", TREE_TYPE (result), decl,
26334 TREE_TYPE (decl));
26335 return;
26338 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26340 error ("explicit instantiation of %q#D", decl);
26341 return;
26343 else
26344 result = decl;
26346 /* Check for various error cases. Note that if the explicit
26347 instantiation is valid the RESULT will currently be marked as an
26348 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26349 until we get here. */
26351 if (DECL_TEMPLATE_SPECIALIZATION (result))
26353 /* DR 259 [temp.spec].
26355 Both an explicit instantiation and a declaration of an explicit
26356 specialization shall not appear in a program unless the explicit
26357 instantiation follows a declaration of the explicit specialization.
26359 For a given set of template parameters, if an explicit
26360 instantiation of a template appears after a declaration of an
26361 explicit specialization for that template, the explicit
26362 instantiation has no effect. */
26363 return;
26365 else if (DECL_EXPLICIT_INSTANTIATION (result))
26367 /* [temp.spec]
26369 No program shall explicitly instantiate any template more
26370 than once.
26372 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26373 the first instantiation was `extern' and the second is not,
26374 and EXTERN_P for the opposite case. */
26375 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26376 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26377 /* If an "extern" explicit instantiation follows an ordinary
26378 explicit instantiation, the template is instantiated. */
26379 if (extern_p)
26380 return;
26382 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26384 error ("no matching template for %qD found", result);
26385 return;
26387 else if (!DECL_TEMPLATE_INFO (result))
26389 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26390 return;
26393 if (storage == NULL_TREE)
26395 else if (storage == ridpointers[(int) RID_EXTERN])
26397 if (cxx_dialect == cxx98)
26398 pedwarn (input_location, OPT_Wpedantic,
26399 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26400 "instantiations");
26401 extern_p = 1;
26403 else
26404 error ("storage class %qD applied to template instantiation", storage);
26406 check_explicit_instantiation_namespace (result);
26407 mark_decl_instantiated (result, extern_p);
26408 if (! extern_p)
26409 instantiate_decl (result, /*defer_ok=*/true,
26410 /*expl_inst_class_mem_p=*/false);
26413 static void
26414 mark_class_instantiated (tree t, int extern_p)
26416 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26417 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26418 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26419 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26420 if (! extern_p)
26422 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26423 rest_of_type_compilation (t, 1);
26427 /* Perform an explicit instantiation of template class T. STORAGE, if
26428 non-null, is the RID for extern, inline or static. COMPLAIN is
26429 nonzero if this is called from the parser, zero if called recursively,
26430 since the standard is unclear (as detailed below). */
26432 void
26433 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26435 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26437 if (tree ti = TYPE_TEMPLATE_INFO (t))
26438 error ("explicit instantiation of non-class template %qD",
26439 TI_TEMPLATE (ti));
26440 else
26441 error ("explicit instantiation of non-template type %qT", t);
26442 return;
26445 complete_type (t);
26447 if (!COMPLETE_TYPE_P (t))
26449 if (complain & tf_error)
26450 error ("explicit instantiation of %q#T before definition of template",
26452 return;
26455 /* At most one of these will be true. */
26456 bool extern_p = false;
26457 bool nomem_p = false;
26458 bool static_p = false;
26460 if (storage != NULL_TREE)
26462 if (storage == ridpointers[(int) RID_EXTERN])
26464 if (cxx_dialect == cxx98)
26465 pedwarn (input_location, OPT_Wpedantic,
26466 "ISO C++ 1998 forbids the use of %<extern%> on "
26467 "explicit instantiations");
26469 else
26470 pedwarn (input_location, OPT_Wpedantic,
26471 "ISO C++ forbids the use of %qE"
26472 " on explicit instantiations", storage);
26474 if (storage == ridpointers[(int) RID_INLINE])
26475 nomem_p = true;
26476 else if (storage == ridpointers[(int) RID_EXTERN])
26477 extern_p = true;
26478 else if (storage == ridpointers[(int) RID_STATIC])
26479 static_p = true;
26480 else
26481 error ("storage class %qD applied to template instantiation",
26482 storage);
26485 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26486 /* DR 259 [temp.spec].
26488 Both an explicit instantiation and a declaration of an explicit
26489 specialization shall not appear in a program unless the
26490 explicit instantiation follows a declaration of the explicit
26491 specialization.
26493 For a given set of template parameters, if an explicit
26494 instantiation of a template appears after a declaration of an
26495 explicit specialization for that template, the explicit
26496 instantiation has no effect. */
26497 return;
26499 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26501 /* We've already instantiated the template. */
26503 /* [temp.spec]
26505 No program shall explicitly instantiate any template more
26506 than once.
26508 If EXTERN_P then this is ok. */
26509 if (!extern_p && (complain & tf_error))
26510 permerror (input_location,
26511 "duplicate explicit instantiation of %q#T", t);
26513 return;
26516 check_explicit_instantiation_namespace (TYPE_NAME (t));
26517 mark_class_instantiated (t, extern_p);
26519 if (nomem_p)
26520 return;
26522 /* In contrast to implicit instantiation, where only the
26523 declarations, and not the definitions, of members are
26524 instantiated, we have here:
26526 [temp.explicit]
26528 An explicit instantiation that names a class template
26529 specialization is also an explicit instantiation of the same
26530 kind (declaration or definition) of each of its members (not
26531 including members inherited from base classes and members
26532 that are templates) that has not been previously explicitly
26533 specialized in the translation unit containing the explicit
26534 instantiation, provided that the associated constraints, if
26535 any, of that member are satisfied by the template arguments
26536 of the explicit instantiation. */
26537 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26538 if ((VAR_P (fld)
26539 || (TREE_CODE (fld) == FUNCTION_DECL
26540 && !static_p
26541 && user_provided_p (fld)))
26542 && DECL_TEMPLATE_INSTANTIATION (fld)
26543 && constraints_satisfied_p (fld))
26545 mark_decl_instantiated (fld, extern_p);
26546 if (! extern_p)
26547 instantiate_decl (fld, /*defer_ok=*/true,
26548 /*expl_inst_class_mem_p=*/true);
26550 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26552 tree type = TREE_TYPE (fld);
26554 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26555 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26556 do_type_instantiation (type, storage, 0);
26560 /* Given a function DECL, which is a specialization of TMPL, modify
26561 DECL to be a re-instantiation of TMPL with the same template
26562 arguments. TMPL should be the template into which tsubst'ing
26563 should occur for DECL, not the most general template.
26565 One reason for doing this is a scenario like this:
26567 template <class T>
26568 void f(const T&, int i);
26570 void g() { f(3, 7); }
26572 template <class T>
26573 void f(const T& t, const int i) { }
26575 Note that when the template is first instantiated, with
26576 instantiate_template, the resulting DECL will have no name for the
26577 first parameter, and the wrong type for the second. So, when we go
26578 to instantiate the DECL, we regenerate it. */
26580 static void
26581 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26583 /* The arguments used to instantiate DECL, from the most general
26584 template. */
26585 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26587 /* Make sure that we can see identifiers, and compute access correctly. */
26588 push_access_scope (decl);
26590 if (TREE_CODE (decl) == FUNCTION_DECL)
26592 tree specs;
26593 int args_depth;
26594 int parms_depth;
26596 /* Don't bother with this for unique friends that can't be redeclared and
26597 might change type if regenerated (PR69836). */
26598 if (DECL_UNIQUE_FRIEND_P (decl))
26599 goto done;
26601 /* Use the source location of the definition. */
26602 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26604 args_depth = TMPL_ARGS_DEPTH (args);
26605 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26606 if (args_depth > parms_depth)
26607 args = get_innermost_template_args (args, parms_depth);
26609 /* Instantiate a dynamic exception-specification. noexcept will be
26610 handled below. */
26611 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26612 if (TREE_VALUE (raises))
26614 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26615 args, tf_error, NULL_TREE,
26616 /*defer_ok*/false);
26617 if (specs && specs != error_mark_node)
26618 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26619 specs);
26622 /* Merge parameter declarations. */
26623 if (tree pattern_parm
26624 = skip_artificial_parms_for (code_pattern,
26625 DECL_ARGUMENTS (code_pattern)))
26627 tree *p = &DECL_ARGUMENTS (decl);
26628 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26629 p = &DECL_CHAIN (*p);
26630 *p = tsubst_decl (pattern_parm, args, tf_error);
26631 for (tree t = *p; t; t = DECL_CHAIN (t))
26632 DECL_CONTEXT (t) = decl;
26635 if (DECL_CONTRACTS (decl))
26637 /* If we're regenerating a specialization, the contracts will have
26638 been copied from the most general template. Replace those with
26639 the ones from the actual specialization. */
26640 tree tmpl = DECL_TI_TEMPLATE (decl);
26641 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26643 remove_contract_attributes (decl);
26644 copy_contract_attributes (decl, code_pattern);
26647 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26650 /* Merge additional specifiers from the CODE_PATTERN. */
26651 if (DECL_DECLARED_INLINE_P (code_pattern)
26652 && !DECL_DECLARED_INLINE_P (decl))
26653 DECL_DECLARED_INLINE_P (decl) = 1;
26655 maybe_instantiate_noexcept (decl, tf_error);
26657 else if (VAR_P (decl))
26659 start_lambda_scope (decl);
26660 DECL_INITIAL (decl) =
26661 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26662 tf_error, DECL_TI_TEMPLATE (decl));
26663 finish_lambda_scope ();
26664 if (VAR_HAD_UNKNOWN_BOUND (decl))
26665 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26666 tf_error, DECL_TI_TEMPLATE (decl));
26668 else
26669 gcc_unreachable ();
26671 done:
26672 pop_access_scope (decl);
26675 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26676 substituted to get DECL. */
26678 tree
26679 template_for_substitution (tree decl)
26681 tree tmpl = DECL_TI_TEMPLATE (decl);
26683 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26684 for the instantiation. This is not always the most general
26685 template. Consider, for example:
26687 template <class T>
26688 struct S { template <class U> void f();
26689 template <> void f<int>(); };
26691 and an instantiation of S<double>::f<int>. We want TD to be the
26692 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26693 while (/* An instantiation cannot have a definition, so we need a
26694 more general template. */
26695 DECL_TEMPLATE_INSTANTIATION (tmpl)
26696 /* We must also deal with friend templates. Given:
26698 template <class T> struct S {
26699 template <class U> friend void f() {};
26702 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26703 so far as the language is concerned, but that's still
26704 where we get the pattern for the instantiation from. On
26705 other hand, if the definition comes outside the class, say:
26707 template <class T> struct S {
26708 template <class U> friend void f();
26710 template <class U> friend void f() {}
26712 we don't need to look any further. That's what the check for
26713 DECL_INITIAL is for. */
26714 || (TREE_CODE (decl) == FUNCTION_DECL
26715 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26716 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26718 /* The present template, TD, should not be a definition. If it
26719 were a definition, we should be using it! Note that we
26720 cannot restructure the loop to just keep going until we find
26721 a template with a definition, since that might go too far if
26722 a specialization was declared, but not defined. */
26724 /* Fetch the more general template. */
26725 tmpl = DECL_TI_TEMPLATE (tmpl);
26728 return tmpl;
26731 /* Returns true if we need to instantiate this template instance even if we
26732 know we aren't going to emit it. */
26734 bool
26735 always_instantiate_p (tree decl)
26737 /* We always instantiate inline functions so that we can inline them. An
26738 explicit instantiation declaration prohibits implicit instantiation of
26739 non-inline functions. With high levels of optimization, we would
26740 normally inline non-inline functions -- but we're not allowed to do
26741 that for "extern template" functions. Therefore, we check
26742 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26743 return ((TREE_CODE (decl) == FUNCTION_DECL
26744 && (DECL_DECLARED_INLINE_P (decl)
26745 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26746 /* And we need to instantiate static data members so that
26747 their initializers are available in integral constant
26748 expressions. */
26749 || (VAR_P (decl)
26750 && decl_maybe_constant_var_p (decl)));
26753 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26754 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26755 error, true otherwise. */
26757 bool
26758 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26760 if (fn == error_mark_node)
26761 return false;
26763 /* Don't instantiate a noexcept-specification from template context. */
26764 if (processing_template_decl
26765 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26766 return true;
26768 tree fntype = TREE_TYPE (fn);
26769 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26771 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26772 && DECL_MAYBE_DELETED (fn))
26774 if (fn == current_function_decl)
26775 /* We're in start_preparsed_function, keep going. */
26776 return true;
26778 ++function_depth;
26779 maybe_synthesize_method (fn);
26780 --function_depth;
26781 return !DECL_DELETED_FN (fn);
26784 if (!spec || !TREE_PURPOSE (spec))
26785 return true;
26787 tree noex = TREE_PURPOSE (spec);
26788 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26789 && TREE_CODE (noex) != DEFERRED_PARSE)
26790 return true;
26792 tree orig_fn = NULL_TREE;
26793 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26794 its FUNCTION_DECL for the rest of this function -- push_access_scope
26795 doesn't accept TEMPLATE_DECLs. */
26796 if (DECL_FUNCTION_TEMPLATE_P (fn))
26798 orig_fn = fn;
26799 fn = DECL_TEMPLATE_RESULT (fn);
26802 if (DECL_CLONED_FUNCTION_P (fn))
26804 tree prime = DECL_CLONED_FUNCTION (fn);
26805 if (!maybe_instantiate_noexcept (prime, complain))
26806 return false;
26807 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26809 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26811 static hash_set<tree>* fns = new hash_set<tree>;
26812 bool added = false;
26813 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26815 spec = get_defaulted_eh_spec (fn, complain);
26816 if (spec == error_mark_node)
26817 /* This might have failed because of an unparsed DMI, so
26818 let's try again later. */
26819 return false;
26821 else if (!(added = !fns->add (fn)))
26823 /* If hash_set::add returns true, the element was already there. */
26824 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26825 DECL_SOURCE_LOCATION (fn));
26826 error_at (loc,
26827 "exception specification of %qD depends on itself",
26828 fn);
26829 spec = noexcept_false_spec;
26831 else if (push_tinst_level (fn))
26833 push_to_top_level ();
26834 push_access_scope (fn);
26835 push_deferring_access_checks (dk_no_deferred);
26836 input_location = DECL_SOURCE_LOCATION (fn);
26838 if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
26839 && !DECL_LOCAL_DECL_P (fn))
26841 /* If needed, set current_class_ptr for the benefit of
26842 tsubst_copy/PARM_DECL. */
26843 tree this_parm = DECL_ARGUMENTS (fn);
26844 current_class_ptr = NULL_TREE;
26845 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26846 current_class_ptr = this_parm;
26849 /* If this function is represented by a TEMPLATE_DECL, then
26850 the deferred noexcept-specification might still contain
26851 dependent types, even after substitution. And we need the
26852 dependency check functions to work in build_noexcept_spec. */
26853 if (orig_fn)
26854 ++processing_template_decl;
26856 /* Do deferred instantiation of the noexcept-specifier. */
26857 noex = tsubst_expr (DEFERRED_NOEXCEPT_PATTERN (noex),
26858 DEFERRED_NOEXCEPT_ARGS (noex),
26859 tf_warning_or_error, fn);
26861 /* Build up the noexcept-specification. */
26862 spec = build_noexcept_spec (noex, tf_warning_or_error);
26864 if (orig_fn)
26865 --processing_template_decl;
26867 pop_deferring_access_checks ();
26868 pop_access_scope (fn);
26869 pop_tinst_level ();
26870 pop_from_top_level ();
26872 else
26873 spec = noexcept_false_spec;
26875 if (added)
26876 fns->remove (fn);
26879 if (spec == error_mark_node)
26881 /* This failed with a hard error, so let's go with false. */
26882 gcc_assert (seen_error ());
26883 spec = noexcept_false_spec;
26886 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26887 if (orig_fn)
26888 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26890 return true;
26893 /* We're starting to process the function INST, an instantiation of PATTERN;
26894 add their parameters to local_specializations. */
26896 void
26897 register_parameter_specializations (tree pattern, tree inst)
26899 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26900 tree spec_parm = DECL_ARGUMENTS (inst);
26901 if (DECL_IOBJ_MEMBER_FUNCTION_P (inst))
26903 register_local_specialization (spec_parm, tmpl_parm);
26904 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26905 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26907 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26909 if (!DECL_PACK_P (tmpl_parm))
26911 register_local_specialization (spec_parm, tmpl_parm);
26912 spec_parm = DECL_CHAIN (spec_parm);
26914 else
26916 /* Register the (value) argument pack as a specialization of
26917 TMPL_PARM, then move on. */
26918 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26919 register_local_specialization (argpack, tmpl_parm);
26922 gcc_assert (!spec_parm);
26925 /* Instantiate the body of D using PATTERN with ARGS. We have
26926 already determined PATTERN is the correct template to use.
26927 NESTED_P is true if this is a nested function, in which case
26928 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26930 static void
26931 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26933 tree td = NULL_TREE;
26934 tree code_pattern = pattern;
26936 if (!nested_p)
26938 td = pattern;
26939 code_pattern = DECL_TEMPLATE_RESULT (td);
26941 else
26942 /* Only OMP reductions are nested. */
26943 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26945 vec<tree> omp_privatization_save;
26946 if (current_function_decl)
26947 save_omp_privatization_clauses (omp_privatization_save);
26949 bool push_to_top = maybe_push_to_top_level (d);
26951 mark_template_arguments_used (pattern, args);
26953 if (VAR_P (d))
26955 /* The variable might be a lambda's extra scope, and that
26956 lambda's visibility depends on D's. */
26957 maybe_commonize_var (d);
26958 determine_visibility (d);
26961 /* Mark D as instantiated so that recursive calls to
26962 instantiate_decl do not try to instantiate it again. */
26963 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26965 if (td)
26966 /* Regenerate the declaration in case the template has been modified
26967 by a subsequent redeclaration. */
26968 regenerate_decl_from_template (d, td, args);
26970 /* We already set the file and line above. Reset them now in case
26971 they changed as a result of calling regenerate_decl_from_template. */
26972 input_location = DECL_SOURCE_LOCATION (d);
26974 if (VAR_P (d))
26976 /* Clear out DECL_RTL; whatever was there before may not be right
26977 since we've reset the type of the declaration. */
26978 SET_DECL_RTL (d, NULL);
26979 DECL_IN_AGGR_P (d) = 0;
26981 /* The initializer is placed in DECL_INITIAL by
26982 regenerate_decl_from_template so we don't need to
26983 push/pop_access_scope again here. Pull it out so that
26984 cp_finish_decl can process it. */
26985 bool const_init = false;
26986 tree init = DECL_INITIAL (d);
26987 DECL_INITIAL (d) = NULL_TREE;
26988 DECL_INITIALIZED_P (d) = 0;
26990 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26991 initializer. That function will defer actual emission until
26992 we have a chance to determine linkage. */
26993 DECL_EXTERNAL (d) = 0;
26995 /* Enter the scope of D so that access-checking works correctly. */
26996 bool enter_context = DECL_CLASS_SCOPE_P (d);
26997 if (enter_context)
26998 push_nested_class (DECL_CONTEXT (d));
27000 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27001 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
27003 if (enter_context)
27004 pop_nested_class ();
27006 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
27007 synthesize_method (d);
27008 else if (TREE_CODE (d) == FUNCTION_DECL)
27010 /* Set up the list of local specializations. */
27011 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
27012 tree block = NULL_TREE;
27014 /* Set up context. */
27015 if (nested_p)
27016 block = push_stmt_list ();
27017 else
27019 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
27021 perform_instantiation_time_access_checks (code_pattern, args);
27024 /* Create substitution entries for the parameters. */
27025 register_parameter_specializations (code_pattern, d);
27027 /* Substitute into the body of the function. */
27028 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27029 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
27030 tf_warning_or_error, d);
27031 else
27033 tsubst_stmt (DECL_SAVED_TREE (code_pattern), args,
27034 tf_warning_or_error, DECL_TI_TEMPLATE (d));
27036 /* Set the current input_location to the end of the function
27037 so that finish_function knows where we are. */
27038 input_location
27039 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
27041 /* Remember if we saw an infinite loop in the template. */
27042 current_function_infinite_loop
27043 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
27046 /* Finish the function. */
27047 if (nested_p)
27048 DECL_SAVED_TREE (d) = pop_stmt_list (block);
27049 else
27051 d = finish_function (/*inline_p=*/false);
27052 expand_or_defer_fn (d);
27055 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27056 cp_check_omp_declare_reduction (d);
27059 /* We're not deferring instantiation any more. */
27060 if (!nested_p)
27061 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
27063 maybe_pop_from_top_level (push_to_top);
27065 if (current_function_decl)
27066 restore_omp_privatization_clauses (omp_privatization_save);
27069 /* Produce the definition of D, a _DECL generated from a template. If
27070 DEFER_OK is true, then we don't have to actually do the
27071 instantiation now; we just have to do it sometime. Normally it is
27072 an error if this is an explicit instantiation but D is undefined.
27073 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
27074 instantiated class template. */
27076 tree
27077 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
27079 tree tmpl = DECL_TI_TEMPLATE (d);
27080 tree gen_args;
27081 tree args;
27082 tree td;
27083 tree code_pattern;
27084 tree spec;
27085 tree gen_tmpl;
27086 bool pattern_defined;
27087 location_t saved_loc = input_location;
27088 bool external_p;
27089 bool deleted_p;
27091 /* This function should only be used to instantiate templates for
27092 functions and static member variables. */
27093 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
27095 /* A concept is never instantiated. */
27096 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
27098 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
27100 if (modules_p ())
27101 /* We may have a pending instantiation of D itself. */
27102 lazy_load_pendings (d);
27104 /* Variables are never deferred; if instantiation is required, they
27105 are instantiated right away. That allows for better code in the
27106 case that an expression refers to the value of the variable --
27107 if the variable has a constant value the referring expression can
27108 take advantage of that fact. */
27109 if (VAR_P (d))
27110 defer_ok = false;
27112 /* Don't instantiate cloned functions. Instead, instantiate the
27113 functions they cloned. */
27114 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
27115 d = DECL_CLONED_FUNCTION (d);
27117 if (DECL_TEMPLATE_INSTANTIATED (d)
27118 || TREE_TYPE (d) == error_mark_node
27119 || (TREE_CODE (d) == FUNCTION_DECL
27120 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
27121 || DECL_TEMPLATE_SPECIALIZATION (d))
27122 /* D has already been instantiated or explicitly specialized, so
27123 there's nothing for us to do here.
27125 It might seem reasonable to check whether or not D is an explicit
27126 instantiation, and, if so, stop here. But when an explicit
27127 instantiation is deferred until the end of the compilation,
27128 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
27129 the instantiation. */
27130 return d;
27132 /* Check to see whether we know that this template will be
27133 instantiated in some other file, as with "extern template"
27134 extension. */
27135 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
27137 /* In general, we do not instantiate such templates. */
27138 if (external_p && !always_instantiate_p (d))
27139 return d;
27141 gen_tmpl = most_general_template (tmpl);
27142 gen_args = DECL_TI_ARGS (d);
27144 /* We should already have the extra args. */
27145 gcc_checking_assert (tmpl == gen_tmpl
27146 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27147 == TMPL_ARGS_DEPTH (gen_args)));
27148 /* And what's in the hash table should match D. */
27149 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27150 == d
27151 || spec == NULL_TREE);
27153 /* This needs to happen before any tsubsting. */
27154 if (! push_tinst_level (d))
27155 return d;
27157 auto_timevar tv (TV_TEMPLATE_INST);
27159 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27160 for the instantiation. */
27161 td = template_for_substitution (d);
27162 args = gen_args;
27164 if (variable_template_specialization_p (d))
27166 /* Look up an explicit specialization, if any. */
27167 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
27168 if (partial_ti && partial_ti != error_mark_node)
27170 td = TI_TEMPLATE (partial_ti);
27171 args = TI_ARGS (partial_ti);
27175 code_pattern = DECL_TEMPLATE_RESULT (td);
27177 /* We should never be trying to instantiate a member of a class
27178 template or partial specialization. */
27179 gcc_assert (d != code_pattern);
27181 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27182 || DECL_TEMPLATE_SPECIALIZATION (td))
27183 /* In the case of a friend template whose definition is provided
27184 outside the class, we may have too many arguments. Drop the
27185 ones we don't need. The same is true for specializations. */
27186 args = get_innermost_template_args
27187 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27189 if (TREE_CODE (d) == FUNCTION_DECL)
27191 deleted_p = DECL_DELETED_FN (code_pattern);
27192 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27193 && DECL_INITIAL (code_pattern) != error_mark_node)
27194 || DECL_DEFAULTED_FN (code_pattern)
27195 || deleted_p);
27197 else
27199 deleted_p = false;
27200 if (DECL_CLASS_SCOPE_P (code_pattern))
27201 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27202 else
27203 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27206 /* We may be in the middle of deferred access check. Disable it now. */
27207 push_deferring_access_checks (dk_no_deferred);
27209 /* Unless an explicit instantiation directive has already determined
27210 the linkage of D, remember that a definition is available for
27211 this entity. */
27212 if (pattern_defined
27213 && !DECL_INTERFACE_KNOWN (d)
27214 && !DECL_NOT_REALLY_EXTERN (d))
27215 mark_definable (d);
27217 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27218 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27219 input_location = DECL_SOURCE_LOCATION (d);
27221 /* If D is a member of an explicitly instantiated class template,
27222 and no definition is available, treat it like an implicit
27223 instantiation. */
27224 if (!pattern_defined && expl_inst_class_mem_p
27225 && DECL_EXPLICIT_INSTANTIATION (d))
27227 /* Leave linkage flags alone on instantiations with anonymous
27228 visibility. */
27229 if (TREE_PUBLIC (d))
27231 DECL_NOT_REALLY_EXTERN (d) = 0;
27232 DECL_INTERFACE_KNOWN (d) = 0;
27234 SET_DECL_IMPLICIT_INSTANTIATION (d);
27237 /* Defer all other templates, unless we have been explicitly
27238 forbidden from doing so. */
27239 if (/* If there is no definition, we cannot instantiate the
27240 template. */
27241 ! pattern_defined
27242 /* If it's OK to postpone instantiation, do so. */
27243 || defer_ok
27244 /* If this is a static data member that will be defined
27245 elsewhere, we don't want to instantiate the entire data
27246 member, but we do want to instantiate the initializer so that
27247 we can substitute that elsewhere. */
27248 || (external_p && VAR_P (d))
27249 /* Handle here a deleted function too, avoid generating
27250 its body (c++/61080). */
27251 || deleted_p)
27253 /* The definition of the static data member is now required so
27254 we must substitute the initializer. */
27255 if (VAR_P (d)
27256 && !DECL_INITIAL (d)
27257 && DECL_INITIAL (code_pattern))
27259 tree ns;
27260 tree init;
27261 bool const_init = false;
27262 bool enter_context = DECL_CLASS_SCOPE_P (d);
27264 ns = decl_namespace_context (d);
27265 push_nested_namespace (ns);
27266 if (enter_context)
27267 push_nested_class (DECL_CONTEXT (d));
27268 init = tsubst_expr (DECL_INITIAL (code_pattern),
27269 args,
27270 tf_warning_or_error, NULL_TREE);
27271 /* If instantiating the initializer involved instantiating this
27272 again, don't call cp_finish_decl twice. */
27273 if (!DECL_INITIAL (d))
27275 /* Make sure the initializer is still constant, in case of
27276 circular dependency (template/instantiate6.C). */
27277 const_init
27278 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27279 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27280 /*asmspec_tree=*/NULL_TREE, 0);
27282 if (enter_context)
27283 pop_nested_class ();
27284 pop_nested_namespace (ns);
27287 /* We restore the source position here because it's used by
27288 add_pending_template. */
27289 input_location = saved_loc;
27291 if (at_eof && !pattern_defined
27292 && DECL_EXPLICIT_INSTANTIATION (d)
27293 && DECL_NOT_REALLY_EXTERN (d))
27294 /* [temp.explicit]
27296 The definition of a non-exported function template, a
27297 non-exported member function template, or a non-exported
27298 member function or static data member of a class template
27299 shall be present in every translation unit in which it is
27300 explicitly instantiated. */
27301 permerror (input_location, "explicit instantiation of %qD "
27302 "but no definition available", d);
27304 /* If we're in unevaluated context, we just wanted to get the
27305 constant value; this isn't an odr use, so don't queue
27306 a full instantiation. */
27307 if (!cp_unevaluated_operand
27308 /* ??? Historically, we have instantiated inline functions, even
27309 when marked as "extern template". */
27310 && !(external_p && VAR_P (d)))
27311 add_pending_template (d);
27313 else
27315 set_instantiating_module (d);
27316 if (variable_template_p (gen_tmpl))
27317 note_vague_linkage_variable (d);
27318 instantiate_body (td, args, d, false);
27321 pop_deferring_access_checks ();
27322 pop_tinst_level ();
27323 input_location = saved_loc;
27325 return d;
27328 /* Run through the list of templates that we wish we could
27329 instantiate, and instantiate any we can. RETRIES is the
27330 number of times we retry pending template instantiation. */
27332 void
27333 instantiate_pending_templates (int retries)
27335 int reconsider;
27336 location_t saved_loc = input_location;
27338 /* Instantiating templates may trigger vtable generation. This in turn
27339 may require further template instantiations. We place a limit here
27340 to avoid infinite loop. */
27341 if (pending_templates && retries >= max_tinst_depth)
27343 tree decl = pending_templates->tinst->maybe_get_node ();
27345 fatal_error (input_location,
27346 "template instantiation depth exceeds maximum of %d"
27347 " instantiating %q+D, possibly from virtual table generation"
27348 " (use %<-ftemplate-depth=%> to increase the maximum)",
27349 max_tinst_depth, decl);
27350 if (TREE_CODE (decl) == FUNCTION_DECL)
27351 /* Pretend that we defined it. */
27352 DECL_INITIAL (decl) = error_mark_node;
27353 return;
27358 struct pending_template **t = &pending_templates;
27359 struct pending_template *last = NULL;
27360 reconsider = 0;
27361 while (*t)
27363 tree instantiation = reopen_tinst_level ((*t)->tinst);
27364 bool complete = false;
27366 if (TYPE_P (instantiation))
27368 if (!COMPLETE_TYPE_P (instantiation))
27370 instantiate_class_template (instantiation);
27371 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27372 for (tree fld = TYPE_FIELDS (instantiation);
27373 fld; fld = TREE_CHAIN (fld))
27374 if ((VAR_P (fld)
27375 || (TREE_CODE (fld) == FUNCTION_DECL
27376 && !DECL_ARTIFICIAL (fld)))
27377 && DECL_TEMPLATE_INSTANTIATION (fld))
27378 instantiate_decl (fld,
27379 /*defer_ok=*/false,
27380 /*expl_inst_class_mem_p=*/false);
27382 if (COMPLETE_TYPE_P (instantiation))
27383 reconsider = 1;
27386 complete = COMPLETE_TYPE_P (instantiation);
27388 else
27390 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27391 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27393 instantiation
27394 = instantiate_decl (instantiation,
27395 /*defer_ok=*/false,
27396 /*expl_inst_class_mem_p=*/false);
27397 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27398 reconsider = 1;
27401 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27402 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27405 if (complete)
27407 /* If INSTANTIATION has been instantiated, then we don't
27408 need to consider it again in the future. */
27409 struct pending_template *drop = *t;
27410 *t = (*t)->next;
27411 set_refcount_ptr (drop->tinst);
27412 pending_template_freelist ().free (drop);
27414 else
27416 last = *t;
27417 t = &(*t)->next;
27419 tinst_depth = 0;
27420 set_refcount_ptr (current_tinst_level);
27422 last_pending_template = last;
27424 while (reconsider);
27426 input_location = saved_loc;
27429 /* Substitute ARGVEC into T, which is a list of initializers for
27430 either base class or a non-static data member. The TREE_PURPOSEs
27431 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27432 instantiate_decl. */
27434 static tree
27435 tsubst_initializer_list (tree t, tree argvec)
27437 tree inits = NULL_TREE;
27438 tree target_ctor = error_mark_node;
27440 for (; t; t = TREE_CHAIN (t))
27442 tree decl;
27443 tree init;
27444 tree expanded_bases = NULL_TREE;
27445 tree expanded_arguments = NULL_TREE;
27446 int i, len = 1;
27448 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27450 tree expr;
27451 tree arg;
27453 /* Expand the base class expansion type into separate base
27454 classes. */
27455 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27456 tf_warning_or_error,
27457 NULL_TREE);
27458 if (expanded_bases == error_mark_node)
27459 continue;
27461 /* We'll be building separate TREE_LISTs of arguments for
27462 each base. */
27463 len = TREE_VEC_LENGTH (expanded_bases);
27464 expanded_arguments = make_tree_vec (len);
27465 for (i = 0; i < len; i++)
27466 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27468 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27469 expand each argument in the TREE_VALUE of t. */
27470 expr = make_node (EXPR_PACK_EXPANSION);
27471 PACK_EXPANSION_LOCAL_P (expr) = true;
27472 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27473 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27475 if (TREE_VALUE (t) == void_type_node)
27476 /* VOID_TYPE_NODE is used to indicate
27477 value-initialization. */
27479 for (i = 0; i < len; i++)
27480 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27482 else
27484 /* Substitute parameter packs into each argument in the
27485 TREE_LIST. */
27486 in_base_initializer = 1;
27487 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27489 tree expanded_exprs;
27491 /* Expand the argument. */
27492 tree value;
27493 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27494 value = TREE_VALUE (arg);
27495 else
27497 value = expr;
27498 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27500 expanded_exprs
27501 = tsubst_pack_expansion (value, argvec,
27502 tf_warning_or_error,
27503 NULL_TREE);
27504 if (expanded_exprs == error_mark_node)
27505 continue;
27507 /* Prepend each of the expanded expressions to the
27508 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27509 for (i = 0; i < len; i++)
27510 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27511 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27512 TREE_VEC_ELT (expanded_arguments, i)
27513 = tree_cons (NULL_TREE,
27514 TREE_VEC_ELT (expanded_exprs, j),
27515 TREE_VEC_ELT (expanded_arguments, i));
27516 else
27517 TREE_VEC_ELT (expanded_arguments, i)
27518 = tree_cons (NULL_TREE,
27519 TREE_VEC_ELT (expanded_exprs, i),
27520 TREE_VEC_ELT (expanded_arguments, i));
27522 in_base_initializer = 0;
27524 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27525 since we built them backwards. */
27526 for (i = 0; i < len; i++)
27528 TREE_VEC_ELT (expanded_arguments, i) =
27529 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27534 for (i = 0; i < len; ++i)
27536 if (expanded_bases)
27538 decl = TREE_VEC_ELT (expanded_bases, i);
27539 decl = expand_member_init (decl);
27540 init = TREE_VEC_ELT (expanded_arguments, i);
27542 else
27544 tree tmp;
27545 if (TYPE_P (TREE_PURPOSE (t)))
27546 decl = tsubst (TREE_PURPOSE (t), argvec,
27547 tf_warning_or_error, NULL_TREE);
27548 else
27549 decl = tsubst_expr (TREE_PURPOSE (t), argvec,
27550 tf_warning_or_error, NULL_TREE);
27552 decl = expand_member_init (decl);
27553 if (decl && !DECL_P (decl))
27554 in_base_initializer = 1;
27556 init = TREE_VALUE (t);
27557 tmp = init;
27558 if (init != void_type_node)
27559 init = tsubst_expr (init, argvec,
27560 tf_warning_or_error, NULL_TREE);
27561 if (init == NULL_TREE && tmp != NULL_TREE)
27562 /* If we had an initializer but it instantiated to nothing,
27563 value-initialize the object. This will only occur when
27564 the initializer was a pack expansion where the parameter
27565 packs used in that expansion were of length zero. */
27566 init = void_type_node;
27567 in_base_initializer = 0;
27570 if (target_ctor != error_mark_node
27571 && init != error_mark_node)
27573 error ("mem-initializer for %qD follows constructor delegation",
27574 decl);
27575 return inits;
27577 /* Look for a target constructor. */
27578 if (init != error_mark_node
27579 && decl && CLASS_TYPE_P (decl)
27580 && same_type_p (decl, current_class_type))
27582 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27583 if (inits)
27585 error ("constructor delegation follows mem-initializer for %qD",
27586 TREE_PURPOSE (inits));
27587 continue;
27589 target_ctor = init;
27592 if (decl)
27594 init = build_tree_list (decl, init);
27595 /* Carry over the dummy TREE_TYPE node containing the source
27596 location. */
27597 TREE_TYPE (init) = TREE_TYPE (t);
27598 TREE_CHAIN (init) = inits;
27599 inits = init;
27603 return inits;
27606 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27607 is the instantiation (which should have been created with
27608 start_enum) and ARGS are the template arguments to use. */
27610 static void
27611 tsubst_enum (tree tag, tree newtag, tree args)
27613 tree e;
27615 if (SCOPED_ENUM_P (newtag))
27616 begin_scope (sk_scoped_enum, newtag);
27618 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27620 tree value;
27621 tree decl = TREE_VALUE (e);
27623 /* Note that in a template enum, the TREE_VALUE is the
27624 CONST_DECL, not the corresponding INTEGER_CST. */
27625 value = tsubst_expr (DECL_INITIAL (decl),
27626 args, tf_warning_or_error, NULL_TREE);
27628 /* Give this enumeration constant the correct access. */
27629 set_current_access_from_decl (decl);
27631 /* Actually build the enumerator itself. Here we're assuming that
27632 enumerators can't have dependent attributes. */
27633 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27634 DECL_ATTRIBUTES (decl),
27635 DECL_SOURCE_LOCATION (decl));
27636 /* Attribute deprecated without an argument isn't sticky: it'll
27637 melt into a tree flag, so we need to propagate the flag here,
27638 since we just created a new enumerator. */
27639 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27640 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27643 if (SCOPED_ENUM_P (newtag))
27644 finish_scope ();
27646 finish_enum_value_list (newtag);
27647 finish_enum (newtag);
27649 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27650 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27651 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27652 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27655 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27656 its type -- but without substituting the innermost set of template
27657 arguments. So, innermost set of template parameters will appear in
27658 the type. */
27660 tree
27661 get_mostly_instantiated_function_type (tree decl)
27663 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27664 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27667 /* Return truthvalue if we're processing a template different from
27668 the last one involved in diagnostics. */
27669 bool
27670 problematic_instantiation_changed (void)
27672 return current_tinst_level != last_error_tinst_level;
27675 /* Remember current template involved in diagnostics. */
27676 void
27677 record_last_problematic_instantiation (void)
27679 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27682 struct tinst_level *
27683 current_instantiation (void)
27685 return current_tinst_level;
27688 /* Return TRUE if current_function_decl is being instantiated, false
27689 otherwise. */
27691 bool
27692 instantiating_current_function_p (void)
27694 return (current_instantiation ()
27695 && (current_instantiation ()->maybe_get_node ()
27696 == current_function_decl));
27699 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27700 type. Return false for ok, true for disallowed. Issue error and
27701 inform messages under control of COMPLAIN. */
27703 static bool
27704 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27706 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27707 return false;
27708 else if (TYPE_PTR_P (type))
27709 return false;
27710 else if (TYPE_REF_P (type)
27711 && !TYPE_REF_IS_RVALUE (type))
27712 return false;
27713 else if (TYPE_PTRMEM_P (type))
27714 return false;
27715 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27717 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27719 if (complain & tf_error)
27720 error ("non-type template parameters of deduced class type only "
27721 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27722 return true;
27724 return false;
27726 else if (TREE_CODE (type) == NULLPTR_TYPE)
27727 return false;
27728 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27729 && cxx_dialect < cxx11)
27730 /* Fall through; before C++11 alias templates, a bound ttp
27731 always instantiates into a class type. */;
27732 else if (WILDCARD_TYPE_P (type))
27733 /* Any other wildcard type not already handled above is allowed. */
27734 return false;
27735 else if (TREE_CODE (type) == COMPLEX_TYPE)
27736 /* Fall through. */;
27737 else if (VOID_TYPE_P (type))
27738 /* Fall through. */;
27739 else if (cxx_dialect >= cxx20)
27741 if (dependent_type_p (type))
27742 return false;
27743 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27744 return true;
27745 if (structural_type_p (type))
27746 return false;
27747 if (complain & tf_error)
27749 auto_diagnostic_group d;
27750 error ("%qT is not a valid type for a template non-type "
27751 "parameter because it is not structural", type);
27752 structural_type_p (type, true);
27754 return true;
27756 else if (CLASS_TYPE_P (type))
27758 if (complain & tf_error)
27759 error ("non-type template parameters of class type only available "
27760 "with %<-std=c++20%> or %<-std=gnu++20%>");
27761 return true;
27764 if (complain & tf_error)
27766 if (type == error_mark_node)
27767 inform (input_location, "invalid template non-type parameter");
27768 else
27769 error ("%q#T is not a valid type for a template non-type parameter",
27770 type);
27772 return true;
27775 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27777 static bool
27778 value_dependent_noexcept_spec_p (tree type)
27780 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27781 if (tree noex = TREE_PURPOSE (spec))
27782 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27783 affect overload resolution and treating it as dependent breaks
27784 things. Same for an unparsed noexcept expression. */
27785 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27786 && TREE_CODE (noex) != DEFERRED_PARSE
27787 && value_dependent_expression_p (noex))
27788 return true;
27790 return false;
27793 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27794 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27796 static bool
27797 dependent_type_p_r (tree type)
27799 tree scope;
27801 /* [temp.dep.type]
27803 A type is dependent if it is:
27805 -- a template parameter. Template template parameters are types
27806 for us (since TYPE_P holds true for them) so we handle
27807 them here. */
27808 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27809 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27810 return true;
27811 /* -- a qualified-id with a nested-name-specifier which contains a
27812 class-name that names a dependent type or whose unqualified-id
27813 names a dependent type. */
27814 if (TREE_CODE (type) == TYPENAME_TYPE)
27815 return true;
27817 /* An alias template specialization can be dependent even if the
27818 resulting type is not. */
27819 if (dependent_alias_template_spec_p (type, nt_transparent))
27820 return true;
27822 /* -- a cv-qualified type where the cv-unqualified type is
27823 dependent.
27824 No code is necessary for this bullet; the code below handles
27825 cv-qualified types, and we don't want to strip aliases with
27826 TYPE_MAIN_VARIANT because of DR 1558. */
27827 /* -- a compound type constructed from any dependent type. */
27828 if (TYPE_PTRMEM_P (type))
27829 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27830 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27831 (type)));
27832 else if (INDIRECT_TYPE_P (type))
27833 return dependent_type_p (TREE_TYPE (type));
27834 else if (FUNC_OR_METHOD_TYPE_P (type))
27836 tree arg_type;
27838 if (dependent_type_p (TREE_TYPE (type)))
27839 return true;
27840 for (arg_type = TYPE_ARG_TYPES (type);
27841 arg_type;
27842 arg_type = TREE_CHAIN (arg_type))
27843 if (dependent_type_p (TREE_VALUE (arg_type)))
27844 return true;
27845 if (cxx_dialect >= cxx17
27846 && value_dependent_noexcept_spec_p (type))
27847 /* A value-dependent noexcept-specifier makes the type dependent. */
27848 return true;
27849 return false;
27851 /* -- an array type constructed from any dependent type or whose
27852 size is specified by a constant expression that is
27853 value-dependent.
27855 We checked for type- and value-dependence of the bounds in
27856 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27857 if (TREE_CODE (type) == ARRAY_TYPE)
27859 if (TYPE_DOMAIN (type)
27860 && dependent_type_p (TYPE_DOMAIN (type)))
27861 return true;
27862 return dependent_type_p (TREE_TYPE (type));
27865 /* -- a template-id in which either the template name is a template
27866 parameter ... */
27867 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27868 return true;
27869 /* ... or any of the template arguments is a dependent type or
27870 an expression that is type-dependent or value-dependent. */
27871 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27872 && (any_dependent_template_arguments_p
27873 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27874 return true;
27876 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27877 dependent; if the argument of the `typeof' expression is not
27878 type-dependent, then it should already been have resolved. */
27879 if (TREE_CODE (type) == TYPEOF_TYPE
27880 || TREE_CODE (type) == DECLTYPE_TYPE
27881 || TREE_CODE (type) == TRAIT_TYPE)
27882 return true;
27884 /* A template argument pack is dependent if any of its packed
27885 arguments are. */
27886 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27888 tree args = ARGUMENT_PACK_ARGS (type);
27889 for (tree arg : tree_vec_range (args))
27890 if (dependent_template_arg_p (arg))
27891 return true;
27894 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27895 be template parameters. */
27896 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27897 return true;
27899 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27900 return true;
27902 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27903 return true;
27905 /* The standard does not specifically mention types that are local
27906 to template functions or local classes, but they should be
27907 considered dependent too. For example:
27909 template <int I> void f() {
27910 enum E { a = I };
27911 S<sizeof (E)> s;
27914 The size of `E' cannot be known until the value of `I' has been
27915 determined. Therefore, `E' must be considered dependent. */
27916 scope = TYPE_CONTEXT (type);
27917 if (scope && TYPE_P (scope))
27918 return dependent_type_p (scope);
27919 /* Don't use type_dependent_expression_p here, as it can lead
27920 to infinite recursion trying to determine whether a lambda
27921 nested in a lambda is dependent (c++/47687). */
27922 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27923 && DECL_LANG_SPECIFIC (scope)
27924 && DECL_TEMPLATE_INFO (scope)
27925 && (any_dependent_template_arguments_p
27926 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27927 return true;
27929 /* Other types are non-dependent. */
27930 return false;
27933 /* Returns TRUE if TYPE is dependent, in the sense of
27934 [temp.dep.type]. Note that a NULL type is considered dependent. */
27936 bool
27937 dependent_type_p (tree type)
27939 /* If there are no template parameters in scope, then there can't be
27940 any dependent types. */
27941 if (!processing_template_decl)
27943 /* If we are not processing a template, then nobody should be
27944 providing us with a dependent type. */
27945 gcc_assert (type);
27946 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27947 return false;
27950 /* If the type is NULL, we have not computed a type for the entity
27951 in question; in that case, the type is dependent. */
27952 if (!type)
27953 return true;
27955 /* Erroneous types can be considered non-dependent. */
27956 if (type == error_mark_node)
27957 return false;
27959 /* If we have not already computed the appropriate value for TYPE,
27960 do so now. */
27961 if (!TYPE_DEPENDENT_P_VALID (type))
27963 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27964 TYPE_DEPENDENT_P_VALID (type) = 1;
27967 return TYPE_DEPENDENT_P (type);
27970 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27971 lookup. In other words, a dependent type that is not the current
27972 instantiation. */
27974 bool
27975 dependent_scope_p (tree scope)
27977 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27978 && !currently_open_class (scope));
27981 /* True if we might find more declarations in SCOPE during instantiation than
27982 we can when parsing the template. */
27984 bool
27985 dependentish_scope_p (tree scope)
27987 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27990 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27991 an unknown base of 'this' (and is therefore instantiation-dependent). */
27993 static bool
27994 unknown_base_ref_p (tree t)
27996 if (!current_class_ptr)
27997 return false;
27999 tree mem = TREE_OPERAND (t, 1);
28000 if (shared_member_p (mem))
28001 return false;
28003 tree cur = current_nonlambda_class_type ();
28004 if (!any_dependent_bases_p (cur))
28005 return false;
28007 tree ctx = TREE_OPERAND (t, 0);
28008 if (DERIVED_FROM_P (ctx, cur))
28009 return false;
28011 return true;
28014 /* T is a SCOPE_REF; return whether we need to consider it
28015 instantiation-dependent so that we can check access at instantiation
28016 time even though we know which member it resolves to. */
28018 static bool
28019 instantiation_dependent_scope_ref_p (tree t)
28021 if (DECL_P (TREE_OPERAND (t, 1))
28022 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
28023 && !dependent_scope_p (TREE_OPERAND (t, 0))
28024 && !unknown_base_ref_p (t)
28025 && accessible_in_template_p (TREE_OPERAND (t, 0),
28026 TREE_OPERAND (t, 1)))
28027 return false;
28028 else
28029 return true;
28032 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
28033 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
28034 expression. */
28036 /* Note that this predicate is not appropriate for general expressions;
28037 only constant expressions (that satisfy potential_constant_expression)
28038 can be tested for value dependence. */
28040 bool
28041 value_dependent_expression_p (tree expression)
28043 if (!processing_template_decl || expression == NULL_TREE)
28044 return false;
28046 /* A type-dependent expression is also value-dependent. */
28047 if (type_dependent_expression_p (expression))
28048 return true;
28050 switch (TREE_CODE (expression))
28052 case BASELINK:
28053 /* A dependent member function of the current instantiation. */
28054 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
28056 case FUNCTION_DECL:
28057 /* A dependent member function of the current instantiation. */
28058 if (DECL_CLASS_SCOPE_P (expression)
28059 && dependent_type_p (DECL_CONTEXT (expression)))
28060 return true;
28061 break;
28063 case IDENTIFIER_NODE:
28064 /* A name that has not been looked up -- must be dependent. */
28065 return true;
28067 case TEMPLATE_PARM_INDEX:
28068 /* A non-type template parm. */
28069 return true;
28071 case CONST_DECL:
28072 /* A non-type template parm. */
28073 if (DECL_TEMPLATE_PARM_P (expression))
28074 return true;
28075 return value_dependent_expression_p (DECL_INITIAL (expression));
28077 case VAR_DECL:
28078 /* A constant with literal type and is initialized
28079 with an expression that is value-dependent. */
28080 if (DECL_DEPENDENT_INIT_P (expression))
28081 return true;
28082 if (DECL_HAS_VALUE_EXPR_P (expression))
28084 tree value_expr = DECL_VALUE_EXPR (expression);
28085 if (value_dependent_expression_p (value_expr)
28086 /* __PRETTY_FUNCTION__ inside a template function is dependent
28087 on the name of the function. */
28088 || (DECL_PRETTY_FUNCTION_P (expression)
28089 /* It might be used in a template, but not a template
28090 function, in which case its DECL_VALUE_EXPR will be
28091 "top level". */
28092 && value_expr == error_mark_node))
28093 return true;
28095 else if (TYPE_REF_P (TREE_TYPE (expression)))
28096 /* FIXME cp_finish_decl doesn't fold reference initializers. */
28097 return true;
28098 /* We have a constexpr variable and we're processing a template. When
28099 there's lifetime extension involved (for which finish_compound_literal
28100 used to create a temporary), we'll not be able to evaluate the
28101 variable until instantiating, so pretend it's value-dependent. */
28102 else if (DECL_DECLARED_CONSTEXPR_P (expression)
28103 && !TREE_CONSTANT (expression))
28104 return true;
28105 return false;
28107 case DYNAMIC_CAST_EXPR:
28108 case STATIC_CAST_EXPR:
28109 case CONST_CAST_EXPR:
28110 case REINTERPRET_CAST_EXPR:
28111 case CAST_EXPR:
28112 case IMPLICIT_CONV_EXPR:
28113 /* These expressions are value-dependent if the type to which
28114 the cast occurs is dependent or the expression being casted
28115 is value-dependent. */
28117 tree type = TREE_TYPE (expression);
28119 if (dependent_type_p (type))
28120 return true;
28122 /* A functional cast has a list of operands. */
28123 expression = TREE_OPERAND (expression, 0);
28124 if (!expression)
28126 /* If there are no operands, it must be an expression such
28127 as "int()". This should not happen for aggregate types
28128 because it would form non-constant expressions. */
28129 gcc_assert (cxx_dialect >= cxx11
28130 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
28132 return false;
28135 if (TREE_CODE (expression) == TREE_LIST)
28136 return any_value_dependent_elements_p (expression);
28138 if (TREE_CODE (type) == REFERENCE_TYPE
28139 && has_value_dependent_address (expression))
28140 return true;
28142 return value_dependent_expression_p (expression);
28145 case SIZEOF_EXPR:
28146 if (SIZEOF_EXPR_TYPE_P (expression))
28147 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
28148 /* FALLTHRU */
28149 case ALIGNOF_EXPR:
28150 case TYPEID_EXPR:
28151 /* A `sizeof' expression is value-dependent if the operand is
28152 type-dependent or is a pack expansion. */
28153 expression = TREE_OPERAND (expression, 0);
28154 if (PACK_EXPANSION_P (expression))
28155 return true;
28156 else if (TYPE_P (expression))
28157 return dependent_type_p (expression);
28158 return instantiation_dependent_uneval_expression_p (expression);
28160 case AT_ENCODE_EXPR:
28161 /* An 'encode' expression is value-dependent if the operand is
28162 type-dependent. */
28163 expression = TREE_OPERAND (expression, 0);
28164 return dependent_type_p (expression);
28166 case NOEXCEPT_EXPR:
28167 expression = TREE_OPERAND (expression, 0);
28168 return instantiation_dependent_uneval_expression_p (expression);
28170 case SCOPE_REF:
28171 /* All instantiation-dependent expressions should also be considered
28172 value-dependent. */
28173 return instantiation_dependent_scope_ref_p (expression);
28175 case COMPONENT_REF:
28176 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28177 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28179 case NONTYPE_ARGUMENT_PACK:
28180 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28181 is value-dependent. */
28182 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28183 if (value_dependent_expression_p (arg))
28184 return true;
28185 return false;
28187 case TRAIT_EXPR:
28189 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28190 return true;
28192 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28193 if (!type2)
28194 return false;
28196 if (TREE_CODE (type2) != TREE_VEC)
28197 return dependent_type_p (type2);
28199 for (tree arg : tree_vec_range (type2))
28200 if (dependent_type_p (arg))
28201 return true;
28203 return false;
28206 case MODOP_EXPR:
28207 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28208 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28210 case ARRAY_REF:
28211 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28212 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28214 case ADDR_EXPR:
28216 tree op = TREE_OPERAND (expression, 0);
28217 return (value_dependent_expression_p (op)
28218 || has_value_dependent_address (op));
28221 case REQUIRES_EXPR:
28222 /* Treat all requires-expressions as value-dependent so
28223 we don't try to fold them. */
28224 return true;
28226 case TYPE_REQ:
28227 return dependent_type_p (TREE_OPERAND (expression, 0));
28229 case CALL_EXPR:
28231 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28232 return true;
28233 tree fn = get_callee_fndecl (expression);
28234 int i, nargs;
28235 nargs = call_expr_nargs (expression);
28236 for (i = 0; i < nargs; ++i)
28238 tree op = CALL_EXPR_ARG (expression, i);
28239 /* In a call to a constexpr member function, look through the
28240 implicit ADDR_EXPR on the object argument so that it doesn't
28241 cause the call to be considered value-dependent. We also
28242 look through it in potential_constant_expression. */
28243 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28244 && DECL_IOBJ_MEMBER_FUNCTION_P (fn)
28245 && TREE_CODE (op) == ADDR_EXPR)
28246 op = TREE_OPERAND (op, 0);
28247 if (value_dependent_expression_p (op))
28248 return true;
28250 return false;
28253 case TEMPLATE_ID_EXPR:
28254 return concept_definition_p (TREE_OPERAND (expression, 0))
28255 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28257 case CONSTRUCTOR:
28259 unsigned ix;
28260 tree val;
28261 if (dependent_type_p (TREE_TYPE (expression)))
28262 return true;
28263 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28264 if (value_dependent_expression_p (val))
28265 return true;
28266 return false;
28269 case STMT_EXPR:
28270 /* Treat a GNU statement expression as dependent to avoid crashing
28271 under instantiate_non_dependent_expr; it can't be constant. */
28272 return true;
28274 case NEW_EXPR:
28275 case VEC_NEW_EXPR:
28276 /* The second operand is a type, which type_dependent_expression_p
28277 (and therefore value_dependent_expression_p) doesn't want to see. */
28278 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28279 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28280 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28282 default:
28283 /* A constant expression is value-dependent if any subexpression is
28284 value-dependent. */
28285 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28287 case tcc_reference:
28288 case tcc_unary:
28289 case tcc_comparison:
28290 case tcc_binary:
28291 case tcc_expression:
28292 case tcc_vl_exp:
28294 int i, len = cp_tree_operand_length (expression);
28296 for (i = 0; i < len; i++)
28298 tree t = TREE_OPERAND (expression, i);
28300 /* In some cases, some of the operands may be missing.
28301 (For example, in the case of PREDECREMENT_EXPR, the
28302 amount to increment by may be missing.) That doesn't
28303 make the expression dependent. */
28304 if (t && value_dependent_expression_p (t))
28305 return true;
28308 break;
28309 default:
28310 break;
28312 break;
28315 /* The expression is not value-dependent. */
28316 return false;
28319 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28320 [temp.dep.expr]. Note that an expression with no type is
28321 considered dependent. Other parts of the compiler arrange for an
28322 expression with type-dependent subexpressions to have no type, so
28323 this function doesn't have to be fully recursive. */
28325 bool
28326 type_dependent_expression_p (tree expression)
28328 if (!processing_template_decl)
28329 return false;
28331 if (expression == NULL_TREE || expression == error_mark_node)
28332 return false;
28334 gcc_checking_assert (!TYPE_P (expression));
28336 STRIP_ANY_LOCATION_WRAPPER (expression);
28338 /* An unresolved name is always dependent. */
28339 if (identifier_p (expression)
28340 || TREE_CODE (expression) == USING_DECL
28341 || TREE_CODE (expression) == WILDCARD_DECL)
28342 return true;
28344 /* A lambda-expression in template context is dependent. dependent_type_p is
28345 true for a lambda in the scope of a class or function template, but that
28346 doesn't cover all template contexts, like a default template argument. */
28347 if (TREE_CODE (expression) == LAMBDA_EXPR)
28348 return true;
28350 /* A fold expression is type-dependent. */
28351 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28352 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28353 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28354 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28355 return true;
28357 /* Some expression forms are never type-dependent. */
28358 if (TREE_CODE (expression) == SIZEOF_EXPR
28359 || TREE_CODE (expression) == ALIGNOF_EXPR
28360 || TREE_CODE (expression) == AT_ENCODE_EXPR
28361 || TREE_CODE (expression) == NOEXCEPT_EXPR
28362 || TREE_CODE (expression) == TRAIT_EXPR
28363 || TREE_CODE (expression) == TYPEID_EXPR
28364 || TREE_CODE (expression) == DELETE_EXPR
28365 || TREE_CODE (expression) == VEC_DELETE_EXPR
28366 || TREE_CODE (expression) == THROW_EXPR
28367 || TREE_CODE (expression) == REQUIRES_EXPR)
28368 return false;
28370 /* The types of these expressions depends only on the type to which
28371 the cast occurs. */
28372 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28373 || TREE_CODE (expression) == STATIC_CAST_EXPR
28374 || TREE_CODE (expression) == CONST_CAST_EXPR
28375 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28376 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28377 || TREE_CODE (expression) == CAST_EXPR)
28378 return dependent_type_p (TREE_TYPE (expression));
28380 /* The types of these expressions depends only on the type created
28381 by the expression. */
28382 if (TREE_CODE (expression) == NEW_EXPR
28383 || TREE_CODE (expression) == VEC_NEW_EXPR)
28385 /* For NEW_EXPR tree nodes created inside a template, either
28386 the object type itself or a TREE_LIST may appear as the
28387 operand 1. */
28388 tree type = TREE_OPERAND (expression, 1);
28389 if (TREE_CODE (type) == TREE_LIST)
28390 /* This is an array type. We need to check array dimensions
28391 as well. */
28392 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28393 || value_dependent_expression_p
28394 (TREE_OPERAND (TREE_VALUE (type), 1));
28395 /* Array type whose dimension has to be deduced. */
28396 else if (TREE_CODE (type) == ARRAY_TYPE
28397 && TREE_OPERAND (expression, 2) == NULL_TREE)
28398 return true;
28399 else
28400 return dependent_type_p (type);
28403 if (TREE_CODE (expression) == SCOPE_REF)
28405 tree scope = TREE_OPERAND (expression, 0);
28406 tree name = TREE_OPERAND (expression, 1);
28408 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28409 contains an identifier associated by name lookup with one or more
28410 declarations declared with a dependent type, or...a
28411 nested-name-specifier or qualified-id that names a member of an
28412 unknown specialization. */
28413 return (type_dependent_expression_p (name)
28414 || dependent_scope_p (scope));
28417 if (TREE_CODE (expression) == TEMPLATE_DECL
28418 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28419 return uses_outer_template_parms (expression);
28421 if (TREE_CODE (expression) == STMT_EXPR)
28422 expression = stmt_expr_value_expr (expression);
28424 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28426 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28427 if (type_dependent_expression_p (elt.value))
28428 return true;
28429 return false;
28432 /* A static data member of the current instantiation with incomplete
28433 array type is type-dependent, as the definition and specializations
28434 can have different bounds. */
28435 if (VAR_P (expression)
28436 && DECL_CLASS_SCOPE_P (expression)
28437 && dependent_type_p (DECL_CONTEXT (expression))
28438 && VAR_HAD_UNKNOWN_BOUND (expression))
28439 return true;
28441 /* An array of unknown bound depending on a variadic parameter, eg:
28443 template<typename... Args>
28444 void foo (Args... args)
28446 int arr[] = { args... };
28449 template<int... vals>
28450 void bar ()
28452 int arr[] = { vals... };
28455 If the array has no length and has an initializer, it must be that
28456 we couldn't determine its length in cp_complete_array_type because
28457 it is dependent. */
28458 if (((VAR_P (expression) && DECL_INITIAL (expression))
28459 || COMPOUND_LITERAL_P (expression))
28460 && TREE_TYPE (expression) != NULL_TREE
28461 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28462 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28463 return true;
28465 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28466 if (BASELINK_P (expression))
28468 if (BASELINK_OPTYPE (expression)
28469 && dependent_type_p (BASELINK_OPTYPE (expression)))
28470 return true;
28471 expression = BASELINK_FUNCTIONS (expression);
28474 /* A function or variable template-id is type-dependent if it has any
28475 dependent template arguments. */
28476 if (VAR_OR_FUNCTION_DECL_P (expression)
28477 && DECL_LANG_SPECIFIC (expression)
28478 && DECL_TEMPLATE_INFO (expression))
28480 /* Consider the innermost template arguments, since those are the ones
28481 that come from the template-id; the template arguments for the
28482 enclosing class do not make it type-dependent unless they are used in
28483 the type of the decl. */
28484 if (instantiates_primary_template_p (expression)
28485 && (any_dependent_template_arguments_p
28486 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28487 return true;
28490 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28491 type-dependent. Checking this is important for functions with auto return
28492 type, which looks like a dependent type. */
28493 if (TREE_CODE (expression) == FUNCTION_DECL
28494 && !(DECL_CLASS_SCOPE_P (expression)
28495 && dependent_type_p (DECL_CONTEXT (expression)))
28496 && !(DECL_LANG_SPECIFIC (expression)
28497 && DECL_UNIQUE_FRIEND_P (expression)
28498 && (!DECL_FRIEND_CONTEXT (expression)
28499 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28500 && !DECL_LOCAL_DECL_P (expression))
28502 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28503 || undeduced_auto_decl (expression));
28504 return false;
28507 /* Otherwise, its constraints could still depend on outer template parameters
28508 from its (dependent) scope. */
28509 if (TREE_CODE (expression) == FUNCTION_DECL
28510 /* As an optimization, check this cheaper sufficient condition first.
28511 (At this point we've established that we're looking at a member of
28512 a dependent class, so it makes sense to start treating say undeduced
28513 auto as dependent.) */
28514 && !dependent_type_p (TREE_TYPE (expression))
28515 && uses_outer_template_parms_in_constraints (expression))
28516 return true;
28518 /* Always dependent, on the number of arguments if nothing else. */
28519 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28520 return true;
28522 if (TREE_TYPE (expression) == unknown_type_node)
28524 if (TREE_CODE (expression) == ADDR_EXPR)
28525 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28526 if (TREE_CODE (expression) == COMPONENT_REF
28527 || TREE_CODE (expression) == OFFSET_REF)
28529 if (type_dependent_object_expression_p (TREE_OPERAND (expression, 0)))
28530 return true;
28531 expression = TREE_OPERAND (expression, 1);
28532 if (identifier_p (expression))
28533 return false;
28535 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28536 if (TREE_CODE (expression) == SCOPE_REF)
28537 return false;
28539 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28540 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28541 || TREE_CODE (expression) == CO_YIELD_EXPR)
28542 return true;
28544 if (BASELINK_P (expression))
28546 if (BASELINK_OPTYPE (expression)
28547 && dependent_type_p (BASELINK_OPTYPE (expression)))
28548 return true;
28549 expression = BASELINK_FUNCTIONS (expression);
28552 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28554 if (any_dependent_template_arguments_p
28555 (TREE_OPERAND (expression, 1)))
28556 return true;
28557 expression = TREE_OPERAND (expression, 0);
28558 if (identifier_p (expression))
28559 return true;
28562 gcc_assert (OVL_P (expression));
28564 for (lkp_iterator iter (expression); iter; ++iter)
28565 if (type_dependent_expression_p (*iter))
28566 return true;
28568 return false;
28571 /* The type of a non-type template parm declared with a placeholder type
28572 depends on the corresponding template argument, even though
28573 placeholders are not normally considered dependent. */
28574 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28575 && is_auto (TREE_TYPE (expression)))
28576 return true;
28578 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28580 /* Dependent type attributes might not have made it from the decl to
28581 the type yet. */
28582 if (DECL_P (expression)
28583 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28584 return true;
28586 return (dependent_type_p (TREE_TYPE (expression)));
28589 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28590 type-dependent if the expression refers to a member of the current
28591 instantiation and the type of the referenced member is dependent, or the
28592 class member access expression refers to a member of an unknown
28593 specialization.
28595 This function returns true if the OBJECT in such a class member access
28596 expression is of an unknown specialization. */
28598 bool
28599 type_dependent_object_expression_p (tree object)
28601 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28602 dependent. */
28603 if (TREE_CODE (object) == IDENTIFIER_NODE)
28604 return true;
28605 tree scope = TREE_TYPE (object);
28606 return (!scope || dependent_scope_p (scope));
28609 /* walk_tree callback function for instantiation_dependent_expression_p,
28610 below. Returns non-zero if a dependent subexpression is found. */
28612 static tree
28613 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28614 void * /*data*/)
28616 if (TYPE_P (*tp))
28618 /* We don't have to worry about decltype currently because decltype
28619 of an instantiation-dependent expr is a dependent type. This
28620 might change depending on the resolution of DR 1172. */
28621 *walk_subtrees = false;
28622 return NULL_TREE;
28624 enum tree_code code = TREE_CODE (*tp);
28625 switch (code)
28627 /* Don't treat an argument list as dependent just because it has no
28628 TREE_TYPE. */
28629 case TREE_LIST:
28630 case TREE_VEC:
28631 case NONTYPE_ARGUMENT_PACK:
28632 return NULL_TREE;
28634 case TEMPLATE_PARM_INDEX:
28635 if (dependent_type_p (TREE_TYPE (*tp)))
28636 return *tp;
28637 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28638 return *tp;
28639 /* We'll check value-dependence separately. */
28640 return NULL_TREE;
28642 /* Handle expressions with type operands. */
28643 case SIZEOF_EXPR:
28644 case ALIGNOF_EXPR:
28645 case TYPEID_EXPR:
28646 case AT_ENCODE_EXPR:
28648 tree op = TREE_OPERAND (*tp, 0);
28649 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28650 op = TREE_TYPE (op);
28651 if (TYPE_P (op))
28653 if (dependent_type_p (op))
28654 return *tp;
28655 else
28657 *walk_subtrees = false;
28658 return NULL_TREE;
28661 break;
28664 case COMPONENT_REF:
28665 if (identifier_p (TREE_OPERAND (*tp, 1)))
28666 /* In a template, finish_class_member_access_expr creates a
28667 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28668 type-dependent, so that we can check access control at
28669 instantiation time (PR 42277). See also Core issue 1273. */
28670 return *tp;
28671 break;
28673 case SCOPE_REF:
28674 if (instantiation_dependent_scope_ref_p (*tp))
28675 return *tp;
28676 else
28677 break;
28679 /* Treat statement-expressions as dependent. */
28680 case BIND_EXPR:
28681 return *tp;
28683 /* Treat requires-expressions as dependent. */
28684 case REQUIRES_EXPR:
28685 return *tp;
28687 case CONSTRUCTOR:
28688 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28689 return *tp;
28690 break;
28692 case TEMPLATE_DECL:
28693 case FUNCTION_DECL:
28694 /* Before C++17, a noexcept-specifier isn't part of the function type
28695 so it doesn't affect type dependence, but we still want to consider it
28696 for instantiation dependence. */
28697 if (cxx_dialect < cxx17
28698 && DECL_DECLARES_FUNCTION_P (*tp)
28699 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28700 return *tp;
28701 break;
28703 default:
28704 break;
28707 if (type_dependent_expression_p (*tp))
28708 return *tp;
28709 else
28710 return NULL_TREE;
28713 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28714 sense defined by the ABI:
28716 "An expression is instantiation-dependent if it is type-dependent
28717 or value-dependent, or it has a subexpression that is type-dependent
28718 or value-dependent."
28720 Except don't actually check value-dependence for unevaluated expressions,
28721 because in sizeof(i) we don't care about the value of i. Checking
28722 type-dependence will in turn check value-dependence of array bounds/template
28723 arguments as needed. */
28725 bool
28726 instantiation_dependent_uneval_expression_p (tree expression)
28728 tree result;
28730 if (!processing_template_decl)
28731 return false;
28733 if (expression == error_mark_node)
28734 return false;
28736 result = cp_walk_tree_without_duplicates (&expression,
28737 instantiation_dependent_r, NULL);
28738 return result != NULL_TREE;
28741 /* As above, but also check value-dependence of the expression as a whole. */
28743 bool
28744 instantiation_dependent_expression_p (tree expression)
28746 return (instantiation_dependent_uneval_expression_p (expression)
28747 || (processing_template_decl
28748 && potential_constant_expression (expression)
28749 && value_dependent_expression_p (expression)));
28752 /* Like type_dependent_expression_p, but it also works while not processing
28753 a template definition, i.e. during substitution or mangling. */
28755 bool
28756 type_dependent_expression_p_push (tree expr)
28758 bool b;
28759 ++processing_template_decl;
28760 b = type_dependent_expression_p (expr);
28761 --processing_template_decl;
28762 return b;
28765 /* Returns TRUE if ARGS contains a type-dependent expression. */
28767 bool
28768 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28770 if (!processing_template_decl || !args)
28771 return false;
28773 for (tree arg : *args)
28774 if (type_dependent_expression_p (arg))
28775 return true;
28777 return false;
28780 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28781 expressions) contains any type-dependent expressions. */
28783 bool
28784 any_type_dependent_elements_p (const_tree list)
28786 for (; list; list = TREE_CHAIN (list))
28787 if (type_dependent_expression_p (TREE_VALUE (list)))
28788 return true;
28790 return false;
28793 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28794 expressions) contains any value-dependent expressions. */
28796 bool
28797 any_value_dependent_elements_p (const_tree list)
28799 for (; list; list = TREE_CHAIN (list))
28800 if (value_dependent_expression_p (TREE_VALUE (list)))
28801 return true;
28803 return false;
28806 /* Returns TRUE if the ARG (a template argument) is dependent. */
28808 bool
28809 dependent_template_arg_p (tree arg)
28811 if (!processing_template_decl)
28812 return false;
28814 /* Assume a template argument that was wrongly written by the user
28815 is dependent. This is consistent with what
28816 any_dependent_template_arguments_p [that calls this function]
28817 does. */
28818 if (!arg || arg == error_mark_node)
28819 return true;
28821 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28822 arg = argument_pack_select_arg (arg);
28824 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28825 return true;
28826 if (TREE_CODE (arg) == TEMPLATE_DECL)
28828 if (DECL_TEMPLATE_PARM_P (arg))
28829 return true;
28830 /* A member template of a dependent class is not necessarily
28831 type-dependent, but it is a dependent template argument because it
28832 will be a member of an unknown specialization to that template. */
28833 tree scope = CP_DECL_CONTEXT (arg);
28834 return TYPE_P (scope) && dependent_type_p (scope);
28836 else if (ARGUMENT_PACK_P (arg))
28838 tree args = ARGUMENT_PACK_ARGS (arg);
28839 for (tree arg : tree_vec_range (args))
28840 if (dependent_template_arg_p (arg))
28841 return true;
28842 return false;
28844 else if (TYPE_P (arg))
28845 return dependent_type_p (arg);
28846 else
28847 return value_dependent_expression_p (arg);
28850 /* Identify any expressions that use function parms. */
28852 static tree
28853 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28855 tree t = *tp;
28856 if (TREE_CODE (t) == PARM_DECL)
28858 *walk_subtrees = 0;
28859 return t;
28861 return NULL_TREE;
28864 /* Returns true if a type specialization formed using the template
28865 arguments ARGS needs to use structural equality. */
28867 bool
28868 any_template_arguments_need_structural_equality_p (tree args)
28870 int i;
28871 int j;
28873 if (!args)
28874 return false;
28875 if (args == error_mark_node)
28876 return true;
28878 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28880 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28881 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28883 tree arg = TREE_VEC_ELT (level, j);
28884 tree packed_args = NULL_TREE;
28885 int k, len = 1;
28887 if (ARGUMENT_PACK_P (arg))
28889 /* Look inside the argument pack. */
28890 packed_args = ARGUMENT_PACK_ARGS (arg);
28891 len = TREE_VEC_LENGTH (packed_args);
28894 for (k = 0; k < len; ++k)
28896 if (packed_args)
28897 arg = TREE_VEC_ELT (packed_args, k);
28899 if (error_operand_p (arg))
28900 return true;
28901 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28902 continue;
28903 else if (arg == any_targ_node)
28904 /* An any_targ_node argument (added by add_defaults_to_ttp)
28905 makes the corresponding specialization not canonicalizable,
28906 since template_args_equal always return true for it. We
28907 may see this when called from bind_template_template_parm. */
28908 return true;
28909 /* Checking current_function_decl because this structural
28910 comparison is only necessary for redeclaration. */
28911 else if (!current_function_decl
28912 && dependent_template_arg_p (arg)
28913 && (cp_walk_tree_without_duplicates
28914 (&arg, find_parm_usage_r, NULL)))
28915 /* The identity of a class template specialization that uses
28916 a function parameter depends on the identity of the function.
28917 And if this specialization appeared in the trailing return
28918 type thereof, we don't know the identity of the function
28919 (e.g. if it's a redeclaration or a new function) until we
28920 form its signature and go through duplicate_decls. Thus
28921 it's unsafe to decide on a canonical type now (which depends
28922 on the DECL_CONTEXT of the function parameter, which can get
28923 mutated after the fact by duplicate_decls), so just require
28924 structural equality in this case (PR52830). */
28925 return true;
28926 else if (TYPE_P (arg)
28927 && TYPE_STRUCTURAL_EQUALITY_P (arg)
28928 && dependent_alias_template_spec_p (arg, nt_transparent))
28929 /* Require structural equality for specializations written
28930 in terms of a dependent alias template specialization. */
28931 return true;
28932 else if (CLASS_TYPE_P (arg)
28933 && TYPE_TEMPLATE_INFO (arg)
28934 && TYPE_STRUCTURAL_EQUALITY_P (arg))
28935 /* Require structural equality for specializations written
28936 in terms of a class template specialization that itself
28937 needs structural equality. */
28938 return true;
28943 return false;
28946 /* Returns true if ARGS (a collection of template arguments) contains
28947 any dependent arguments. */
28949 bool
28950 any_dependent_template_arguments_p (const_tree args)
28952 if (args == error_mark_node)
28953 return true;
28954 if (!processing_template_decl || !args)
28955 return false;
28957 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28959 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28960 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28961 if (dependent_template_arg_p (arg))
28962 return true;
28965 return false;
28968 /* Returns true if ARGS contains any errors. */
28970 bool
28971 any_erroneous_template_args_p (const_tree args)
28973 int i;
28974 int j;
28976 if (args == error_mark_node)
28977 return true;
28979 if (args && TREE_CODE (args) != TREE_VEC)
28981 if (tree ti = get_template_info (args))
28982 args = TI_ARGS (ti);
28983 else
28984 args = NULL_TREE;
28987 if (!args)
28988 return false;
28990 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28992 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28993 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28994 if (error_operand_p (TREE_VEC_ELT (level, j)))
28995 return true;
28998 return false;
29001 /* Returns TRUE if the template TMPL is type-dependent. */
29003 bool
29004 dependent_template_p (tree tmpl)
29006 if (TREE_CODE (tmpl) == OVERLOAD)
29008 for (lkp_iterator iter (tmpl); iter; ++iter)
29009 if (dependent_template_p (*iter))
29010 return true;
29011 return false;
29014 /* Template template parameters are dependent. */
29015 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
29016 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
29017 return true;
29018 /* So are names that have not been looked up. */
29019 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
29020 return true;
29021 return false;
29024 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
29026 bool
29027 dependent_template_id_p (tree tmpl, tree args)
29029 return (dependent_template_p (tmpl)
29030 || any_dependent_template_arguments_p (args));
29033 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
29034 are dependent. */
29036 bool
29037 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
29039 int i;
29041 if (!processing_template_decl)
29042 return false;
29044 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
29046 tree decl = TREE_VEC_ELT (declv, i);
29047 tree init = TREE_VEC_ELT (initv, i);
29048 tree cond = TREE_VEC_ELT (condv, i);
29049 tree incr = TREE_VEC_ELT (incrv, i);
29051 if (type_dependent_expression_p (decl)
29052 || TREE_CODE (decl) == SCOPE_REF)
29053 return true;
29055 if (init && type_dependent_expression_p (init))
29056 return true;
29058 if (cond == global_namespace)
29059 return true;
29061 if (type_dependent_expression_p (cond))
29062 return true;
29064 if (COMPARISON_CLASS_P (cond)
29065 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
29066 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
29067 return true;
29069 if (TREE_CODE (incr) == MODOP_EXPR)
29071 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
29072 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
29073 return true;
29075 else if (type_dependent_expression_p (incr))
29076 return true;
29077 else if (TREE_CODE (incr) == MODIFY_EXPR)
29079 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
29080 return true;
29081 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
29083 tree t = TREE_OPERAND (incr, 1);
29084 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
29085 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
29086 return true;
29088 /* If this loop has a class iterator with != comparison
29089 with increment other than i++/++i/i--/--i, make sure the
29090 increment is constant. */
29091 if (CLASS_TYPE_P (TREE_TYPE (decl))
29092 && TREE_CODE (cond) == NE_EXPR)
29094 if (TREE_OPERAND (t, 0) == decl)
29095 t = TREE_OPERAND (t, 1);
29096 else
29097 t = TREE_OPERAND (t, 0);
29098 if (TREE_CODE (t) != INTEGER_CST)
29099 return true;
29105 return false;
29108 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
29109 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
29110 no such TYPE can be found. Note that this function peers inside
29111 uninstantiated templates and therefore should be used only in
29112 extremely limited situations. ONLY_CURRENT_P restricts this
29113 peering to the currently open classes hierarchy (which is required
29114 when comparing types). */
29116 tree
29117 resolve_typename_type (tree type, bool only_current_p)
29119 tree scope;
29120 tree name;
29121 tree decl;
29122 int quals;
29123 tree pushed_scope;
29124 tree result;
29126 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
29128 scope = TYPE_CONTEXT (type);
29129 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
29130 gcc_checking_assert (uses_template_parms (scope));
29132 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
29133 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
29134 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
29135 representing the typedef. In that case TYPE_IDENTIFIER (type) is
29136 not the non-qualified identifier of the TYPENAME_TYPE anymore.
29137 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
29138 the TYPENAME_TYPE instead, we avoid messing up with a possible
29139 typedef variant case. */
29140 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
29142 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
29143 it first before we can figure out what NAME refers to. */
29144 if (TREE_CODE (scope) == TYPENAME_TYPE)
29146 if (TYPENAME_IS_RESOLVING_P (scope))
29147 /* Given a class template A with a dependent base with nested type C,
29148 typedef typename A::C::C C will land us here, as trying to resolve
29149 the initial A::C leads to the local C typedef, which leads back to
29150 A::C::C. So we break the recursion now. */
29151 return type;
29152 else
29153 scope = resolve_typename_type (scope, only_current_p);
29155 /* If we don't know what SCOPE refers to, then we cannot resolve the
29156 TYPENAME_TYPE. */
29157 if (!CLASS_TYPE_P (scope))
29158 return type;
29159 /* If this is a typedef, we don't want to look inside (c++/11987). */
29160 if (typedef_variant_p (type))
29161 return type;
29162 /* If SCOPE isn't the template itself, it will not have a valid
29163 TYPE_FIELDS list. */
29164 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29165 /* scope is either the template itself or a compatible instantiation
29166 like X<T>, so look up the name in the original template. */
29167 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29168 /* If scope has no fields, it can't be a current instantiation. Check this
29169 before currently_open_class to avoid infinite recursion (71515). */
29170 if (!TYPE_FIELDS (scope))
29171 return type;
29172 /* If the SCOPE is not the current instantiation, there's no reason
29173 to look inside it. */
29174 if (only_current_p && !currently_open_class (scope))
29175 return type;
29176 /* Enter the SCOPE so that name lookup will be resolved as if we
29177 were in the class definition. In particular, SCOPE will no
29178 longer be considered a dependent type. */
29179 pushed_scope = push_scope (scope);
29180 /* Look up the declaration. */
29181 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29182 tf_warning_or_error);
29184 result = NULL_TREE;
29186 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29187 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29188 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29189 if (!decl)
29190 /*nop*/;
29191 else if (identifier_p (fullname)
29192 && TREE_CODE (decl) == TYPE_DECL)
29194 result = TREE_TYPE (decl);
29195 if (result == error_mark_node)
29196 result = NULL_TREE;
29198 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29199 && DECL_CLASS_TEMPLATE_P (decl))
29201 /* Obtain the template and the arguments. */
29202 tree tmpl = TREE_OPERAND (fullname, 0);
29203 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29205 /* We get here with a plain identifier because a previous tentative
29206 parse of the nested-name-specifier as part of a ptr-operator saw
29207 ::template X<A>. The use of ::template is necessary in a
29208 ptr-operator, but wrong in a declarator-id.
29210 [temp.names]: In a qualified-id of a declarator-id, the keyword
29211 template shall not appear at the top level. */
29212 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29213 "keyword %<template%> not allowed in declarator-id");
29214 tmpl = decl;
29216 tree args = TREE_OPERAND (fullname, 1);
29217 /* Instantiate the template. */
29218 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29219 /*entering_scope=*/true,
29220 tf_error | tf_user);
29221 if (result == error_mark_node)
29222 result = NULL_TREE;
29225 /* Leave the SCOPE. */
29226 if (pushed_scope)
29227 pop_scope (pushed_scope);
29229 /* If we failed to resolve it, return the original typename. */
29230 if (!result)
29231 return type;
29233 /* If lookup found a typename type, resolve that too. */
29234 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29236 /* Ill-formed programs can cause infinite recursion here, so we
29237 must catch that. */
29238 TYPENAME_IS_RESOLVING_P (result) = 1;
29239 result = resolve_typename_type (result, only_current_p);
29240 TYPENAME_IS_RESOLVING_P (result) = 0;
29243 /* Qualify the resulting type. */
29244 quals = cp_type_quals (type);
29245 if (quals)
29246 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29248 return result;
29251 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29252 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29253 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29255 static tree
29256 make_auto_1 (tree name, bool set_canonical, int level = -1)
29258 if (level == -1)
29259 level = current_template_depth + 1;
29260 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29261 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29262 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29263 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29264 (0, level, level, TYPE_NAME (au), NULL_TREE);
29265 if (set_canonical)
29266 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29267 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29268 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29269 if (name == decltype_auto_identifier)
29270 AUTO_IS_DECLTYPE (au) = true;
29272 return au;
29275 tree
29276 make_decltype_auto (void)
29278 return make_auto_1 (decltype_auto_identifier, true);
29281 tree
29282 make_auto (void)
29284 return make_auto_1 (auto_identifier, true);
29287 /* Return a C++17 deduction placeholder for class template TMPL.
29288 There are represented as an 'auto' with the special level 0 and
29289 CLASS_PLACEHOLDER_TEMPLATE set. */
29291 tree
29292 make_template_placeholder (tree tmpl)
29294 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29295 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29296 /* Our canonical type depends on the placeholder. */
29297 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29298 return t;
29301 /* True iff T is a C++17 class template deduction placeholder. */
29303 bool
29304 template_placeholder_p (tree t)
29306 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29309 /* Make a "constrained auto" type-specifier. This is an auto or
29310 decltype(auto) type with constraints that must be associated after
29311 deduction. The constraint is formed from the given concept CON
29312 and its optional sequence of template arguments ARGS.
29314 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29316 static tree
29317 make_constrained_placeholder_type (tree type, tree con, tree args)
29319 /* Build the constraint. */
29320 tree tmpl = DECL_TI_TEMPLATE (con);
29321 tree expr = tmpl;
29322 if (TREE_CODE (con) == FUNCTION_DECL)
29323 expr = ovl_make (tmpl);
29324 ++processing_template_decl;
29325 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29326 --processing_template_decl;
29328 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29329 = build_tree_list (current_template_parms, expr);
29331 /* Our canonical type depends on the constraint. */
29332 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29334 /* Attach the constraint to the type declaration. */
29335 return TYPE_NAME (type);
29338 /* Make a "constrained auto" type-specifier. */
29340 tree
29341 make_constrained_auto (tree con, tree args)
29343 tree type = make_auto_1 (auto_identifier, false);
29344 return make_constrained_placeholder_type (type, con, args);
29347 /* Make a "constrained decltype(auto)" type-specifier. */
29349 tree
29350 make_constrained_decltype_auto (tree con, tree args)
29352 tree type = make_auto_1 (decltype_auto_identifier, false);
29353 return make_constrained_placeholder_type (type, con, args);
29356 /* Returns true if the placeholder type constraint T has any dependent
29357 (explicit) template arguments. */
29359 static bool
29360 placeholder_type_constraint_dependent_p (tree t)
29362 tree id = unpack_concept_check (t);
29363 tree args = TREE_OPERAND (id, 1);
29364 tree first = TREE_VEC_ELT (args, 0);
29365 if (ARGUMENT_PACK_P (first))
29367 args = expand_template_argument_pack (args);
29368 first = TREE_VEC_ELT (args, 0);
29370 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29371 || is_auto (first));
29372 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29373 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29374 return true;
29375 return false;
29378 /* Build and return a concept definition. Like other templates, the
29379 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29380 the TEMPLATE_DECL. */
29382 tree
29383 finish_concept_definition (cp_expr id, tree init, tree attrs)
29385 gcc_assert (identifier_p (id));
29386 gcc_assert (processing_template_decl);
29388 location_t loc = id.get_location();
29390 /* A concept-definition shall not have associated constraints. */
29391 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29393 error_at (loc, "a concept cannot be constrained");
29394 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29397 /* A concept-definition shall appear in namespace scope. Templates
29398 aren't allowed in block scope, so we only need to check for class
29399 scope. */
29400 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29402 error_at (loc, "concept %qE not in namespace scope", *id);
29403 return error_mark_node;
29406 if (current_template_depth > 1)
29408 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29409 return error_mark_node;
29412 /* Initially build the concept declaration; its type is bool. */
29413 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29414 DECL_CONTEXT (decl) = current_scope ();
29415 DECL_INITIAL (decl) = init;
29417 if (attrs)
29418 cplus_decl_attributes (&decl, attrs, 0);
29420 set_originating_module (decl, false);
29422 /* Push the enclosing template. */
29423 return push_template_decl (decl);
29426 /* Given type ARG, return std::initializer_list<ARG>. */
29428 static tree
29429 listify (tree arg)
29431 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29433 if (std_init_list == error_mark_node
29434 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29436 gcc_rich_location richloc (input_location);
29437 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29438 error_at (&richloc,
29439 "deducing from brace-enclosed initializer list"
29440 " requires %<#include <initializer_list>%>");
29442 return error_mark_node;
29444 tree argvec = make_tree_vec (1);
29445 TREE_VEC_ELT (argvec, 0) = arg;
29447 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29448 NULL_TREE, 0, tf_warning_or_error);
29451 /* Replace auto in TYPE with std::initializer_list<auto>. */
29453 static tree
29454 listify_autos (tree type, tree auto_node)
29456 tree init_auto = listify (strip_top_quals (auto_node));
29457 tree argvec = make_tree_vec (1);
29458 TREE_VEC_ELT (argvec, 0) = init_auto;
29459 if (processing_template_decl)
29460 argvec = add_to_template_args (current_template_args (), argvec);
29461 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29464 /* Hash traits for hashing possibly constrained 'auto'
29465 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29467 struct auto_hash : default_hash_traits<tree>
29469 static inline hashval_t hash (tree);
29470 static inline bool equal (tree, tree);
29473 /* Hash the 'auto' T. */
29475 inline hashval_t
29476 auto_hash::hash (tree t)
29478 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29479 /* Matching constrained-type-specifiers denote the same template
29480 parameter, so hash the constraint. */
29481 return hash_placeholder_constraint (c);
29482 else
29483 /* But unconstrained autos are all separate, so just hash the pointer. */
29484 return iterative_hash_object (t, 0);
29487 /* Compare two 'auto's. */
29489 inline bool
29490 auto_hash::equal (tree t1, tree t2)
29492 if (t1 == t2)
29493 return true;
29495 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29496 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29498 /* Two unconstrained autos are distinct. */
29499 if (!c1 || !c2)
29500 return false;
29502 return equivalent_placeholder_constraints (c1, c2);
29505 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29506 constrained) auto, add it to the vector. */
29508 static int
29509 extract_autos_r (tree t, void *data)
29511 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29512 if (is_auto (t) && !template_placeholder_p (t))
29514 /* All the autos were built with index 0; fix that up now. */
29515 tree *p = hash.find_slot (t, INSERT);
29516 int idx;
29517 if (*p)
29518 /* If this is a repeated constrained-type-specifier, use the index we
29519 chose before. */
29520 idx = TEMPLATE_TYPE_IDX (*p);
29521 else
29523 /* Otherwise this is new, so use the current count. */
29524 *p = t;
29525 idx = hash.elements () - 1;
29527 if (idx != TEMPLATE_TYPE_IDX (t))
29529 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29530 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29531 TEMPLATE_TYPE_IDX (t) = idx;
29532 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29536 /* Always keep walking. */
29537 return 0;
29540 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29541 says they can appear anywhere in the type. */
29543 static tree
29544 extract_autos (tree type)
29546 hash_set<tree> visited;
29547 hash_table<auto_hash> hash (2);
29549 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29551 tree tree_vec = make_tree_vec (hash.elements());
29552 for (tree elt : hash)
29554 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29555 TREE_VEC_ELT (tree_vec, i)
29556 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29559 return tree_vec;
29562 /* The stem for deduction guide names. */
29563 const char *const dguide_base = "__dguide_";
29565 /* Return the name for a deduction guide for class template TMPL. */
29567 tree
29568 dguide_name (tree tmpl)
29570 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29571 tree tname = TYPE_IDENTIFIER (type);
29572 char *buf = (char *) alloca (1 + strlen (dguide_base)
29573 + IDENTIFIER_LENGTH (tname));
29574 memcpy (buf, dguide_base, strlen (dguide_base));
29575 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29576 IDENTIFIER_LENGTH (tname) + 1);
29577 tree dname = get_identifier (buf);
29578 TREE_TYPE (dname) = type;
29579 return dname;
29582 /* True if NAME is the name of a deduction guide. */
29584 bool
29585 dguide_name_p (tree name)
29587 return (TREE_CODE (name) == IDENTIFIER_NODE
29588 && TREE_TYPE (name)
29589 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29592 /* True if FN is a deduction guide. */
29594 bool
29595 deduction_guide_p (const_tree fn)
29597 if (DECL_P (fn))
29598 if (tree name = DECL_NAME (fn))
29599 return dguide_name_p (name);
29600 return false;
29603 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29605 bool
29606 copy_guide_p (const_tree fn)
29608 gcc_assert (deduction_guide_p (fn));
29609 if (!DECL_ARTIFICIAL (fn))
29610 return false;
29611 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29612 return (TREE_CHAIN (parms) == void_list_node
29613 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29616 /* True if FN is a guide generated from a constructor template. */
29618 bool
29619 template_guide_p (const_tree fn)
29621 gcc_assert (deduction_guide_p (fn));
29622 if (!DECL_ARTIFICIAL (fn))
29623 return false;
29624 tree tmpl = DECL_TI_TEMPLATE (fn);
29625 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29626 return PRIMARY_TEMPLATE_P (org);
29627 return false;
29630 /* True if FN is an aggregate initialization guide or the copy deduction
29631 guide. */
29633 bool
29634 builtin_guide_p (const_tree fn)
29636 if (!deduction_guide_p (fn))
29637 return false;
29638 if (!DECL_ARTIFICIAL (fn))
29639 /* Explicitly declared. */
29640 return false;
29641 if (DECL_ABSTRACT_ORIGIN (fn))
29642 /* Derived from a constructor. */
29643 return false;
29644 return true;
29647 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29648 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29649 template parameter types. Note that the handling of template template
29650 parameters relies on current_template_parms being set appropriately for the
29651 new template. */
29653 static tree
29654 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29655 tree tsubst_args, tsubst_flags_t complain)
29657 if (olddecl == error_mark_node)
29658 return error_mark_node;
29660 tree oldidx = get_template_parm_index (olddecl);
29662 tree newtype;
29663 if (TREE_CODE (olddecl) == TYPE_DECL
29664 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29666 tree oldtype = TREE_TYPE (olddecl);
29667 newtype = cxx_make_type (TREE_CODE (oldtype));
29668 TYPE_MAIN_VARIANT (newtype) = newtype;
29670 else
29672 newtype = TREE_TYPE (olddecl);
29673 if (type_uses_auto (newtype))
29675 // Substitute once to fix references to other template parameters.
29676 newtype = tsubst (newtype, tsubst_args,
29677 complain|tf_partial, NULL_TREE);
29678 // Now substitute again to reduce the level of the auto.
29679 newtype = tsubst (newtype, current_template_args (),
29680 complain, NULL_TREE);
29682 else
29683 newtype = tsubst (newtype, tsubst_args,
29684 complain, NULL_TREE);
29687 tree newdecl
29688 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29689 DECL_NAME (olddecl), newtype);
29690 SET_DECL_TEMPLATE_PARM_P (newdecl);
29692 tree newidx;
29693 if (TREE_CODE (olddecl) == TYPE_DECL
29694 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29696 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29697 = build_template_parm_index (index, level, level,
29698 newdecl, newtype);
29699 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29700 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29701 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29703 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29705 tree newresult
29706 = build_lang_decl_loc (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29707 DECL_NAME (olddecl), newtype);
29708 DECL_ARTIFICIAL (newresult) = true;
29709 DECL_TEMPLATE_RESULT (newdecl) = newresult;
29710 // First create a copy (ttargs) of tsubst_args with an
29711 // additional level for the template template parameter's own
29712 // template parameters (ttparms).
29713 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29714 (DECL_TEMPLATE_PARMS (olddecl)));
29715 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29716 tree ttargs = make_tree_vec (depth + 1);
29717 for (int i = 0; i < depth; ++i)
29718 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29719 TREE_VEC_ELT (ttargs, depth)
29720 = template_parms_level_to_args (ttparms);
29721 // Substitute ttargs into ttparms to fix references to
29722 // other template parameters.
29723 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29724 complain|tf_partial);
29725 // Now substitute again with args based on tparms, to reduce
29726 // the level of the ttparms.
29727 ttargs = current_template_args ();
29728 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29729 complain);
29730 // Finally, tack the adjusted parms onto tparms.
29731 ttparms = tree_cons (size_int (level + 1), ttparms,
29732 copy_node (current_template_parms));
29733 // As with all template template parms, the parameter list captured
29734 // by this template template parm that corresponds to its own level
29735 // should be empty. This avoids infinite recursion when structurally
29736 // comparing two such rewritten template template parms (PR102479).
29737 gcc_assert (!TREE_VEC_LENGTH
29738 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29739 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29740 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29741 // All done.
29742 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29743 DECL_TEMPLATE_INFO (newresult)
29744 = build_template_info (newdecl, template_parms_to_args (ttparms));
29747 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29748 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29749 else
29750 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29752 else
29754 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29755 tree newconst
29756 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29757 TREE_CODE (oldconst),
29758 DECL_NAME (oldconst), newtype);
29759 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29760 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29761 SET_DECL_TEMPLATE_PARM_P (newconst);
29762 newidx = build_template_parm_index (index, level, level,
29763 newconst, newtype);
29764 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29765 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29766 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29769 return newdecl;
29772 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29773 template parameter. */
29775 static tree
29776 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29777 tree targs, unsigned targs_index, tsubst_flags_t complain)
29779 tree olddecl = TREE_VALUE (oldelt);
29780 tree newdecl = rewrite_template_parm (olddecl, index, level,
29781 targs, complain);
29782 if (newdecl == error_mark_node)
29783 return error_mark_node;
29784 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29785 targs, complain, NULL_TREE);
29786 tree list = build_tree_list (newdef, newdecl);
29787 TEMPLATE_PARM_CONSTRAINTS (list)
29788 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29789 targs, complain, NULL_TREE);
29790 int depth = TMPL_ARGS_DEPTH (targs);
29791 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29792 return list;
29795 /* Returns a C++17 class deduction guide template based on the constructor
29796 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29797 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29798 aggregate initialization guide. OUTER_ARGS are the template arguments
29799 for the enclosing scope of the class. */
29801 static tree
29802 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29804 tree tparms, targs, fparms, fargs, ci;
29805 bool memtmpl = false;
29806 bool explicit_p;
29807 location_t loc;
29808 tree fn_tmpl = NULL_TREE;
29810 if (outer_args)
29812 ++processing_template_decl;
29813 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29814 --processing_template_decl;
29817 if (!DECL_DECLARES_FUNCTION_P (ctor))
29819 if (TYPE_P (ctor))
29821 bool copy_p = TYPE_REF_P (ctor);
29822 if (copy_p)
29823 fparms = tree_cons (NULL_TREE, type, void_list_node);
29824 else
29825 fparms = void_list_node;
29827 else if (TREE_CODE (ctor) == TREE_LIST)
29828 fparms = ctor;
29829 else
29830 gcc_unreachable ();
29832 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29833 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29834 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29835 ci = NULL_TREE;
29836 fargs = NULL_TREE;
29837 loc = DECL_SOURCE_LOCATION (ctmpl);
29838 explicit_p = false;
29840 else
29842 ++processing_template_decl;
29843 bool ok = true;
29845 complain |= tf_dguide;
29847 fn_tmpl
29848 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29849 : DECL_TI_TEMPLATE (ctor));
29850 if (outer_args)
29851 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29852 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29854 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29855 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29856 fully specialized args for the enclosing class. Strip those off, as
29857 the deduction guide won't have those template parameters. */
29858 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29859 TMPL_PARMS_DEPTH (tparms));
29860 /* Discard the 'this' parameter. */
29861 fparms = FUNCTION_ARG_CHAIN (ctor);
29862 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29863 ci = get_constraints (ctor);
29864 loc = DECL_SOURCE_LOCATION (ctor);
29865 explicit_p = DECL_NONCONVERTING_P (ctor);
29867 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29869 memtmpl = true;
29871 /* For a member template constructor, we need to flatten the two
29872 template parameter lists into one, and then adjust the function
29873 signature accordingly. This gets...complicated. */
29874 tree save_parms = current_template_parms;
29876 /* For a member template we should have two levels of parms/args, one
29877 for the class and one for the constructor. We stripped
29878 specialized args for further enclosing classes above. */
29879 const int depth = 2;
29880 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29882 /* Template args for translating references to the two-level template
29883 parameters into references to the one-level template parameters we
29884 are creating. */
29885 tree tsubst_args = copy_node (targs);
29886 TMPL_ARGS_LEVEL (tsubst_args, depth)
29887 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29889 /* Template parms for the constructor template. */
29890 tree ftparms = TREE_VALUE (tparms);
29891 unsigned flen = TREE_VEC_LENGTH (ftparms);
29892 /* Template parms for the class template. */
29893 tparms = TREE_CHAIN (tparms);
29894 tree ctparms = TREE_VALUE (tparms);
29895 unsigned clen = TREE_VEC_LENGTH (ctparms);
29896 /* Template parms for the deduction guide start as a copy of the
29897 template parms for the class. We set current_template_parms for
29898 lookup_template_class_1. */
29899 current_template_parms = tparms = copy_node (tparms);
29900 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29901 for (unsigned i = 0; i < clen; ++i)
29902 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29904 /* Now we need to rewrite the constructor parms to append them to the
29905 class parms. */
29906 for (unsigned i = 0; i < flen; ++i)
29908 unsigned index = i + clen;
29909 unsigned level = 1;
29910 tree oldelt = TREE_VEC_ELT (ftparms, i);
29911 tree newelt
29912 = rewrite_tparm_list (oldelt, index, level,
29913 tsubst_args, i, complain);
29914 if (newelt == error_mark_node)
29915 ok = false;
29916 TREE_VEC_ELT (new_vec, index) = newelt;
29919 /* Now we have a final set of template parms to substitute into the
29920 function signature. */
29921 targs = template_parms_to_args (tparms);
29922 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29923 complain, ctor);
29924 if (fparms == error_mark_node)
29925 ok = false;
29926 if (ci)
29928 if (outer_args)
29929 /* FIXME: We'd like to avoid substituting outer template
29930 arguments into the constraint ahead of time, but the
29931 construction of tsubst_args assumes that outer arguments
29932 are already substituted in. */
29933 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29934 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29937 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29938 cp_unevaluated_operand. */
29939 cp_evaluated ev;
29940 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29941 current_template_parms = save_parms;
29943 else
29945 /* Substitute in the same arguments to rewrite class members into
29946 references to members of an unknown specialization. */
29947 cp_evaluated ev;
29948 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29949 fargs = tsubst (fargs, targs, complain, ctor);
29950 if (ci)
29952 if (outer_args)
29953 /* FIXME: As above. */
29954 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29955 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29959 --processing_template_decl;
29960 if (!ok)
29961 return error_mark_node;
29964 if (!memtmpl)
29966 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29967 tparms = copy_node (tparms);
29968 INNERMOST_TEMPLATE_PARMS (tparms)
29969 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29972 tree fntype = build_function_type (type, fparms);
29973 tree ded_fn = build_lang_decl_loc (loc,
29974 FUNCTION_DECL,
29975 dguide_name (type), fntype);
29976 DECL_ARGUMENTS (ded_fn) = fargs;
29977 DECL_ARTIFICIAL (ded_fn) = true;
29978 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29979 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29980 DECL_ARTIFICIAL (ded_tmpl) = true;
29981 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29982 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29983 if (DECL_P (ctor))
29984 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29985 if (ci)
29986 set_constraints (ded_tmpl, ci);
29988 return ded_tmpl;
29991 /* Add to LIST the member types for the reshaped initializer CTOR. */
29993 static tree
29994 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29996 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29997 tree idx, val; unsigned i;
29998 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
30000 tree ftype = elt ? elt : TREE_TYPE (idx);
30001 if (BRACE_ENCLOSED_INITIALIZER_P (val)
30002 && CONSTRUCTOR_BRACES_ELIDED_P (val))
30004 tree subelt = NULL_TREE;
30005 if (TREE_CODE (ftype) == ARRAY_TYPE)
30006 subelt = TREE_TYPE (ftype);
30007 list = collect_ctor_idx_types (val, list, subelt);
30008 continue;
30010 tree arg = NULL_TREE;
30011 if (i == v->length() - 1
30012 && PACK_EXPANSION_P (ftype))
30013 /* Give the trailing pack expansion parameter a default argument to
30014 match aggregate initialization behavior, even if we deduce the
30015 length of the pack separately to more than we have initializers. */
30016 arg = build_constructor (init_list_type_node, NULL);
30017 /* if ei is of array type and xi is a braced-init-list or string literal,
30018 Ti is an rvalue reference to the declared type of ei */
30019 STRIP_ANY_LOCATION_WRAPPER (val);
30020 if (TREE_CODE (ftype) == ARRAY_TYPE
30021 && (BRACE_ENCLOSED_INITIALIZER_P (val)
30022 || TREE_CODE (val) == STRING_CST))
30024 if (TREE_CODE (val) == STRING_CST)
30025 ftype = cp_build_qualified_type
30026 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
30027 ftype = (cp_build_reference_type
30028 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
30030 list = tree_cons (arg, ftype, list);
30033 return list;
30036 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
30038 static bool
30039 is_spec_or_derived (tree etype, tree tmpl)
30041 if (!etype || !CLASS_TYPE_P (etype))
30042 return false;
30044 etype = cv_unqualified (etype);
30045 tree type = TREE_TYPE (tmpl);
30046 tree tparms = (INNERMOST_TEMPLATE_PARMS
30047 (DECL_TEMPLATE_PARMS (tmpl)));
30048 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30049 int err = unify (tparms, targs, type, etype,
30050 UNIFY_ALLOW_DERIVED, /*explain*/false);
30051 ggc_free (targs);
30052 return !err;
30055 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30056 INIT. */
30058 static tree
30059 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30061 if (cxx_dialect < cxx20)
30062 return NULL_TREE;
30064 if (init == NULL_TREE)
30065 return NULL_TREE;
30067 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30069 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30070 tree tinfo = get_template_info (under);
30071 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30072 return alias_ctad_tweaks (tmpl, guide);
30073 return NULL_TREE;
30076 /* We might be creating a guide for a class member template, e.g.,
30078 template<typename U> struct A {
30079 template<typename T> struct B { T t; };
30082 At this point, A will have been instantiated. Below, we need to
30083 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30084 const bool member_template_p
30085 = (DECL_TEMPLATE_INFO (tmpl)
30086 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30087 tree type = TREE_TYPE (tmpl);
30088 tree template_type = (member_template_p
30089 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30090 : type);
30091 if (!CP_AGGREGATE_TYPE_P (template_type))
30092 return NULL_TREE;
30094 /* No aggregate candidate for copy-initialization. */
30095 if (args->length() == 1)
30097 tree val = (*args)[0];
30098 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30099 return NULL_TREE;
30102 /* If we encounter a problem, we just won't add the candidate. */
30103 tsubst_flags_t complain = tf_none;
30105 tree parms = NULL_TREE;
30106 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30108 init = reshape_init (template_type, init, complain);
30109 if (init == error_mark_node)
30110 return NULL_TREE;
30111 parms = collect_ctor_idx_types (init, parms);
30112 /* If we're creating a deduction guide for a member class template,
30113 we've used the original template pattern type for the reshape_init
30114 above; this is done because we want PARMS to be a template parameter
30115 type, something that can be deduced when used as a function template
30116 parameter. At this point the outer class template has already been
30117 partially instantiated (we deferred the deduction until the enclosing
30118 scope is non-dependent). Therefore we have to partially instantiate
30119 PARMS, so that its template level is properly reduced and we don't get
30120 mismatches when deducing types using the guide with PARMS. */
30121 if (member_template_p)
30123 ++processing_template_decl;
30124 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30125 --processing_template_decl;
30128 else if (TREE_CODE (init) == TREE_LIST)
30130 int len = list_length (init);
30131 for (tree field = TYPE_FIELDS (type);
30132 len;
30133 --len, field = DECL_CHAIN (field))
30135 field = next_aggregate_field (field);
30136 if (!field)
30137 return NULL_TREE;
30138 tree ftype = finish_decltype_type (field, true, complain);
30139 parms = tree_cons (NULL_TREE, ftype, parms);
30142 else
30143 /* Aggregate initialization doesn't apply to an initializer expression. */
30144 return NULL_TREE;
30146 if (parms)
30148 tree last = parms;
30149 parms = nreverse (parms);
30150 TREE_CHAIN (last) = void_list_node;
30151 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30152 return guide;
30155 return NULL_TREE;
30158 /* UGUIDES are the deduction guides for the underlying template of alias
30159 template TMPL; adjust them to be deduction guides for TMPL.
30161 This routine also handles C++23 inherited CTAD, in which case TMPL is a
30162 TREE_LIST representing a synthetic alias template whose TREE_PURPOSE is
30163 the template parameter list of the alias template (equivalently, of the
30164 derived class) and TREE_VALUE the defining-type-id (equivalently, the
30165 base whose guides we're inheriting). UGUIDES are the base's guides. */
30167 static tree
30168 alias_ctad_tweaks (tree tmpl, tree uguides)
30170 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30171 class type (9.2.8.2) where the template-name names an alias template A,
30172 the defining-type-id of A must be of the form
30174 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30176 as specified in 9.2.8.2. The guides of A are the set of functions or
30177 function templates formed as follows. For each function or function
30178 template f in the guides of the template named by the simple-template-id
30179 of the defining-type-id, the template arguments of the return type of f
30180 are deduced from the defining-type-id of A according to the process in
30181 13.10.2.5 with the exception that deduction does not fail if not all
30182 template arguments are deduced. Let g denote the result of substituting
30183 these deductions into f. If substitution succeeds, form a function or
30184 function template f' with the following properties and add it to the set
30185 of guides of A:
30187 * The function type of f' is the function type of g.
30189 * If f is a function template, f' is a function template whose template
30190 parameter list consists of all the template parameters of A (including
30191 their default template arguments) that appear in the above deductions or
30192 (recursively) in their default template arguments, followed by the
30193 template parameters of f that were not deduced (including their default
30194 template arguments), otherwise f' is not a function template.
30196 * The associated constraints (13.5.2) are the conjunction of the
30197 associated constraints of g and a constraint that is satisfied if and only
30198 if the arguments of A are deducible (see below) from the return type.
30200 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30201 be so as well.
30203 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30204 considered to be so as well.
30206 * The explicit-specifier of f' is the explicit-specifier of g (if
30207 any). */
30209 enum { alias, inherited } ctad_kind;
30210 tree atype, fullatparms, utype;
30211 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30213 ctad_kind = alias;
30214 atype = TREE_TYPE (tmpl);
30215 fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30216 utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30218 else
30220 ctad_kind = inherited;
30221 atype = NULL_TREE;
30222 fullatparms = TREE_PURPOSE (tmpl);
30223 utype = TREE_VALUE (tmpl);
30226 tsubst_flags_t complain = tf_warning_or_error;
30227 tree aguides = NULL_TREE;
30228 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30229 unsigned natparms = TREE_VEC_LENGTH (atparms);
30230 for (ovl_iterator iter (uguides); iter; ++iter)
30232 tree f = *iter;
30233 tree in_decl = f;
30234 location_t loc = DECL_SOURCE_LOCATION (f);
30235 tree ret = TREE_TYPE (TREE_TYPE (f));
30236 tree fprime = f;
30237 if (TREE_CODE (f) == TEMPLATE_DECL)
30239 processing_template_decl_sentinel ptds (/*reset*/false);
30240 ++processing_template_decl;
30242 /* Deduce template arguments for f from the type-id of A. */
30243 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30244 unsigned len = TREE_VEC_LENGTH (ftparms);
30245 tree targs = make_tree_vec (len);
30246 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30247 if (err)
30248 /* CWG2664: Discard any deductions, still build the guide. */
30249 for (unsigned i = 0; i < len; ++i)
30250 TREE_VEC_ELT (targs, i) = NULL_TREE;
30252 /* The number of parms for f' is the number of parms of A used in
30253 the deduced arguments plus non-deduced parms of f. */
30254 unsigned ndlen = 0;
30255 unsigned j;
30256 for (unsigned i = 0; i < len; ++i)
30257 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30258 ++ndlen;
30259 find_template_parameter_info ftpi (fullatparms);
30260 ftpi.find_in_recursive (targs);
30261 unsigned nusedatparms = ftpi.num_found ();
30262 unsigned nfparms = nusedatparms + ndlen;
30263 tree gtparms = make_tree_vec (nfparms);
30265 /* Set current_template_parms as in build_deduction_guide. */
30266 auto ctp = make_temp_override (current_template_parms);
30267 current_template_parms = copy_node (fullatparms);
30268 TREE_VALUE (current_template_parms) = gtparms;
30270 j = 0;
30271 unsigned level = 1;
30273 /* First copy over the used parms of A. */
30274 tree atargs = make_tree_vec (natparms);
30275 for (unsigned i = 0; i < natparms; ++i)
30277 tree elt = TREE_VEC_ELT (atparms, i);
30278 if (ftpi.found (elt))
30280 unsigned index = j++;
30281 tree nelt = rewrite_tparm_list (elt, index, level,
30282 atargs, i, complain);
30283 TREE_VEC_ELT (gtparms, index) = nelt;
30286 gcc_checking_assert (j == nusedatparms);
30288 /* Adjust the deduced template args for f to refer to the A parms
30289 with their new indexes. */
30290 if (nusedatparms && nusedatparms != natparms)
30291 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30293 /* Now rewrite the non-deduced parms of f. */
30294 for (unsigned i = 0; ndlen && i < len; ++i)
30295 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30297 --ndlen;
30298 unsigned index = j++;
30299 tree oldlist = TREE_VEC_ELT (ftparms, i);
30300 tree list = rewrite_tparm_list (oldlist, index, level,
30301 targs, i, complain);
30302 TREE_VEC_ELT (gtparms, index) = list;
30304 gtparms = build_tree_list (size_one_node, gtparms);
30306 /* Substitute the deduced arguments plus the rewritten template
30307 parameters into f to get g. This covers the type, copyness,
30308 guideness, and explicit-specifier. */
30309 tree g;
30311 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30312 if cp_unevaluated_operand. */
30313 cp_evaluated ev;
30314 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain,
30315 /*use_spec_table=*/false);
30317 if (g == error_mark_node)
30318 continue;
30319 if (nfparms == 0)
30321 /* The targs are all non-dependent, so g isn't a template. */
30322 fprime = g;
30323 ret = TREE_TYPE (TREE_TYPE (fprime));
30324 goto non_template;
30326 DECL_USE_TEMPLATE (g) = 0;
30327 fprime = build_template_decl (g, gtparms, false);
30328 DECL_TEMPLATE_RESULT (fprime) = g;
30329 TREE_TYPE (fprime) = TREE_TYPE (g);
30330 tree gtargs = template_parms_to_args (gtparms);
30331 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30332 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30334 /* Substitute the associated constraints. */
30335 tree ci = get_constraints (f);
30336 if (ci)
30337 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30338 if (ci == error_mark_node)
30339 continue;
30341 /* Add a constraint that the return type matches the instantiation of
30342 A with the same template arguments. */
30343 ret = TREE_TYPE (TREE_TYPE (fprime));
30344 if (ctad_kind == alias
30345 && (!same_type_p (atype, ret)
30346 /* FIXME this should mean they don't compare as equivalent. */
30347 || dependent_alias_template_spec_p (atype, nt_opaque)))
30349 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30350 ci = append_constraint (ci, same);
30353 if (ci)
30355 remove_constraints (fprime);
30356 set_constraints (fprime, ci);
30359 else
30361 /* For a non-template deduction guide, if the arguments of A aren't
30362 deducible from the return type, don't add the candidate. */
30363 non_template:
30364 if (ctad_kind == alias
30365 && !type_targs_deducible_from (tmpl, ret))
30366 continue;
30369 /* Rewrite the return type of the inherited guide in terms of the
30370 derived class. This is specified as replacing the return type R
30371 with typename CC<R>::type where the partially specialized CC maps a
30372 base class specialization to a specialization of the derived class
30373 having such a base (inducing substitution failure if no such derived
30374 class exists).
30376 As specified this mapping would be done at instantiation time using
30377 non-dependent template arguments, but we do it ahead of time using
30378 the generic arguments. This seems to be good enough since generic
30379 deduction should succeed only if concrete deduction would. */
30380 if (ctad_kind == inherited)
30382 processing_template_decl_sentinel ptds (/*reset*/false);
30383 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30384 ++processing_template_decl;
30386 tree targs = type_targs_deducible_from (tmpl, ret);
30387 if (!targs)
30388 continue;
30390 if (TREE_CODE (f) != TEMPLATE_DECL)
30391 fprime = copy_decl (fprime);
30392 tree fntype = TREE_TYPE (fprime);
30393 ret = lookup_template_class (TPARMS_PRIMARY_TEMPLATE (atparms), targs,
30394 in_decl, NULL_TREE, false, complain);
30395 fntype = build_function_type (ret, TYPE_ARG_TYPES (fntype));
30396 TREE_TYPE (fprime) = fntype;
30397 if (TREE_CODE (fprime) == TEMPLATE_DECL)
30398 TREE_TYPE (DECL_TEMPLATE_RESULT (fprime)) = fntype;
30401 aguides = lookup_add (fprime, aguides);
30404 return aguides;
30407 /* CTOR is a using-decl inheriting the constructors of some base of the class
30408 template TMPL; adjust the base's guides be deduction guides for TMPL. */
30410 static tree
30411 inherited_ctad_tweaks (tree tmpl, tree ctor, tsubst_flags_t complain)
30413 /* [over.match.class.deduct]: In addition, if C is defined and inherits
30414 constructors ([namespace.udecl]) from a direct base class denoted in the
30415 base-specifier-list by a class-or-decltype B, let A be an alias template
30416 whose template parameter list is that of C and whose defining-type-id is
30417 B. If A is a deducible template ([dcl.type.simple]), the set contains the
30418 guides of A with the return type R of each guide replaced with typename
30419 CC::type given a class template
30421 template <typename> class CC;
30423 whose primary template is not defined and with a single partial
30424 specialization whose template parameter list is that of A and whose
30425 template argument list is a specialization of A with the template argument
30426 list of A ([temp.dep.type]) having a member typedef type designating a
30427 template specialization with the template argument list of A but with C as
30428 the template. */
30430 /* FIXME: Also recognize inherited constructors of the form 'using C::B::B',
30431 which seem to be represented with TYPENAME_TYPE C::B as USING_DECL_SCOPE?
30432 And recognize constructors inherited from a non-dependent base class, which
30433 seem to be missing from the overload set entirely? */
30434 tree scope = USING_DECL_SCOPE (ctor);
30435 if (!CLASS_TYPE_P (scope)
30436 || !CLASSTYPE_TEMPLATE_INFO (scope)
30437 || !PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (scope)))
30438 return NULL_TREE;
30440 tree t = build_tree_list (DECL_TEMPLATE_PARMS (tmpl), scope);
30441 bool any_dguides_p;
30442 tree uguides = deduction_guides_for (CLASSTYPE_TI_TEMPLATE (scope),
30443 any_dguides_p, complain);
30444 return alias_ctad_tweaks (t, uguides);
30447 /* If template arguments for TMPL can be deduced from TYPE, return
30448 the deduced arguments, otherwise return NULL_TREE.
30449 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30450 [over.match.class.deduct].
30452 This check is specified in terms of partial specialization, so the behavior
30453 should be parallel to that of get_partial_spec_bindings. */
30455 tree
30456 type_targs_deducible_from (tree tmpl, tree type)
30458 tree tparms, ttype;
30459 if (TREE_CODE (tmpl) == TEMPLATE_DECL)
30461 /* If tmpl is a class template, this is trivial: it's deducible if
30462 TYPE is a specialization of TMPL. */
30463 if (DECL_CLASS_TEMPLATE_P (tmpl))
30465 if (CLASS_TYPE_P (type)
30466 && CLASSTYPE_TEMPLATE_INFO (type)
30467 && CLASSTYPE_TI_TEMPLATE (type) == tmpl)
30468 return INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
30469 else
30470 return NULL_TREE;
30473 /* Otherwise it's an alias template. */
30474 tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30475 ttype = TREE_TYPE (tmpl);
30477 else
30479 /* TMPL is a synthetic alias template represented as a TREE_LIST as
30480 per alias_ctad_tweaks. */
30481 tparms = INNERMOST_TEMPLATE_PARMS (TREE_PURPOSE (tmpl));
30482 ttype = TREE_VALUE (tmpl);
30483 tmpl = TI_TEMPLATE (TYPE_TEMPLATE_INFO_MAYBE_ALIAS (ttype));
30486 int len = TREE_VEC_LENGTH (tparms);
30487 tree targs = make_tree_vec (len);
30488 bool tried_array_deduction = (cxx_dialect < cxx17);
30490 again:
30491 if (unify (tparms, targs, ttype, type,
30492 UNIFY_ALLOW_NONE, false))
30493 return NULL_TREE;
30495 /* We don't fail on an undeduced targ the second time through (like
30496 get_partial_spec_bindings) because we're going to try defaults. */
30497 for (int i = 0; i < len; ++i)
30498 if (! TREE_VEC_ELT (targs, i))
30500 tree tparm = TREE_VEC_ELT (tparms, i);
30501 tparm = TREE_VALUE (tparm);
30503 if (!tried_array_deduction
30504 && TREE_CODE (tparm) == TYPE_DECL)
30506 try_array_deduction (tparms, targs, ttype);
30507 tried_array_deduction = true;
30508 if (TREE_VEC_ELT (targs, i))
30509 goto again;
30511 /* If the type parameter is a parameter pack, then it will be deduced
30512 to an empty parameter pack. This is another case that doesn't model
30513 well as partial specialization. */
30514 if (template_parameter_pack_p (tparm))
30516 tree arg;
30517 if (TREE_CODE (tparm) == PARM_DECL)
30519 arg = make_node (NONTYPE_ARGUMENT_PACK);
30520 TREE_CONSTANT (arg) = 1;
30522 else
30523 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30524 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30525 TREE_VEC_ELT (targs, i) = arg;
30529 /* Maybe add in default template args. This seems like a flaw in the
30530 specification in terms of partial specialization, since it says the
30531 partial specialization has the the template parameter list of A, but a
30532 partial specialization can't have default targs. */
30533 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30534 if (targs == error_mark_node)
30535 return NULL_TREE;
30537 /* I believe we don't need the template_template_parm_bindings_ok_p call
30538 because coerce_template_parms did coerce_template_template_parms. */
30540 if (!constraints_satisfied_p (tmpl, targs))
30541 return NULL_TREE;
30543 return targs;
30546 /* Return artificial deduction guides built from the constructors of class
30547 template TMPL. */
30549 static tree
30550 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30552 tree outer_args = outer_template_args (tmpl);
30553 tree type = TREE_TYPE (most_general_template (tmpl));
30555 tree cands = NULL_TREE;
30557 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30559 /* We handle C++23 inherited CTAD below. */
30560 if (iter.using_p ())
30561 continue;
30563 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30564 cands = lookup_add (guide, cands);
30567 if (cxx_dialect >= cxx23)
30568 for (tree ctor : ovl_range (CLASSTYPE_CONSTRUCTORS (type)))
30569 if (TREE_CODE (ctor) == USING_DECL)
30571 tree uguides = inherited_ctad_tweaks (tmpl, ctor, complain);
30572 if (uguides)
30573 cands = lookup_add (uguides, cands);
30576 /* Add implicit default constructor deduction guide. */
30577 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30579 tree guide = build_deduction_guide (type, type, outer_args,
30580 complain);
30581 cands = lookup_add (guide, cands);
30584 /* Add copy guide. */
30586 tree gtype = build_reference_type (type);
30587 tree guide = build_deduction_guide (type, gtype, outer_args,
30588 complain);
30589 cands = lookup_add (guide, cands);
30592 return cands;
30595 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30597 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30598 aggregate candidate is added separately because it depends on the
30599 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30600 guide. */
30602 static tree
30603 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30605 tree guides = NULL_TREE;
30606 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30608 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30609 tree tinfo = get_template_info (under);
30610 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30611 complain);
30613 else
30615 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30616 dguide_name (tmpl),
30617 LOOK_want::NORMAL, /*complain*/false);
30618 if (guides == error_mark_node)
30619 guides = NULL_TREE;
30620 else
30621 any_dguides_p = true;
30624 /* Cache the deduction guides for a template. We also remember the result of
30625 lookup, and rebuild everything if it changes; should be very rare. */
30626 /* FIXME: Also rebuild if this is a class template that inherits guides from a
30627 base class, and lookup for the latter changed. */
30628 tree_pair_p cache = NULL;
30629 if (tree_pair_p &r
30630 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30632 cache = r;
30633 if (cache->purpose == guides)
30634 return cache->value;
30636 else
30638 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30639 cache->purpose = guides;
30642 tree cands = NULL_TREE;
30643 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30644 cands = alias_ctad_tweaks (tmpl, guides);
30645 else
30647 cands = ctor_deduction_guides_for (tmpl, complain);
30648 for (ovl_iterator it (guides); it; ++it)
30649 cands = lookup_add (*it, cands);
30652 cache->value = cands;
30653 return cands;
30656 /* Return whether TMPL is a (class template argument-) deducible template. */
30658 bool
30659 ctad_template_p (tree tmpl)
30661 /* A deducible template is either a class template or is an alias template
30662 whose defining-type-id is of the form
30664 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30666 where the nested-name-specifier (if any) is non-dependent and the
30667 template-name of the simple-template-id names a deducible template. */
30669 if (DECL_CLASS_TEMPLATE_P (tmpl)
30670 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30671 return true;
30672 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30673 return false;
30674 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30675 if (tree tinfo = get_template_info (orig))
30676 return ctad_template_p (TI_TEMPLATE (tinfo));
30677 return false;
30680 /* Deduce template arguments for the class template placeholder PTYPE for
30681 template TMPL based on the initializer INIT, and return the resulting
30682 type. */
30684 static tree
30685 do_class_deduction (tree ptype, tree tmpl, tree init, tree outer_targs,
30686 int flags, tsubst_flags_t complain)
30688 /* We should have handled this in the caller. */
30689 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30690 return ptype;
30692 /* If the class was erroneous, don't try to deduce, because that
30693 can generate a lot of diagnostic. */
30694 if (TREE_TYPE (tmpl)
30695 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30696 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30697 return ptype;
30699 /* Wait until the enclosing scope is non-dependent. */
30700 if (DECL_CLASS_SCOPE_P (tmpl)
30701 && dependent_type_p (DECL_CONTEXT (tmpl)))
30702 return ptype;
30704 /* Initializing one placeholder from another. */
30705 if (init
30706 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30707 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30708 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30709 == TEMPLATE_PARM_INDEX)))
30710 && is_auto (TREE_TYPE (init))
30711 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30712 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30714 if (!ctad_template_p (tmpl))
30716 if (complain & tf_error)
30717 error ("non-deducible template %qT used without template arguments", tmpl);
30718 return error_mark_node;
30720 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30722 if (complain & tf_error)
30724 /* Be permissive with equivalent alias templates. */
30725 tree u = get_underlying_template (tmpl);
30726 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30727 bool complained
30728 = emit_diagnostic (dk, input_location, 0,
30729 "alias template deduction only available "
30730 "with %<-std=c++20%> or %<-std=gnu++20%>");
30731 if (u == tmpl)
30732 return error_mark_node;
30733 else if (complained)
30735 inform (input_location, "use %qD directly instead", u);
30736 tmpl = u;
30739 else
30740 return error_mark_node;
30743 /* Wait until the initializer is non-dependent. */
30744 if (type_dependent_expression_p (init))
30745 return ptype;
30747 if (outer_targs)
30749 int args_depth = TMPL_ARGS_DEPTH (outer_targs);
30750 int parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
30751 if (parms_depth > 1)
30753 /* Substitute outer arguments into this CTAD template from the
30754 current instantiation. */
30755 int want = std::min (args_depth, parms_depth - 1);
30756 outer_targs = strip_innermost_template_args (outer_targs,
30757 args_depth - want);
30758 tmpl = tsubst (tmpl, outer_targs, complain, NULL_TREE);
30759 if (tmpl == error_mark_node)
30760 return error_mark_node;
30764 /* Don't bother with the alias rules for an equivalent template. */
30765 tmpl = get_underlying_template (tmpl);
30767 tree type = TREE_TYPE (tmpl);
30769 bool try_list_cand = false;
30770 bool list_init_p = false;
30772 releasing_vec rv_args = NULL;
30773 vec<tree,va_gc> *&args = *&rv_args;
30774 if (init == NULL_TREE)
30775 args = make_tree_vector ();
30776 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30778 list_init_p = true;
30779 try_list_cand = true;
30780 if (CONSTRUCTOR_NELTS (init) == 1
30781 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30783 /* As an exception, the first phase in 16.3.1.7 (considering the
30784 initializer list as a single argument) is omitted if the
30785 initializer list consists of a single expression of type cv U,
30786 where U is a specialization of C or a class derived from a
30787 specialization of C. */
30788 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30789 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30790 try_list_cand = false;
30792 if (try_list_cand || is_std_init_list (type))
30793 args = make_tree_vector_single (init);
30794 else
30795 args = make_tree_vector_from_ctor (init);
30797 else if (TREE_CODE (init) == TREE_LIST)
30798 args = make_tree_vector_from_list (init);
30799 else
30800 args = make_tree_vector_single (init);
30802 /* Do this now to avoid problems with erroneous args later on. */
30803 args = resolve_args (args, complain);
30804 if (args == NULL)
30805 return error_mark_node;
30807 bool any_dguides_p = false;
30808 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30809 if (cands == error_mark_node)
30810 return error_mark_node;
30812 /* Prune explicit deduction guides in copy-initialization context (but
30813 not copy-list-initialization). */
30814 bool elided = false;
30815 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30817 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30818 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30819 elided = true;
30821 if (elided)
30823 /* Found a nonconverting guide, prune the candidates. */
30824 tree pruned = NULL_TREE;
30825 for (lkp_iterator iter (cands); iter; ++iter)
30826 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30827 pruned = lookup_add (*iter, pruned);
30829 cands = pruned;
30833 if (!any_dguides_p)
30834 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30835 cands = lookup_add (guide, cands);
30837 tree fndecl = error_mark_node;
30839 /* If this is list-initialization and the class has a list guide, first
30840 try deducing from the list as a single argument, as [over.match.list]. */
30841 if (try_list_cand)
30843 tree list_cands = NULL_TREE;
30844 for (tree dg : lkp_range (cands))
30845 if (is_list_ctor (dg))
30846 list_cands = lookup_add (dg, list_cands);
30847 if (list_cands)
30848 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30849 if (fndecl == error_mark_node)
30851 /* That didn't work, now try treating the list as a sequence of
30852 arguments. */
30853 release_tree_vector (args);
30854 args = make_tree_vector_from_ctor (init);
30855 args = resolve_args (args, complain);
30856 if (args == NULL)
30857 return error_mark_node;
30861 if (elided && !cands)
30863 error ("cannot deduce template arguments for copy-initialization"
30864 " of %qT, as it has no non-explicit deduction guides or "
30865 "user-declared constructors", type);
30866 return error_mark_node;
30868 else if (!cands && fndecl == error_mark_node)
30870 error ("cannot deduce template arguments of %qT, as it has no viable "
30871 "deduction guides", type);
30872 return error_mark_node;
30875 if (fndecl == error_mark_node)
30876 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30878 if (fndecl == error_mark_node)
30880 if (complain & tf_warning_or_error)
30882 error ("class template argument deduction failed:");
30883 perform_dguide_overload_resolution (cands, args, complain);
30884 if (elided)
30885 inform (input_location, "explicit deduction guides not considered "
30886 "for copy-initialization");
30888 return error_mark_node;
30890 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30891 constructor is chosen, the initialization is ill-formed. */
30892 else if (flags & LOOKUP_ONLYCONVERTING)
30894 if (DECL_NONCONVERTING_P (fndecl))
30896 if (complain & tf_warning_or_error)
30898 // TODO: Pass down location from cp_finish_decl.
30899 error ("class template argument deduction for %qT failed: "
30900 "explicit deduction guide selected in "
30901 "copy-list-initialization", type);
30902 inform (DECL_SOURCE_LOCATION (fndecl),
30903 "explicit deduction guide declared here");
30906 return error_mark_node;
30910 /* If CTAD succeeded but the type doesn't have any explicit deduction
30911 guides, this deduction might not be what the user intended. */
30912 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30914 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30915 || global_dc->m_warn_system_headers)
30916 && warning (OPT_Wctad_maybe_unsupported,
30917 "%qT may not intend to support class template argument "
30918 "deduction", type))
30919 inform (input_location, "add a deduction guide to suppress this "
30920 "warning");
30923 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30924 cp_type_quals (ptype));
30927 /* Return true if INIT is an unparenthesized id-expression or an
30928 unparenthesized class member access. Used for the argument of
30929 decltype(auto). */
30931 bool
30932 unparenthesized_id_or_class_member_access_p (tree init)
30934 STRIP_ANY_LOCATION_WRAPPER (init);
30936 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30937 reference type). Only the latter is an id-expression. */
30938 if (REFERENCE_REF_P (init)
30939 && !REF_PARENTHESIZED_P (init))
30940 init = TREE_OPERAND (init, 0);
30941 return (DECL_P (init)
30942 || ((TREE_CODE (init) == COMPONENT_REF
30943 || TREE_CODE (init) == SCOPE_REF)
30944 && !REF_PARENTHESIZED_P (init)));
30947 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30948 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30949 The CONTEXT determines the context in which auto deduction is performed
30950 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30952 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30953 to properly substitute the result. It's also used in the adc_unify and
30954 adc_requirement contexts to communicate the necessary template arguments
30955 to satisfaction. OUTER_TARGS is ignored in other contexts.
30957 Additionally for adc_unify contexts TMPL is the template for which TYPE
30958 is a template parameter type.
30960 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30961 scope may be appended to the list of deduced template arguments prior to
30962 determining constraint satisfaction as appropriate. */
30964 tree
30965 do_auto_deduction (tree type, tree init, tree auto_node,
30966 tsubst_flags_t complain /* = tf_warning_or_error */,
30967 auto_deduction_context context /* = adc_unspecified */,
30968 tree outer_targs /* = NULL_TREE */,
30969 int flags /* = LOOKUP_NORMAL */,
30970 tree tmpl /* = NULL_TREE */)
30972 if (type == error_mark_node || init == error_mark_node)
30973 return error_mark_node;
30975 if (init && type_dependent_expression_p (init)
30976 && context != adc_unify)
30977 /* Defining a subset of type-dependent expressions that we can deduce
30978 from ahead of time isn't worth the trouble. */
30979 return type;
30981 /* Similarly, we can't deduce from another undeduced decl. */
30982 if (init && undeduced_auto_decl (init))
30983 return type;
30985 /* We may be doing a partial substitution, but we still want to replace
30986 auto_node. */
30987 complain &= ~tf_partial;
30989 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30991 /* We don't recurse here because we can't deduce from a nested
30992 initializer_list. */
30993 if (CONSTRUCTOR_ELTS (init))
30994 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30995 elt.value = resolve_nondeduced_context (elt.value, complain);
30997 else if (init)
30998 init = resolve_nondeduced_context (init, complain);
31000 /* In C++23, we must deduce the type to int&& for code like
31001 decltype(auto) f(int&& x) { return (x); }
31003 auto&& f(int x) { return x; }
31004 so we use treat_lvalue_as_rvalue_p. But don't do it for
31005 decltype(auto) f(int x) { return x; }
31006 where we should deduce 'int' rather than 'int&&'; transmogrifying
31007 INIT to an rvalue would break that. */
31008 tree r;
31009 if (cxx_dialect >= cxx23
31010 && context == adc_return_type
31011 && (!AUTO_IS_DECLTYPE (auto_node)
31012 || !unparenthesized_id_or_class_member_access_p (init))
31013 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
31014 /*return*/true)))
31015 init = r;
31017 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
31018 /* C++17 class template argument deduction. */
31019 return do_class_deduction (type, ctmpl, init, outer_targs, flags, complain);
31021 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
31022 /* Nothing we can do with this, even in deduction context. */
31023 return type;
31025 location_t loc = cp_expr_loc_or_input_loc (init);
31027 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
31028 with either a new invented type template parameter U or, if the
31029 initializer is a braced-init-list (8.5.4), with
31030 std::initializer_list<U>. */
31031 if (BRACE_ENCLOSED_INITIALIZER_P (init))
31033 if (!DIRECT_LIST_INIT_P (init))
31034 type = listify_autos (type, auto_node);
31035 else if (CONSTRUCTOR_NELTS (init) == 1)
31036 init = CONSTRUCTOR_ELT (init, 0)->value;
31037 else
31039 if (complain & tf_warning_or_error)
31041 if (permerror (loc, "direct-list-initialization of "
31042 "%<auto%> requires exactly one element"))
31043 inform (loc,
31044 "for deduction to %<std::initializer_list%>, use copy-"
31045 "list-initialization (i.e. add %<=%> before the %<{%>)");
31047 type = listify_autos (type, auto_node);
31051 if (type == error_mark_node || init == error_mark_node)
31052 return error_mark_node;
31054 tree targs;
31055 if (context == adc_decomp_type
31056 && auto_node == type
31057 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
31059 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
31060 and initializer has array type, deduce cv-qualified array type. */
31061 targs = make_tree_vec (1);
31062 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
31064 else if (AUTO_IS_DECLTYPE (auto_node))
31066 const bool id = unparenthesized_id_or_class_member_access_p (init);
31067 tree deduced = finish_decltype_type (init, id, complain);
31068 deduced = canonicalize_type_argument (deduced, complain);
31069 if (deduced == error_mark_node)
31070 return error_mark_node;
31071 targs = make_tree_vec (1);
31072 TREE_VEC_ELT (targs, 0) = deduced;
31074 else
31076 if (error_operand_p (init))
31077 return error_mark_node;
31079 tree parms = build_tree_list (NULL_TREE, type);
31080 tree tparms;
31082 if (flag_concepts_ts)
31083 tparms = extract_autos (type);
31084 else
31086 tparms = make_tree_vec (1);
31087 TREE_VEC_ELT (tparms, 0)
31088 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
31091 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
31092 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
31093 DEDUCE_CALL,
31094 NULL, /*explain_p=*/false);
31095 if (val > 0)
31097 if (processing_template_decl)
31098 /* Try again at instantiation time. */
31099 return type;
31100 if (type && type != error_mark_node
31101 && (complain & tf_error))
31102 /* If type is error_mark_node a diagnostic must have been
31103 emitted by now. Also, having a mention to '<type error>'
31104 in the diagnostic is not really useful to the user. */
31106 if (cfun
31107 && FNDECL_USED_AUTO (current_function_decl)
31108 && (auto_node
31109 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
31110 && LAMBDA_FUNCTION_P (current_function_decl))
31111 error_at (loc, "unable to deduce lambda return type from %qE",
31112 init);
31113 else
31114 error_at (loc, "unable to deduce %qT from %qE", type, init);
31115 type_unification_real (tparms, targs, parms, &init, 1, 0,
31116 DEDUCE_CALL,
31117 NULL, /*explain_p=*/true);
31119 return error_mark_node;
31123 /* Check any placeholder constraints against the deduced type. */
31124 if (processing_template_decl && context == adc_unify)
31125 /* Constraints will be checked after deduction. */;
31126 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
31128 if (processing_template_decl)
31130 gcc_checking_assert (context == adc_variable_type
31131 || context == adc_return_type
31132 || context == adc_decomp_type);
31133 gcc_checking_assert (!type_dependent_expression_p (init));
31134 /* If the constraint is dependent, we need to wait until
31135 instantiation time to resolve the placeholder. */
31136 if (placeholder_type_constraint_dependent_p (constr))
31137 return type;
31140 if (context == adc_return_type
31141 || context == adc_variable_type
31142 || context == adc_decomp_type)
31143 if (tree fn = current_function_decl)
31144 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
31146 outer_targs = DECL_TEMPLATE_INFO (fn)
31147 ? DECL_TI_ARGS (fn) : NULL_TREE;
31148 if (LAMBDA_FUNCTION_P (fn))
31150 /* As in satisfy_declaration_constraints. */
31151 tree regen_args = lambda_regenerating_args (fn);
31152 if (outer_targs)
31153 outer_targs = add_to_template_args (regen_args, outer_targs);
31154 else
31155 outer_targs = regen_args;
31159 tree full_targs = outer_targs;
31160 if (context == adc_unify && tmpl)
31161 full_targs = add_outermost_template_args (tmpl, full_targs);
31162 full_targs = add_to_template_args (full_targs, targs);
31164 /* HACK: Compensate for callers not always communicating all levels of
31165 outer template arguments by filling in the outermost missing levels
31166 with dummy levels before checking satisfaction. We'll still crash
31167 if the constraint depends on a template argument belonging to one of
31168 these missing levels, but this hack otherwise allows us to handle a
31169 large subset of possible constraints (including all non-dependent
31170 constraints). */
31171 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
31172 - TMPL_ARGS_DEPTH (full_targs)))
31174 tree dummy_levels = make_tree_vec (missing_levels);
31175 for (int i = 0; i < missing_levels; ++i)
31176 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
31177 full_targs = add_to_template_args (dummy_levels, full_targs);
31180 if (!constraints_satisfied_p (auto_node, full_targs))
31182 if (complain & tf_warning_or_error)
31184 auto_diagnostic_group d;
31185 switch (context)
31187 case adc_unspecified:
31188 case adc_unify:
31189 error_at (loc, "placeholder constraints not satisfied");
31190 break;
31191 case adc_variable_type:
31192 case adc_decomp_type:
31193 error_at (loc, "deduced initializer does not satisfy "
31194 "placeholder constraints");
31195 break;
31196 case adc_return_type:
31197 error_at (loc, "deduced return type does not satisfy "
31198 "placeholder constraints");
31199 break;
31200 case adc_requirement:
31201 error_at (loc, "deduced expression type does not satisfy "
31202 "placeholder constraints");
31203 break;
31205 diagnose_constraints (loc, auto_node, full_targs);
31207 return error_mark_node;
31211 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31212 /* The outer template arguments are already substituted into type
31213 (but we still may have used them for constraint checking above). */;
31214 else if (context == adc_unify)
31215 targs = add_to_template_args (outer_targs, targs);
31216 else if (processing_template_decl)
31217 targs = add_to_template_args (current_template_args (), targs);
31218 return tsubst (type, targs, complain, NULL_TREE);
31221 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31222 result. */
31224 tree
31225 splice_late_return_type (tree type, tree late_return_type)
31227 if (late_return_type)
31229 gcc_assert (is_auto (type) || seen_error ());
31230 return late_return_type;
31233 if (tree auto_node = find_type_usage (type, is_auto))
31234 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31236 /* In an abbreviated function template we didn't know we were dealing
31237 with a function template when we saw the auto return type, so rebuild
31238 the return type using an auto with the correct level. */
31239 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31240 tree auto_vec = make_tree_vec (1);
31241 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31242 tree targs = add_outermost_template_args (current_template_args (),
31243 auto_vec);
31244 /* Also rebuild the constraint info in terms of the new auto. */
31245 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31246 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31247 = build_tree_list (current_template_parms,
31248 tsubst_constraint (TREE_VALUE (ci), targs,
31249 tf_none, NULL_TREE));
31250 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31251 return tsubst (type, targs, tf_none, NULL_TREE);
31253 return type;
31256 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31257 'decltype(auto)' or a deduced class template. */
31259 bool
31260 is_auto (const_tree type)
31262 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31263 && (TYPE_IDENTIFIER (type) == auto_identifier
31264 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31265 return true;
31266 else
31267 return false;
31270 /* for_each_template_parm callback for type_uses_auto. */
31273 is_auto_r (tree tp, void */*data*/)
31275 return is_auto (tp);
31278 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31279 a use of `auto'. Returns NULL_TREE otherwise. */
31281 tree
31282 type_uses_auto (tree type)
31284 if (type == NULL_TREE)
31285 return NULL_TREE;
31287 /* For parameter packs, check the contents of the pack. */
31288 if (PACK_EXPANSION_P (type))
31289 type = PACK_EXPANSION_PATTERN (type);
31291 if (flag_concepts_ts)
31293 /* The Concepts TS allows multiple autos in one type-specifier; just
31294 return the first one we find, do_auto_deduction will collect all of
31295 them. */
31296 if (uses_template_parms (type))
31297 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31298 /*visited*/NULL, /*nondeduced*/false);
31299 else
31300 return NULL_TREE;
31302 else
31303 return find_type_usage (type, is_auto);
31306 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31307 concepts are enabled, auto is acceptable in template arguments, but
31308 only when TEMPL identifies a template class. Return TRUE if any
31309 such errors were reported. */
31311 bool
31312 check_auto_in_tmpl_args (tree tmpl, tree args)
31314 if (!flag_concepts_ts)
31315 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31316 have already been rejected by the parser more generally. */
31317 return false;
31319 /* If there were previous errors, nevermind. */
31320 if (!args || TREE_CODE (args) != TREE_VEC)
31321 return false;
31323 /* If TMPL is an identifier, we're parsing and we can't tell yet
31324 whether TMPL is supposed to be a type, a function or a variable.
31325 We'll only be able to tell during template substitution, so we
31326 expect to be called again then. If concepts are enabled and we
31327 know we have a type, we're ok. */
31328 if (identifier_p (tmpl)
31329 || (DECL_P (tmpl)
31330 && (DECL_TYPE_TEMPLATE_P (tmpl)
31331 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31332 return false;
31334 /* Quickly search for any occurrences of auto; usually there won't
31335 be any, and then we'll avoid allocating the vector. */
31336 if (!type_uses_auto (args))
31337 return false;
31339 bool errors = false;
31341 tree vec = extract_autos (args);
31342 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31344 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31345 error_at (DECL_SOURCE_LOCATION (xauto),
31346 "invalid use of %qT in template argument", xauto);
31347 errors = true;
31350 return errors;
31353 /* Recursively walk over && expressions searching for EXPR. Return a reference
31354 to that expression. */
31356 static tree *find_template_requirement (tree *t, tree key)
31358 if (*t == key)
31359 return t;
31360 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31362 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31363 return p;
31364 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31365 return p;
31367 return 0;
31370 /* Convert the generic type parameters in PARM that match the types given in the
31371 range [START_IDX, END_IDX) from the current_template_parms into generic type
31372 packs. */
31374 tree
31375 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31377 tree current = current_template_parms;
31378 int depth = TMPL_PARMS_DEPTH (current);
31379 current = INNERMOST_TEMPLATE_PARMS (current);
31380 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31382 for (int i = 0; i < start_idx; ++i)
31383 TREE_VEC_ELT (replacement, i)
31384 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31386 for (int i = start_idx; i < end_idx; ++i)
31388 /* Create a distinct parameter pack type from the current parm and add it
31389 to the replacement args to tsubst below into the generic function
31390 parameter. */
31391 tree node = TREE_VEC_ELT (current, i);
31392 tree o = TREE_TYPE (TREE_VALUE (node));
31393 tree t = copy_type (o);
31394 TEMPLATE_TYPE_PARM_INDEX (t)
31395 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31396 t, 0, 0, tf_none);
31397 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31398 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31399 TYPE_MAIN_VARIANT (t) = t;
31400 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31401 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31402 TREE_VEC_ELT (replacement, i) = t;
31404 /* Replace the current template parameter with new pack. */
31405 TREE_VALUE (node) = TREE_CHAIN (t);
31407 /* Surgically adjust the associated constraint of adjusted parameter
31408 and it's corresponding contribution to the current template
31409 requirements. */
31410 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31412 tree id = unpack_concept_check (constr);
31413 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31414 /* Use UNKNOWN_LOCATION so write_template_args can tell the
31415 difference between this and a fold the user wrote. */
31416 location_t loc = UNKNOWN_LOCATION;
31417 tree fold = finish_left_unary_fold_expr (loc, constr,
31418 TRUTH_ANDIF_EXPR);
31419 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31421 /* If there was a constraint, we also need to replace that in
31422 the template requirements, which we've already built. */
31423 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31424 reqs = find_template_requirement (reqs, constr);
31425 *reqs = fold;
31429 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31430 TREE_VEC_ELT (replacement, i)
31431 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31433 /* If there are more levels then build up the replacement with the outer
31434 template parms. */
31435 if (depth > 1)
31436 replacement = add_to_template_args (template_parms_to_args
31437 (TREE_CHAIN (current_template_parms)),
31438 replacement);
31440 return tsubst (parm, replacement, tf_none, NULL_TREE);
31443 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31444 0..N-1. */
31446 void
31447 declare_integer_pack (void)
31449 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31450 build_function_type_list (integer_type_node,
31451 integer_type_node,
31452 NULL_TREE),
31453 NULL_TREE, ECF_CONST);
31454 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31455 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31456 CP_BUILT_IN_INTEGER_PACK);
31459 /* Walk the decl or type specialization table calling FN on each
31460 entry. */
31462 void
31463 walk_specializations (bool decls_p,
31464 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31465 void *data)
31467 spec_hash_table *table = decls_p ? decl_specializations
31468 : type_specializations;
31469 spec_hash_table::iterator end (table->end ());
31470 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31471 fn (decls_p, *iter, data);
31474 /* Lookup the specialization of *ELT, in the decl or type
31475 specialization table. Return the SPEC that's already there, or
31476 NULL if nothing. */
31478 tree
31479 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31481 hash_table<spec_hasher> *specializations
31482 = decl_p ? decl_specializations : type_specializations;
31483 hashval_t hash = spec_hasher::hash (elt);
31484 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31486 if (slot)
31487 return (*slot)->spec;
31489 return NULL_TREE;
31492 /* Return flags encoding whether SPEC is on the instantiation and/or
31493 specialization lists of TMPL. */
31495 unsigned
31496 get_mergeable_specialization_flags (tree tmpl, tree decl)
31498 unsigned flags = 0;
31500 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31501 inst; inst = TREE_CHAIN (inst))
31502 if (TREE_VALUE (inst) == decl)
31504 flags |= 1;
31505 break;
31508 if (CLASS_TYPE_P (TREE_TYPE (decl))
31509 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31510 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31511 /* Only need to search if DECL is a partial specialization. */
31512 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31513 part; part = TREE_CHAIN (part))
31514 if (TREE_VALUE (part) == decl)
31516 flags |= 2;
31517 break;
31520 return flags;
31523 /* Add a new specialization described by SPEC. DECL is the
31524 maybe-template decl and FLAGS is as returned from
31525 get_mergeable_specialization_flags. */
31527 void
31528 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31529 tree decl, unsigned flags)
31531 hashval_t hash = spec_hasher::hash (elt);
31532 if (decl_p)
31534 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31536 gcc_checking_assert (!*slot);
31537 auto entry = ggc_alloc<spec_entry> ();
31538 *entry = *elt;
31539 *slot = entry;
31541 if (alias_p)
31543 elt->spec = TREE_TYPE (elt->spec);
31544 gcc_checking_assert (elt->spec);
31548 if (!decl_p || alias_p)
31550 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31552 /* We don't distinguish different constrained partial type
31553 specializations, so there could be duplicates. Everything else
31554 must be new. */
31555 if (!(flags & 2 && *slot))
31557 gcc_checking_assert (!*slot);
31559 auto entry = ggc_alloc<spec_entry> ();
31560 *entry = *elt;
31561 *slot = entry;
31565 if (flags & 1)
31566 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31567 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31569 if (flags & 2)
31571 /* A partial specialization. */
31572 tree cons = tree_cons (elt->args, decl,
31573 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31574 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31575 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31579 /* Set up the hash tables for template instantiations. */
31581 void
31582 init_template_processing (void)
31584 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31585 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31587 if (cxx_dialect >= cxx11)
31588 declare_integer_pack ();
31591 /* Print stats about the template hash tables for -fstats. */
31593 void
31594 print_template_statistics (void)
31596 fprintf (stderr, "decl_specializations: size " HOST_SIZE_T_PRINT_DEC ", "
31597 HOST_SIZE_T_PRINT_DEC " elements, %f collisions\n",
31598 (fmt_size_t) decl_specializations->size (),
31599 (fmt_size_t) decl_specializations->elements (),
31600 decl_specializations->collisions ());
31601 fprintf (stderr, "type_specializations: size " HOST_SIZE_T_PRINT_DEC ", "
31602 HOST_SIZE_T_PRINT_DEC " elements, %f collisions\n",
31603 (fmt_size_t) type_specializations->size (),
31604 (fmt_size_t) type_specializations->elements (),
31605 type_specializations->collisions ());
31608 #if CHECKING_P
31610 namespace selftest {
31612 /* Verify that type_dependent_expression_p () works correctly, even
31613 in the presence of location wrapper nodes. */
31615 static void
31616 test_type_dependent_expression_p ()
31618 location_t loc = BUILTINS_LOCATION;
31620 tree name = get_identifier ("foo");
31622 /* If no templates are involved, nothing is type-dependent. */
31623 gcc_assert (!processing_template_decl);
31624 ASSERT_FALSE (type_dependent_expression_p (name));
31626 ++processing_template_decl;
31628 /* Within a template, an unresolved name is always type-dependent. */
31629 ASSERT_TRUE (type_dependent_expression_p (name));
31631 /* Ensure it copes with NULL_TREE and errors. */
31632 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31633 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31635 /* A USING_DECL in a template should be type-dependent, even if wrapped
31636 with a location wrapper (PR c++/83799). */
31637 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31638 TREE_TYPE (using_decl) = integer_type_node;
31639 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31640 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31641 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31642 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31644 --processing_template_decl;
31647 /* Run all of the selftests within this file. */
31649 void
31650 cp_pt_cc_tests ()
31652 test_type_dependent_expression_p ();
31655 } // namespace selftest
31657 #endif /* #if CHECKING_P */
31659 #include "gt-cp-pt.h"