c++: maybe_substitute_reqs_for fix
[official-gcc.git] / gcc / cp / pt.cc
blobc017591f235b30ff202748c8dc954437452ecf3d
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2023 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"
50 /* The type of functions taking a tree, and some additional data, and
51 returning an int. */
52 typedef int (*tree_fn_t) (tree, void*);
54 /* The PENDING_TEMPLATES is a list of templates whose instantiations
55 have been deferred, either because their definitions were not yet
56 available, or because we were putting off doing the work. */
57 struct GTY ((chain_next ("%h.next"))) pending_template
59 struct pending_template *next;
60 struct tinst_level *tinst;
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
66 int processing_template_parmlist;
67 static int template_header_count;
69 static vec<int> inline_parm_levels;
71 static GTY(()) struct tinst_level *current_tinst_level;
73 static GTY(()) vec<tree, va_gc> *saved_access_scope;
75 /* Live only within one (recursive) call to tsubst_expr. We use
76 this to pass the statement expression node from the STMT_EXPR
77 to the EXPR_STMT that is its result. */
78 static tree cur_stmt_expr;
80 // -------------------------------------------------------------------------- //
81 // Local Specialization Stack
83 // Implementation of the RAII helper for creating new local
84 // specializations.
85 local_specialization_stack::local_specialization_stack (lss_policy policy)
86 : saved (local_specializations)
88 if (policy == lss_nop)
90 else if (policy == lss_blank || !saved)
91 local_specializations = new hash_map<tree, tree>;
92 else
93 local_specializations = new hash_map<tree, tree>(*saved);
96 local_specialization_stack::~local_specialization_stack ()
98 if (local_specializations != saved)
100 delete local_specializations;
101 local_specializations = saved;
105 /* True if we've recursed into fn_type_unification too many times. */
106 static bool excessive_deduction_depth;
108 struct spec_hasher : ggc_ptr_hash<spec_entry>
110 static hashval_t hash (tree, tree);
111 static hashval_t hash (spec_entry *);
112 static bool equal (spec_entry *, spec_entry *);
115 /* The general template is not in these tables. */
116 typedef hash_table<spec_hasher> spec_hash_table;
117 static GTY (()) spec_hash_table *decl_specializations;
118 static GTY (()) spec_hash_table *type_specializations;
120 /* Contains canonical template parameter types. The vector is indexed by
121 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
122 TREE_LIST, whose TREE_VALUEs contain the canonical template
123 parameters of various types and levels. */
124 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
126 #define UNIFY_ALLOW_NONE 0
127 #define UNIFY_ALLOW_MORE_CV_QUAL 1
128 #define UNIFY_ALLOW_LESS_CV_QUAL 2
129 #define UNIFY_ALLOW_DERIVED 4
130 #define UNIFY_ALLOW_INTEGER 8
131 #define UNIFY_ALLOW_OUTER_LEVEL 16
132 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
133 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
135 enum template_base_result {
136 tbr_incomplete_type,
137 tbr_ambiguous_baseclass,
138 tbr_success
141 static bool resolve_overloaded_unification (tree, tree, tree, tree,
142 unification_kind_t, int,
143 bool);
144 static int try_one_overload (tree, tree, tree, tree, tree,
145 unification_kind_t, int, bool, bool);
146 static int unify (tree, tree, tree, tree, int, bool);
147 static void add_pending_template (tree);
148 static tree reopen_tinst_level (struct tinst_level *);
149 static tree tsubst_initializer_list (tree, tree);
150 static tree get_partial_spec_bindings (tree, tree, tree);
151 static void tsubst_enum (tree, tree, tree);
152 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
153 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
154 struct conversion **, bool);
155 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
156 tree*, tree*, tree);
157 static int type_unification_real (tree, tree, tree, const tree *,
158 unsigned int, int, unification_kind_t,
159 vec<deferred_access_check, va_gc> **,
160 bool);
161 static void note_template_header (int);
162 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
163 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
164 static tree convert_template_argument (tree, tree, tree,
165 tsubst_flags_t, int, tree);
166 static tree for_each_template_parm (tree, tree_fn_t, void*,
167 hash_set<tree> *, bool, tree_fn_t = NULL);
168 static tree expand_template_argument_pack (tree);
169 static tree build_template_parm_index (int, int, int, tree, tree);
170 static bool inline_needs_template_parms (tree, bool);
171 static void push_inline_template_parms_recursive (tree, int);
172 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
173 static int mark_template_parm (tree, void *);
174 static int template_parm_this_level_p (tree, void *);
175 static tree tsubst_friend_function (tree, tree);
176 static tree tsubst_friend_class (tree, tree);
177 static int can_complete_type_without_circularity (tree);
178 static tree get_bindings (tree, tree, tree, bool);
179 static int template_decl_level (tree);
180 static int check_cv_quals_for_unify (int, tree, tree);
181 static int unify_pack_expansion (tree, tree, tree,
182 tree, unification_kind_t, bool, bool);
183 static tree copy_template_args (tree);
184 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
185 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
186 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
187 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
188 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
190 static bool check_specialization_scope (void);
191 static tree process_partial_specialization (tree);
192 static enum template_base_result get_template_base (tree, tree, tree, tree,
193 bool , tree *);
194 static tree try_class_unification (tree, tree, tree, tree, bool);
195 static bool class_nttp_const_wrapper_p (tree t);
196 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
197 tree, tree);
198 static bool template_template_parm_bindings_ok_p (tree, tree);
199 static void tsubst_default_arguments (tree, tsubst_flags_t);
200 static tree for_each_template_parm_r (tree *, int *, void *);
201 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
202 static void copy_default_args_to_explicit_spec (tree);
203 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
204 static bool dependent_template_arg_p (tree);
205 static bool dependent_type_p_r (tree);
206 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
207 static tree tsubst_decl (tree, tree, tsubst_flags_t, bool = true);
208 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
209 static void perform_instantiation_time_access_checks (tree, tree);
210 static tree listify (tree);
211 static tree listify_autos (tree, tree);
212 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
213 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
214 static bool complex_alias_template_p (const_tree tmpl);
215 static tree get_underlying_template (tree);
216 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
217 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
218 static tree make_argument_pack (tree);
219 static tree enclosing_instantiation_of (tree tctx);
220 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
221 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
222 static void mark_template_arguments_used (tree, tree);
223 static bool uses_outer_template_parms (tree);
225 /* Make the current scope suitable for access checking when we are
226 processing T. T can be FUNCTION_DECL for instantiated function
227 template, VAR_DECL for static member variable, or TYPE_DECL for
228 for a class or alias template (needed by instantiate_decl). */
230 void
231 push_access_scope (tree t)
233 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
234 || TREE_CODE (t) == TYPE_DECL);
236 if (DECL_FRIEND_CONTEXT (t))
237 push_nested_class (DECL_FRIEND_CONTEXT (t));
238 else if (DECL_IMPLICIT_TYPEDEF_P (t)
239 && CLASS_TYPE_P (TREE_TYPE (t)))
240 push_nested_class (TREE_TYPE (t));
241 else if (DECL_CLASS_SCOPE_P (t))
242 push_nested_class (DECL_CONTEXT (t));
243 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
244 /* An artificial deduction guide should have the same access as
245 the constructor. */
246 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
247 else
248 push_to_top_level ();
250 if (TREE_CODE (t) == FUNCTION_DECL)
252 vec_safe_push (saved_access_scope, current_function_decl);
253 current_function_decl = t;
257 /* Restore the scope set up by push_access_scope. T is the node we
258 are processing. */
260 void
261 pop_access_scope (tree t)
263 if (TREE_CODE (t) == FUNCTION_DECL)
264 current_function_decl = saved_access_scope->pop();
266 if (DECL_FRIEND_CONTEXT (t)
267 || (DECL_IMPLICIT_TYPEDEF_P (t)
268 && CLASS_TYPE_P (TREE_TYPE (t)))
269 || DECL_CLASS_SCOPE_P (t)
270 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
271 pop_nested_class ();
272 else
273 pop_from_top_level ();
276 /* Do any processing required when DECL (a member template
277 declaration) is finished. Returns the TEMPLATE_DECL corresponding
278 to DECL, unless it is a specialization, in which case the DECL
279 itself is returned. */
281 tree
282 finish_member_template_decl (tree decl)
284 if (decl == error_mark_node)
285 return error_mark_node;
287 gcc_assert (DECL_P (decl));
289 if (TREE_CODE (decl) == TYPE_DECL)
291 tree type;
293 type = TREE_TYPE (decl);
294 if (type == error_mark_node)
295 return error_mark_node;
296 if (MAYBE_CLASS_TYPE_P (type)
297 && CLASSTYPE_TEMPLATE_INFO (type)
298 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
300 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
301 check_member_template (tmpl);
302 return tmpl;
304 return NULL_TREE;
306 else if (TREE_CODE (decl) == FIELD_DECL)
307 error_at (DECL_SOURCE_LOCATION (decl),
308 "data member %qD cannot be a member template", decl);
309 else if (DECL_TEMPLATE_INFO (decl))
311 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
313 check_member_template (DECL_TI_TEMPLATE (decl));
314 return DECL_TI_TEMPLATE (decl);
316 else
317 return NULL_TREE;
319 else
320 error_at (DECL_SOURCE_LOCATION (decl),
321 "invalid member template declaration %qD", decl);
323 return error_mark_node;
326 /* Create a template info node. */
328 tree
329 build_template_info (tree template_decl, tree template_args)
331 tree result = make_node (TEMPLATE_INFO);
332 TI_TEMPLATE (result) = template_decl;
333 TI_ARGS (result) = template_args;
334 return result;
337 /* Return the template info node corresponding to T, whatever T is. */
339 tree
340 get_template_info (const_tree t)
342 tree tinfo = NULL_TREE;
344 if (!t || t == error_mark_node)
345 return NULL;
347 if (TREE_CODE (t) == NAMESPACE_DECL
348 || TREE_CODE (t) == PARM_DECL)
349 return NULL;
351 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
352 tinfo = DECL_TEMPLATE_INFO (t);
354 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
355 t = TREE_TYPE (t);
357 if (OVERLOAD_TYPE_P (t))
358 tinfo = TYPE_TEMPLATE_INFO (t);
359 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
360 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
362 return tinfo;
365 /* Returns the template nesting level of the indicated class TYPE.
367 For example, in:
368 template <class T>
369 struct A
371 template <class U>
372 struct B {};
375 A<T>::B<U> has depth two, while A<T> has depth one.
376 Both A<T>::B<int> and A<int>::B<U> have depth one, if
377 they are instantiations, not specializations.
379 This function is guaranteed to return 0 if passed NULL_TREE so
380 that, for example, `template_class_depth (current_class_type)' is
381 always safe. */
384 template_class_depth (tree type)
386 int depth;
388 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
390 tree tinfo = get_template_info (type);
392 if (tinfo
393 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
394 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
395 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
396 ++depth;
398 if (DECL_P (type))
400 if (tree fctx = DECL_FRIEND_CONTEXT (type))
401 type = fctx;
402 else
403 type = CP_DECL_CONTEXT (type);
405 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
406 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
407 else
408 type = CP_TYPE_CONTEXT (type);
411 return depth;
414 /* Return TRUE if NODE instantiates a template that has arguments of
415 its own, be it directly a primary template or indirectly through a
416 partial specializations. */
417 static bool
418 instantiates_primary_template_p (tree node)
420 tree tinfo = get_template_info (node);
421 if (!tinfo)
422 return false;
424 tree tmpl = TI_TEMPLATE (tinfo);
425 if (PRIMARY_TEMPLATE_P (tmpl))
426 return true;
428 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
429 return false;
431 /* So now we know we have a specialization, but it could be a full
432 or a partial specialization. To tell which, compare the depth of
433 its template arguments with those of its context. */
435 tree ctxt = DECL_CONTEXT (tmpl);
436 tree ctinfo = get_template_info (ctxt);
437 if (!ctinfo)
438 return true;
440 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
441 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
444 /* Subroutine of maybe_begin_member_template_processing.
445 Returns true if processing DECL needs us to push template parms. */
447 static bool
448 inline_needs_template_parms (tree decl, bool nsdmi)
450 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
451 return false;
453 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
454 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
457 /* Subroutine of maybe_begin_member_template_processing.
458 Push the template parms in PARMS, starting from LEVELS steps into the
459 chain, and ending at the beginning, since template parms are listed
460 innermost first. */
462 static void
463 push_inline_template_parms_recursive (tree parmlist, int levels)
465 tree parms = TREE_VALUE (parmlist);
466 int i;
468 if (levels > 1)
469 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
471 ++processing_template_decl;
472 current_template_parms
473 = tree_cons (size_int (current_template_depth + 1),
474 parms, current_template_parms);
475 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
476 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
477 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
479 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
480 NULL);
481 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
483 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
485 if (error_operand_p (parm))
486 continue;
488 gcc_assert (DECL_P (parm));
490 switch (TREE_CODE (parm))
492 case TYPE_DECL:
493 case TEMPLATE_DECL:
494 pushdecl (parm);
495 break;
497 case PARM_DECL:
498 /* Push the CONST_DECL. */
499 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
500 break;
502 default:
503 gcc_unreachable ();
508 /* Restore the template parameter context for a member template, a
509 friend template defined in a class definition, or a non-template
510 member of template class. */
512 void
513 maybe_begin_member_template_processing (tree decl)
515 tree parms;
516 int levels = 0;
517 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
519 if (nsdmi)
521 tree ctx = DECL_CONTEXT (decl);
522 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
523 /* Disregard full specializations (c++/60999). */
524 && uses_template_parms (ctx)
525 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
528 if (inline_needs_template_parms (decl, nsdmi))
530 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
531 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
533 if (DECL_TEMPLATE_SPECIALIZATION (decl))
535 --levels;
536 parms = TREE_CHAIN (parms);
539 push_inline_template_parms_recursive (parms, levels);
542 /* Remember how many levels of template parameters we pushed so that
543 we can pop them later. */
544 inline_parm_levels.safe_push (levels);
547 /* Undo the effects of maybe_begin_member_template_processing. */
549 void
550 maybe_end_member_template_processing (void)
552 int i;
553 int last;
555 if (inline_parm_levels.length () == 0)
556 return;
558 last = inline_parm_levels.pop ();
559 for (i = 0; i < last; ++i)
561 --processing_template_decl;
562 current_template_parms = TREE_CHAIN (current_template_parms);
563 poplevel (0, 0, 0);
567 /* Return a new template argument vector which contains all of ARGS,
568 but has as its innermost set of arguments the EXTRA_ARGS. */
570 tree
571 add_to_template_args (tree args, tree extra_args)
573 tree new_args;
574 int extra_depth;
575 int i;
576 int j;
578 if (args == NULL_TREE || extra_args == error_mark_node)
579 return extra_args;
581 extra_depth = TMPL_ARGS_DEPTH (extra_args);
582 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
584 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
585 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
587 for (j = 1; j <= extra_depth; ++j, ++i)
588 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
590 return new_args;
593 /* Like add_to_template_args, but only the outermost ARGS are added to
594 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
595 (EXTRA_ARGS) levels are added. This function is used to combine
596 the template arguments from a partial instantiation with the
597 template arguments used to attain the full instantiation from the
598 partial instantiation.
600 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
602 tree
603 add_outermost_template_args (tree args, tree extra_args)
605 tree new_args;
607 if (!args)
608 return extra_args;
609 if (TREE_CODE (args) == TEMPLATE_DECL)
611 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
612 args = TI_ARGS (ti);
615 /* If there are more levels of EXTRA_ARGS than there are ARGS,
616 something very fishy is going on. */
617 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
619 /* If *all* the new arguments will be the EXTRA_ARGS, just return
620 them. */
621 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
622 return extra_args;
624 /* For the moment, we make ARGS look like it contains fewer levels. */
625 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
627 new_args = add_to_template_args (args, extra_args);
629 /* Now, we restore ARGS to its full dimensions. */
630 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
632 return new_args;
635 /* Return the N levels of innermost template arguments from the ARGS. */
637 tree
638 get_innermost_template_args (tree args, int n)
640 tree new_args;
641 int extra_levels;
642 int i;
644 gcc_assert (n >= 0);
646 /* If N is 1, just return the innermost set of template arguments. */
647 if (n == 1)
648 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
650 /* If we're not removing anything, just return the arguments we were
651 given. */
652 extra_levels = TMPL_ARGS_DEPTH (args) - n;
653 gcc_assert (extra_levels >= 0);
654 if (extra_levels == 0)
655 return args;
657 /* Make a new set of arguments, not containing the outer arguments. */
658 new_args = make_tree_vec (n);
659 for (i = 1; i <= n; ++i)
660 SET_TMPL_ARGS_LEVEL (new_args, i,
661 TMPL_ARGS_LEVEL (args, i + extra_levels));
663 return new_args;
666 /* The inverse of get_innermost_template_args: Return all but the innermost
667 EXTRA_LEVELS levels of template arguments from the ARGS. */
669 static tree
670 strip_innermost_template_args (tree args, int extra_levels)
672 tree new_args;
673 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
674 int i;
676 gcc_assert (n >= 0);
678 /* If N is 1, just return the outermost set of template arguments. */
679 if (n == 1)
680 return TMPL_ARGS_LEVEL (args, 1);
682 /* If we're not removing anything, just return the arguments we were
683 given. */
684 gcc_assert (extra_levels >= 0);
685 if (extra_levels == 0)
686 return args;
688 /* Make a new set of arguments, not containing the inner 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));
694 return new_args;
697 /* We've got a template header coming up; push to a new level for storing
698 the parms. */
700 void
701 begin_template_parm_list (void)
703 /* We use a non-tag-transparent scope here, which causes pushtag to
704 put tags in this scope, rather than in the enclosing class or
705 namespace scope. This is the right thing, since we want
706 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
707 global template class, push_template_decl handles putting the
708 TEMPLATE_DECL into top-level scope. For a nested template class,
709 e.g.:
711 template <class T> struct S1 {
712 template <class T> struct S2 {};
715 pushtag contains special code to insert the TEMPLATE_DECL for S2
716 at the right scope. */
717 begin_scope (sk_template_parms, NULL);
718 ++processing_template_decl;
719 ++processing_template_parmlist;
720 note_template_header (0);
722 /* Add a dummy parameter level while we process the parameter list. */
723 current_template_parms
724 = tree_cons (size_int (current_template_depth + 1),
725 make_tree_vec (0),
726 current_template_parms);
729 /* This routine is called when a specialization is declared. If it is
730 invalid to declare a specialization here, an error is reported and
731 false is returned, otherwise this routine will return true. */
733 static bool
734 check_specialization_scope (void)
736 tree scope = current_scope ();
738 /* [temp.expl.spec]
740 An explicit specialization shall be declared in the namespace of
741 which the template is a member, or, for member templates, in the
742 namespace of which the enclosing class or enclosing class
743 template is a member. An explicit specialization of a member
744 function, member class or static data member of a class template
745 shall be declared in the namespace of which the class template
746 is a member. */
747 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
749 error ("explicit specialization in non-namespace scope %qD", scope);
750 return false;
753 /* [temp.expl.spec]
755 In an explicit specialization declaration for a member of a class
756 template or a member template that appears in namespace scope,
757 the member template and some of its enclosing class templates may
758 remain unspecialized, except that the declaration shall not
759 explicitly specialize a class member template if its enclosing
760 class templates are not explicitly specialized as well. */
761 if (current_template_parms)
763 error ("enclosing class templates are not explicitly specialized");
764 return false;
767 return true;
770 /* We've just seen template <>. */
772 bool
773 begin_specialization (void)
775 begin_scope (sk_template_spec, NULL);
776 note_template_header (1);
777 return check_specialization_scope ();
780 /* Called at then end of processing a declaration preceded by
781 template<>. */
783 void
784 end_specialization (void)
786 finish_scope ();
787 reset_specialization ();
790 /* Any template <>'s that we have seen thus far are not referring to a
791 function specialization. */
793 void
794 reset_specialization (void)
796 processing_specialization = 0;
797 template_header_count = 0;
800 /* We've just seen a template header. If SPECIALIZATION is nonzero,
801 it was of the form template <>. */
803 static void
804 note_template_header (int specialization)
806 processing_specialization = specialization;
807 template_header_count++;
810 /* We're beginning an explicit instantiation. */
812 void
813 begin_explicit_instantiation (void)
815 gcc_assert (!processing_explicit_instantiation);
816 processing_explicit_instantiation = true;
820 void
821 end_explicit_instantiation (void)
823 gcc_assert (processing_explicit_instantiation);
824 processing_explicit_instantiation = false;
827 /* An explicit specialization or partial specialization of TMPL is being
828 declared. Check that the namespace in which the specialization is
829 occurring is permissible. Returns false iff it is invalid to
830 specialize TMPL in the current namespace. */
832 static bool
833 check_specialization_namespace (tree tmpl)
835 tree tpl_ns = decl_namespace_context (tmpl);
837 /* [tmpl.expl.spec]
839 An explicit specialization shall be declared in a namespace enclosing the
840 specialized template. An explicit specialization whose declarator-id is
841 not qualified shall be declared in the nearest enclosing namespace of the
842 template, or, if the namespace is inline (7.3.1), any namespace from its
843 enclosing namespace set. */
844 if (current_scope() != DECL_CONTEXT (tmpl)
845 && !at_namespace_scope_p ())
847 error ("specialization of %qD must appear at namespace scope", tmpl);
848 return false;
851 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
852 /* Same or enclosing namespace. */
853 return true;
854 else
856 auto_diagnostic_group d;
857 if (permerror (input_location,
858 "specialization of %qD in different namespace", tmpl))
859 inform (DECL_SOURCE_LOCATION (tmpl),
860 " from definition of %q#D", tmpl);
861 return false;
865 /* SPEC is an explicit instantiation. Check that it is valid to
866 perform this explicit instantiation in the current namespace. */
868 static void
869 check_explicit_instantiation_namespace (tree spec)
871 tree ns;
873 /* DR 275: An explicit instantiation shall appear in an enclosing
874 namespace of its template. */
875 ns = decl_namespace_context (spec);
876 if (!is_nested_namespace (current_namespace, ns))
877 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
878 "(which does not enclose namespace %qD)",
879 spec, current_namespace, ns);
882 /* Returns true if TYPE is a new partial specialization that needs to be
883 set up. This may also modify TYPE to point to the correct (new or
884 existing) constrained partial specialization. */
886 static bool
887 maybe_new_partial_specialization (tree& type)
889 /* An implicit instantiation of an incomplete type implies
890 the definition of a new class template.
892 template<typename T>
893 struct S;
895 template<typename T>
896 struct S<T*>;
898 Here, S<T*> is an implicit instantiation of S whose type
899 is incomplete. */
900 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
901 return true;
903 /* It can also be the case that TYPE is a completed specialization.
904 Continuing the previous example, suppose we also declare:
906 template<typename T>
907 requires Integral<T>
908 struct S<T*>;
910 Here, S<T*> refers to the specialization S<T*> defined
911 above. However, we need to differentiate definitions because
912 we intend to define a new partial specialization. In this case,
913 we rely on the fact that the constraints are different for
914 this declaration than that above.
916 Note that we also get here for injected class names and
917 late-parsed template definitions. We must ensure that we
918 do not create new type declarations for those cases. */
919 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
921 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
922 tree args = CLASSTYPE_TI_ARGS (type);
924 /* If there are no template parameters, this cannot be a new
925 partial template specialization? */
926 if (!current_template_parms)
927 return false;
929 /* The injected-class-name is not a new partial specialization. */
930 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
931 return false;
933 /* If the constraints are not the same as those of the primary
934 then, we can probably create a new specialization. */
935 tree type_constr = current_template_constraints ();
937 if (type == TREE_TYPE (tmpl))
939 tree main_constr = get_constraints (tmpl);
940 if (equivalent_constraints (type_constr, main_constr))
941 return false;
944 /* Also, if there's a pre-existing specialization with matching
945 constraints, then this also isn't new. */
946 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
947 while (specs)
949 tree spec_tmpl = TREE_VALUE (specs);
950 tree spec_args = TREE_PURPOSE (specs);
951 tree spec_constr = get_constraints (spec_tmpl);
952 if (comp_template_args (args, spec_args)
953 && equivalent_constraints (type_constr, spec_constr))
955 type = TREE_TYPE (spec_tmpl);
956 return false;
958 specs = TREE_CHAIN (specs);
961 /* Create a new type node (and corresponding type decl)
962 for the newly declared specialization. */
963 tree t = make_class_type (TREE_CODE (type));
964 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
965 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
967 /* We only need a separate type node for storing the definition of this
968 partial specialization; uses of S<T*> are unconstrained, so all are
969 equivalent. So keep TYPE_CANONICAL the same. */
970 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
972 /* Build the corresponding type decl. */
973 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
974 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
975 DECL_SOURCE_LOCATION (d) = input_location;
976 TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
977 TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
979 set_instantiating_module (d);
980 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
982 type = t;
983 return true;
986 return false;
989 /* The TYPE is being declared. If it is a template type, that means it
990 is a partial specialization. Do appropriate error-checking. */
992 tree
993 maybe_process_partial_specialization (tree type)
995 tree context;
997 if (type == error_mark_node)
998 return error_mark_node;
1000 /* A lambda that appears in specialization context is not itself a
1001 specialization. */
1002 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1003 return type;
1005 /* An injected-class-name is not a specialization. */
1006 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1007 return type;
1009 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1011 error ("name of class shadows template template parameter %qD",
1012 TYPE_NAME (type));
1013 return error_mark_node;
1016 context = TYPE_CONTEXT (type);
1018 if (TYPE_ALIAS_P (type))
1020 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1022 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1023 error ("specialization of alias template %qD",
1024 TI_TEMPLATE (tinfo));
1025 else
1026 error ("explicit specialization of non-template %qT", type);
1027 return error_mark_node;
1029 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1031 /* This is for ordinary explicit specialization and partial
1032 specialization of a template class such as:
1034 template <> class C<int>;
1038 template <class T> class C<T*>;
1040 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1042 if (maybe_new_partial_specialization (type))
1044 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1045 && !at_namespace_scope_p ())
1046 return error_mark_node;
1047 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1048 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1049 if (processing_template_decl)
1051 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1052 if (decl == error_mark_node)
1053 return error_mark_node;
1054 return TREE_TYPE (decl);
1057 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1058 error ("specialization of %qT after instantiation", type);
1059 else if (errorcount && !processing_specialization
1060 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1061 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1062 /* Trying to define a specialization either without a template<> header
1063 or in an inappropriate place. We've already given an error, so just
1064 bail now so we don't actually define the specialization. */
1065 return error_mark_node;
1067 else if (CLASS_TYPE_P (type)
1068 && !CLASSTYPE_USE_TEMPLATE (type)
1069 && CLASSTYPE_TEMPLATE_INFO (type)
1070 && context && CLASS_TYPE_P (context)
1071 && CLASSTYPE_TEMPLATE_INFO (context))
1073 /* This is for an explicit specialization of member class
1074 template according to [temp.expl.spec/18]:
1076 template <> template <class U> class C<int>::D;
1078 The context `C<int>' must be an implicit instantiation.
1079 Otherwise this is just a member class template declared
1080 earlier like:
1082 template <> class C<int> { template <class U> class D; };
1083 template <> template <class U> class C<int>::D;
1085 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1086 while in the second case, `C<int>::D' is a primary template
1087 and `C<T>::D' may not exist. */
1089 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1090 && !COMPLETE_TYPE_P (type))
1092 tree t;
1093 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1095 if (current_namespace
1096 != decl_namespace_context (tmpl))
1098 if (permerror (input_location,
1099 "specialization of %qD in different namespace",
1100 type))
1101 inform (DECL_SOURCE_LOCATION (tmpl),
1102 "from definition of %q#D", tmpl);
1105 /* Check for invalid specialization after instantiation:
1107 template <> template <> class C<int>::D<int>;
1108 template <> template <class U> class C<int>::D; */
1110 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1111 t; t = TREE_CHAIN (t))
1113 tree inst = TREE_VALUE (t);
1114 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1115 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1117 /* We already have a full specialization of this partial
1118 instantiation, or a full specialization has been
1119 looked up but not instantiated. Reassign it to the
1120 new member specialization template. */
1121 spec_entry elt;
1122 spec_entry *entry;
1124 elt.tmpl = most_general_template (tmpl);
1125 elt.args = CLASSTYPE_TI_ARGS (inst);
1126 elt.spec = inst;
1128 type_specializations->remove_elt (&elt);
1130 elt.tmpl = tmpl;
1131 CLASSTYPE_TI_ARGS (inst)
1132 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1134 spec_entry **slot
1135 = type_specializations->find_slot (&elt, INSERT);
1136 entry = ggc_alloc<spec_entry> ();
1137 *entry = elt;
1138 *slot = entry;
1140 else
1141 /* But if we've had an implicit instantiation, that's a
1142 problem ([temp.expl.spec]/6). */
1143 error ("specialization %qT after instantiation %qT",
1144 type, inst);
1147 /* Mark TYPE as a specialization. And as a result, we only
1148 have one level of template argument for the innermost
1149 class template. */
1150 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1151 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1152 CLASSTYPE_TI_ARGS (type)
1153 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1156 else if (processing_specialization)
1158 /* Someday C++0x may allow for enum template specialization. */
1159 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1160 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1161 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1162 "of %qD not allowed by ISO C++", type);
1163 else
1165 error ("explicit specialization of non-template %qT", type);
1166 return error_mark_node;
1170 return type;
1173 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1174 gone through coerce_template_parms by now. */
1176 static void
1177 verify_unstripped_args_1 (tree inner)
1179 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1181 tree arg = TREE_VEC_ELT (inner, i);
1182 if (TREE_CODE (arg) == TEMPLATE_DECL)
1183 /* OK */;
1184 else if (TYPE_P (arg))
1185 gcc_assert (strip_typedefs (arg, NULL) == arg);
1186 else if (ARGUMENT_PACK_P (arg))
1187 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1188 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1189 /* Allow typedefs on the type of a non-type argument, since a
1190 parameter can have them. */;
1191 else
1192 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1196 static void
1197 verify_unstripped_args (tree args)
1199 ++processing_template_decl;
1200 if (!any_dependent_template_arguments_p (args))
1201 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1202 --processing_template_decl;
1205 /* Retrieve the specialization (in the sense of [temp.spec] - a
1206 specialization is either an instantiation or an explicit
1207 specialization) of TMPL for the given template ARGS. If there is
1208 no such specialization, return NULL_TREE. The ARGS are a vector of
1209 arguments, or a vector of vectors of arguments, in the case of
1210 templates with more than one level of parameters.
1212 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1213 then we search for a partial specialization matching ARGS. This
1214 parameter is ignored if TMPL is not a class template.
1216 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1217 result is a NONTYPE_ARGUMENT_PACK. */
1219 static tree
1220 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1222 if (tmpl == NULL_TREE)
1223 return NULL_TREE;
1225 if (args == error_mark_node)
1226 return NULL_TREE;
1228 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1229 || TREE_CODE (tmpl) == FIELD_DECL);
1231 /* There should be as many levels of arguments as there are
1232 levels of parameters. */
1233 gcc_assert (TMPL_ARGS_DEPTH (args)
1234 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1235 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1236 : template_class_depth (DECL_CONTEXT (tmpl))));
1238 if (flag_checking)
1239 verify_unstripped_args (args);
1241 /* Lambda functions in templates aren't instantiated normally, but through
1242 tsubst_lambda_expr. */
1243 if (lambda_fn_in_template_p (tmpl))
1244 return NULL_TREE;
1246 spec_entry elt;
1247 elt.tmpl = tmpl;
1248 elt.args = args;
1249 elt.spec = NULL_TREE;
1251 spec_hash_table *specializations;
1252 if (DECL_CLASS_TEMPLATE_P (tmpl))
1253 specializations = type_specializations;
1254 else
1255 specializations = decl_specializations;
1257 if (hash == 0)
1258 hash = spec_hasher::hash (&elt);
1259 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1260 return found->spec;
1262 return NULL_TREE;
1265 /* Like retrieve_specialization, but for local declarations. */
1267 tree
1268 retrieve_local_specialization (tree tmpl)
1270 if (local_specializations == NULL)
1271 return NULL_TREE;
1273 tree *slot = local_specializations->get (tmpl);
1274 return slot ? *slot : NULL_TREE;
1277 /* Returns nonzero iff DECL is a specialization of TMPL. */
1280 is_specialization_of (tree decl, tree tmpl)
1282 tree t;
1284 if (TREE_CODE (decl) == FUNCTION_DECL)
1286 for (t = decl;
1287 t != NULL_TREE;
1288 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1289 if (t == tmpl)
1290 return 1;
1292 else
1294 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1296 for (t = TREE_TYPE (decl);
1297 t != NULL_TREE;
1298 t = CLASSTYPE_USE_TEMPLATE (t)
1299 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1300 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1301 return 1;
1304 return 0;
1307 /* Returns nonzero iff DECL is a specialization of friend declaration
1308 FRIEND_DECL according to [temp.friend]. */
1310 bool
1311 is_specialization_of_friend (tree decl, tree friend_decl)
1313 bool need_template = true;
1314 int template_depth;
1316 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1317 || TREE_CODE (decl) == TYPE_DECL);
1319 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1320 of a template class, we want to check if DECL is a specialization
1321 if this. */
1322 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1323 && DECL_CLASS_SCOPE_P (friend_decl)
1324 && DECL_TEMPLATE_INFO (friend_decl)
1325 && !DECL_USE_TEMPLATE (friend_decl))
1327 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1328 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1329 need_template = false;
1331 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1332 && !PRIMARY_TEMPLATE_P (friend_decl))
1333 need_template = false;
1335 /* There is nothing to do if this is not a template friend. */
1336 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1337 return false;
1339 if (is_specialization_of (decl, friend_decl))
1340 return true;
1342 /* [temp.friend/6]
1343 A member of a class template may be declared to be a friend of a
1344 non-template class. In this case, the corresponding member of
1345 every specialization of the class template is a friend of the
1346 class granting friendship.
1348 For example, given a template friend declaration
1350 template <class T> friend void A<T>::f();
1352 the member function below is considered a friend
1354 template <> struct A<int> {
1355 void f();
1358 For this type of template friend, TEMPLATE_DEPTH below will be
1359 nonzero. To determine if DECL is a friend of FRIEND, we first
1360 check if the enclosing class is a specialization of another. */
1362 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1363 if (template_depth
1364 && DECL_CLASS_SCOPE_P (decl)
1365 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1366 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1368 /* Next, we check the members themselves. In order to handle
1369 a few tricky cases, such as when FRIEND_DECL's are
1371 template <class T> friend void A<T>::g(T t);
1372 template <class T> template <T t> friend void A<T>::h();
1374 and DECL's are
1376 void A<int>::g(int);
1377 template <int> void A<int>::h();
1379 we need to figure out ARGS, the template arguments from
1380 the context of DECL. This is required for template substitution
1381 of `T' in the function parameter of `g' and template parameter
1382 of `h' in the above examples. Here ARGS corresponds to `int'. */
1384 tree context = DECL_CONTEXT (decl);
1385 tree args = NULL_TREE;
1386 int current_depth = 0;
1388 while (current_depth < template_depth)
1390 if (CLASSTYPE_TEMPLATE_INFO (context))
1392 if (current_depth == 0)
1393 args = TYPE_TI_ARGS (context);
1394 else
1395 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1396 current_depth++;
1398 context = TYPE_CONTEXT (context);
1401 if (TREE_CODE (decl) == FUNCTION_DECL)
1403 bool is_template;
1404 tree friend_type;
1405 tree decl_type;
1406 tree friend_args_type;
1407 tree decl_args_type;
1409 /* Make sure that both DECL and FRIEND_DECL are templates or
1410 non-templates. */
1411 is_template = DECL_TEMPLATE_INFO (decl)
1412 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1413 if (need_template ^ is_template)
1414 return false;
1415 else if (is_template)
1417 /* If both are templates, check template parameter list. */
1418 tree friend_parms
1419 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1420 args, tf_none);
1421 if (!comp_template_parms
1422 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1423 friend_parms))
1424 return false;
1426 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1428 else
1429 decl_type = TREE_TYPE (decl);
1431 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1432 tf_none, NULL_TREE);
1433 if (friend_type == error_mark_node)
1434 return false;
1436 /* Check if return types match. */
1437 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1438 return false;
1440 /* Check if function parameter types match, ignoring the
1441 `this' parameter. */
1442 friend_args_type = TYPE_ARG_TYPES (friend_type);
1443 decl_args_type = TYPE_ARG_TYPES (decl_type);
1444 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1445 friend_args_type = TREE_CHAIN (friend_args_type);
1446 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1447 decl_args_type = TREE_CHAIN (decl_args_type);
1449 return compparms (decl_args_type, friend_args_type);
1451 else
1453 /* DECL is a TYPE_DECL */
1454 bool is_template;
1455 tree decl_type = TREE_TYPE (decl);
1457 /* Make sure that both DECL and FRIEND_DECL are templates or
1458 non-templates. */
1459 is_template
1460 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1461 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1463 if (need_template ^ is_template)
1464 return false;
1465 else if (is_template)
1467 tree friend_parms;
1468 /* If both are templates, check the name of the two
1469 TEMPLATE_DECL's first because is_friend didn't. */
1470 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1471 != DECL_NAME (friend_decl))
1472 return false;
1474 /* Now check template parameter list. */
1475 friend_parms
1476 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1477 args, tf_none);
1478 return comp_template_parms
1479 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1480 friend_parms);
1482 else
1483 return (DECL_NAME (decl)
1484 == DECL_NAME (friend_decl));
1487 return false;
1490 /* Register the specialization SPEC as a specialization of TMPL with
1491 the indicated ARGS. IS_FRIEND indicates whether the specialization
1492 is actually just a friend declaration. ATTRLIST is the list of
1493 attributes that the specialization is declared with or NULL when
1494 it isn't. Returns SPEC, or an equivalent prior declaration, if
1495 available.
1497 We also store instantiations of field packs in the hash table, even
1498 though they are not themselves templates, to make lookup easier. */
1500 static tree
1501 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1502 hashval_t hash)
1504 tree fn;
1506 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1507 || (TREE_CODE (tmpl) == FIELD_DECL
1508 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1510 if (TREE_CODE (spec) == FUNCTION_DECL
1511 && uses_template_parms (DECL_TI_ARGS (spec)))
1512 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1513 register it; we want the corresponding TEMPLATE_DECL instead.
1514 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1515 the more obvious `uses_template_parms (spec)' to avoid problems
1516 with default function arguments. In particular, given
1517 something like this:
1519 template <class T> void f(T t1, T t = T())
1521 the default argument expression is not substituted for in an
1522 instantiation unless and until it is actually needed. */
1523 return spec;
1525 spec_entry elt;
1526 elt.tmpl = tmpl;
1527 elt.args = args;
1528 elt.spec = spec;
1530 if (hash == 0)
1531 hash = spec_hasher::hash (&elt);
1533 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1534 if (*slot)
1535 fn = (*slot)->spec;
1536 else
1537 fn = NULL_TREE;
1539 /* We can sometimes try to re-register a specialization that we've
1540 already got. In particular, regenerate_decl_from_template calls
1541 duplicate_decls which will update the specialization list. But,
1542 we'll still get called again here anyhow. It's more convenient
1543 to simply allow this than to try to prevent it. */
1544 if (fn == spec)
1545 return spec;
1546 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1548 if (DECL_TEMPLATE_INSTANTIATION (fn))
1550 if (DECL_ODR_USED (fn)
1551 || DECL_EXPLICIT_INSTANTIATION (fn))
1553 error ("specialization of %qD after instantiation",
1554 fn);
1555 return error_mark_node;
1557 else
1559 tree clone;
1560 /* This situation should occur only if the first
1561 specialization is an implicit instantiation, the
1562 second is an explicit specialization, and the
1563 implicit instantiation has not yet been used. That
1564 situation can occur if we have implicitly
1565 instantiated a member function and then specialized
1566 it later.
1568 We can also wind up here if a friend declaration that
1569 looked like an instantiation turns out to be a
1570 specialization:
1572 template <class T> void foo(T);
1573 class S { friend void foo<>(int) };
1574 template <> void foo(int);
1576 We transform the existing DECL in place so that any
1577 pointers to it become pointers to the updated
1578 declaration.
1580 If there was a definition for the template, but not
1581 for the specialization, we want this to look as if
1582 there were no definition, and vice versa. */
1583 DECL_INITIAL (fn) = NULL_TREE;
1584 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1586 /* The call to duplicate_decls will have applied
1587 [temp.expl.spec]:
1589 An explicit specialization of a function template
1590 is inline only if it is explicitly declared to be,
1591 and independently of whether its function template
1594 to the primary function; now copy the inline bits to
1595 the various clones. */
1596 FOR_EACH_CLONE (clone, fn)
1598 DECL_DECLARED_INLINE_P (clone)
1599 = DECL_DECLARED_INLINE_P (fn);
1600 DECL_SOURCE_LOCATION (clone)
1601 = DECL_SOURCE_LOCATION (fn);
1602 DECL_DELETED_FN (clone)
1603 = DECL_DELETED_FN (fn);
1605 check_specialization_namespace (tmpl);
1607 return fn;
1610 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1612 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1613 if (dd == error_mark_node)
1614 /* We've already complained in duplicate_decls. */
1615 return error_mark_node;
1617 if (dd == NULL_TREE && DECL_INITIAL (spec))
1618 /* Dup decl failed, but this is a new definition. Set the
1619 line number so any errors match this new
1620 definition. */
1621 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1623 return fn;
1626 else if (fn)
1627 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1629 /* A specialization must be declared in the same namespace as the
1630 template it is specializing. */
1631 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1632 && !check_specialization_namespace (tmpl))
1633 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1635 spec_entry *entry = ggc_alloc<spec_entry> ();
1636 gcc_assert (tmpl && args && spec);
1637 *entry = elt;
1638 *slot = entry;
1639 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1640 && PRIMARY_TEMPLATE_P (tmpl)
1641 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1642 || variable_template_p (tmpl))
1643 /* If TMPL is a forward declaration of a template function, keep a list
1644 of all specializations in case we need to reassign them to a friend
1645 template later in tsubst_friend_function.
1647 Also keep a list of all variable template instantiations so that
1648 process_partial_specialization can check whether a later partial
1649 specialization would have used it. */
1650 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1651 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1653 return spec;
1656 /* Restricts tree and type comparisons. */
1657 int comparing_specializations;
1658 int comparing_dependent_aliases;
1660 /* Returns true iff two spec_entry nodes are equivalent. */
1662 bool
1663 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1665 int equal;
1667 ++comparing_specializations;
1668 ++comparing_dependent_aliases;
1669 ++processing_template_decl;
1670 equal = (e1->tmpl == e2->tmpl
1671 && comp_template_args (e1->args, e2->args));
1672 if (equal && flag_concepts
1673 /* tmpl could be a FIELD_DECL for a capture pack. */
1674 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1675 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1676 && uses_template_parms (e1->args))
1678 /* Partial specializations of a variable template can be distinguished by
1679 constraints. */
1680 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1681 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1682 equal = equivalent_constraints (c1, c2);
1684 --processing_template_decl;
1685 --comparing_dependent_aliases;
1686 --comparing_specializations;
1688 return equal;
1691 /* Returns a hash for a template TMPL and template arguments ARGS. */
1693 static hashval_t
1694 hash_tmpl_and_args (tree tmpl, tree args)
1696 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1697 return iterative_hash_template_arg (args, val);
1700 hashval_t
1701 spec_hasher::hash (tree tmpl, tree args)
1703 ++comparing_specializations;
1704 hashval_t val = hash_tmpl_and_args (tmpl, args);
1705 --comparing_specializations;
1706 return val;
1709 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1710 ignoring SPEC. */
1712 hashval_t
1713 spec_hasher::hash (spec_entry *e)
1715 return spec_hasher::hash (e->tmpl, e->args);
1718 /* Recursively calculate a hash value for a template argument ARG, for use
1719 in the hash tables of template specializations. We must be
1720 careful to (at least) skip the same entities template_args_equal
1721 does. */
1723 hashval_t
1724 iterative_hash_template_arg (tree arg, hashval_t val)
1726 if (arg == NULL_TREE)
1727 return iterative_hash_object (arg, val);
1729 if (!TYPE_P (arg))
1730 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1731 while (CONVERT_EXPR_P (arg)
1732 || TREE_CODE (arg) == NON_LVALUE_EXPR
1733 || class_nttp_const_wrapper_p (arg))
1734 arg = TREE_OPERAND (arg, 0);
1736 enum tree_code code = TREE_CODE (arg);
1738 val = iterative_hash_object (code, val);
1740 switch (code)
1742 case ARGUMENT_PACK_SELECT:
1743 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1744 preserving it in a hash table, which is bad because it will change
1745 meaning when gen_elem_of_pack_expansion_instantiation changes the
1746 ARGUMENT_PACK_SELECT_INDEX. */
1747 gcc_unreachable ();
1749 case ERROR_MARK:
1750 return val;
1752 case IDENTIFIER_NODE:
1753 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1755 case TREE_VEC:
1756 for (tree elt : tree_vec_range (arg))
1757 val = iterative_hash_template_arg (elt, val);
1758 return val;
1760 case TYPE_PACK_EXPANSION:
1761 case EXPR_PACK_EXPANSION:
1762 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1763 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1765 case TYPE_ARGUMENT_PACK:
1766 case NONTYPE_ARGUMENT_PACK:
1767 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1769 case TREE_LIST:
1770 for (; arg; arg = TREE_CHAIN (arg))
1771 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1772 return val;
1774 case OVERLOAD:
1775 for (lkp_iterator iter (arg); iter; ++iter)
1776 val = iterative_hash_template_arg (*iter, val);
1777 return val;
1779 case CONSTRUCTOR:
1781 iterative_hash_template_arg (TREE_TYPE (arg), val);
1782 for (auto &e: CONSTRUCTOR_ELTS (arg))
1784 val = iterative_hash_template_arg (e.index, val);
1785 val = iterative_hash_template_arg (e.value, val);
1787 return val;
1790 case PARM_DECL:
1791 if (!DECL_ARTIFICIAL (arg))
1793 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1794 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1796 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1798 case TARGET_EXPR:
1799 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1801 case PTRMEM_CST:
1802 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1803 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1805 case TEMPLATE_PARM_INDEX:
1806 val = iterative_hash_template_arg
1807 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1808 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1809 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1811 case TRAIT_EXPR:
1812 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1813 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1814 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1816 case BASELINK:
1817 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1818 val);
1819 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1820 val);
1822 case MODOP_EXPR:
1823 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1824 code = TREE_CODE (TREE_OPERAND (arg, 1));
1825 val = iterative_hash_object (code, val);
1826 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1828 case LAMBDA_EXPR:
1829 /* [temp.over.link] Two lambda-expressions are never considered
1830 equivalent.
1832 So just hash the closure type. */
1833 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1835 case CAST_EXPR:
1836 case IMPLICIT_CONV_EXPR:
1837 case STATIC_CAST_EXPR:
1838 case REINTERPRET_CAST_EXPR:
1839 case CONST_CAST_EXPR:
1840 case DYNAMIC_CAST_EXPR:
1841 case NEW_EXPR:
1842 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1843 /* Now hash operands as usual. */
1844 break;
1846 case CALL_EXPR:
1848 tree fn = CALL_EXPR_FN (arg);
1849 if (tree name = call_expr_dependent_name (arg))
1851 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1852 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1853 fn = name;
1855 val = iterative_hash_template_arg (fn, val);
1856 call_expr_arg_iterator ai;
1857 for (tree x = first_call_expr_arg (arg, &ai); x;
1858 x = next_call_expr_arg (&ai))
1859 val = iterative_hash_template_arg (x, val);
1860 return val;
1863 default:
1864 break;
1867 char tclass = TREE_CODE_CLASS (code);
1868 switch (tclass)
1870 case tcc_type:
1871 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1873 // We want an alias specialization that survived strip_typedefs
1874 // to hash differently from its TYPE_CANONICAL, to avoid hash
1875 // collisions that compare as different in template_args_equal.
1876 // These could be dependent specializations that strip_typedefs
1877 // left alone, or untouched specializations because
1878 // coerce_template_parms returns the unconverted template
1879 // arguments if it sees incomplete argument packs.
1880 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1881 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1884 switch (code)
1886 case DECLTYPE_TYPE:
1887 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1888 break;
1890 case TYPENAME_TYPE:
1891 if (comparing_specializations)
1893 /* Hash the components that are relevant to TYPENAME_TYPE
1894 equivalence as determined by structural_comptypes. We
1895 can only coherently do this when comparing_specializations
1896 is set, because otherwise structural_comptypes tries
1897 resolving TYPENAME_TYPE via the current instantiation. */
1898 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1899 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1900 val = iterative_hash_template_arg (context, val);
1901 val = iterative_hash_template_arg (fullname, val);
1903 break;
1905 default:
1906 if (tree canonical = TYPE_CANONICAL (arg))
1907 val = iterative_hash_object (TYPE_HASH (canonical), val);
1908 break;
1911 return val;
1913 case tcc_declaration:
1914 case tcc_constant:
1915 return iterative_hash_expr (arg, val);
1917 default:
1918 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1919 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1920 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1921 return val;
1925 /* Unregister the specialization SPEC as a specialization of TMPL.
1926 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1927 if the SPEC was listed as a specialization of TMPL.
1929 Note that SPEC has been ggc_freed, so we can't look inside it. */
1931 bool
1932 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1934 spec_entry *entry;
1935 spec_entry elt;
1937 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1938 elt.args = TI_ARGS (tinfo);
1939 elt.spec = NULL_TREE;
1941 entry = decl_specializations->find (&elt);
1942 if (entry != NULL)
1944 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1945 gcc_assert (new_spec != NULL_TREE);
1946 entry->spec = new_spec;
1947 return 1;
1950 return 0;
1953 /* Like register_specialization, but for local declarations. We are
1954 registering SPEC, an instantiation of TMPL. */
1956 void
1957 register_local_specialization (tree spec, tree tmpl)
1959 gcc_assert (tmpl != spec);
1960 local_specializations->put (tmpl, spec);
1963 /* Registers T as a specialization of itself. This is used to preserve
1964 the references to already-parsed parameters when instantiating
1965 postconditions. */
1967 void
1968 register_local_identity (tree t)
1970 local_specializations->put (t, t);
1973 /* TYPE is a class type. Returns true if TYPE is an explicitly
1974 specialized class. */
1976 bool
1977 explicit_class_specialization_p (tree type)
1979 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1980 return false;
1981 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1984 /* Print the list of functions at FNS, going through all the overloads
1985 for each element of the list. Alternatively, FNS cannot be a
1986 TREE_LIST, in which case it will be printed together with all the
1987 overloads.
1989 MORE and *STR should respectively be FALSE and NULL when the function
1990 is called from the outside. They are used internally on recursive
1991 calls. print_candidates manages the two parameters and leaves NULL
1992 in *STR when it ends. */
1994 static void
1995 print_candidates_1 (tree fns, char **str, bool more = false)
1997 if (TREE_CODE (fns) == TREE_LIST)
1998 for (; fns; fns = TREE_CHAIN (fns))
1999 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2000 else
2001 for (lkp_iterator iter (fns); iter;)
2003 tree cand = *iter;
2004 ++iter;
2006 const char *pfx = *str;
2007 if (!pfx)
2009 if (more || iter)
2010 pfx = _("candidates are:");
2011 else
2012 pfx = _("candidate is:");
2013 *str = get_spaces (pfx);
2015 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2019 /* Print the list of candidate FNS in an error message. FNS can also
2020 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2022 void
2023 print_candidates (tree fns)
2025 char *str = NULL;
2026 print_candidates_1 (fns, &str);
2027 free (str);
2030 /* Get a (possibly) constrained template declaration for the
2031 purpose of ordering candidates. */
2032 static tree
2033 get_template_for_ordering (tree list)
2035 gcc_assert (TREE_CODE (list) == TREE_LIST);
2036 tree f = TREE_VALUE (list);
2037 if (tree ti = DECL_TEMPLATE_INFO (f))
2038 return TI_TEMPLATE (ti);
2039 return f;
2042 /* Among candidates having the same signature, return the
2043 most constrained or NULL_TREE if there is no best candidate.
2044 If the signatures of candidates vary (e.g., template
2045 specialization vs. member function), then there can be no
2046 most constrained.
2048 Note that we don't compare constraints on the functions
2049 themselves, but rather those of their templates. */
2050 static tree
2051 most_constrained_function (tree candidates)
2053 // Try to find the best candidate in a first pass.
2054 tree champ = candidates;
2055 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2057 int winner = more_constrained (get_template_for_ordering (champ),
2058 get_template_for_ordering (c));
2059 if (winner == -1)
2060 champ = c; // The candidate is more constrained
2061 else if (winner == 0)
2062 return NULL_TREE; // Neither is more constrained
2065 // Verify that the champ is better than previous candidates.
2066 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2067 if (!more_constrained (get_template_for_ordering (champ),
2068 get_template_for_ordering (c)))
2069 return NULL_TREE;
2072 return champ;
2076 /* Returns the template (one of the functions given by TEMPLATE_ID)
2077 which can be specialized to match the indicated DECL with the
2078 explicit template args given in TEMPLATE_ID. The DECL may be
2079 NULL_TREE if none is available. In that case, the functions in
2080 TEMPLATE_ID are non-members.
2082 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2083 specialization of a member template.
2085 The TEMPLATE_COUNT is the number of references to qualifying
2086 template classes that appeared in the name of the function. See
2087 check_explicit_specialization for a more accurate description.
2089 TSK indicates what kind of template declaration (if any) is being
2090 declared. TSK_TEMPLATE indicates that the declaration given by
2091 DECL, though a FUNCTION_DECL, has template parameters, and is
2092 therefore a template function.
2094 The template args (those explicitly specified and those deduced)
2095 are output in a newly created vector *TARGS_OUT.
2097 If it is impossible to determine the result, an error message is
2098 issued. The error_mark_node is returned to indicate failure. */
2100 static tree
2101 determine_specialization (tree template_id,
2102 tree decl,
2103 tree* targs_out,
2104 int need_member_template,
2105 int template_count,
2106 tmpl_spec_kind tsk)
2108 tree fns;
2109 tree targs;
2110 tree explicit_targs;
2111 tree candidates = NULL_TREE;
2113 /* A TREE_LIST of templates of which DECL may be a specialization.
2114 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2115 corresponding TREE_PURPOSE is the set of template arguments that,
2116 when used to instantiate the template, would produce a function
2117 with the signature of DECL. */
2118 tree templates = NULL_TREE;
2119 int header_count;
2120 cp_binding_level *b;
2122 *targs_out = NULL_TREE;
2124 if (template_id == error_mark_node || decl == error_mark_node)
2125 return error_mark_node;
2127 /* We shouldn't be specializing a member template of an
2128 unspecialized class template; we already gave an error in
2129 check_specialization_scope, now avoid crashing. */
2130 if (!VAR_P (decl)
2131 && template_count && DECL_CLASS_SCOPE_P (decl)
2132 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2134 gcc_assert (errorcount);
2135 return error_mark_node;
2138 fns = TREE_OPERAND (template_id, 0);
2139 explicit_targs = TREE_OPERAND (template_id, 1);
2141 if (fns == error_mark_node)
2142 return error_mark_node;
2144 /* Check for baselinks. */
2145 if (BASELINK_P (fns))
2146 fns = BASELINK_FUNCTIONS (fns);
2148 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2150 error_at (DECL_SOURCE_LOCATION (decl),
2151 "%qD is not a function template", fns);
2152 return error_mark_node;
2154 else if (VAR_P (decl) && !variable_template_p (fns))
2156 error ("%qD is not a variable template", fns);
2157 return error_mark_node;
2160 /* Count the number of template headers specified for this
2161 specialization. */
2162 header_count = 0;
2163 for (b = current_binding_level;
2164 b->kind == sk_template_parms;
2165 b = b->level_chain)
2166 ++header_count;
2168 tree orig_fns = fns;
2169 bool header_mismatch = false;
2171 if (variable_template_p (fns))
2173 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2174 targs = coerce_template_parms (parms, explicit_targs, fns,
2175 tf_warning_or_error);
2176 if (targs != error_mark_node
2177 && constraints_satisfied_p (fns, targs))
2178 templates = tree_cons (targs, fns, templates);
2180 else for (lkp_iterator iter (fns); iter; ++iter)
2182 tree fn = *iter;
2184 if (TREE_CODE (fn) == TEMPLATE_DECL)
2186 tree decl_arg_types;
2187 tree fn_arg_types;
2189 /* In case of explicit specialization, we need to check if
2190 the number of template headers appearing in the specialization
2191 is correct. This is usually done in check_explicit_specialization,
2192 but the check done there cannot be exhaustive when specializing
2193 member functions. Consider the following code:
2195 template <> void A<int>::f(int);
2196 template <> template <> void A<int>::f(int);
2198 Assuming that A<int> is not itself an explicit specialization
2199 already, the first line specializes "f" which is a non-template
2200 member function, whilst the second line specializes "f" which
2201 is a template member function. So both lines are syntactically
2202 correct, and check_explicit_specialization does not reject
2203 them.
2205 Here, we can do better, as we are matching the specialization
2206 against the declarations. We count the number of template
2207 headers, and we check if they match TEMPLATE_COUNT + 1
2208 (TEMPLATE_COUNT is the number of qualifying template classes,
2209 plus there must be another header for the member template
2210 itself).
2212 Notice that if header_count is zero, this is not a
2213 specialization but rather a template instantiation, so there
2214 is no check we can perform here. */
2215 if (header_count && header_count != template_count + 1)
2217 header_mismatch = true;
2218 continue;
2221 /* Check that the number of template arguments at the
2222 innermost level for DECL is the same as for FN. */
2223 if (current_binding_level->kind == sk_template_parms
2224 && !current_binding_level->explicit_spec_p
2225 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2226 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2227 (current_template_parms))))
2228 continue;
2230 /* DECL might be a specialization of FN. */
2231 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2232 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2234 /* For a non-static member function, we need to make sure
2235 that the const qualification is the same. Since
2236 get_bindings does not try to merge the "this" parameter,
2237 we must do the comparison explicitly. */
2238 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2240 if (!same_type_p (TREE_VALUE (fn_arg_types),
2241 TREE_VALUE (decl_arg_types)))
2242 continue;
2244 /* And the ref-qualification. */
2245 if (type_memfn_rqual (TREE_TYPE (decl))
2246 != type_memfn_rqual (TREE_TYPE (fn)))
2247 continue;
2250 /* Skip the "this" parameter and, for constructors of
2251 classes with virtual bases, the VTT parameter. A
2252 full specialization of a constructor will have a VTT
2253 parameter, but a template never will. */
2254 decl_arg_types
2255 = skip_artificial_parms_for (decl, decl_arg_types);
2256 fn_arg_types
2257 = skip_artificial_parms_for (fn, fn_arg_types);
2259 /* Function templates cannot be specializations; there are
2260 no partial specializations of functions. Therefore, if
2261 the type of DECL does not match FN, there is no
2262 match.
2264 Note that it should never be the case that we have both
2265 candidates added here, and for regular member functions
2266 below. */
2267 if (tsk == tsk_template)
2269 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2270 current_template_parms))
2271 continue;
2272 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2273 TREE_TYPE (TREE_TYPE (fn))))
2274 continue;
2275 if (!compparms (fn_arg_types, decl_arg_types))
2276 continue;
2278 tree freq = get_constraints (fn);
2279 tree dreq = get_constraints (decl);
2280 if (!freq != !dreq)
2281 continue;
2282 if (freq)
2284 /* C++20 CA104: Substitute directly into the
2285 constraint-expression. */
2286 tree fargs = DECL_TI_ARGS (fn);
2287 tsubst_flags_t complain = tf_none;
2288 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2289 if (!cp_tree_equal (freq, dreq))
2290 continue;
2293 candidates = tree_cons (NULL_TREE, fn, candidates);
2294 continue;
2297 /* See whether this function might be a specialization of this
2298 template. Suppress access control because we might be trying
2299 to make this specialization a friend, and we have already done
2300 access control for the declaration of the specialization. */
2301 push_deferring_access_checks (dk_no_check);
2302 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2303 pop_deferring_access_checks ();
2305 if (!targs)
2306 /* We cannot deduce template arguments that when used to
2307 specialize TMPL will produce DECL. */
2308 continue;
2310 if (uses_template_parms (targs))
2311 /* We deduced something involving 'auto', which isn't a valid
2312 template argument. */
2313 continue;
2315 /* Save this template, and the arguments deduced. */
2316 templates = tree_cons (targs, fn, templates);
2318 else if (need_member_template)
2319 /* FN is an ordinary member function, and we need a
2320 specialization of a member template. */
2322 else if (TREE_CODE (fn) != FUNCTION_DECL)
2323 /* We can get IDENTIFIER_NODEs here in certain erroneous
2324 cases. */
2326 else if (!DECL_FUNCTION_MEMBER_P (fn))
2327 /* This is just an ordinary non-member function. Nothing can
2328 be a specialization of that. */
2330 else if (DECL_ARTIFICIAL (fn))
2331 /* Cannot specialize functions that are created implicitly. */
2333 else
2335 tree decl_arg_types;
2337 /* This is an ordinary member function. However, since
2338 we're here, we can assume its enclosing class is a
2339 template class. For example,
2341 template <typename T> struct S { void f(); };
2342 template <> void S<int>::f() {}
2344 Here, S<int>::f is a non-template, but S<int> is a
2345 template class. If FN has the same type as DECL, we
2346 might be in business. */
2348 if (!DECL_TEMPLATE_INFO (fn))
2349 /* Its enclosing class is an explicit specialization
2350 of a template class. This is not a candidate. */
2351 continue;
2353 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2354 TREE_TYPE (TREE_TYPE (fn))))
2355 /* The return types differ. */
2356 continue;
2358 /* Adjust the type of DECL in case FN is a static member. */
2359 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2360 if (DECL_STATIC_FUNCTION_P (fn)
2361 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2362 decl_arg_types = TREE_CHAIN (decl_arg_types);
2364 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2365 decl_arg_types))
2366 continue;
2368 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2369 && (type_memfn_rqual (TREE_TYPE (decl))
2370 != type_memfn_rqual (TREE_TYPE (fn))))
2371 continue;
2373 // If the deduced arguments do not satisfy the constraints,
2374 // this is not a candidate.
2375 if (flag_concepts && !constraints_satisfied_p (fn))
2376 continue;
2378 // Add the candidate.
2379 candidates = tree_cons (NULL_TREE, fn, candidates);
2383 if (templates && TREE_CHAIN (templates))
2385 /* We have:
2387 [temp.expl.spec]
2389 It is possible for a specialization with a given function
2390 signature to be instantiated from more than one function
2391 template. In such cases, explicit specification of the
2392 template arguments must be used to uniquely identify the
2393 function template specialization being specialized.
2395 Note that here, there's no suggestion that we're supposed to
2396 determine which of the candidate templates is most
2397 specialized. However, we, also have:
2399 [temp.func.order]
2401 Partial ordering of overloaded function template
2402 declarations is used in the following contexts to select
2403 the function template to which a function template
2404 specialization refers:
2406 -- when an explicit specialization refers to a function
2407 template.
2409 So, we do use the partial ordering rules, at least for now.
2410 This extension can only serve to make invalid programs valid,
2411 so it's safe. And, there is strong anecdotal evidence that
2412 the committee intended the partial ordering rules to apply;
2413 the EDG front end has that behavior, and John Spicer claims
2414 that the committee simply forgot to delete the wording in
2415 [temp.expl.spec]. */
2416 tree tmpl = most_specialized_instantiation (templates);
2417 if (tmpl != error_mark_node)
2419 templates = tmpl;
2420 TREE_CHAIN (templates) = NULL_TREE;
2424 // Concepts allows multiple declarations of member functions
2425 // with the same signature. Like above, we need to rely on
2426 // on the partial ordering of those candidates to determine which
2427 // is the best.
2428 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2430 if (tree cand = most_constrained_function (candidates))
2432 candidates = cand;
2433 TREE_CHAIN (cand) = NULL_TREE;
2437 if (templates == NULL_TREE && candidates == NULL_TREE)
2439 error ("template-id %qD for %q+D does not match any template "
2440 "declaration", template_id, decl);
2441 if (header_mismatch)
2442 inform (DECL_SOURCE_LOCATION (decl),
2443 "saw %d %<template<>%>, need %d for "
2444 "specializing a member function template",
2445 header_count, template_count + 1);
2446 print_candidates (orig_fns);
2447 return error_mark_node;
2449 else if ((templates && TREE_CHAIN (templates))
2450 || (candidates && TREE_CHAIN (candidates))
2451 || (templates && candidates))
2453 error ("ambiguous template specialization %qD for %q+D",
2454 template_id, decl);
2455 candidates = chainon (candidates, templates);
2456 print_candidates (candidates);
2457 return error_mark_node;
2460 /* We have one, and exactly one, match. */
2461 if (candidates)
2463 tree fn = TREE_VALUE (candidates);
2464 *targs_out = copy_node (DECL_TI_ARGS (fn));
2466 /* Propagate the candidate's constraints to the declaration. */
2467 if (tsk != tsk_template)
2468 set_constraints (decl, get_constraints (fn));
2470 /* DECL is a re-declaration or partial instantiation of a template
2471 function. */
2472 if (TREE_CODE (fn) == TEMPLATE_DECL)
2473 return fn;
2474 /* It was a specialization of an ordinary member function in a
2475 template class. */
2476 return DECL_TI_TEMPLATE (fn);
2479 /* It was a specialization of a template. */
2480 tree tmpl = TREE_VALUE (templates);
2481 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2483 /* Propagate the template's constraints to the declaration. */
2484 if (tsk != tsk_template)
2485 set_constraints (decl, get_constraints (tmpl));
2487 return tmpl;
2490 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2491 but with the default argument values filled in from those in the
2492 TMPL_TYPES. */
2494 static tree
2495 copy_default_args_to_explicit_spec_1 (tree spec_types,
2496 tree tmpl_types)
2498 tree new_spec_types;
2500 if (!spec_types)
2501 return NULL_TREE;
2503 if (spec_types == void_list_node)
2504 return void_list_node;
2506 /* Substitute into the rest of the list. */
2507 new_spec_types =
2508 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2509 TREE_CHAIN (tmpl_types));
2511 /* Add the default argument for this parameter. */
2512 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2513 TREE_VALUE (spec_types),
2514 new_spec_types);
2517 /* DECL is an explicit specialization. Replicate default arguments
2518 from the template it specializes. (That way, code like:
2520 template <class T> void f(T = 3);
2521 template <> void f(double);
2522 void g () { f (); }
2524 works, as required.) An alternative approach would be to look up
2525 the correct default arguments at the call-site, but this approach
2526 is consistent with how implicit instantiations are handled. */
2528 static void
2529 copy_default_args_to_explicit_spec (tree decl)
2531 tree tmpl;
2532 tree spec_types;
2533 tree tmpl_types;
2534 tree new_spec_types;
2535 tree old_type;
2536 tree new_type;
2537 tree t;
2538 tree object_type = NULL_TREE;
2539 tree in_charge = NULL_TREE;
2540 tree vtt = NULL_TREE;
2542 /* See if there's anything we need to do. */
2543 tmpl = DECL_TI_TEMPLATE (decl);
2544 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2545 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2546 if (TREE_PURPOSE (t))
2547 break;
2548 if (!t)
2549 return;
2551 old_type = TREE_TYPE (decl);
2552 spec_types = TYPE_ARG_TYPES (old_type);
2554 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2556 /* Remove the this pointer, but remember the object's type for
2557 CV quals. */
2558 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2559 spec_types = TREE_CHAIN (spec_types);
2560 tmpl_types = TREE_CHAIN (tmpl_types);
2562 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2564 /* DECL may contain more parameters than TMPL due to the extra
2565 in-charge parameter in constructors and destructors. */
2566 in_charge = spec_types;
2567 spec_types = TREE_CHAIN (spec_types);
2569 if (DECL_HAS_VTT_PARM_P (decl))
2571 vtt = spec_types;
2572 spec_types = TREE_CHAIN (spec_types);
2576 /* Compute the merged default arguments. */
2577 new_spec_types =
2578 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2580 /* Compute the new FUNCTION_TYPE. */
2581 if (object_type)
2583 if (vtt)
2584 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2585 TREE_VALUE (vtt),
2586 new_spec_types);
2588 if (in_charge)
2589 /* Put the in-charge parameter back. */
2590 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2591 TREE_VALUE (in_charge),
2592 new_spec_types);
2594 new_type = build_method_type_directly (object_type,
2595 TREE_TYPE (old_type),
2596 new_spec_types);
2598 else
2599 new_type = build_function_type (TREE_TYPE (old_type),
2600 new_spec_types);
2601 new_type = cp_build_type_attribute_variant (new_type,
2602 TYPE_ATTRIBUTES (old_type));
2603 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2605 TREE_TYPE (decl) = new_type;
2608 /* Return the number of template headers we expect to see for a definition
2609 or specialization of CTYPE or one of its non-template members. */
2612 num_template_headers_for_class (tree ctype)
2614 int num_templates = 0;
2616 while (ctype && CLASS_TYPE_P (ctype))
2618 /* You're supposed to have one `template <...>' for every
2619 template class, but you don't need one for a full
2620 specialization. For example:
2622 template <class T> struct S{};
2623 template <> struct S<int> { void f(); };
2624 void S<int>::f () {}
2626 is correct; there shouldn't be a `template <>' for the
2627 definition of `S<int>::f'. */
2628 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2629 /* If CTYPE does not have template information of any
2630 kind, then it is not a template, nor is it nested
2631 within a template. */
2632 break;
2633 if (explicit_class_specialization_p (ctype))
2634 break;
2635 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2636 ++num_templates;
2638 ctype = TYPE_CONTEXT (ctype);
2641 return num_templates;
2644 /* Do a simple sanity check on the template headers that precede the
2645 variable declaration DECL. */
2647 void
2648 check_template_variable (tree decl)
2650 tree ctx = CP_DECL_CONTEXT (decl);
2651 int wanted = num_template_headers_for_class (ctx);
2652 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2653 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2655 if (cxx_dialect < cxx14)
2656 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2657 "variable templates only available with "
2658 "%<-std=c++14%> or %<-std=gnu++14%>");
2660 // Namespace-scope variable templates should have a template header.
2661 ++wanted;
2663 if (template_header_count > wanted)
2665 auto_diagnostic_group d;
2666 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2667 "too many template headers for %qD "
2668 "(should be %d)",
2669 decl, wanted);
2670 if (warned && CLASS_TYPE_P (ctx)
2671 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2672 inform (DECL_SOURCE_LOCATION (decl),
2673 "members of an explicitly specialized class are defined "
2674 "without a template header");
2678 /* An explicit specialization whose declarator-id or class-head-name is not
2679 qualified shall be declared in the nearest enclosing namespace of the
2680 template, or, if the namespace is inline (7.3.1), any namespace from its
2681 enclosing namespace set.
2683 If the name declared in the explicit instantiation is an unqualified name,
2684 the explicit instantiation shall appear in the namespace where its template
2685 is declared or, if that namespace is inline (7.3.1), any namespace from its
2686 enclosing namespace set. */
2688 void
2689 check_unqualified_spec_or_inst (tree t, location_t loc)
2691 tree tmpl = most_general_template (t);
2692 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2693 && !is_nested_namespace (current_namespace,
2694 CP_DECL_CONTEXT (tmpl), true))
2696 if (processing_specialization)
2697 permerror (loc, "explicit specialization of %qD outside its "
2698 "namespace must use a nested-name-specifier", tmpl);
2699 else if (processing_explicit_instantiation
2700 && cxx_dialect >= cxx11)
2701 /* This was allowed in C++98, so only pedwarn. */
2702 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2703 "outside its namespace must use a nested-name-"
2704 "specifier", tmpl);
2708 /* Warn for a template specialization SPEC that is missing some of a set
2709 of function or type attributes that the template TEMPL is declared with.
2710 ATTRLIST is a list of additional attributes that SPEC should be taken
2711 to ultimately be declared with. */
2713 static void
2714 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2716 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2717 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2719 /* Avoid warning if the difference between the primary and
2720 the specialization is not in one of the attributes below. */
2721 const char* const blacklist[] = {
2722 "alloc_align", "alloc_size", "assume_aligned", "format",
2723 "format_arg", "malloc", "nonnull", NULL
2726 /* Put together a list of the black listed attributes that the primary
2727 template is declared with that the specialization is not, in case
2728 it's not apparent from the most recent declaration of the primary. */
2729 pretty_printer str;
2730 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2731 blacklist, &str);
2733 if (!nattrs)
2734 return;
2736 auto_diagnostic_group d;
2737 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2738 "explicit specialization %q#D may be missing attributes",
2739 spec))
2740 inform (DECL_SOURCE_LOCATION (tmpl),
2741 nattrs > 1
2742 ? G_("missing primary template attributes %s")
2743 : G_("missing primary template attribute %s"),
2744 pp_formatted_text (&str));
2747 /* Check to see if the function just declared, as indicated in
2748 DECLARATOR, and in DECL, is a specialization of a function
2749 template. We may also discover that the declaration is an explicit
2750 instantiation at this point.
2752 Returns DECL, or an equivalent declaration that should be used
2753 instead if all goes well. Issues an error message if something is
2754 amiss. Returns error_mark_node if the error is not easily
2755 recoverable.
2757 FLAGS is a bitmask consisting of the following flags:
2759 2: The function has a definition.
2760 4: The function is a friend.
2762 The TEMPLATE_COUNT is the number of references to qualifying
2763 template classes that appeared in the name of the function. For
2764 example, in
2766 template <class T> struct S { void f(); };
2767 void S<int>::f();
2769 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2770 classes are not counted in the TEMPLATE_COUNT, so that in
2772 template <class T> struct S {};
2773 template <> struct S<int> { void f(); }
2774 template <> void S<int>::f();
2776 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2777 invalid; there should be no template <>.)
2779 If the function is a specialization, it is marked as such via
2780 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2781 is set up correctly, and it is added to the list of specializations
2782 for that template. */
2784 tree
2785 check_explicit_specialization (tree declarator,
2786 tree decl,
2787 int template_count,
2788 int flags,
2789 tree attrlist)
2791 int have_def = flags & 2;
2792 int is_friend = flags & 4;
2793 bool is_concept = flags & 8;
2794 int specialization = 0;
2795 int explicit_instantiation = 0;
2796 int member_specialization = 0;
2797 tree ctype = DECL_CLASS_CONTEXT (decl);
2798 tree dname = DECL_NAME (decl);
2799 tmpl_spec_kind tsk;
2801 if (is_friend)
2803 if (!processing_specialization)
2804 tsk = tsk_none;
2805 else
2806 tsk = tsk_excessive_parms;
2808 else
2809 tsk = current_tmpl_spec_kind (template_count);
2811 switch (tsk)
2813 case tsk_none:
2814 if (processing_specialization && !VAR_P (decl))
2816 specialization = 1;
2817 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2819 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2820 || (DECL_LANG_SPECIFIC (decl)
2821 && DECL_IMPLICIT_INSTANTIATION (decl)))
2823 if (is_friend)
2824 /* This could be something like:
2826 template <class T> void f(T);
2827 class S { friend void f<>(int); } */
2828 specialization = 1;
2829 else
2831 /* This case handles bogus declarations like template <>
2832 template <class T> void f<int>(); */
2834 error_at (cp_expr_loc_or_input_loc (declarator),
2835 "template-id %qE in declaration of primary template",
2836 declarator);
2837 return decl;
2840 break;
2842 case tsk_invalid_member_spec:
2843 /* The error has already been reported in
2844 check_specialization_scope. */
2845 return error_mark_node;
2847 case tsk_invalid_expl_inst:
2848 error ("template parameter list used in explicit instantiation");
2850 /* Fall through. */
2852 case tsk_expl_inst:
2853 if (have_def)
2854 error ("definition provided for explicit instantiation");
2856 explicit_instantiation = 1;
2857 break;
2859 case tsk_excessive_parms:
2860 case tsk_insufficient_parms:
2861 if (tsk == tsk_excessive_parms)
2862 error ("too many template parameter lists in declaration of %qD",
2863 decl);
2864 else if (template_header_count)
2865 error("too few template parameter lists in declaration of %qD", decl);
2866 else
2867 error("explicit specialization of %qD must be introduced by "
2868 "%<template <>%>", decl);
2870 /* Fall through. */
2871 case tsk_expl_spec:
2872 if (is_concept)
2873 error ("explicit specialization declared %<concept%>");
2875 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2876 /* In cases like template<> constexpr bool v = true;
2877 We'll give an error in check_template_variable. */
2878 break;
2880 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2881 if (ctype)
2882 member_specialization = 1;
2883 else
2884 specialization = 1;
2885 break;
2887 case tsk_template:
2888 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2890 /* This case handles bogus declarations like template <>
2891 template <class T> void f<int>(); */
2893 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2894 error_at (cp_expr_loc_or_input_loc (declarator),
2895 "template-id %qE in declaration of primary template",
2896 declarator);
2897 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2899 /* Partial specialization of variable template. */
2900 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2901 specialization = 1;
2902 goto ok;
2904 else if (cxx_dialect < cxx14)
2905 error_at (cp_expr_loc_or_input_loc (declarator),
2906 "non-type partial specialization %qE "
2907 "is not allowed", declarator);
2908 else
2909 error_at (cp_expr_loc_or_input_loc (declarator),
2910 "non-class, non-variable partial specialization %qE "
2911 "is not allowed", declarator);
2912 return decl;
2913 ok:;
2916 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2917 /* This is a specialization of a member template, without
2918 specialization the containing class. Something like:
2920 template <class T> struct S {
2921 template <class U> void f (U);
2923 template <> template <class U> void S<int>::f(U) {}
2925 That's a specialization -- but of the entire template. */
2926 specialization = 1;
2927 break;
2929 default:
2930 gcc_unreachable ();
2933 if ((specialization || member_specialization)
2934 /* This doesn't apply to variable templates. */
2935 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2937 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2938 for (; t; t = TREE_CHAIN (t))
2939 if (TREE_PURPOSE (t))
2941 permerror (input_location,
2942 "default argument specified in explicit specialization");
2943 break;
2947 if (specialization || member_specialization || explicit_instantiation)
2949 tree tmpl = NULL_TREE;
2950 tree targs = NULL_TREE;
2951 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2952 bool found_hidden = false;
2954 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2955 if (!was_template_id)
2957 tree fns;
2959 gcc_assert (identifier_p (declarator));
2960 if (ctype)
2961 fns = dname;
2962 else
2964 /* If there is no class context, the explicit instantiation
2965 must be at namespace scope. */
2966 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2968 /* Find the namespace binding, using the declaration
2969 context. */
2970 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2971 LOOK_want::NORMAL, true);
2972 if (fns == error_mark_node)
2974 /* If lookup fails, look for a friend declaration so we can
2975 give a better diagnostic. */
2976 fns = (lookup_qualified_name
2977 (CP_DECL_CONTEXT (decl), dname,
2978 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
2979 /*complain*/true));
2980 found_hidden = true;
2983 if (fns == error_mark_node || !is_overloaded_fn (fns))
2985 error ("%qD is not a template function", dname);
2986 fns = error_mark_node;
2990 declarator = lookup_template_function (fns, NULL_TREE);
2993 if (declarator == error_mark_node)
2994 return error_mark_node;
2996 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2998 if (!explicit_instantiation)
2999 /* A specialization in class scope. This is invalid,
3000 but the error will already have been flagged by
3001 check_specialization_scope. */
3002 return error_mark_node;
3003 else
3005 /* It's not valid to write an explicit instantiation in
3006 class scope, e.g.:
3008 class C { template void f(); }
3010 This case is caught by the parser. However, on
3011 something like:
3013 template class C { void f(); };
3015 (which is invalid) we can get here. The error will be
3016 issued later. */
3020 return decl;
3022 else if (ctype != NULL_TREE
3023 && (identifier_p (TREE_OPERAND (declarator, 0))))
3025 // We'll match variable templates in start_decl.
3026 if (VAR_P (decl))
3027 return decl;
3029 /* Find the list of functions in ctype that have the same
3030 name as the declared function. */
3031 tree name = TREE_OPERAND (declarator, 0);
3033 if (constructor_name_p (name, ctype))
3035 if (DECL_CONSTRUCTOR_P (decl)
3036 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3037 : !CLASSTYPE_DESTRUCTOR (ctype))
3039 /* From [temp.expl.spec]:
3041 If such an explicit specialization for the member
3042 of a class template names an implicitly-declared
3043 special member function (clause _special_), the
3044 program is ill-formed.
3046 Similar language is found in [temp.explicit]. */
3047 error ("specialization of implicitly-declared special member function");
3048 return error_mark_node;
3051 name = DECL_NAME (decl);
3054 /* For a type-conversion operator, We might be looking for
3055 `operator int' which will be a specialization of
3056 `operator T'. Grab all the conversion operators, and
3057 then select from them. */
3058 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3059 ? conv_op_identifier : name);
3061 if (fns == NULL_TREE)
3063 error ("no member function %qD declared in %qT", name, ctype);
3064 return error_mark_node;
3066 else
3067 TREE_OPERAND (declarator, 0) = fns;
3070 /* Figure out what exactly is being specialized at this point.
3071 Note that for an explicit instantiation, even one for a
3072 member function, we cannot tell a priori whether the
3073 instantiation is for a member template, or just a member
3074 function of a template class. Even if a member template is
3075 being instantiated, the member template arguments may be
3076 elided if they can be deduced from the rest of the
3077 declaration. */
3078 tmpl = determine_specialization (declarator, decl,
3079 &targs,
3080 member_specialization,
3081 template_count,
3082 tsk);
3084 if (!tmpl || tmpl == error_mark_node)
3085 /* We couldn't figure out what this declaration was
3086 specializing. */
3087 return error_mark_node;
3088 else
3090 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3092 auto_diagnostic_group d;
3093 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3094 "friend declaration %qD is not visible to "
3095 "explicit specialization", tmpl))
3096 inform (DECL_SOURCE_LOCATION (tmpl),
3097 "friend declaration here");
3100 if (!ctype && !is_friend
3101 && CP_DECL_CONTEXT (decl) == current_namespace)
3102 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3104 tree gen_tmpl = most_general_template (tmpl);
3106 if (explicit_instantiation)
3108 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3109 is done by do_decl_instantiation later. */
3111 int arg_depth = TMPL_ARGS_DEPTH (targs);
3112 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3114 if (arg_depth > parm_depth)
3116 /* If TMPL is not the most general template (for
3117 example, if TMPL is a friend template that is
3118 injected into namespace scope), then there will
3119 be too many levels of TARGS. Remove some of them
3120 here. */
3121 int i;
3122 tree new_targs;
3124 new_targs = make_tree_vec (parm_depth);
3125 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3126 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3127 = TREE_VEC_ELT (targs, i);
3128 targs = new_targs;
3131 return instantiate_template (tmpl, targs, tf_error);
3134 /* If we thought that the DECL was a member function, but it
3135 turns out to be specializing a static member function,
3136 make DECL a static member function as well. */
3137 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3138 && DECL_STATIC_FUNCTION_P (tmpl)
3139 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3140 revert_static_member_fn (decl);
3142 /* If this is a specialization of a member template of a
3143 template class, we want to return the TEMPLATE_DECL, not
3144 the specialization of it. */
3145 if (tsk == tsk_template && !was_template_id)
3147 tree result = DECL_TEMPLATE_RESULT (tmpl);
3148 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3149 DECL_INITIAL (result) = NULL_TREE;
3150 if (have_def)
3152 tree parm;
3153 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3154 DECL_SOURCE_LOCATION (result)
3155 = DECL_SOURCE_LOCATION (decl);
3156 /* We want to use the argument list specified in the
3157 definition, not in the original declaration. */
3158 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3159 for (parm = DECL_ARGUMENTS (result); parm;
3160 parm = DECL_CHAIN (parm))
3161 DECL_CONTEXT (parm) = result;
3163 decl = register_specialization (tmpl, gen_tmpl, targs,
3164 is_friend, 0);
3165 remove_contract_attributes (result);
3166 return decl;
3169 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3170 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3172 if (was_template_id)
3173 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3175 /* Inherit default function arguments from the template
3176 DECL is specializing. */
3177 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3178 copy_default_args_to_explicit_spec (decl);
3180 /* This specialization has the same protection as the
3181 template it specializes. */
3182 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3183 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3185 /* 7.1.1-1 [dcl.stc]
3187 A storage-class-specifier shall not be specified in an
3188 explicit specialization...
3190 The parser rejects these, so unless action is taken here,
3191 explicit function specializations will always appear with
3192 global linkage.
3194 The action recommended by the C++ CWG in response to C++
3195 defect report 605 is to make the storage class and linkage
3196 of the explicit specialization match the templated function:
3198 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3200 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3202 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3203 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3205 /* A concept cannot be specialized. */
3206 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3208 error ("explicit specialization of function concept %qD",
3209 gen_tmpl);
3210 return error_mark_node;
3213 /* This specialization has the same linkage and visibility as
3214 the function template it specializes. */
3215 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3216 if (! TREE_PUBLIC (decl))
3218 DECL_INTERFACE_KNOWN (decl) = 1;
3219 DECL_NOT_REALLY_EXTERN (decl) = 1;
3221 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3222 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3224 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3225 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3229 /* If DECL is a friend declaration, declared using an
3230 unqualified name, the namespace associated with DECL may
3231 have been set incorrectly. For example, in:
3233 template <typename T> void f(T);
3234 namespace N {
3235 struct S { friend void f<int>(int); }
3238 we will have set the DECL_CONTEXT for the friend
3239 declaration to N, rather than to the global namespace. */
3240 if (DECL_NAMESPACE_SCOPE_P (decl))
3241 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3243 if (is_friend && !have_def)
3244 /* This is not really a declaration of a specialization.
3245 It's just the name of an instantiation. But, it's not
3246 a request for an instantiation, either. */
3247 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3248 else if (TREE_CODE (decl) == FUNCTION_DECL)
3249 /* A specialization is not necessarily COMDAT. */
3250 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3251 && DECL_DECLARED_INLINE_P (decl));
3252 else if (VAR_P (decl))
3253 DECL_COMDAT (decl) = false;
3255 /* If this is a full specialization, register it so that we can find
3256 it again. Partial specializations will be registered in
3257 process_partial_specialization. */
3258 if (!processing_template_decl)
3260 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3262 decl = register_specialization (decl, gen_tmpl, targs,
3263 is_friend, 0);
3266 /* If this is a specialization, splice any contracts that may have
3267 been inherited from the template, removing them. */
3268 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3269 remove_contract_attributes (decl);
3271 /* A 'structor should already have clones. */
3272 gcc_assert (decl == error_mark_node
3273 || variable_template_p (tmpl)
3274 || !(DECL_CONSTRUCTOR_P (decl)
3275 || DECL_DESTRUCTOR_P (decl))
3276 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3280 return decl;
3283 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3284 parameters. These are represented in the same format used for
3285 DECL_TEMPLATE_PARMS. */
3288 comp_template_parms (const_tree parms1, const_tree parms2)
3290 const_tree p1;
3291 const_tree p2;
3293 if (parms1 == parms2)
3294 return 1;
3296 for (p1 = parms1, p2 = parms2;
3297 p1 != NULL_TREE && p2 != NULL_TREE;
3298 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3300 tree t1 = TREE_VALUE (p1);
3301 tree t2 = TREE_VALUE (p2);
3302 int i;
3304 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3305 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3307 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3308 return 0;
3310 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3312 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3313 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3315 /* If either of the template parameters are invalid, assume
3316 they match for the sake of error recovery. */
3317 if (error_operand_p (parm1) || error_operand_p (parm2))
3318 return 1;
3320 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3321 return 0;
3323 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3324 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3325 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3326 continue;
3327 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3328 return 0;
3332 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3333 /* One set of parameters has more parameters lists than the
3334 other. */
3335 return 0;
3337 return 1;
3340 /* Returns true if two template parameters are declared with
3341 equivalent constraints. */
3343 static bool
3344 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3346 tree req1 = TREE_TYPE (parm1);
3347 tree req2 = TREE_TYPE (parm2);
3348 if (!req1 != !req2)
3349 return false;
3350 if (req1)
3351 return cp_tree_equal (req1, req2);
3352 return true;
3355 /* Returns true when two template parameters are equivalent. */
3357 static bool
3358 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3360 tree decl1 = TREE_VALUE (parm1);
3361 tree decl2 = TREE_VALUE (parm2);
3363 /* If either of the template parameters are invalid, assume
3364 they match for the sake of error recovery. */
3365 if (error_operand_p (decl1) || error_operand_p (decl2))
3366 return true;
3368 /* ... they declare parameters of the same kind. */
3369 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3370 return false;
3372 /* ... one parameter was introduced by a parameter declaration, then
3373 both are. This case arises as a result of eagerly rewriting declarations
3374 during parsing. */
3375 if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3376 return false;
3378 /* ... if either declares a pack, they both do. */
3379 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3380 return false;
3382 if (TREE_CODE (decl1) == PARM_DECL)
3384 /* ... if they declare non-type parameters, the types are equivalent. */
3385 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3386 return false;
3388 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3390 /* ... if they declare template template parameters, their template
3391 parameter lists are equivalent. */
3392 if (!template_heads_equivalent_p (decl1, decl2))
3393 return false;
3396 /* ... if they are declared with a qualified-concept name, they both
3397 are, and those names are equivalent. */
3398 return template_parameter_constraints_equivalent_p (parm1, parm2);
3401 /* Returns true if two template parameters lists are equivalent.
3402 Two template parameter lists are equivalent if they have the
3403 same length and their corresponding parameters are equivalent.
3405 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3406 data structure returned by DECL_TEMPLATE_PARMS.
3408 This is generally the same implementation as comp_template_parms
3409 except that it also the concept names and arguments used to
3410 introduce parameters. */
3412 static bool
3413 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3415 if (parms1 == parms2)
3416 return true;
3418 const_tree p1 = parms1;
3419 const_tree p2 = parms2;
3420 while (p1 != NULL_TREE && p2 != NULL_TREE)
3422 tree list1 = TREE_VALUE (p1);
3423 tree list2 = TREE_VALUE (p2);
3425 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3426 return 0;
3428 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3430 tree parm1 = TREE_VEC_ELT (list1, i);
3431 tree parm2 = TREE_VEC_ELT (list2, i);
3432 if (!template_parameters_equivalent_p (parm1, parm2))
3433 return false;
3436 p1 = TREE_CHAIN (p1);
3437 p2 = TREE_CHAIN (p2);
3440 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3441 return false;
3443 return true;
3446 /* Return true if the requires-clause of the template parameter lists are
3447 equivalent and false otherwise. */
3448 static bool
3449 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3451 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3452 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3453 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3454 return false;
3455 if (!cp_tree_equal (req1, req2))
3456 return false;
3457 return true;
3460 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3461 Two template heads are equivalent if their template parameter
3462 lists are equivalent and their requires clauses are equivalent.
3464 In pre-C++20, this is equivalent to calling comp_template_parms
3465 for the template parameters of TMPL1 and TMPL2. */
3467 bool
3468 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3470 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3471 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3473 /* Don't change the matching rules for pre-C++20. */
3474 if (cxx_dialect < cxx20)
3475 return comp_template_parms (parms1, parms2);
3477 /* ... have the same number of template parameters, and their
3478 corresponding parameters are equivalent. */
3479 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3480 return false;
3482 /* ... if either has a requires-clause, they both do and their
3483 corresponding constraint-expressions are equivalent. */
3484 return template_requirements_equivalent_p (parms1, parms2);
3487 /* Determine whether PARM is a parameter pack. */
3489 bool
3490 template_parameter_pack_p (const_tree parm)
3492 /* Determine if we have a non-type template parameter pack. */
3493 if (TREE_CODE (parm) == PARM_DECL)
3494 return (DECL_TEMPLATE_PARM_P (parm)
3495 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3496 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3497 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3499 /* If this is a list of template parameters, we could get a
3500 TYPE_DECL or a TEMPLATE_DECL. */
3501 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3502 parm = TREE_TYPE (parm);
3504 /* Otherwise it must be a type template parameter. */
3505 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3506 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3507 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3510 /* Determine if T is a function parameter pack. */
3512 bool
3513 function_parameter_pack_p (const_tree t)
3515 if (t && TREE_CODE (t) == PARM_DECL)
3516 return DECL_PACK_P (t);
3517 return false;
3520 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3521 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3523 tree
3524 get_function_template_decl (const_tree primary_func_tmpl_inst)
3526 if (! primary_func_tmpl_inst
3527 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3528 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3529 return NULL;
3531 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3534 /* Return true iff the function parameter PARAM_DECL was expanded
3535 from the function parameter pack PACK. */
3537 bool
3538 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3540 if (DECL_ARTIFICIAL (param_decl)
3541 || !function_parameter_pack_p (pack))
3542 return false;
3544 /* The parameter pack and its pack arguments have the same
3545 DECL_PARM_INDEX. */
3546 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3549 /* Determine whether ARGS describes a variadic template args list,
3550 i.e., one that is terminated by a template argument pack. */
3552 static bool
3553 template_args_variadic_p (tree args)
3555 int nargs;
3556 tree last_parm;
3558 if (args == NULL_TREE)
3559 return false;
3561 args = INNERMOST_TEMPLATE_ARGS (args);
3562 nargs = TREE_VEC_LENGTH (args);
3564 if (nargs == 0)
3565 return false;
3567 last_parm = TREE_VEC_ELT (args, nargs - 1);
3569 return ARGUMENT_PACK_P (last_parm);
3572 /* Generate a new name for the parameter pack name NAME (an
3573 IDENTIFIER_NODE) that incorporates its */
3575 static tree
3576 make_ith_pack_parameter_name (tree name, int i)
3578 /* Munge the name to include the parameter index. */
3579 #define NUMBUF_LEN 128
3580 char numbuf[NUMBUF_LEN];
3581 char* newname;
3582 int newname_len;
3584 if (name == NULL_TREE)
3585 return name;
3586 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3587 newname_len = IDENTIFIER_LENGTH (name)
3588 + strlen (numbuf) + 2;
3589 newname = (char*)alloca (newname_len);
3590 snprintf (newname, newname_len,
3591 "%s#%i", IDENTIFIER_POINTER (name), i);
3592 return get_identifier (newname);
3595 /* Return true if T is a primary function, class or alias template
3596 specialization, not including the template pattern. */
3598 bool
3599 primary_template_specialization_p (const_tree t)
3601 if (!t)
3602 return false;
3604 if (VAR_OR_FUNCTION_DECL_P (t))
3605 return (DECL_LANG_SPECIFIC (t)
3606 && DECL_USE_TEMPLATE (t)
3607 && DECL_TEMPLATE_INFO (t)
3608 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3609 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3610 return (CLASSTYPE_TEMPLATE_INFO (t)
3611 && CLASSTYPE_USE_TEMPLATE (t)
3612 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3613 else if (alias_template_specialization_p (t, nt_transparent))
3614 return true;
3615 return false;
3618 /* Return true if PARM is a template template parameter. */
3620 bool
3621 template_template_parameter_p (const_tree parm)
3623 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3626 /* Return true iff PARM is a DECL representing a type template
3627 parameter. */
3629 bool
3630 template_type_parameter_p (const_tree parm)
3632 return (parm
3633 && (TREE_CODE (parm) == TYPE_DECL
3634 || TREE_CODE (parm) == TEMPLATE_DECL)
3635 && DECL_TEMPLATE_PARM_P (parm));
3638 /* Return the template parameters of T if T is a
3639 primary template instantiation, NULL otherwise. */
3641 tree
3642 get_primary_template_innermost_parameters (const_tree t)
3644 tree parms = NULL, template_info = NULL;
3646 if ((template_info = get_template_info (t))
3647 && primary_template_specialization_p (t))
3648 parms = INNERMOST_TEMPLATE_PARMS
3649 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3651 return parms;
3654 /* Returns the template arguments of T if T is a template instantiation,
3655 NULL otherwise. */
3657 tree
3658 get_template_innermost_arguments (const_tree t)
3660 tree args = NULL, template_info = NULL;
3662 if ((template_info = get_template_info (t))
3663 && TI_ARGS (template_info))
3664 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3666 return args;
3669 /* Return the argument pack elements of T if T is a template argument pack,
3670 NULL otherwise. */
3672 tree
3673 get_template_argument_pack_elems (const_tree t)
3675 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3676 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3677 return NULL;
3679 return ARGUMENT_PACK_ARGS (t);
3682 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3683 ARGUMENT_PACK_SELECT represents. */
3685 static tree
3686 argument_pack_select_arg (tree t)
3688 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3689 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3691 /* If the selected argument is an expansion E, that most likely means we were
3692 called from gen_elem_of_pack_expansion_instantiation during the
3693 substituting of an argument pack (of which the Ith element is a pack
3694 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3695 In this case, the Ith element resulting from this substituting is going to
3696 be a pack expansion, which pattern is the pattern of E. Let's return the
3697 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3698 resulting pack expansion from it. */
3699 if (PACK_EXPANSION_P (arg))
3701 /* Make sure we aren't throwing away arg info. */
3702 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3703 arg = PACK_EXPANSION_PATTERN (arg);
3706 return arg;
3709 /* Return a modification of ARGS that's suitable for preserving inside a hash
3710 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3711 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3713 static tree
3714 preserve_args (tree args, bool cow_p = true)
3716 if (!args)
3717 return NULL_TREE;
3719 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3721 tree t = TREE_VEC_ELT (args, i);
3722 tree r;
3723 if (!t)
3724 r = NULL_TREE;
3725 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3726 r = argument_pack_select_arg (t);
3727 else if (TREE_CODE (t) == TREE_VEC)
3728 r = preserve_args (t, cow_p);
3729 else
3730 r = t;
3731 if (r != t)
3733 if (cow_p)
3735 args = copy_template_args (args);
3736 cow_p = false;
3738 TREE_VEC_ELT (args, i) = r;
3742 return args;
3745 /* True iff FN is a function representing a built-in variadic parameter
3746 pack. */
3748 bool
3749 builtin_pack_fn_p (tree fn)
3751 if (!fn
3752 || TREE_CODE (fn) != FUNCTION_DECL
3753 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3754 return false;
3756 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3757 return true;
3759 return false;
3762 /* True iff CALL is a call to a function representing a built-in variadic
3763 parameter pack. */
3765 static bool
3766 builtin_pack_call_p (tree call)
3768 if (TREE_CODE (call) != CALL_EXPR)
3769 return false;
3770 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3773 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3775 static tree
3776 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3777 tree in_decl)
3779 tree ohi = CALL_EXPR_ARG (call, 0);
3780 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl);
3782 if (instantiation_dependent_expression_p (hi))
3784 if (hi != ohi)
3786 call = copy_node (call);
3787 CALL_EXPR_ARG (call, 0) = hi;
3789 tree ex = make_pack_expansion (call, complain);
3790 tree vec = make_tree_vec (1);
3791 TREE_VEC_ELT (vec, 0) = ex;
3792 return vec;
3794 else
3796 hi = instantiate_non_dependent_expr (hi, complain);
3797 hi = cxx_constant_value (hi, complain);
3798 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3800 /* Calculate the largest value of len that won't make the size of the vec
3801 overflow an int. The compiler will exceed resource limits long before
3802 this, but it seems a decent place to diagnose. */
3803 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3805 if (len < 0 || len > max)
3807 if ((complain & tf_error)
3808 && hi != error_mark_node)
3809 error ("argument to %<__integer_pack%> must be between 0 and %d",
3810 max);
3811 return error_mark_node;
3814 tree vec = make_tree_vec (len);
3816 for (int i = 0; i < len; ++i)
3817 TREE_VEC_ELT (vec, i) = size_int (i);
3819 return vec;
3823 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3824 CALL. */
3826 static tree
3827 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3828 tree in_decl)
3830 if (!builtin_pack_call_p (call))
3831 return NULL_TREE;
3833 tree fn = CALL_EXPR_FN (call);
3835 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3836 return expand_integer_pack (call, args, complain, in_decl);
3838 return NULL_TREE;
3841 /* Return true if the tree T has the extra args mechanism for
3842 avoiding partial instantiation. */
3844 static bool
3845 has_extra_args_mechanism_p (const_tree t)
3847 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3848 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3849 || (TREE_CODE (t) == IF_STMT
3850 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3853 /* Structure used to track the progress of find_parameter_packs_r. */
3854 struct find_parameter_pack_data
3856 /* TREE_LIST that will contain all of the parameter packs found by
3857 the traversal. */
3858 tree* parameter_packs;
3860 /* Set of AST nodes that have been visited by the traversal. */
3861 hash_set<tree> *visited;
3863 /* True iff we're making a type pack expansion. */
3864 bool type_pack_expansion_p;
3866 /* True iff we found a subtree that has the extra args mechanism. */
3867 bool found_extra_args_tree_p = false;
3870 /* Identifies all of the argument packs that occur in a template
3871 argument and appends them to the TREE_LIST inside DATA, which is a
3872 find_parameter_pack_data structure. This is a subroutine of
3873 make_pack_expansion and uses_parameter_packs. */
3874 static tree
3875 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3877 tree t = *tp;
3878 struct find_parameter_pack_data* ppd =
3879 (struct find_parameter_pack_data*)data;
3880 bool parameter_pack_p = false;
3882 #define WALK_SUBTREE(NODE) \
3883 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3884 ppd, ppd->visited) \
3886 /* Don't look through typedefs; we are interested in whether a
3887 parameter pack is actually written in the expression/type we're
3888 looking at, not the target type. */
3889 if (TYPE_P (t) && typedef_variant_p (t))
3891 /* But do look at arguments for an alias template. */
3892 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3893 cp_walk_tree (&TI_ARGS (tinfo),
3894 &find_parameter_packs_r,
3895 ppd, ppd->visited);
3896 *walk_subtrees = 0;
3897 return NULL_TREE;
3900 /* Identify whether this is a parameter pack or not. */
3901 switch (TREE_CODE (t))
3903 case TEMPLATE_PARM_INDEX:
3904 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3905 parameter_pack_p = true;
3906 break;
3908 case TEMPLATE_TYPE_PARM:
3909 t = TYPE_MAIN_VARIANT (t);
3910 /* FALLTHRU */
3911 case TEMPLATE_TEMPLATE_PARM:
3912 /* If the placeholder appears in the decl-specifier-seq of a function
3913 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3914 is a pack expansion, the invented template parameter is a template
3915 parameter pack. */
3916 if (ppd->type_pack_expansion_p && is_auto (t))
3917 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3918 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3919 parameter_pack_p = true;
3920 break;
3922 case FIELD_DECL:
3923 case PARM_DECL:
3924 if (DECL_PACK_P (t))
3926 /* We don't want to walk into the type of a PARM_DECL,
3927 because we don't want to see the type parameter pack. */
3928 *walk_subtrees = 0;
3929 parameter_pack_p = true;
3931 break;
3933 case VAR_DECL:
3934 if (DECL_PACK_P (t))
3936 /* We don't want to walk into the type of a variadic capture proxy,
3937 because we don't want to see the type parameter pack. */
3938 *walk_subtrees = 0;
3939 parameter_pack_p = true;
3941 else if (variable_template_specialization_p (t))
3943 cp_walk_tree (&DECL_TI_ARGS (t),
3944 find_parameter_packs_r,
3945 ppd, ppd->visited);
3946 *walk_subtrees = 0;
3948 break;
3950 case CALL_EXPR:
3951 if (builtin_pack_call_p (t))
3952 parameter_pack_p = true;
3953 break;
3955 case BASES:
3956 parameter_pack_p = true;
3957 break;
3958 default:
3959 /* Not a parameter pack. */
3960 break;
3963 if (parameter_pack_p)
3965 /* Add this parameter pack to the list. */
3966 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3969 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3970 ppd->found_extra_args_tree_p = true;
3972 if (TYPE_P (t))
3973 cp_walk_tree (&TYPE_CONTEXT (t),
3974 &find_parameter_packs_r, ppd, ppd->visited);
3976 /* This switch statement will return immediately if we don't find a
3977 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3978 switch (TREE_CODE (t))
3980 case BOUND_TEMPLATE_TEMPLATE_PARM:
3981 /* Check the template itself. */
3982 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3983 &find_parameter_packs_r, ppd, ppd->visited);
3984 return NULL_TREE;
3986 case DECL_EXPR:
3988 tree decl = DECL_EXPR_DECL (t);
3989 /* Ignore the declaration of a capture proxy for a parameter pack. */
3990 if (is_capture_proxy (decl))
3991 *walk_subtrees = 0;
3992 if (is_typedef_decl (decl))
3993 /* Since we stop at typedefs above, we need to look through them at
3994 the point of the DECL_EXPR. */
3995 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3996 &find_parameter_packs_r, ppd, ppd->visited);
3997 return NULL_TREE;
4000 case TEMPLATE_DECL:
4001 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4002 return NULL_TREE;
4003 cp_walk_tree (&TREE_TYPE (t),
4004 &find_parameter_packs_r, ppd, ppd->visited);
4005 return NULL_TREE;
4007 case TYPE_PACK_EXPANSION:
4008 case EXPR_PACK_EXPANSION:
4009 *walk_subtrees = 0;
4010 return NULL_TREE;
4012 case INTEGER_TYPE:
4013 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4014 ppd, ppd->visited);
4015 *walk_subtrees = 0;
4016 return NULL_TREE;
4018 case IDENTIFIER_NODE:
4019 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4020 ppd->visited);
4021 *walk_subtrees = 0;
4022 return NULL_TREE;
4024 case LAMBDA_EXPR:
4026 /* Since we defer implicit capture, look in the parms and body. */
4027 tree fn = lambda_function (t);
4028 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4029 ppd->visited);
4030 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4031 ppd->visited);
4032 return NULL_TREE;
4035 case DECLTYPE_TYPE:
4037 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4038 type_pack_expansion_p to false so that any placeholders
4039 within the expression don't get marked as parameter packs. */
4040 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4041 ppd->type_pack_expansion_p = false;
4042 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4043 ppd, ppd->visited);
4044 ppd->type_pack_expansion_p = type_pack_expansion_p;
4045 *walk_subtrees = 0;
4046 return NULL_TREE;
4049 case IF_STMT:
4050 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4051 ppd, ppd->visited);
4052 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4053 ppd, ppd->visited);
4054 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4055 ppd, ppd->visited);
4056 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4057 *walk_subtrees = 0;
4058 return NULL_TREE;
4060 case TAG_DEFN:
4061 t = TREE_TYPE (t);
4062 if (CLASS_TYPE_P (t))
4064 /* Local class, need to look through the whole definition.
4065 TYPE_BINFO might be unset for a partial instantiation. */
4066 if (TYPE_BINFO (t))
4067 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4068 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4069 ppd, ppd->visited);
4071 else
4072 /* Enum, look at the values. */
4073 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4074 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4075 &find_parameter_packs_r,
4076 ppd, ppd->visited);
4077 return NULL_TREE;
4079 case FUNCTION_TYPE:
4080 case METHOD_TYPE:
4081 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4082 break;
4084 default:
4085 return NULL_TREE;
4088 #undef WALK_SUBTREE
4090 return NULL_TREE;
4093 /* Determines if the expression or type T uses any parameter packs. */
4094 tree
4095 uses_parameter_packs (tree t)
4097 tree parameter_packs = NULL_TREE;
4098 struct find_parameter_pack_data ppd;
4099 ppd.parameter_packs = &parameter_packs;
4100 ppd.visited = new hash_set<tree>;
4101 ppd.type_pack_expansion_p = false;
4102 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4103 delete ppd.visited;
4104 return parameter_packs;
4107 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4108 representation a base-class initializer into a parameter pack
4109 expansion. If all goes well, the resulting node will be an
4110 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4111 respectively. */
4112 tree
4113 make_pack_expansion (tree arg, tsubst_flags_t complain)
4115 tree result;
4116 tree parameter_packs = NULL_TREE;
4117 bool for_types = false;
4118 struct find_parameter_pack_data ppd;
4120 if (!arg || arg == error_mark_node)
4121 return arg;
4123 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4125 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4126 class initializer. In this case, the TREE_PURPOSE will be a
4127 _TYPE node (representing the base class expansion we're
4128 initializing) and the TREE_VALUE will be a TREE_LIST
4129 containing the initialization arguments.
4131 The resulting expansion looks somewhat different from most
4132 expansions. Rather than returning just one _EXPANSION, we
4133 return a TREE_LIST whose TREE_PURPOSE is a
4134 TYPE_PACK_EXPANSION containing the bases that will be
4135 initialized. The TREE_VALUE will be identical to the
4136 original TREE_VALUE, which is a list of arguments that will
4137 be passed to each base. We do not introduce any new pack
4138 expansion nodes into the TREE_VALUE (although it is possible
4139 that some already exist), because the TREE_PURPOSE and
4140 TREE_VALUE all need to be expanded together with the same
4141 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4142 resulting TREE_PURPOSE will mention the parameter packs in
4143 both the bases and the arguments to the bases. */
4144 tree purpose;
4145 tree value;
4146 tree parameter_packs = NULL_TREE;
4148 /* Determine which parameter packs will be used by the base
4149 class expansion. */
4150 ppd.visited = new hash_set<tree>;
4151 ppd.parameter_packs = &parameter_packs;
4152 ppd.type_pack_expansion_p = false;
4153 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4154 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4155 &ppd, ppd.visited);
4157 if (parameter_packs == NULL_TREE)
4159 if (complain & tf_error)
4160 error ("base initializer expansion %qT contains no parameter packs",
4161 arg);
4162 delete ppd.visited;
4163 return error_mark_node;
4166 if (TREE_VALUE (arg) != void_type_node)
4168 /* Collect the sets of parameter packs used in each of the
4169 initialization arguments. */
4170 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4172 /* Determine which parameter packs will be expanded in this
4173 argument. */
4174 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4175 &ppd, ppd.visited);
4179 delete ppd.visited;
4181 /* Create the pack expansion type for the base type. */
4182 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4183 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4184 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4185 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4187 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4188 they will rarely be compared to anything. */
4189 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4191 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4194 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4195 for_types = true;
4197 /* Build the PACK_EXPANSION_* node. */
4198 result = for_types
4199 ? cxx_make_type (TYPE_PACK_EXPANSION)
4200 : make_node (EXPR_PACK_EXPANSION);
4201 PACK_EXPANSION_PATTERN (result) = arg;
4202 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4204 /* Propagate type and const-expression information. */
4205 TREE_TYPE (result) = TREE_TYPE (arg);
4206 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4207 /* Mark this read now, since the expansion might be length 0. */
4208 mark_exp_read (arg);
4210 else
4211 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4212 they will rarely be compared to anything. */
4213 SET_TYPE_STRUCTURAL_EQUALITY (result);
4215 /* Determine which parameter packs will be expanded. */
4216 ppd.parameter_packs = &parameter_packs;
4217 ppd.visited = new hash_set<tree>;
4218 ppd.type_pack_expansion_p = TYPE_P (arg);
4219 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4220 delete ppd.visited;
4222 /* Make sure we found some parameter packs. */
4223 if (parameter_packs == NULL_TREE)
4225 if (complain & tf_error)
4227 if (TYPE_P (arg))
4228 error ("expansion pattern %qT contains no parameter packs", arg);
4229 else
4230 error ("expansion pattern %qE contains no parameter packs", arg);
4232 return error_mark_node;
4234 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4236 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4237 if (ppd.found_extra_args_tree_p)
4238 /* If the pattern of this pack expansion contains a subtree that has
4239 the extra args mechanism for avoiding partial instantiation, then
4240 force this pack expansion to also use extra args. Otherwise
4241 partial instantiation of this pack expansion may not lower the
4242 level of some parameter packs within the pattern, which would
4243 confuse tsubst_pack_expansion later (PR101764). */
4244 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4246 return result;
4249 /* Checks T for any "bare" parameter packs, which have not yet been
4250 expanded, and issues an error if any are found. This operation can
4251 only be done on full expressions or types (e.g., an expression
4252 statement, "if" condition, etc.), because we could have expressions like:
4254 foo(f(g(h(args)))...)
4256 where "args" is a parameter pack. check_for_bare_parameter_packs
4257 should not be called for the subexpressions args, h(args),
4258 g(h(args)), or f(g(h(args))), because we would produce erroneous
4259 error messages.
4261 Returns TRUE and emits an error if there were bare parameter packs,
4262 returns FALSE otherwise. */
4263 bool
4264 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4266 tree parameter_packs = NULL_TREE;
4267 struct find_parameter_pack_data ppd;
4269 if (!processing_template_decl || !t || t == error_mark_node)
4270 return false;
4272 if (TREE_CODE (t) == TYPE_DECL)
4273 t = TREE_TYPE (t);
4275 ppd.parameter_packs = &parameter_packs;
4276 ppd.visited = new hash_set<tree>;
4277 ppd.type_pack_expansion_p = false;
4278 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4279 delete ppd.visited;
4281 if (!parameter_packs)
4282 return false;
4284 if (loc == UNKNOWN_LOCATION)
4285 loc = cp_expr_loc_or_input_loc (t);
4287 /* It's OK for a lambda to have an unexpanded parameter pack from the
4288 containing context, but do complain about unexpanded capture packs. */
4289 tree lam = current_lambda_expr ();
4290 if (lam)
4291 lam = TREE_TYPE (lam);
4293 if (lam && lam != current_class_type)
4295 /* We're in a lambda, but it isn't the innermost class.
4296 This should work, but currently doesn't. */
4297 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4298 return true;
4301 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4302 for (; parameter_packs;
4303 parameter_packs = TREE_CHAIN (parameter_packs))
4305 tree pack = TREE_VALUE (parameter_packs);
4306 if (is_capture_proxy (pack)
4307 || (TREE_CODE (pack) == PARM_DECL
4308 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4309 break;
4312 if (parameter_packs)
4314 error_at (loc, "parameter packs not expanded with %<...%>:");
4315 while (parameter_packs)
4317 tree pack = TREE_VALUE (parameter_packs);
4318 tree name = NULL_TREE;
4320 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4321 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4322 name = TYPE_NAME (pack);
4323 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4324 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4325 else if (TREE_CODE (pack) == CALL_EXPR)
4326 name = DECL_NAME (CALL_EXPR_FN (pack));
4327 else
4328 name = DECL_NAME (pack);
4330 if (name)
4331 inform (loc, " %qD", name);
4332 else
4333 inform (loc, " %s", "<anonymous>");
4335 parameter_packs = TREE_CHAIN (parameter_packs);
4338 return true;
4341 return false;
4344 /* Expand any parameter packs that occur in the template arguments in
4345 ARGS. */
4346 tree
4347 expand_template_argument_pack (tree args)
4349 if (args == error_mark_node)
4350 return error_mark_node;
4352 tree result_args = NULL_TREE;
4353 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4354 int num_result_args = -1;
4355 int non_default_args_count = -1;
4357 /* First, determine if we need to expand anything, and the number of
4358 slots we'll need. */
4359 for (in_arg = 0; in_arg < nargs; ++in_arg)
4361 tree arg = TREE_VEC_ELT (args, in_arg);
4362 if (arg == NULL_TREE)
4363 return args;
4364 if (ARGUMENT_PACK_P (arg))
4366 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4367 if (num_result_args < 0)
4368 num_result_args = in_arg + num_packed;
4369 else
4370 num_result_args += num_packed;
4372 else
4374 if (num_result_args >= 0)
4375 num_result_args++;
4379 /* If no expansion is necessary, we're done. */
4380 if (num_result_args < 0)
4381 return args;
4383 /* Expand arguments. */
4384 result_args = make_tree_vec (num_result_args);
4385 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4386 non_default_args_count =
4387 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4388 for (in_arg = 0; in_arg < nargs; ++in_arg)
4390 tree arg = TREE_VEC_ELT (args, in_arg);
4391 if (ARGUMENT_PACK_P (arg))
4393 tree packed = ARGUMENT_PACK_ARGS (arg);
4394 int i, num_packed = TREE_VEC_LENGTH (packed);
4395 for (i = 0; i < num_packed; ++i, ++out_arg)
4396 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4397 if (non_default_args_count > 0)
4398 non_default_args_count += num_packed - 1;
4400 else
4402 TREE_VEC_ELT (result_args, out_arg) = arg;
4403 ++out_arg;
4406 if (non_default_args_count >= 0)
4407 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4408 return result_args;
4411 /* Checks if DECL shadows a template parameter.
4413 [temp.local]: A template-parameter shall not be redeclared within its
4414 scope (including nested scopes).
4416 Emits an error and returns TRUE if the DECL shadows a parameter,
4417 returns FALSE otherwise. */
4419 bool
4420 check_template_shadow (tree decl)
4422 tree olddecl;
4424 /* If we're not in a template, we can't possibly shadow a template
4425 parameter. */
4426 if (!current_template_parms)
4427 return true;
4429 /* Figure out what we're shadowing. */
4430 decl = OVL_FIRST (decl);
4431 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4433 /* If there's no previous binding for this name, we're not shadowing
4434 anything, let alone a template parameter. */
4435 if (!olddecl)
4436 return true;
4438 /* If we're not shadowing a template parameter, we're done. Note
4439 that OLDDECL might be an OVERLOAD (or perhaps even an
4440 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4441 node. */
4442 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4443 return true;
4445 /* We check for decl != olddecl to avoid bogus errors for using a
4446 name inside a class. We check TPFI to avoid duplicate errors for
4447 inline member templates. */
4448 if (decl == olddecl
4449 || (DECL_TEMPLATE_PARM_P (decl)
4450 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4451 return true;
4453 /* Don't complain about the injected class name, as we've already
4454 complained about the class itself. */
4455 if (DECL_SELF_REFERENCE_P (decl))
4456 return false;
4458 if (DECL_TEMPLATE_PARM_P (decl))
4459 error ("declaration of template parameter %q+D shadows "
4460 "template parameter", decl);
4461 else
4462 error ("declaration of %q+#D shadows template parameter", decl);
4463 inform (DECL_SOURCE_LOCATION (olddecl),
4464 "template parameter %qD declared here", olddecl);
4465 return false;
4468 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4469 ORIG_LEVEL, DECL, and TYPE. */
4471 static tree
4472 build_template_parm_index (int index,
4473 int level,
4474 int orig_level,
4475 tree decl,
4476 tree type)
4478 tree t = make_node (TEMPLATE_PARM_INDEX);
4479 TEMPLATE_PARM_IDX (t) = index;
4480 TEMPLATE_PARM_LEVEL (t) = level;
4481 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4482 TEMPLATE_PARM_DECL (t) = decl;
4483 TREE_TYPE (t) = type;
4484 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4485 TREE_READONLY (t) = TREE_READONLY (decl);
4487 return t;
4490 struct ctp_hasher : ggc_ptr_hash<tree_node>
4492 static hashval_t hash (tree t)
4494 ++comparing_specializations;
4495 tree_code code = TREE_CODE (t);
4496 hashval_t val = iterative_hash_object (code, 0);
4497 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4498 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4499 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4500 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4501 --comparing_specializations;
4502 return val;
4505 static bool equal (tree t, tree u)
4507 ++comparing_specializations;
4508 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4509 --comparing_specializations;
4510 return eq;
4514 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4516 /* Find the canonical type parameter for the given template type
4517 parameter. Returns the canonical type parameter, which may be TYPE
4518 if no such parameter existed. */
4520 tree
4521 canonical_type_parameter (tree type)
4523 if (ctp_table == NULL)
4524 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4526 tree& slot = *ctp_table->find_slot (type, INSERT);
4527 if (slot == NULL_TREE)
4528 slot = type;
4529 return slot;
4532 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4533 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4534 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4535 new one is created. */
4537 static tree
4538 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4539 tsubst_flags_t complain)
4541 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4542 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4543 != TEMPLATE_PARM_LEVEL (index) - levels)
4544 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4546 tree orig_decl = TEMPLATE_PARM_DECL (index);
4548 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4549 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4550 type);
4551 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4552 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4553 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4554 DECL_ARTIFICIAL (decl) = 1;
4555 SET_DECL_TEMPLATE_PARM_P (decl);
4557 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4558 TEMPLATE_PARM_LEVEL (index) - levels,
4559 TEMPLATE_PARM_ORIG_LEVEL (index),
4560 decl, type);
4561 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4562 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4563 = TEMPLATE_PARM_PARAMETER_PACK (index);
4565 /* Template template parameters need this. */
4566 tree inner = decl;
4567 if (TREE_CODE (decl) == TEMPLATE_DECL)
4569 inner = build_lang_decl_loc (DECL_SOURCE_LOCATION (decl),
4570 TYPE_DECL, DECL_NAME (decl), type);
4571 DECL_TEMPLATE_RESULT (decl) = inner;
4572 DECL_ARTIFICIAL (inner) = true;
4573 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (orig_decl),
4574 args, complain);
4575 DECL_TEMPLATE_PARMS (decl) = parms;
4576 tree orig_inner = DECL_TEMPLATE_RESULT (orig_decl);
4577 DECL_TEMPLATE_INFO (inner)
4578 = build_template_info (DECL_TI_TEMPLATE (orig_inner),
4579 template_parms_to_args (parms));
4582 /* Attach the TPI to the decl. */
4583 if (TREE_CODE (inner) == TYPE_DECL)
4584 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4585 else
4586 DECL_INITIAL (decl) = tpi;
4589 return TEMPLATE_PARM_DESCENDANTS (index);
4592 /* Process information from new template parameter PARM and append it
4593 to the LIST being built. This new parameter is a non-type
4594 parameter iff IS_NON_TYPE is true. This new parameter is a
4595 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4596 is in PARM_LOC. */
4598 tree
4599 process_template_parm (tree list, location_t parm_loc, tree parm,
4600 bool is_non_type, bool is_parameter_pack)
4602 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4603 tree prev = NULL_TREE;
4604 int idx = 0;
4606 if (list)
4608 prev = tree_last (list);
4610 tree p = TREE_VALUE (prev);
4611 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4612 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4613 else if (TREE_CODE (p) == PARM_DECL)
4614 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4616 ++idx;
4619 tree decl = NULL_TREE;
4620 tree defval = TREE_PURPOSE (parm);
4621 tree constr = TREE_TYPE (parm);
4623 if (is_non_type)
4625 parm = TREE_VALUE (parm);
4627 SET_DECL_TEMPLATE_PARM_P (parm);
4629 if (TREE_TYPE (parm) != error_mark_node)
4631 /* [temp.param]
4633 The top-level cv-qualifiers on the template-parameter are
4634 ignored when determining its type. */
4635 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4636 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4637 TREE_TYPE (parm) = error_mark_node;
4638 else if (uses_parameter_packs (TREE_TYPE (parm))
4639 && !is_parameter_pack
4640 /* If we're in a nested template parameter list, the template
4641 template parameter could be a parameter pack. */
4642 && processing_template_parmlist == 1)
4644 /* This template parameter is not a parameter pack, but it
4645 should be. Complain about "bare" parameter packs. */
4646 check_for_bare_parameter_packs (TREE_TYPE (parm));
4648 /* Recover by calling this a parameter pack. */
4649 is_parameter_pack = true;
4653 /* A template parameter is not modifiable. */
4654 TREE_CONSTANT (parm) = 1;
4655 TREE_READONLY (parm) = 1;
4656 decl = build_decl (parm_loc,
4657 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4658 TREE_CONSTANT (decl) = 1;
4659 TREE_READONLY (decl) = 1;
4660 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4661 = build_template_parm_index (idx, current_template_depth,
4662 current_template_depth,
4663 decl, TREE_TYPE (parm));
4665 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4666 = is_parameter_pack;
4668 else
4670 tree t;
4671 parm = TREE_VALUE (TREE_VALUE (parm));
4673 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4675 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4676 /* This is for distinguishing between real templates and template
4677 template parameters */
4678 TREE_TYPE (parm) = t;
4680 /* any_template_parm_r expects to be able to get the targs of a
4681 DECL_TEMPLATE_RESULT. */
4682 tree result = DECL_TEMPLATE_RESULT (parm);
4683 TREE_TYPE (result) = t;
4684 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4685 tree tinfo = build_template_info (parm, args);
4686 retrofit_lang_decl (result);
4687 DECL_TEMPLATE_INFO (result) = tinfo;
4689 decl = parm;
4691 else
4693 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4694 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4695 decl = build_decl (parm_loc,
4696 TYPE_DECL, parm, t);
4699 TYPE_NAME (t) = decl;
4700 TYPE_STUB_DECL (t) = decl;
4701 parm = decl;
4702 TEMPLATE_TYPE_PARM_INDEX (t)
4703 = build_template_parm_index (idx, current_template_depth,
4704 current_template_depth,
4705 decl, TREE_TYPE (parm));
4706 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4707 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4709 DECL_ARTIFICIAL (decl) = 1;
4710 SET_DECL_TEMPLATE_PARM_P (decl);
4712 if (TREE_CODE (parm) == TEMPLATE_DECL
4713 && !uses_outer_template_parms (parm))
4714 TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
4716 /* Build requirements for the type/template parameter.
4717 This must be done after SET_DECL_TEMPLATE_PARM_P or
4718 process_template_parm could fail. */
4719 tree reqs = finish_shorthand_constraint (parm, constr);
4721 decl = pushdecl (decl);
4722 if (!is_non_type)
4723 parm = decl;
4725 /* Build the parameter node linking the parameter declaration,
4726 its default argument (if any), and its constraints (if any). */
4727 parm = build_tree_list (defval, parm);
4728 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4730 if (prev)
4731 TREE_CHAIN (prev) = parm;
4732 else
4733 list = parm;
4735 return list;
4738 /* The end of a template parameter list has been reached. Process the
4739 tree list into a parameter vector, converting each parameter into a more
4740 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4741 as PARM_DECLs. */
4743 tree
4744 end_template_parm_list (tree parms)
4746 tree saved_parmlist = make_tree_vec (list_length (parms));
4748 /* Pop the dummy parameter level and add the real one. We do not
4749 morph the dummy parameter in place, as it might have been
4750 captured by a (nested) template-template-parm. */
4751 current_template_parms = TREE_CHAIN (current_template_parms);
4753 current_template_parms
4754 = tree_cons (size_int (current_template_depth + 1),
4755 saved_parmlist, current_template_parms);
4757 for (unsigned ix = 0; parms; ix++)
4759 tree parm = parms;
4760 parms = TREE_CHAIN (parms);
4761 TREE_CHAIN (parm) = NULL_TREE;
4763 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4766 --processing_template_parmlist;
4768 return saved_parmlist;
4771 // Explicitly indicate the end of the template parameter list. We assume
4772 // that the current template parameters have been constructed and/or
4773 // managed explicitly, as when creating new template template parameters
4774 // from a shorthand constraint.
4775 void
4776 end_template_parm_list ()
4778 --processing_template_parmlist;
4781 /* end_template_decl is called after a template declaration is seen. */
4783 void
4784 end_template_decl (void)
4786 reset_specialization ();
4788 if (! processing_template_decl)
4789 return;
4791 /* This matches the pushlevel in begin_template_parm_list. */
4792 finish_scope ();
4794 --processing_template_decl;
4795 current_template_parms = TREE_CHAIN (current_template_parms);
4798 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4799 thereof, and converts it into an argument suitable to be passed to
4800 the type substitution functions. Note that if the TREE_LIST contains
4801 an error_mark node, the returned argument is error_mark_node. */
4803 tree
4804 template_parm_to_arg (tree t)
4806 if (!t)
4807 return NULL_TREE;
4809 if (TREE_CODE (t) == TREE_LIST)
4810 t = TREE_VALUE (t);
4812 if (error_operand_p (t))
4813 return error_mark_node;
4815 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4817 if (TREE_CODE (t) == TYPE_DECL
4818 || TREE_CODE (t) == TEMPLATE_DECL)
4819 t = TREE_TYPE (t);
4820 else
4821 t = DECL_INITIAL (t);
4824 gcc_assert (TEMPLATE_PARM_P (t));
4826 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4827 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4829 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4831 /* Turn this argument into a TYPE_ARGUMENT_PACK
4832 with a single element, which expands T. */
4833 tree vec = make_tree_vec (1);
4834 if (CHECKING_P)
4835 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4837 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4839 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4840 ARGUMENT_PACK_ARGS (t) = vec;
4843 else
4845 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4847 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4848 with a single element, which expands T. */
4849 tree vec = make_tree_vec (1);
4850 if (CHECKING_P)
4851 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4853 t = convert_from_reference (t);
4854 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4856 t = make_node (NONTYPE_ARGUMENT_PACK);
4857 ARGUMENT_PACK_ARGS (t) = vec;
4859 else
4860 t = convert_from_reference (t);
4862 return t;
4865 /* If T looks like a generic template argument produced by template_parm_to_arg,
4866 return the corresponding template parameter, otherwise return NULL_TREE. */
4868 static tree
4869 template_arg_to_parm (tree t)
4871 if (t == NULL_TREE)
4872 return NULL_TREE;
4874 if (ARGUMENT_PACK_P (t))
4876 tree args = ARGUMENT_PACK_ARGS (t);
4877 if (TREE_VEC_LENGTH (args) == 1
4878 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4879 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4882 if (REFERENCE_REF_P (t))
4883 t = TREE_OPERAND (t, 0);
4885 if (TEMPLATE_PARM_P (t))
4886 return t;
4887 else
4888 return NULL_TREE;
4891 /* Given a single level of template parameters (a TREE_VEC), return it
4892 as a set of template arguments. */
4894 tree
4895 template_parms_level_to_args (tree parms)
4897 parms = copy_node (parms);
4898 TREE_TYPE (parms) = NULL_TREE;
4899 for (tree& parm : tree_vec_range (parms))
4900 parm = template_parm_to_arg (parm);
4902 if (CHECKING_P)
4903 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4905 return parms;
4908 /* Given a set of template parameters, return them as a set of template
4909 arguments. The template parameters are represented as a TREE_VEC, in
4910 the form documented in cp-tree.h for template arguments. */
4912 tree
4913 template_parms_to_args (tree parms)
4915 tree header;
4916 tree args = NULL_TREE;
4917 int length = TMPL_PARMS_DEPTH (parms);
4918 int l = length;
4920 /* If there is only one level of template parameters, we do not
4921 create a TREE_VEC of TREE_VECs. Instead, we return a single
4922 TREE_VEC containing the arguments. */
4923 if (length > 1)
4924 args = make_tree_vec (length);
4926 for (header = parms; header; header = TREE_CHAIN (header))
4928 tree a = template_parms_level_to_args (TREE_VALUE (header));
4930 if (length > 1)
4931 TREE_VEC_ELT (args, --l) = a;
4932 else
4933 args = a;
4936 return args;
4939 /* Within the declaration of a template, return the currently active
4940 template parameters as an argument TREE_VEC. */
4942 static tree
4943 current_template_args (void)
4945 return template_parms_to_args (current_template_parms);
4948 /* Return the fully generic arguments for of TMPL, i.e. what
4949 current_template_args would be while parsing it. */
4951 tree
4952 generic_targs_for (tree tmpl)
4954 if (tmpl == NULL_TREE)
4955 return NULL_TREE;
4956 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4957 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4958 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4959 template parameter, it has no TEMPLATE_INFO; for a partial
4960 specialization, it has the arguments for the primary template, and we
4961 want the arguments for the partial specialization. */;
4962 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4963 if (tree ti = get_template_info (result))
4964 return TI_ARGS (ti);
4965 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4968 /* Return the template arguments corresponding to the template parameters of
4969 DECL's enclosing scope. When DECL is a member of a partial specialization,
4970 this returns the arguments for the partial specialization as opposed to those
4971 for the primary template, which is the main difference between this function
4972 and simply using e.g. the TYPE_TI_ARGS of DECL's DECL_CONTEXT. */
4974 tree
4975 outer_template_args (const_tree decl)
4977 if (TREE_CODE (decl) == TEMPLATE_DECL)
4978 decl = DECL_TEMPLATE_RESULT (decl);
4979 tree ti = get_template_info (decl);
4980 if (!ti)
4981 return NULL_TREE;
4982 tree args = TI_ARGS (ti);
4983 if (!PRIMARY_TEMPLATE_P (TI_TEMPLATE (ti)))
4984 return args;
4985 if (TMPL_ARGS_DEPTH (args) == 1)
4986 return NULL_TREE;
4987 return strip_innermost_template_args (args, 1);
4990 /* Update the declared TYPE by doing any lookups which were thought to be
4991 dependent, but are not now that we know the SCOPE of the declarator. */
4993 tree
4994 maybe_update_decl_type (tree orig_type, tree scope)
4996 tree type = orig_type;
4998 if (type == NULL_TREE)
4999 return type;
5001 if (TREE_CODE (orig_type) == TYPE_DECL)
5002 type = TREE_TYPE (type);
5004 if (scope && TYPE_P (scope) && dependent_type_p (scope)
5005 && dependent_type_p (type)
5006 /* Don't bother building up the args in this case. */
5007 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5009 /* tsubst in the args corresponding to the template parameters,
5010 including auto if present. Most things will be unchanged, but
5011 make_typename_type and tsubst_qualified_id will resolve
5012 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5013 tree args = current_template_args ();
5014 tree auto_node = type_uses_auto (type);
5015 tree pushed;
5016 if (auto_node)
5018 tree auto_vec = make_tree_vec (1);
5019 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5020 args = add_to_template_args (args, auto_vec);
5022 pushed = push_scope (scope);
5023 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5024 if (pushed)
5025 pop_scope (scope);
5028 if (type == error_mark_node)
5029 return orig_type;
5031 if (TREE_CODE (orig_type) == TYPE_DECL)
5033 if (same_type_p (type, TREE_TYPE (orig_type)))
5034 type = orig_type;
5035 else
5036 type = TYPE_NAME (type);
5038 return type;
5041 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5042 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5043 the new template is a member template. */
5045 static tree
5046 build_template_decl (tree decl, tree parms, bool member_template_p)
5048 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5050 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5051 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5052 DECL_TEMPLATE_PARMS (tmpl) = parms;
5053 DECL_TEMPLATE_RESULT (tmpl) = decl;
5054 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5055 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5056 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5057 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5059 /* Propagate module information from the decl. */
5060 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5062 return tmpl;
5065 struct template_parm_data
5067 /* The level of the template parameters we are currently
5068 processing. */
5069 int level;
5071 /* The index of the specialization argument we are currently
5072 processing. */
5073 int current_arg;
5075 /* An array whose size is the number of template parameters. The
5076 elements are nonzero if the parameter has been used in any one
5077 of the arguments processed so far. */
5078 int* parms;
5080 /* An array whose size is the number of template arguments. The
5081 elements are nonzero if the argument makes use of template
5082 parameters of this level. */
5083 int* arg_uses_template_parms;
5086 /* Subroutine of push_template_decl used to see if each template
5087 parameter in a partial specialization is used in the explicit
5088 argument list. If T is of the LEVEL given in DATA (which is
5089 treated as a template_parm_data*), then DATA->PARMS is marked
5090 appropriately. */
5092 static int
5093 mark_template_parm (tree t, void* data)
5095 int level;
5096 int idx;
5097 struct template_parm_data* tpd = (struct template_parm_data*) data;
5099 template_parm_level_and_index (t, &level, &idx);
5101 if (level == tpd->level)
5103 tpd->parms[idx] = 1;
5104 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5107 /* In C++17 the type of a non-type argument is a deduced context. */
5108 if (cxx_dialect >= cxx17
5109 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5110 for_each_template_parm (TREE_TYPE (t),
5111 &mark_template_parm,
5112 data,
5113 NULL,
5114 /*include_nondeduced_p=*/false);
5116 /* Return zero so that for_each_template_parm will continue the
5117 traversal of the tree; we want to mark *every* template parm. */
5118 return 0;
5121 /* Process the partial specialization DECL. */
5123 static tree
5124 process_partial_specialization (tree decl)
5126 tree type = TREE_TYPE (decl);
5127 tree tinfo = get_template_info (decl);
5128 tree maintmpl = TI_TEMPLATE (tinfo);
5129 tree specargs = TI_ARGS (tinfo);
5130 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5131 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5132 tree inner_parms;
5133 tree inst;
5134 int nargs = TREE_VEC_LENGTH (inner_args);
5135 int ntparms;
5136 int i;
5137 bool did_error_intro = false;
5138 struct template_parm_data tpd;
5139 struct template_parm_data tpd2;
5141 gcc_assert (current_template_parms);
5143 /* A concept cannot be specialized. */
5144 if (flag_concepts && variable_concept_p (maintmpl))
5146 error ("specialization of variable concept %q#D", maintmpl);
5147 return error_mark_node;
5150 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5151 ntparms = TREE_VEC_LENGTH (inner_parms);
5153 /* We check that each of the template parameters given in the
5154 partial specialization is used in the argument list to the
5155 specialization. For example:
5157 template <class T> struct S;
5158 template <class T> struct S<T*>;
5160 The second declaration is OK because `T*' uses the template
5161 parameter T, whereas
5163 template <class T> struct S<int>;
5165 is no good. Even trickier is:
5167 template <class T>
5168 struct S1
5170 template <class U>
5171 struct S2;
5172 template <class U>
5173 struct S2<T>;
5176 The S2<T> declaration is actually invalid; it is a
5177 full-specialization. Of course,
5179 template <class U>
5180 struct S2<T (*)(U)>;
5182 or some such would have been OK. */
5183 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5184 tpd.parms = XALLOCAVEC (int, ntparms);
5185 memset (tpd.parms, 0, sizeof (int) * ntparms);
5187 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5188 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5189 for (i = 0; i < nargs; ++i)
5191 tpd.current_arg = i;
5192 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5193 &mark_template_parm,
5194 &tpd,
5195 NULL,
5196 /*include_nondeduced_p=*/false);
5198 for (i = 0; i < ntparms; ++i)
5199 if (tpd.parms[i] == 0)
5201 /* One of the template parms was not used in a deduced context in the
5202 specialization. */
5203 if (!did_error_intro)
5205 error ("template parameters not deducible in "
5206 "partial specialization:");
5207 did_error_intro = true;
5210 inform (input_location, " %qD",
5211 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5214 if (did_error_intro)
5215 return error_mark_node;
5217 /* [temp.class.spec]
5219 The argument list of the specialization shall not be identical to
5220 the implicit argument list of the primary template. */
5221 tree main_args
5222 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5223 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5224 && (!flag_concepts
5225 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5227 if (!flag_concepts)
5228 error ("partial specialization %q+D does not specialize "
5229 "any template arguments; to define the primary template, "
5230 "remove the template argument list", decl);
5231 else
5232 error ("partial specialization %q+D does not specialize any "
5233 "template arguments and is not more constrained than "
5234 "the primary template; to define the primary template, "
5235 "remove the template argument list", decl);
5236 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5239 /* A partial specialization that replaces multiple parameters of the
5240 primary template with a pack expansion is less specialized for those
5241 parameters. */
5242 if (nargs < DECL_NTPARMS (maintmpl))
5244 error ("partial specialization is not more specialized than the "
5245 "primary template because it replaces multiple parameters "
5246 "with a pack expansion");
5247 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5248 /* Avoid crash in process_partial_specialization. */
5249 return decl;
5252 else if (nargs > DECL_NTPARMS (maintmpl))
5254 error ("too many arguments for partial specialization %qT", type);
5255 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5256 /* Avoid crash below. */
5257 return decl;
5260 /* If we aren't in a dependent class, we can actually try deduction. */
5261 else if (tpd.level == 1
5262 /* FIXME we should be able to handle a partial specialization of a
5263 partial instantiation, but currently we can't (c++/41727). */
5264 && TMPL_ARGS_DEPTH (specargs) == 1
5265 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5267 auto_diagnostic_group d;
5268 if (pedwarn (input_location, 0,
5269 "partial specialization %qD is not more specialized than",
5270 decl))
5271 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5272 maintmpl);
5275 /* [temp.spec.partial]
5277 The type of a template parameter corresponding to a specialized
5278 non-type argument shall not be dependent on a parameter of the
5279 specialization.
5281 Also, we verify that pack expansions only occur at the
5282 end of the argument list. */
5283 tpd2.parms = 0;
5284 for (i = 0; i < nargs; ++i)
5286 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5287 tree arg = TREE_VEC_ELT (inner_args, i);
5288 tree packed_args = NULL_TREE;
5289 int j, len = 1;
5291 if (ARGUMENT_PACK_P (arg))
5293 /* Extract the arguments from the argument pack. We'll be
5294 iterating over these in the following loop. */
5295 packed_args = ARGUMENT_PACK_ARGS (arg);
5296 len = TREE_VEC_LENGTH (packed_args);
5299 for (j = 0; j < len; j++)
5301 if (packed_args)
5302 /* Get the Jth argument in the parameter pack. */
5303 arg = TREE_VEC_ELT (packed_args, j);
5305 if (PACK_EXPANSION_P (arg))
5307 /* Pack expansions must come at the end of the
5308 argument list. */
5309 if ((packed_args && j < len - 1)
5310 || (!packed_args && i < nargs - 1))
5312 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5313 error ("parameter pack argument %qE must be at the "
5314 "end of the template argument list", arg);
5315 else
5316 error ("parameter pack argument %qT must be at the "
5317 "end of the template argument list", arg);
5321 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5322 /* We only care about the pattern. */
5323 arg = PACK_EXPANSION_PATTERN (arg);
5325 if (/* These first two lines are the `non-type' bit. */
5326 !TYPE_P (arg)
5327 && TREE_CODE (arg) != TEMPLATE_DECL
5328 /* This next two lines are the `argument expression is not just a
5329 simple identifier' condition and also the `specialized
5330 non-type argument' bit. */
5331 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5332 && !((REFERENCE_REF_P (arg)
5333 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5334 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5336 /* Look at the corresponding template parameter,
5337 marking which template parameters its type depends
5338 upon. */
5339 tree type = TREE_TYPE (parm);
5341 if (!tpd2.parms)
5343 /* We haven't yet initialized TPD2. Do so now. */
5344 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5345 /* The number of parameters here is the number in the
5346 main template, which, as checked in the assertion
5347 above, is NARGS. */
5348 tpd2.parms = XALLOCAVEC (int, nargs);
5349 tpd2.level =
5350 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5353 /* Mark the template parameters. But this time, we're
5354 looking for the template parameters of the main
5355 template, not in the specialization. */
5356 tpd2.current_arg = i;
5357 tpd2.arg_uses_template_parms[i] = 0;
5358 memset (tpd2.parms, 0, sizeof (int) * nargs);
5359 for_each_template_parm (type,
5360 &mark_template_parm,
5361 &tpd2,
5362 NULL,
5363 /*include_nondeduced_p=*/false);
5365 if (tpd2.arg_uses_template_parms [i])
5367 /* The type depended on some template parameters.
5368 If they are fully specialized in the
5369 specialization, that's OK. */
5370 int j;
5371 int count = 0;
5372 for (j = 0; j < nargs; ++j)
5373 if (tpd2.parms[j] != 0
5374 && tpd.arg_uses_template_parms [j])
5375 ++count;
5376 if (count != 0)
5377 error_n (input_location, count,
5378 "type %qT of template argument %qE depends "
5379 "on a template parameter",
5380 "type %qT of template argument %qE depends "
5381 "on template parameters",
5382 type,
5383 arg);
5389 /* We should only get here once. */
5390 if (TREE_CODE (decl) == TYPE_DECL)
5391 gcc_assert (!COMPLETE_TYPE_P (type));
5393 // Build the template decl.
5394 tree tmpl = build_template_decl (decl, current_template_parms,
5395 DECL_MEMBER_TEMPLATE_P (maintmpl));
5396 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5397 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5398 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5400 /* Give template template parms a DECL_CONTEXT of the template
5401 for which they are a parameter. */
5402 for (i = 0; i < ntparms; ++i)
5404 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5405 if (TREE_CODE (parm) == TEMPLATE_DECL)
5406 DECL_CONTEXT (parm) = tmpl;
5409 if (VAR_P (decl))
5410 /* We didn't register this in check_explicit_specialization so we could
5411 wait until the constraints were set. */
5412 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5413 else
5414 associate_classtype_constraints (type);
5416 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5417 = tree_cons (specargs, tmpl,
5418 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5419 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5420 /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL. */
5421 gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
5422 TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
5424 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5425 inst = TREE_CHAIN (inst))
5427 tree instance = TREE_VALUE (inst);
5428 if (TYPE_P (instance)
5429 ? (COMPLETE_TYPE_P (instance)
5430 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5431 : DECL_TEMPLATE_INSTANTIATION (instance))
5433 tree partial_ti = most_specialized_partial_spec (instance, tf_none,
5434 /*rechecking=*/true);
5435 tree inst_decl = (DECL_P (instance)
5436 ? instance : TYPE_NAME (instance));
5437 if (!partial_ti)
5438 /* OK */;
5439 else if (partial_ti == error_mark_node)
5440 permerror (input_location,
5441 "declaration of %qD ambiguates earlier template "
5442 "instantiation for %qD", decl, inst_decl);
5443 else if (TI_TEMPLATE (partial_ti) == tmpl)
5444 permerror (input_location,
5445 "partial specialization of %qD after instantiation "
5446 "of %qD", decl, inst_decl);
5450 return decl;
5453 /* PARM is a template parameter of some form; return the corresponding
5454 TEMPLATE_PARM_INDEX. */
5456 static tree
5457 get_template_parm_index (tree parm)
5459 if (TREE_CODE (parm) == PARM_DECL
5460 || TREE_CODE (parm) == CONST_DECL)
5461 parm = DECL_INITIAL (parm);
5462 else if (TREE_CODE (parm) == TYPE_DECL
5463 || TREE_CODE (parm) == TEMPLATE_DECL)
5464 parm = TREE_TYPE (parm);
5465 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5466 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5467 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5468 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5469 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5470 return parm;
5473 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5474 parameter packs used by the template parameter PARM. */
5476 static void
5477 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5479 /* A type parm can't refer to another parm. */
5480 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5481 return;
5482 else if (TREE_CODE (parm) == PARM_DECL)
5484 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5485 ppd, ppd->visited);
5486 return;
5489 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5491 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5492 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5494 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5495 if (template_parameter_pack_p (p))
5496 /* Any packs in the type are expanded by this parameter. */;
5497 else
5498 fixed_parameter_pack_p_1 (p, ppd);
5502 /* PARM is a template parameter pack. Return any parameter packs used in
5503 its type or the type of any of its template parameters. If there are
5504 any such packs, it will be instantiated into a fixed template parameter
5505 list by partial instantiation rather than be fully deduced. */
5507 tree
5508 fixed_parameter_pack_p (tree parm)
5510 /* This can only be true in a member template. */
5511 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5512 return NULL_TREE;
5513 /* This can only be true for a parameter pack. */
5514 if (!template_parameter_pack_p (parm))
5515 return NULL_TREE;
5516 /* A type parm can't refer to another parm. */
5517 if (TREE_CODE (parm) == TYPE_DECL)
5518 return NULL_TREE;
5520 tree parameter_packs = NULL_TREE;
5521 struct find_parameter_pack_data ppd;
5522 ppd.parameter_packs = &parameter_packs;
5523 ppd.visited = new hash_set<tree>;
5524 ppd.type_pack_expansion_p = false;
5526 fixed_parameter_pack_p_1 (parm, &ppd);
5528 delete ppd.visited;
5529 return parameter_packs;
5532 /* Check that a template declaration's use of default arguments and
5533 parameter packs is not invalid. Here, PARMS are the template
5534 parameters. IS_PRIMARY is true if DECL is the thing declared by
5535 a primary template. IS_PARTIAL is true if DECL is a partial
5536 specialization.
5538 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5539 function template declaration or a friend class template
5540 declaration. In the function case, 1 indicates a declaration, 2
5541 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5542 emitted for extraneous default arguments.
5544 Returns TRUE if there were no errors found, FALSE otherwise. */
5546 bool
5547 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5548 bool is_partial, int is_friend_decl)
5550 const char *msg;
5551 int last_level_to_check;
5552 tree parm_level;
5553 bool no_errors = true;
5555 /* [temp.param]
5557 A default template-argument shall not be specified in a
5558 function template declaration or a function template definition, nor
5559 in the template-parameter-list of the definition of a member of a
5560 class template. */
5562 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5563 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5564 /* You can't have a function template declaration in a local
5565 scope, nor you can you define a member of a class template in a
5566 local scope. */
5567 return true;
5569 if ((TREE_CODE (decl) == TYPE_DECL
5570 && TREE_TYPE (decl)
5571 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5572 || (TREE_CODE (decl) == FUNCTION_DECL
5573 && LAMBDA_FUNCTION_P (decl)))
5574 /* A lambda doesn't have an explicit declaration; don't complain
5575 about the parms of the enclosing class. */
5576 return true;
5578 if (current_class_type
5579 && !TYPE_BEING_DEFINED (current_class_type)
5580 && DECL_LANG_SPECIFIC (decl)
5581 && DECL_DECLARES_FUNCTION_P (decl)
5582 /* If this is either a friend defined in the scope of the class
5583 or a member function. */
5584 && (DECL_FUNCTION_MEMBER_P (decl)
5585 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5586 : DECL_FRIEND_CONTEXT (decl)
5587 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5588 : false)
5589 /* And, if it was a member function, it really was defined in
5590 the scope of the class. */
5591 && (!DECL_FUNCTION_MEMBER_P (decl)
5592 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5593 /* We already checked these parameters when the template was
5594 declared, so there's no need to do it again now. This function
5595 was defined in class scope, but we're processing its body now
5596 that the class is complete. */
5597 return true;
5599 /* Core issue 226 (C++0x only): the following only applies to class
5600 templates. */
5601 if (is_primary
5602 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5604 /* [temp.param]
5606 If a template-parameter has a default template-argument, all
5607 subsequent template-parameters shall have a default
5608 template-argument supplied. */
5609 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5611 tree inner_parms = TREE_VALUE (parm_level);
5612 int ntparms = TREE_VEC_LENGTH (inner_parms);
5613 int seen_def_arg_p = 0;
5614 int i;
5616 for (i = 0; i < ntparms; ++i)
5618 tree parm = TREE_VEC_ELT (inner_parms, i);
5620 if (parm == error_mark_node)
5621 continue;
5623 if (TREE_PURPOSE (parm))
5624 seen_def_arg_p = 1;
5625 else if (seen_def_arg_p
5626 && !template_parameter_pack_p (TREE_VALUE (parm)))
5628 error ("no default argument for %qD", TREE_VALUE (parm));
5629 /* For better subsequent error-recovery, we indicate that
5630 there should have been a default argument. */
5631 TREE_PURPOSE (parm) = error_mark_node;
5632 no_errors = false;
5634 else if (!is_partial
5635 && !is_friend_decl
5636 /* Don't complain about an enclosing partial
5637 specialization. */
5638 && parm_level == parms
5639 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5640 && i < ntparms - 1
5641 && template_parameter_pack_p (TREE_VALUE (parm))
5642 /* A fixed parameter pack will be partially
5643 instantiated into a fixed length list. */
5644 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5646 /* A primary class template, primary variable template
5647 (DR 2032), or alias template can only have one
5648 parameter pack, at the end of the template
5649 parameter list. */
5651 error ("parameter pack %q+D must be at the end of the"
5652 " template parameter list", TREE_VALUE (parm));
5654 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5655 = error_mark_node;
5656 no_errors = false;
5662 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5663 || is_partial
5664 || !is_primary
5665 || is_friend_decl)
5666 /* For an ordinary class template, default template arguments are
5667 allowed at the innermost level, e.g.:
5668 template <class T = int>
5669 struct S {};
5670 but, in a partial specialization, they're not allowed even
5671 there, as we have in [temp.class.spec]:
5673 The template parameter list of a specialization shall not
5674 contain default template argument values.
5676 So, for a partial specialization, or for a function template
5677 (in C++98/C++03), we look at all of them. */
5679 else
5680 /* But, for a primary class template that is not a partial
5681 specialization we look at all template parameters except the
5682 innermost ones. */
5683 parms = TREE_CHAIN (parms);
5685 /* Figure out what error message to issue. */
5686 if (is_friend_decl == 2)
5687 msg = G_("default template arguments may not be used in function template "
5688 "friend re-declaration");
5689 else if (is_friend_decl)
5690 msg = G_("default template arguments may not be used in template "
5691 "friend declarations");
5692 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5693 msg = G_("default template arguments may not be used in function templates "
5694 "without %<-std=c++11%> or %<-std=gnu++11%>");
5695 else if (is_partial)
5696 msg = G_("default template arguments may not be used in "
5697 "partial specializations");
5698 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5699 msg = G_("default argument for template parameter for class enclosing %qD");
5700 else
5701 /* Per [temp.param]/9, "A default template-argument shall not be
5702 specified in the template-parameter-lists of the definition of
5703 a member of a class template that appears outside of the member's
5704 class.", thus if we aren't handling a member of a class template
5705 there is no need to examine the parameters. */
5706 return true;
5708 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5709 /* If we're inside a class definition, there's no need to
5710 examine the parameters to the class itself. On the one
5711 hand, they will be checked when the class is defined, and,
5712 on the other, default arguments are valid in things like:
5713 template <class T = double>
5714 struct S { template <class U> void f(U); };
5715 Here the default argument for `S' has no bearing on the
5716 declaration of `f'. */
5717 last_level_to_check = template_class_depth (current_class_type) + 1;
5718 else
5719 /* Check everything. */
5720 last_level_to_check = 0;
5722 for (parm_level = parms;
5723 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5724 parm_level = TREE_CHAIN (parm_level))
5726 tree inner_parms = TREE_VALUE (parm_level);
5727 int i;
5728 int ntparms;
5730 ntparms = TREE_VEC_LENGTH (inner_parms);
5731 for (i = 0; i < ntparms; ++i)
5733 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5734 continue;
5736 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5738 if (msg)
5740 no_errors = false;
5741 if (is_friend_decl == 2)
5742 return no_errors;
5744 error (msg, decl);
5745 msg = 0;
5748 /* Clear out the default argument so that we are not
5749 confused later. */
5750 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5754 /* At this point, if we're still interested in issuing messages,
5755 they must apply to classes surrounding the object declared. */
5756 if (msg)
5757 msg = G_("default argument for template parameter for class "
5758 "enclosing %qD");
5761 return no_errors;
5764 /* Worker for push_template_decl_real, called via
5765 for_each_template_parm. DATA is really an int, indicating the
5766 level of the parameters we are interested in. If T is a template
5767 parameter of that level, return nonzero. */
5769 static int
5770 template_parm_this_level_p (tree t, void* data)
5772 int this_level = *(int *)data;
5773 int level;
5775 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5776 level = TEMPLATE_PARM_LEVEL (t);
5777 else
5778 level = TEMPLATE_TYPE_LEVEL (t);
5779 return level == this_level;
5782 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5783 DATA is really an int, indicating the innermost outer level of parameters.
5784 If T is a template parameter of that level or further out, return
5785 nonzero. */
5787 static int
5788 template_parm_outer_level (tree t, void *data)
5790 int this_level = *(int *)data;
5791 int level;
5793 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5794 level = TEMPLATE_PARM_LEVEL (t);
5795 else
5796 level = TEMPLATE_TYPE_LEVEL (t);
5797 return level <= this_level;
5800 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5801 parameters given by current_template_args, or reuses a
5802 previously existing one, if appropriate. Returns the DECL, or an
5803 equivalent one, if it is replaced via a call to duplicate_decls.
5805 If IS_FRIEND is true, DECL is a friend declaration. */
5807 tree
5808 push_template_decl (tree decl, bool is_friend)
5810 if (decl == error_mark_node || !current_template_parms)
5811 return error_mark_node;
5813 /* See if this is a partial specialization. */
5814 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5815 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5816 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5817 || (VAR_P (decl)
5818 && DECL_LANG_SPECIFIC (decl)
5819 && DECL_TEMPLATE_SPECIALIZATION (decl)
5820 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5822 /* No surprising friend functions. */
5823 gcc_checking_assert (is_friend
5824 || !(TREE_CODE (decl) == FUNCTION_DECL
5825 && DECL_UNIQUE_FRIEND_P (decl)));
5827 tree ctx;
5828 if (is_friend)
5829 /* For a friend, we want the context of the friend, not
5830 the type of which it is a friend. */
5831 ctx = CP_DECL_CONTEXT (decl);
5832 else if (CP_DECL_CONTEXT (decl)
5833 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5834 /* In the case of a virtual function, we want the class in which
5835 it is defined. */
5836 ctx = CP_DECL_CONTEXT (decl);
5837 else
5838 /* Otherwise, if we're currently defining some class, the DECL
5839 is assumed to be a member of the class. */
5840 ctx = current_scope ();
5842 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5843 ctx = NULL_TREE;
5845 if (!DECL_CONTEXT (decl))
5846 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5848 /* See if this is a primary template. */
5849 bool is_primary = false;
5850 if (is_friend && ctx
5851 && uses_template_parms_level (ctx, current_template_depth))
5852 /* A friend template that specifies a class context, i.e.
5853 template <typename T> friend void A<T>::f();
5854 is not primary. */
5856 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5857 /* Lambdas are not primary. */
5859 else
5860 is_primary = template_parm_scope_p ();
5862 /* True if the template is a member template, in the sense of
5863 [temp.mem]. */
5864 bool member_template_p = false;
5866 if (is_primary)
5868 warning (OPT_Wtemplates, "template %qD declared", decl);
5870 if (DECL_CLASS_SCOPE_P (decl))
5871 member_template_p = true;
5873 if (TREE_CODE (decl) == TYPE_DECL
5874 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5876 error ("template class without a name");
5877 return error_mark_node;
5879 else if (TREE_CODE (decl) == FUNCTION_DECL)
5881 if (member_template_p)
5883 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5884 error ("member template %qD may not have virt-specifiers", decl);
5886 if (DECL_DESTRUCTOR_P (decl))
5888 /* [temp.mem]
5890 A destructor shall not be a member template. */
5891 error_at (DECL_SOURCE_LOCATION (decl),
5892 "destructor %qD declared as member template", decl);
5893 return error_mark_node;
5895 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5896 && (!prototype_p (TREE_TYPE (decl))
5897 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5898 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5899 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5900 == void_list_node)))
5902 /* [basic.stc.dynamic.allocation]
5904 An allocation function can be a function
5905 template. ... Template allocation functions shall
5906 have two or more parameters. */
5907 error ("invalid template declaration of %qD", decl);
5908 return error_mark_node;
5911 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5912 && CLASS_TYPE_P (TREE_TYPE (decl)))
5913 /* Class template. */;
5914 else if (TREE_CODE (decl) == TYPE_DECL
5915 && TYPE_DECL_ALIAS_P (decl))
5916 /* alias-declaration */
5917 gcc_assert (!DECL_ARTIFICIAL (decl));
5918 else if (VAR_P (decl))
5919 /* C++14 variable template. */;
5920 else if (TREE_CODE (decl) == CONCEPT_DECL)
5921 /* C++20 concept definitions. */;
5922 else
5924 error ("template declaration of %q#D", decl);
5925 return error_mark_node;
5929 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5930 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5931 || (VAR_OR_FUNCTION_DECL_P (decl)
5932 && DECL_LOCAL_DECL_P (decl))));
5934 /* Check to see that the rules regarding the use of default
5935 arguments are not being violated. We check args for a friend
5936 functions when we know whether it's a definition, introducing
5937 declaration or re-declaration. */
5938 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5939 check_default_tmpl_args (decl, current_template_parms,
5940 is_primary, is_partial, is_friend);
5942 /* Ensure that there are no parameter packs in the type of this
5943 declaration that have not been expanded. */
5944 if (TREE_CODE (decl) == FUNCTION_DECL)
5946 /* Check each of the arguments individually to see if there are
5947 any bare parameter packs. */
5948 tree type = TREE_TYPE (decl);
5949 tree arg = DECL_ARGUMENTS (decl);
5950 tree argtype = TYPE_ARG_TYPES (type);
5952 while (arg && argtype)
5954 if (!DECL_PACK_P (arg)
5955 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5957 /* This is a PARM_DECL that contains unexpanded parameter
5958 packs. We have already complained about this in the
5959 check_for_bare_parameter_packs call, so just replace
5960 these types with ERROR_MARK_NODE. */
5961 TREE_TYPE (arg) = error_mark_node;
5962 TREE_VALUE (argtype) = error_mark_node;
5965 arg = DECL_CHAIN (arg);
5966 argtype = TREE_CHAIN (argtype);
5969 /* Check for bare parameter packs in the return type and the
5970 exception specifiers. */
5971 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5972 /* Errors were already issued, set return type to int
5973 as the frontend doesn't expect error_mark_node as
5974 the return type. */
5975 TREE_TYPE (type) = integer_type_node;
5976 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5977 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5979 else
5981 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5982 ? DECL_ORIGINAL_TYPE (decl)
5983 : TREE_TYPE (decl)))
5985 TREE_TYPE (decl) = error_mark_node;
5986 return error_mark_node;
5989 if (is_partial && VAR_P (decl)
5990 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5991 return error_mark_node;
5994 if (is_partial)
5995 return process_partial_specialization (decl);
5997 tree args = current_template_args ();
5998 tree tmpl = NULL_TREE;
5999 bool new_template_p = false;
6000 if (local_p)
6002 /* Does not get a template head. */
6003 tmpl = NULL_TREE;
6004 gcc_checking_assert (!is_primary);
6006 else if (!ctx
6007 || TREE_CODE (ctx) == FUNCTION_DECL
6008 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6009 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6010 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6011 && DECL_TEMPLATE_INFO (decl))))
6013 if (DECL_LANG_SPECIFIC (decl)
6014 && DECL_TEMPLATE_INFO (decl)
6015 && DECL_TI_TEMPLATE (decl))
6016 tmpl = DECL_TI_TEMPLATE (decl);
6017 /* If DECL is a TYPE_DECL for a class-template, then there won't
6018 be DECL_LANG_SPECIFIC. The information equivalent to
6019 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6020 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6021 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6022 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6024 /* Since a template declaration already existed for this
6025 class-type, we must be redeclaring it here. Make sure
6026 that the redeclaration is valid. */
6027 redeclare_class_template (TREE_TYPE (decl),
6028 current_template_parms,
6029 current_template_constraints ());
6030 /* We don't need to create a new TEMPLATE_DECL; just use the
6031 one we already had. */
6032 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6034 else
6036 tmpl = build_template_decl (decl, current_template_parms,
6037 member_template_p);
6038 new_template_p = true;
6040 if (DECL_LANG_SPECIFIC (decl)
6041 && DECL_TEMPLATE_SPECIALIZATION (decl))
6043 /* A specialization of a member template of a template
6044 class. */
6045 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6046 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6047 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6051 else
6053 tree a, t, current, parms;
6054 int i;
6055 tree tinfo = get_template_info (decl);
6057 if (!tinfo)
6059 error ("template definition of non-template %q#D", decl);
6060 return error_mark_node;
6063 tmpl = TI_TEMPLATE (tinfo);
6065 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6066 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6067 && DECL_TEMPLATE_SPECIALIZATION (decl)
6068 && DECL_MEMBER_TEMPLATE_P (tmpl))
6070 /* The declaration is a specialization of a member
6071 template, declared outside the class. Therefore, the
6072 innermost template arguments will be NULL, so we
6073 replace them with the arguments determined by the
6074 earlier call to check_explicit_specialization. */
6075 args = DECL_TI_ARGS (decl);
6077 tree new_tmpl
6078 = build_template_decl (decl, current_template_parms,
6079 member_template_p);
6080 DECL_TI_TEMPLATE (decl) = new_tmpl;
6081 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6082 DECL_TEMPLATE_INFO (new_tmpl)
6083 = build_template_info (tmpl, args);
6085 register_specialization (new_tmpl,
6086 most_general_template (tmpl),
6087 args,
6088 is_friend, 0);
6089 return decl;
6092 /* Make sure the template headers we got make sense. */
6094 parms = DECL_TEMPLATE_PARMS (tmpl);
6095 i = TMPL_PARMS_DEPTH (parms);
6096 if (TMPL_ARGS_DEPTH (args) != i)
6098 error ("expected %d levels of template parms for %q#D, got %d",
6099 i, decl, TMPL_ARGS_DEPTH (args));
6100 DECL_INTERFACE_KNOWN (decl) = 1;
6101 return error_mark_node;
6103 else
6104 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6106 a = TMPL_ARGS_LEVEL (args, i);
6107 t = INNERMOST_TEMPLATE_PARMS (parms);
6109 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6111 if (current == decl)
6112 error ("got %d template parameters for %q#D",
6113 TREE_VEC_LENGTH (a), decl);
6114 else
6115 error ("got %d template parameters for %q#T",
6116 TREE_VEC_LENGTH (a), current);
6117 error (" but %d required", TREE_VEC_LENGTH (t));
6118 /* Avoid crash in import_export_decl. */
6119 DECL_INTERFACE_KNOWN (decl) = 1;
6120 return error_mark_node;
6123 if (current == decl)
6124 current = ctx;
6125 else if (current == NULL_TREE)
6126 /* Can happen in erroneous input. */
6127 break;
6128 else
6129 current = get_containing_scope (current);
6132 /* Check that the parms are used in the appropriate qualifying scopes
6133 in the declarator. */
6134 if (!comp_template_args
6135 (TI_ARGS (tinfo),
6136 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6138 error ("template arguments to %qD do not match original "
6139 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6140 if (!uses_template_parms (TI_ARGS (tinfo)))
6141 inform (input_location, "use %<template<>%> for"
6142 " an explicit specialization");
6143 /* Avoid crash in import_export_decl. */
6144 DECL_INTERFACE_KNOWN (decl) = 1;
6145 return error_mark_node;
6148 /* Check that the constraints for each enclosing template scope are
6149 consistent with the original declarations. */
6150 if (flag_concepts)
6152 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6153 tree scope_parms = current_template_parms;
6154 if (PRIMARY_TEMPLATE_P (tmpl))
6156 decl_parms = TREE_CHAIN (decl_parms);
6157 scope_parms = TREE_CHAIN (scope_parms);
6159 while (decl_parms)
6161 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6163 error ("redeclaration of %qD with different constraints",
6164 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6165 break;
6167 decl_parms = TREE_CHAIN (decl_parms);
6168 scope_parms = TREE_CHAIN (scope_parms);
6173 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6175 if (new_template_p)
6177 /* Push template declarations for global functions and types.
6178 Note that we do not try to push a global template friend
6179 declared in a template class; such a thing may well depend on
6180 the template parameters of the class and we'll push it when
6181 instantiating the befriending class. */
6182 if (!ctx
6183 && !(is_friend && template_class_depth (current_class_type) > 0))
6185 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6186 if (pushed == error_mark_node)
6187 return error_mark_node;
6189 /* pushdecl may have found an existing template. */
6190 if (pushed != tmpl)
6192 decl = DECL_TEMPLATE_RESULT (pushed);
6193 tmpl = NULL_TREE;
6196 else if (is_friend)
6198 /* Record this decl as belonging to the current class. It's
6199 not chained onto anything else. */
6200 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6201 gcc_checking_assert (!DECL_CHAIN (tmpl));
6202 DECL_CHAIN (tmpl) = current_scope ();
6205 else if (tmpl)
6206 /* The type may have been completed, or (erroneously) changed. */
6207 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6209 if (tmpl)
6211 if (is_primary)
6213 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6215 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6217 /* Give template template parms a DECL_CONTEXT of the template
6218 for which they are a parameter. */
6219 parms = INNERMOST_TEMPLATE_PARMS (parms);
6220 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6222 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6223 if (TREE_CODE (parm) == TEMPLATE_DECL)
6224 DECL_CONTEXT (parm) = tmpl;
6227 if (TREE_CODE (decl) == TYPE_DECL
6228 && TYPE_DECL_ALIAS_P (decl))
6230 if (tree constr
6231 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6233 /* ??? Why don't we do this here for all templates? */
6234 constr = build_constraints (constr, NULL_TREE);
6235 set_constraints (decl, constr);
6237 if (complex_alias_template_p (tmpl))
6238 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6242 /* The DECL_TI_ARGS of DECL contains full set of arguments
6243 referring wback to its most general template. If TMPL is a
6244 specialization, ARGS may only have the innermost set of
6245 arguments. Add the missing argument levels if necessary. */
6246 if (DECL_TEMPLATE_INFO (tmpl))
6247 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6249 tree info = build_template_info (tmpl, args);
6251 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6252 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6253 else
6255 retrofit_lang_decl (decl);
6256 DECL_TEMPLATE_INFO (decl) = info;
6260 if (flag_implicit_templates
6261 && !is_friend
6262 && TREE_PUBLIC (decl)
6263 && VAR_OR_FUNCTION_DECL_P (decl))
6264 /* Set DECL_COMDAT on template instantiations; if we force
6265 them to be emitted by explicit instantiation,
6266 mark_needed will tell cgraph to do the right thing. */
6267 DECL_COMDAT (decl) = true;
6269 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6271 return decl;
6274 /* FN is an inheriting constructor that inherits from the constructor
6275 template INHERITED; turn FN into a constructor template with a matching
6276 template header. */
6278 tree
6279 add_inherited_template_parms (tree fn, tree inherited)
6281 tree inner_parms
6282 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6283 inner_parms = copy_node (inner_parms);
6284 tree parms
6285 = tree_cons (size_int (current_template_depth + 1),
6286 inner_parms, current_template_parms);
6287 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6288 tree args = template_parms_to_args (parms);
6289 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6290 DECL_ARTIFICIAL (tmpl) = true;
6291 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6292 return tmpl;
6295 /* Called when a class template TYPE is redeclared with the indicated
6296 template PARMS, e.g.:
6298 template <class T> struct S;
6299 template <class T> struct S {}; */
6301 bool
6302 redeclare_class_template (tree type, tree parms, tree cons)
6304 tree tmpl;
6305 tree tmpl_parms;
6306 int i;
6308 if (!TYPE_TEMPLATE_INFO (type))
6310 error ("%qT is not a template type", type);
6311 return false;
6314 tmpl = TYPE_TI_TEMPLATE (type);
6315 if (!PRIMARY_TEMPLATE_P (tmpl))
6316 /* The type is nested in some template class. Nothing to worry
6317 about here; there are no new template parameters for the nested
6318 type. */
6319 return true;
6321 if (!parms)
6323 error ("template specifiers not specified in declaration of %qD",
6324 tmpl);
6325 return false;
6328 parms = INNERMOST_TEMPLATE_PARMS (parms);
6329 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6331 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6333 error_n (input_location, TREE_VEC_LENGTH (parms),
6334 "redeclared with %d template parameter",
6335 "redeclared with %d template parameters",
6336 TREE_VEC_LENGTH (parms));
6337 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6338 "previous declaration %qD used %d template parameter",
6339 "previous declaration %qD used %d template parameters",
6340 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6341 return false;
6344 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6346 tree tmpl_parm;
6347 tree parm;
6349 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6350 || TREE_VEC_ELT (parms, i) == error_mark_node)
6351 continue;
6353 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6354 if (error_operand_p (tmpl_parm))
6355 return false;
6357 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6359 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6360 TEMPLATE_DECL. */
6361 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6362 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6363 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6364 || (TREE_CODE (tmpl_parm) != PARM_DECL
6365 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6366 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6367 || (TREE_CODE (tmpl_parm) == PARM_DECL
6368 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6369 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6371 auto_diagnostic_group d;
6372 error ("template parameter %q+#D", tmpl_parm);
6373 if (DECL_P (parm))
6374 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6375 else
6376 inform (input_location, "redeclared here");
6377 return false;
6380 /* The parameters can be declared to introduce different
6381 constraints. */
6382 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6383 tree p2 = TREE_VEC_ELT (parms, i);
6384 if (!template_parameter_constraints_equivalent_p (p1, p2))
6386 auto_diagnostic_group d;
6387 error ("declaration of template parameter %q+#D with different "
6388 "constraints", parm);
6389 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6390 "original declaration appeared here");
6391 return false;
6394 /* Give each template template parm in this redeclaration a
6395 DECL_CONTEXT of the template for which they are a parameter. */
6396 if (TREE_CODE (parm) == TEMPLATE_DECL)
6398 gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
6399 || DECL_CONTEXT (parm) == tmpl);
6400 DECL_CONTEXT (parm) = tmpl;
6404 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6405 return false;
6407 tree ci = get_constraints (tmpl);
6408 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6409 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6411 /* Two classes with different constraints declare different entities. */
6412 if (!cp_tree_equal (req1, req2))
6414 auto_diagnostic_group d;
6415 error_at (input_location, "redeclaration of %q#D with different "
6416 "constraints", tmpl);
6417 inform (DECL_SOURCE_LOCATION (tmpl),
6418 "original declaration appeared here");
6419 return false;
6422 return true;
6425 /* The actual substitution part of instantiate_non_dependent_expr,
6426 to be used when the caller has already checked
6427 !instantiation_dependent_uneval_expression_p (expr)
6428 and cleared processing_template_decl. */
6430 tree
6431 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6433 return tsubst_copy_and_build (expr,
6434 /*args=*/NULL_TREE,
6435 complain,
6436 /*in_decl=*/NULL_TREE);
6439 /* Instantiate the non-dependent expression EXPR. */
6441 tree
6442 instantiate_non_dependent_expr (tree expr,
6443 tsubst_flags_t complain /* = tf_error */)
6445 if (expr == NULL_TREE)
6446 return NULL_TREE;
6448 if (processing_template_decl)
6450 /* The caller should have checked this already. */
6451 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6452 processing_template_decl_sentinel s;
6453 expr = instantiate_non_dependent_expr_internal (expr, complain);
6455 return expr;
6458 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6459 expression is dependent or non-constant. */
6461 tree
6462 instantiate_non_dependent_or_null (tree expr)
6464 if (expr == NULL_TREE)
6465 return NULL_TREE;
6466 if (processing_template_decl)
6468 if (!is_nondependent_constant_expression (expr))
6469 expr = NULL_TREE;
6470 else
6472 processing_template_decl_sentinel s;
6473 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6476 return expr;
6479 /* True iff T is a specialization of a variable template. */
6481 bool
6482 variable_template_specialization_p (tree t)
6484 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6485 return false;
6486 tree tmpl = DECL_TI_TEMPLATE (t);
6487 return variable_template_p (tmpl);
6490 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6491 template declaration, or a TYPE_DECL for an alias declaration. */
6493 bool
6494 alias_type_or_template_p (tree t)
6496 if (t == NULL_TREE)
6497 return false;
6498 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6499 || (TYPE_P (t)
6500 && TYPE_NAME (t)
6501 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6502 || DECL_ALIAS_TEMPLATE_P (t));
6505 /* If T is a specialization of an alias template, return it; otherwise return
6506 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6508 tree
6509 alias_template_specialization_p (const_tree t,
6510 bool transparent_typedefs)
6512 if (!TYPE_P (t))
6513 return NULL_TREE;
6515 /* It's an alias template specialization if it's an alias and its
6516 TYPE_NAME is a specialization of a primary template. */
6517 if (typedef_variant_p (t))
6519 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6520 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6521 return CONST_CAST_TREE (t);
6522 if (transparent_typedefs)
6523 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6524 (TYPE_NAME (t)),
6525 transparent_typedefs);
6528 return NULL_TREE;
6531 /* Data structure for complex_alias_template_*. */
6533 struct uses_all_template_parms_data
6535 int level;
6536 bool *seen;
6539 /* walk_tree callback for complex_alias_template_p. */
6541 static tree
6542 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6544 tree t = *tp;
6545 auto &data = *(struct uses_all_template_parms_data*)data_;
6547 switch (TREE_CODE (t))
6549 case TEMPLATE_TYPE_PARM:
6550 case TEMPLATE_PARM_INDEX:
6551 case TEMPLATE_TEMPLATE_PARM:
6552 case BOUND_TEMPLATE_TEMPLATE_PARM:
6554 tree idx = get_template_parm_index (t);
6555 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6556 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6559 default:;
6562 if (!PACK_EXPANSION_P (t))
6563 return 0;
6565 /* An alias template with a pack expansion that expands a pack from the
6566 enclosing class needs to be considered complex, to avoid confusion with
6567 the same pack being used as an argument to the alias's own template
6568 parameter (91966). */
6569 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6570 pack = TREE_CHAIN (pack))
6572 tree parm_pack = TREE_VALUE (pack);
6573 if (!TEMPLATE_PARM_P (parm_pack))
6574 continue;
6575 int idx, level;
6576 template_parm_level_and_index (parm_pack, &level, &idx);
6577 if (level < data.level)
6578 return t;
6580 /* Consider the expanded packs to be used outside the expansion... */
6581 data.seen[idx] = true;
6584 /* ...but don't walk into the pattern. Consider PR104008:
6586 template <typename T, typename... Ts>
6587 using IsOneOf = disjunction<is_same<T, Ts>...>;
6589 where IsOneOf seemingly uses all of its template parameters in its
6590 expansion (and does not expand a pack from the enclosing class), so the
6591 alias was not marked as complex. However, if it is used like
6592 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6593 expansion. So only Ts is considered used by the pack expansion. */
6594 *walk_subtrees = false;
6596 return 0;
6599 /* An alias template is complex from a SFINAE perspective if a template-id
6600 using that alias can be ill-formed when the expansion is not, as with
6601 the void_t template.
6603 Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6604 template arguments are empty packs. */
6606 static bool
6607 complex_alias_template_p (const_tree tmpl)
6609 /* A renaming alias isn't complex. */
6610 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6611 return false;
6613 /* Any other constrained alias is complex. */
6614 if (get_constraints (tmpl))
6615 return true;
6617 struct uses_all_template_parms_data data;
6618 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6619 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6620 data.level = TMPL_PARMS_DEPTH (parms);
6621 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6622 data.seen = XALLOCAVEC (bool, len);
6623 for (int i = 0; i < len; ++i)
6624 data.seen[i] = false;
6626 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6627 return true;
6628 for (int i = 0; i < len; ++i)
6629 if (!data.seen[i])
6630 return true;
6631 return false;
6634 /* If T is a specialization of a complex alias template with dependent
6635 template-arguments, return it; otherwise return NULL_TREE. If T is a
6636 typedef to such a specialization, return the specialization. */
6638 tree
6639 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6641 if (t == error_mark_node)
6642 return NULL_TREE;
6643 gcc_assert (TYPE_P (t));
6645 if (!typedef_variant_p (t))
6646 return NULL_TREE;
6648 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6649 if (tinfo
6650 && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6651 && (any_dependent_template_arguments_p
6652 (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6653 return CONST_CAST_TREE (t);
6655 if (transparent_typedefs)
6657 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6658 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6661 return NULL_TREE;
6664 /* Return the number of innermost template parameters in TMPL. */
6666 static int
6667 num_innermost_template_parms (const_tree tmpl)
6669 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6670 return TREE_VEC_LENGTH (parms);
6673 /* Return either TMPL or another template that it is equivalent to under DR
6674 1286: An alias that just changes the name of a template is equivalent to
6675 the other template. */
6677 static tree
6678 get_underlying_template (tree tmpl)
6680 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6681 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6683 /* Determine if the alias is equivalent to an underlying template. */
6684 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6685 /* The underlying type may have been ill-formed. Don't proceed. */
6686 if (!orig_type)
6687 break;
6688 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6689 if (!tinfo)
6690 break;
6692 tree underlying = TI_TEMPLATE (tinfo);
6693 if (!PRIMARY_TEMPLATE_P (underlying)
6694 || (num_innermost_template_parms (tmpl)
6695 != num_innermost_template_parms (underlying)))
6696 break;
6698 /* Does the alias add cv-quals? */
6699 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6700 break;
6702 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6703 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6704 break;
6706 /* Are any default template arguments equivalent? */
6707 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6708 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6709 const int nparms = TREE_VEC_LENGTH (aparms);
6710 for (int i = 0; i < nparms; ++i)
6712 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6713 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6714 if (!template_args_equal (adefarg, udefarg))
6715 goto top_break;
6718 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6719 it's appropriate to treat a less-constrained alias as equivalent. */
6720 if (!at_least_as_constrained (underlying, tmpl))
6721 break;
6723 /* Alias is equivalent. Strip it and repeat. */
6724 tmpl = underlying;
6726 top_break:;
6728 return tmpl;
6731 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6732 must be a reference-to-function or a pointer-to-function type, as specified
6733 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6734 and check that the resulting function has external linkage. */
6736 static tree
6737 convert_nontype_argument_function (tree type, tree expr,
6738 tsubst_flags_t complain)
6740 tree fns = expr;
6741 tree fn, fn_no_ptr;
6742 linkage_kind linkage;
6744 fn = instantiate_type (type, fns, tf_none);
6745 if (fn == error_mark_node)
6746 return error_mark_node;
6748 if (value_dependent_expression_p (fn))
6749 goto accept;
6751 fn_no_ptr = fn;
6752 if (REFERENCE_REF_P (fn_no_ptr))
6753 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6754 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6755 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6756 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6757 if (BASELINK_P (fn_no_ptr))
6758 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6760 /* [temp.arg.nontype]/1
6762 A template-argument for a non-type, non-template template-parameter
6763 shall be one of:
6764 [...]
6765 -- the address of an object or function with external [C++11: or
6766 internal] linkage. */
6768 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6769 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6771 if (complain & tf_error)
6773 location_t loc = cp_expr_loc_or_input_loc (expr);
6774 error_at (loc, "%qE is not a valid template argument for type %qT",
6775 expr, type);
6776 if (TYPE_PTR_P (type))
6777 inform (loc, "it must be the address of a function "
6778 "with external linkage");
6779 else
6780 inform (loc, "it must be the name of a function with "
6781 "external linkage");
6783 return NULL_TREE;
6786 linkage = decl_linkage (fn_no_ptr);
6787 if ((cxx_dialect < cxx11 && linkage != lk_external)
6788 || (cxx_dialect < cxx17 && linkage == lk_none))
6790 if (complain & tf_error)
6792 location_t loc = cp_expr_loc_or_input_loc (expr);
6793 if (cxx_dialect >= cxx11)
6794 error_at (loc, "%qE is not a valid template argument for type "
6795 "%qT because %qD has no linkage",
6796 expr, type, fn_no_ptr);
6797 else
6798 error_at (loc, "%qE is not a valid template argument for type "
6799 "%qT because %qD does not have external linkage",
6800 expr, type, fn_no_ptr);
6802 return NULL_TREE;
6805 accept:
6806 if (TYPE_REF_P (type))
6808 if (REFERENCE_REF_P (fn))
6809 fn = TREE_OPERAND (fn, 0);
6810 else
6811 fn = build_address (fn);
6813 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6814 fn = build_nop (type, fn);
6816 return fn;
6819 /* Subroutine of convert_nontype_argument.
6820 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6821 Emit an error otherwise. */
6823 static bool
6824 check_valid_ptrmem_cst_expr (tree type, tree expr,
6825 tsubst_flags_t complain)
6827 tree orig_expr = expr;
6828 STRIP_NOPS (expr);
6829 if (null_ptr_cst_p (expr))
6830 return true;
6831 if (TREE_CODE (expr) == PTRMEM_CST
6832 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6833 PTRMEM_CST_CLASS (expr)))
6834 return true;
6835 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6836 return true;
6837 if (processing_template_decl
6838 && TREE_CODE (expr) == ADDR_EXPR
6839 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6840 return true;
6841 if (complain & tf_error)
6843 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6844 error_at (loc, "%qE is not a valid template argument for type %qT",
6845 orig_expr, type);
6846 if (TREE_CODE (expr) != PTRMEM_CST)
6847 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6848 else
6849 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6851 return false;
6854 /* Returns TRUE iff the address of OP is value-dependent.
6856 14.6.2.4 [temp.dep.temp]:
6857 A non-integral non-type template-argument is dependent if its type is
6858 dependent or it has either of the following forms
6859 qualified-id
6860 & qualified-id
6861 and contains a nested-name-specifier which specifies a class-name that
6862 names a dependent type.
6864 We generalize this to just say that the address of a member of a
6865 dependent class is value-dependent; the above doesn't cover the
6866 address of a static data member named with an unqualified-id. */
6868 static bool
6869 has_value_dependent_address (tree op)
6871 STRIP_ANY_LOCATION_WRAPPER (op);
6873 /* We could use get_inner_reference here, but there's no need;
6874 this is only relevant for template non-type arguments, which
6875 can only be expressed as &id-expression. */
6876 if (DECL_P (op))
6878 tree ctx = CP_DECL_CONTEXT (op);
6880 if (TYPE_P (ctx) && dependent_type_p (ctx))
6881 return true;
6883 if (VAR_P (op)
6884 && TREE_STATIC (op)
6885 && TREE_CODE (ctx) == FUNCTION_DECL
6886 && type_dependent_expression_p (ctx))
6887 return true;
6890 return false;
6893 /* The next set of functions are used for providing helpful explanatory
6894 diagnostics for failed overload resolution. Their messages should be
6895 indented by two spaces for consistency with the messages in
6896 call.cc */
6898 static int
6899 unify_success (bool /*explain_p*/)
6901 return 0;
6904 /* Other failure functions should call this one, to provide a single function
6905 for setting a breakpoint on. */
6907 static int
6908 unify_invalid (bool /*explain_p*/)
6910 return 1;
6913 static int
6914 unify_parameter_deduction_failure (bool explain_p, tree parm)
6916 if (explain_p)
6917 inform (input_location,
6918 " couldn%'t deduce template parameter %qD", parm);
6919 return unify_invalid (explain_p);
6922 static int
6923 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6925 if (explain_p)
6926 inform (input_location,
6927 " types %qT and %qT have incompatible cv-qualifiers",
6928 parm, arg);
6929 return unify_invalid (explain_p);
6932 static int
6933 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6935 if (explain_p)
6936 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6937 return unify_invalid (explain_p);
6940 static int
6941 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6943 if (explain_p)
6944 inform (input_location,
6945 " template parameter %qD is not a parameter pack, but "
6946 "argument %qD is",
6947 parm, arg);
6948 return unify_invalid (explain_p);
6951 static int
6952 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6954 if (explain_p)
6955 inform (input_location,
6956 " template argument %qE does not match "
6957 "pointer-to-member constant %qE",
6958 arg, parm);
6959 return unify_invalid (explain_p);
6962 static int
6963 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6965 if (explain_p)
6966 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6967 return unify_invalid (explain_p);
6970 static int
6971 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6973 if (explain_p)
6974 inform (input_location,
6975 " inconsistent parameter pack deduction with %qT and %qT",
6976 old_arg, new_arg);
6977 return unify_invalid (explain_p);
6980 static int
6981 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6983 if (explain_p)
6985 if (TYPE_P (parm))
6986 inform (input_location,
6987 " deduced conflicting types for parameter %qT (%qT and %qT)",
6988 parm, first, second);
6989 else
6990 inform (input_location,
6991 " deduced conflicting values for non-type parameter "
6992 "%qE (%qE and %qE)", parm, first, second);
6994 return unify_invalid (explain_p);
6997 static int
6998 unify_vla_arg (bool explain_p, tree arg)
7000 if (explain_p)
7001 inform (input_location,
7002 " variable-sized array type %qT is not "
7003 "a valid template argument",
7004 arg);
7005 return unify_invalid (explain_p);
7008 static int
7009 unify_method_type_error (bool explain_p, tree arg)
7011 if (explain_p)
7012 inform (input_location,
7013 " member function type %qT is not a valid template argument",
7014 arg);
7015 return unify_invalid (explain_p);
7018 static int
7019 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7021 if (explain_p)
7023 if (least_p)
7024 inform_n (input_location, wanted,
7025 " candidate expects at least %d argument, %d provided",
7026 " candidate expects at least %d arguments, %d provided",
7027 wanted, have);
7028 else
7029 inform_n (input_location, wanted,
7030 " candidate expects %d argument, %d provided",
7031 " candidate expects %d arguments, %d provided",
7032 wanted, have);
7034 return unify_invalid (explain_p);
7037 static int
7038 unify_too_many_arguments (bool explain_p, int have, int wanted)
7040 return unify_arity (explain_p, have, wanted);
7043 static int
7044 unify_too_few_arguments (bool explain_p, int have, int wanted,
7045 bool least_p = false)
7047 return unify_arity (explain_p, have, wanted, least_p);
7050 static int
7051 unify_arg_conversion (bool explain_p, tree to_type,
7052 tree from_type, tree arg)
7054 if (explain_p)
7055 inform (cp_expr_loc_or_input_loc (arg),
7056 " cannot convert %qE (type %qT) to type %qT",
7057 arg, from_type, to_type);
7058 return unify_invalid (explain_p);
7061 static int
7062 unify_no_common_base (bool explain_p, enum template_base_result r,
7063 tree parm, tree arg)
7065 if (explain_p)
7066 switch (r)
7068 case tbr_ambiguous_baseclass:
7069 inform (input_location, " %qT is an ambiguous base class of %qT",
7070 parm, arg);
7071 break;
7072 default:
7073 inform (input_location, " %qT is not derived from %qT", arg, parm);
7074 break;
7076 return unify_invalid (explain_p);
7079 static int
7080 unify_inconsistent_template_template_parameters (bool explain_p)
7082 if (explain_p)
7083 inform (input_location,
7084 " template parameters of a template template argument are "
7085 "inconsistent with other deduced template arguments");
7086 return unify_invalid (explain_p);
7089 static int
7090 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7092 if (explain_p)
7093 inform (input_location,
7094 " cannot deduce a template for %qT from non-template type %qT",
7095 parm, arg);
7096 return unify_invalid (explain_p);
7099 static int
7100 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7102 if (explain_p)
7103 inform (input_location,
7104 " template argument %qE does not match %qE", arg, parm);
7105 return unify_invalid (explain_p);
7108 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7109 argument for TYPE, points to an unsuitable object.
7111 Also adjust the type of the index in C++20 array subobject references. */
7113 static bool
7114 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7116 switch (TREE_CODE (expr))
7118 CASE_CONVERT:
7119 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7120 complain);
7122 case TARGET_EXPR:
7123 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7124 complain);
7126 case CONSTRUCTOR:
7128 for (auto &e: CONSTRUCTOR_ELTS (expr))
7129 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7130 return true;
7132 break;
7134 case ADDR_EXPR:
7136 tree decl = TREE_OPERAND (expr, 0);
7138 if (cxx_dialect >= cxx20)
7139 while (TREE_CODE (decl) == COMPONENT_REF
7140 || TREE_CODE (decl) == ARRAY_REF)
7142 tree &op = TREE_OPERAND (decl, 1);
7143 if (TREE_CODE (decl) == ARRAY_REF
7144 && TREE_CODE (op) == INTEGER_CST)
7145 /* Canonicalize array offsets to ptrdiff_t; how they were
7146 written doesn't matter for subobject identity. */
7147 op = fold_convert (ptrdiff_type_node, op);
7148 decl = TREE_OPERAND (decl, 0);
7151 if (!VAR_OR_FUNCTION_DECL_P (decl))
7153 if (complain & tf_error)
7154 error_at (cp_expr_loc_or_input_loc (expr),
7155 "%qE is not a valid template argument of type %qT "
7156 "because %qE is not a variable or function",
7157 expr, type, decl);
7158 return true;
7160 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7162 if (complain & tf_error)
7163 error_at (cp_expr_loc_or_input_loc (expr),
7164 "%qE is not a valid template argument of type %qT "
7165 "in C++98 because %qD does not have external linkage",
7166 expr, type, decl);
7167 return true;
7169 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7170 && decl_linkage (decl) == lk_none)
7172 if (complain & tf_error)
7173 error_at (cp_expr_loc_or_input_loc (expr),
7174 "%qE is not a valid template argument of type %qT "
7175 "because %qD has no linkage", expr, type, decl);
7176 return true;
7178 /* C++17: For a non-type template-parameter of reference or pointer
7179 type, the value of the constant expression shall not refer to (or
7180 for a pointer type, shall not be the address of):
7181 * a subobject (4.5),
7182 * a temporary object (15.2),
7183 * a string literal (5.13.5),
7184 * the result of a typeid expression (8.2.8), or
7185 * a predefined __func__ variable (11.4.1). */
7186 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl))
7188 if (complain & tf_error)
7189 error ("the address of %qD is not a valid template argument",
7190 decl);
7191 return true;
7193 else if (cxx_dialect < cxx20
7194 && !(same_type_ignoring_top_level_qualifiers_p
7195 (strip_array_types (TREE_TYPE (type)),
7196 strip_array_types (TREE_TYPE (decl)))))
7198 if (complain & tf_error)
7199 error ("the address of the %qT subobject of %qD is not a "
7200 "valid template argument", TREE_TYPE (type), decl);
7201 return true;
7203 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7205 if (complain & tf_error)
7206 error ("the address of %qD is not a valid template argument "
7207 "because it does not have static storage duration",
7208 decl);
7209 return true;
7212 break;
7214 default:
7215 if (!INDIRECT_TYPE_P (type))
7216 /* We're only concerned about pointers and references here. */;
7217 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7218 /* Null pointer values are OK in C++11. */;
7219 else
7221 if (VAR_P (expr))
7223 if (complain & tf_error)
7224 error ("%qD is not a valid template argument "
7225 "because %qD is a variable, not the address of "
7226 "a variable", expr, expr);
7227 return true;
7229 else
7231 if (complain & tf_error)
7232 error ("%qE is not a valid template argument for %qT "
7233 "because it is not the address of a variable",
7234 expr, type);
7235 return true;
7239 return false;
7243 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7244 template argument EXPR. */
7246 static tree
7247 create_template_parm_object (tree expr, tsubst_flags_t complain)
7249 if (TREE_CODE (expr) == TARGET_EXPR)
7250 expr = TARGET_EXPR_INITIAL (expr);
7252 if (!TREE_CONSTANT (expr))
7254 if ((complain & tf_error)
7255 && require_rvalue_constant_expression (expr))
7256 cxx_constant_value (expr);
7257 return error_mark_node;
7259 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7260 return error_mark_node;
7262 /* This is no longer a compound literal. */
7263 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7265 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7268 /* The template arguments corresponding to template parameter objects of types
7269 that contain pointers to members. */
7271 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7273 /* Find or build an nttp object for (already-validated) EXPR with name
7274 NAME. */
7276 tree
7277 get_template_parm_object (tree expr, tree name)
7279 tree decl = get_global_binding (name);
7280 if (decl)
7281 return decl;
7283 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7284 decl = create_temporary_var (type);
7285 DECL_NTTP_OBJECT_P (decl) = true;
7286 DECL_CONTEXT (decl) = NULL_TREE;
7287 TREE_STATIC (decl) = true;
7288 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7289 TREE_READONLY (decl) = true;
7290 DECL_NAME (decl) = name;
7291 SET_DECL_ASSEMBLER_NAME (decl, name);
7292 comdat_linkage (decl);
7294 if (!zero_init_p (type))
7296 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7297 lower_var_init before we're done mangling. So store the original
7298 value elsewhere. */
7299 tree copy = unshare_constructor (expr);
7300 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7303 pushdecl_top_level_and_finish (decl, expr);
7305 return decl;
7308 /* Return the actual template argument corresponding to template parameter
7309 object VAR. */
7311 tree
7312 tparm_object_argument (tree var)
7314 if (zero_init_p (TREE_TYPE (var)))
7315 return DECL_INITIAL (var);
7316 return *(tparm_obj_values->get (var));
7319 /* Attempt to convert the non-type template parameter EXPR to the
7320 indicated TYPE. If the conversion is successful, return the
7321 converted value. If the conversion is unsuccessful, return
7322 NULL_TREE if we issued an error message, or error_mark_node if we
7323 did not. We issue error messages for out-and-out bad template
7324 parameters, but not simply because the conversion failed, since we
7325 might be just trying to do argument deduction. Both TYPE and EXPR
7326 must be non-dependent.
7328 The conversion follows the special rules described in
7329 [temp.arg.nontype], and it is much more strict than an implicit
7330 conversion.
7332 This function is called twice for each template argument (see
7333 lookup_template_class for a more accurate description of this
7334 problem). This means that we need to handle expressions which
7335 are not valid in a C++ source, but can be created from the
7336 first call (for instance, casts to perform conversions). These
7337 hacks can go away after we fix the double coercion problem. */
7339 static tree
7340 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7342 tree expr_type;
7343 location_t loc = cp_expr_loc_or_input_loc (expr);
7345 /* Detect immediately string literals as invalid non-type argument.
7346 This special-case is not needed for correctness (we would easily
7347 catch this later), but only to provide better diagnostic for this
7348 common user mistake. As suggested by DR 100, we do not mention
7349 linkage issues in the diagnostic as this is not the point. */
7350 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7352 if (complain & tf_error)
7353 error ("%qE is not a valid template argument for type %qT "
7354 "because string literals can never be used in this context",
7355 expr, type);
7356 return NULL_TREE;
7359 /* Add the ADDR_EXPR now for the benefit of
7360 value_dependent_expression_p. */
7361 if (TYPE_PTROBV_P (type)
7362 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7364 expr = decay_conversion (expr, complain);
7365 if (expr == error_mark_node)
7366 return error_mark_node;
7369 /* If we are in a template, EXPR may be non-dependent, but still
7370 have a syntactic, rather than semantic, form. For example, EXPR
7371 might be a SCOPE_REF, rather than the VAR_DECL to which the
7372 SCOPE_REF refers. Preserving the qualifying scope is necessary
7373 so that access checking can be performed when the template is
7374 instantiated -- but here we need the resolved form so that we can
7375 convert the argument. */
7376 bool non_dep = false;
7377 if (TYPE_REF_OBJ_P (type)
7378 && has_value_dependent_address (expr))
7379 /* If we want the address and it's value-dependent, don't fold. */;
7380 else if (processing_template_decl
7381 && !instantiation_dependent_expression_p (expr))
7382 non_dep = true;
7383 if (error_operand_p (expr))
7384 return error_mark_node;
7385 expr_type = TREE_TYPE (expr);
7387 /* If the argument is non-dependent, perform any conversions in
7388 non-dependent context as well. */
7389 processing_template_decl_sentinel s (non_dep);
7390 if (non_dep)
7391 expr = instantiate_non_dependent_expr_internal (expr, complain);
7393 bool val_dep_p = value_dependent_expression_p (expr);
7394 if (val_dep_p)
7395 expr = canonicalize_expr_argument (expr, complain);
7396 else
7397 STRIP_ANY_LOCATION_WRAPPER (expr);
7399 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7400 to a non-type argument of "nullptr". */
7401 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7402 expr = fold_simple (convert (type, expr));
7404 /* In C++11, integral or enumeration non-type template arguments can be
7405 arbitrary constant expressions. Pointer and pointer to
7406 member arguments can be general constant expressions that evaluate
7407 to a null value, but otherwise still need to be of a specific form. */
7408 if (cxx_dialect >= cxx11)
7410 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7411 /* A PTRMEM_CST is already constant, and a valid template
7412 argument for a parameter of pointer to member type, we just want
7413 to leave it in that form rather than lower it to a
7414 CONSTRUCTOR. */;
7415 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7416 || cxx_dialect >= cxx17)
7418 /* C++17: A template-argument for a non-type template-parameter shall
7419 be a converted constant expression (8.20) of the type of the
7420 template-parameter. */
7421 expr = build_converted_constant_expr (type, expr, complain);
7422 if (expr == error_mark_node)
7423 /* Make sure we return NULL_TREE only if we have really issued
7424 an error, as described above. */
7425 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7426 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7428 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7429 return expr;
7431 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7432 expr = convert_from_reference (expr);
7433 /* EXPR may have become value-dependent. */
7434 val_dep_p = value_dependent_expression_p (expr);
7436 else if (TYPE_PTR_OR_PTRMEM_P (type))
7438 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7439 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7440 : null_member_pointer_value_p (folded))
7441 expr = folded;
7445 if (TYPE_REF_P (type))
7446 expr = mark_lvalue_use (expr);
7447 else
7448 expr = mark_rvalue_use (expr);
7450 /* HACK: Due to double coercion, we can get a
7451 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7452 which is the tree that we built on the first call (see
7453 below when coercing to reference to object or to reference to
7454 function). We just strip everything and get to the arg.
7455 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7456 for examples. */
7457 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7459 /* Check this before we strip *& to avoid redundancy. */
7460 if (!mark_single_function (expr, complain))
7461 return error_mark_node;
7463 tree probe_type, probe = expr;
7464 if (REFERENCE_REF_P (probe))
7465 probe = TREE_OPERAND (probe, 0);
7466 probe_type = TREE_TYPE (probe);
7467 if (TREE_CODE (probe) == NOP_EXPR)
7469 /* ??? Maybe we could use convert_from_reference here, but we
7470 would need to relax its constraints because the NOP_EXPR
7471 could actually change the type to something more cv-qualified,
7472 and this is not folded by convert_from_reference. */
7473 tree addr = TREE_OPERAND (probe, 0);
7474 if (TYPE_REF_P (probe_type)
7475 && TREE_CODE (addr) == ADDR_EXPR
7476 && TYPE_PTR_P (TREE_TYPE (addr))
7477 && (same_type_ignoring_top_level_qualifiers_p
7478 (TREE_TYPE (probe_type),
7479 TREE_TYPE (TREE_TYPE (addr)))))
7481 expr = TREE_OPERAND (addr, 0);
7482 expr_type = TREE_TYPE (probe_type);
7487 /* [temp.arg.nontype]/5, bullet 1
7489 For a non-type template-parameter of integral or enumeration type,
7490 integral promotions (_conv.prom_) and integral conversions
7491 (_conv.integral_) are applied. */
7492 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7493 || SCALAR_FLOAT_TYPE_P (type))
7495 if (cxx_dialect < cxx11)
7497 tree t = build_converted_constant_expr (type, expr, complain);
7498 t = maybe_constant_value (t);
7499 if (t != error_mark_node)
7500 expr = t;
7503 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7504 return error_mark_node;
7506 /* Notice that there are constant expressions like '4 % 0' which
7507 do not fold into integer constants. */
7508 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7510 if (complain & tf_error)
7512 int errs = errorcount, warns = warningcount + werrorcount;
7513 if (!require_potential_constant_expression (expr))
7514 expr = error_mark_node;
7515 else
7516 expr = cxx_constant_value (expr);
7517 if (errorcount > errs || warningcount + werrorcount > warns)
7518 inform (loc, "in template argument for type %qT", type);
7519 if (expr == error_mark_node)
7520 return NULL_TREE;
7521 /* else cxx_constant_value complained but gave us
7522 a real constant, so go ahead. */
7523 if (!CONSTANT_CLASS_P (expr))
7525 /* Some assemble time constant expressions like
7526 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7527 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7528 as we can emit them into .rodata initializers of
7529 variables, yet they can't fold into an INTEGER_CST at
7530 compile time. Refuse them here. */
7531 gcc_checking_assert (reduced_constant_expression_p (expr));
7532 error_at (loc, "template argument %qE for type %qT not "
7533 "a compile-time constant", expr, type);
7534 return NULL_TREE;
7537 else
7538 return NULL_TREE;
7541 /* Avoid typedef problems. */
7542 if (TREE_TYPE (expr) != type)
7543 expr = fold_convert (type, expr);
7545 /* [temp.arg.nontype]/5, bullet 2
7547 For a non-type template-parameter of type pointer to object,
7548 qualification conversions (_conv.qual_) and the array-to-pointer
7549 conversion (_conv.array_) are applied. */
7550 else if (TYPE_PTROBV_P (type))
7552 tree decayed = expr;
7554 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7555 decay_conversion or an explicit cast. If it's a problematic cast,
7556 we'll complain about it below. */
7557 if (TREE_CODE (expr) == NOP_EXPR)
7559 tree probe = expr;
7560 STRIP_NOPS (probe);
7561 if (TREE_CODE (probe) == ADDR_EXPR
7562 && TYPE_PTR_P (TREE_TYPE (probe)))
7564 expr = probe;
7565 expr_type = TREE_TYPE (expr);
7569 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7571 A template-argument for a non-type, non-template template-parameter
7572 shall be one of: [...]
7574 -- the name of a non-type template-parameter;
7575 -- the address of an object or function with external linkage, [...]
7576 expressed as "& id-expression" where the & is optional if the name
7577 refers to a function or array, or if the corresponding
7578 template-parameter is a reference.
7580 Here, we do not care about functions, as they are invalid anyway
7581 for a parameter of type pointer-to-object. */
7583 if (val_dep_p)
7584 /* Non-type template parameters are OK. */
7586 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7587 /* Null pointer values are OK in C++11. */;
7588 else if (TREE_CODE (expr) != ADDR_EXPR
7589 && !INDIRECT_TYPE_P (expr_type))
7590 /* Other values, like integer constants, might be valid
7591 non-type arguments of some other type. */
7592 return error_mark_node;
7593 else if (invalid_tparm_referent_p (type, expr, complain))
7594 return NULL_TREE;
7596 expr = decayed;
7598 expr = perform_qualification_conversions (type, expr);
7599 if (expr == error_mark_node)
7600 return error_mark_node;
7602 /* [temp.arg.nontype]/5, bullet 3
7604 For a non-type template-parameter of type reference to object, no
7605 conversions apply. The type referred to by the reference may be more
7606 cv-qualified than the (otherwise identical) type of the
7607 template-argument. The template-parameter is bound directly to the
7608 template-argument, which must be an lvalue. */
7609 else if (TYPE_REF_OBJ_P (type))
7611 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7612 expr_type))
7613 return error_mark_node;
7615 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7617 if (complain & tf_error)
7618 error ("%qE is not a valid template argument for type %qT "
7619 "because of conflicts in cv-qualification", expr, type);
7620 return NULL_TREE;
7623 if (!lvalue_p (expr))
7625 if (complain & tf_error)
7626 error ("%qE is not a valid template argument for type %qT "
7627 "because it is not an lvalue", expr, type);
7628 return NULL_TREE;
7631 /* [temp.arg.nontype]/1
7633 A template-argument for a non-type, non-template template-parameter
7634 shall be one of: [...]
7636 -- the address of an object or function with external linkage. */
7637 if (INDIRECT_REF_P (expr)
7638 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7640 expr = TREE_OPERAND (expr, 0);
7641 if (DECL_P (expr))
7643 if (complain & tf_error)
7644 error ("%q#D is not a valid template argument for type %qT "
7645 "because a reference variable does not have a constant "
7646 "address", expr, type);
7647 return NULL_TREE;
7651 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7652 /* OK, dependent reference. We don't want to ask whether a DECL is
7653 itself value-dependent, since what we want here is its address. */;
7654 else
7656 expr = build_address (expr);
7658 if (invalid_tparm_referent_p (type, expr, complain))
7659 return NULL_TREE;
7662 if (!same_type_p (type, TREE_TYPE (expr)))
7663 expr = build_nop (type, expr);
7665 /* [temp.arg.nontype]/5, bullet 4
7667 For a non-type template-parameter of type pointer to function, only
7668 the function-to-pointer conversion (_conv.func_) is applied. If the
7669 template-argument represents a set of overloaded functions (or a
7670 pointer to such), the matching function is selected from the set
7671 (_over.over_). */
7672 else if (TYPE_PTRFN_P (type))
7674 /* If the argument is a template-id, we might not have enough
7675 context information to decay the pointer. */
7676 if (!type_unknown_p (expr_type))
7678 expr = decay_conversion (expr, complain);
7679 if (expr == error_mark_node)
7680 return error_mark_node;
7683 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7684 /* Null pointer values are OK in C++11. */
7685 return perform_qualification_conversions (type, expr);
7687 expr = convert_nontype_argument_function (type, expr, complain);
7688 if (!expr || expr == error_mark_node)
7689 return expr;
7691 /* [temp.arg.nontype]/5, bullet 5
7693 For a non-type template-parameter of type reference to function, no
7694 conversions apply. If the template-argument represents a set of
7695 overloaded functions, the matching function is selected from the set
7696 (_over.over_). */
7697 else if (TYPE_REFFN_P (type))
7699 if (TREE_CODE (expr) == ADDR_EXPR)
7701 if (complain & tf_error)
7703 error ("%qE is not a valid template argument for type %qT "
7704 "because it is a pointer", expr, type);
7705 inform (input_location, "try using %qE instead",
7706 TREE_OPERAND (expr, 0));
7708 return NULL_TREE;
7711 expr = convert_nontype_argument_function (type, expr, complain);
7712 if (!expr || expr == error_mark_node)
7713 return expr;
7715 /* [temp.arg.nontype]/5, bullet 6
7717 For a non-type template-parameter of type pointer to member function,
7718 no conversions apply. If the template-argument represents a set of
7719 overloaded member functions, the matching member function is selected
7720 from the set (_over.over_). */
7721 else if (TYPE_PTRMEMFUNC_P (type))
7723 expr = instantiate_type (type, expr, tf_none);
7724 if (expr == error_mark_node)
7725 return error_mark_node;
7727 /* [temp.arg.nontype] bullet 1 says the pointer to member
7728 expression must be a pointer-to-member constant. */
7729 if (!val_dep_p
7730 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7731 return NULL_TREE;
7733 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7734 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7735 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7736 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7738 /* [temp.arg.nontype]/5, bullet 7
7740 For a non-type template-parameter of type pointer to data member,
7741 qualification conversions (_conv.qual_) are applied. */
7742 else if (TYPE_PTRDATAMEM_P (type))
7744 /* [temp.arg.nontype] bullet 1 says the pointer to member
7745 expression must be a pointer-to-member constant. */
7746 if (!val_dep_p
7747 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7748 return NULL_TREE;
7750 expr = perform_qualification_conversions (type, expr);
7751 if (expr == error_mark_node)
7752 return expr;
7754 else if (NULLPTR_TYPE_P (type))
7756 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7758 if (complain & tf_error)
7759 error ("%qE is not a valid template argument for type %qT "
7760 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7761 return NULL_TREE;
7763 return expr;
7765 else if (CLASS_TYPE_P (type))
7767 /* Replace the argument with a reference to the corresponding template
7768 parameter object. */
7769 if (!val_dep_p)
7770 expr = create_template_parm_object (expr, complain);
7771 if (expr == error_mark_node)
7772 return NULL_TREE;
7774 /* A template non-type parameter must be one of the above. */
7775 else
7776 gcc_unreachable ();
7778 /* Sanity check: did we actually convert the argument to the
7779 right type? */
7780 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7781 (type, TREE_TYPE (expr)));
7782 return convert_from_reference (expr);
7785 /* Subroutine of coerce_template_template_parms, which returns 1 if
7786 PARM_PARM and ARG_PARM match using the rule for the template
7787 parameters of template template parameters. Both PARM and ARG are
7788 template parameters; the rest of the arguments are the same as for
7789 coerce_template_template_parms.
7791 static int
7792 coerce_template_template_parm (tree parm,
7793 tree arg,
7794 tsubst_flags_t complain,
7795 tree in_decl,
7796 tree outer_args)
7798 if (arg == NULL_TREE || error_operand_p (arg)
7799 || parm == NULL_TREE || error_operand_p (parm))
7800 return 0;
7802 if (TREE_CODE (arg) != TREE_CODE (parm))
7803 return 0;
7805 switch (TREE_CODE (parm))
7807 case TEMPLATE_DECL:
7808 /* We encounter instantiations of templates like
7809 template <template <template <class> class> class TT>
7810 class C; */
7812 if (!coerce_template_template_parms
7813 (parm, arg, complain, in_decl, outer_args))
7814 return 0;
7816 /* Fall through. */
7818 case TYPE_DECL:
7819 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7820 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7821 /* Argument is a parameter pack but parameter is not. */
7822 return 0;
7823 break;
7825 case PARM_DECL:
7826 /* The tsubst call is used to handle cases such as
7828 template <int> class C {};
7829 template <class T, template <T> class TT> class D {};
7830 D<int, C> d;
7832 i.e. the parameter list of TT depends on earlier parameters. */
7833 if (!uses_template_parms (TREE_TYPE (arg)))
7835 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7836 if (!uses_template_parms (t)
7837 && !same_type_p (t, TREE_TYPE (arg)))
7838 return 0;
7841 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7842 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7843 /* Argument is a parameter pack but parameter is not. */
7844 return 0;
7846 break;
7848 default:
7849 gcc_unreachable ();
7852 return 1;
7855 /* Coerce template argument list ARGLIST for use with template
7856 template-parameter TEMPL. */
7858 static tree
7859 coerce_template_args_for_ttp (tree templ, tree arglist,
7860 tsubst_flags_t complain)
7862 /* Consider an example where a template template parameter declared as
7864 template <class T, class U = std::allocator<T> > class TT
7866 The template parameter level of T and U are one level larger than
7867 of TT. To proper process the default argument of U, say when an
7868 instantiation `TT<int>' is seen, we need to build the full
7869 arguments containing {int} as the innermost level. Outer levels,
7870 available when not appearing as default template argument, can be
7871 obtained from the arguments of the enclosing template.
7873 Suppose that TT is later substituted with std::vector. The above
7874 instantiation is `TT<int, std::allocator<T> >' with TT at
7875 level 1, and T at level 2, while the template arguments at level 1
7876 becomes {std::vector} and the inner level 2 is {int}. */
7878 tree outer = DECL_CONTEXT (templ);
7879 if (outer)
7880 outer = generic_targs_for (outer);
7881 else if (current_template_parms)
7883 /* This is an argument of the current template, so we haven't set
7884 DECL_CONTEXT yet. We can also get here when level-lowering a
7885 bound ttp. */
7886 tree relevant_template_parms;
7888 /* Parameter levels that are greater than the level of the given
7889 template template parm are irrelevant. */
7890 relevant_template_parms = current_template_parms;
7891 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7892 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7893 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7895 outer = template_parms_to_args (relevant_template_parms);
7898 if (outer)
7899 arglist = add_to_template_args (outer, arglist);
7901 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7902 return coerce_template_parms (parmlist, arglist, templ, complain);
7905 /* A cache of template template parameters with match-all default
7906 arguments. */
7907 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7909 /* T is a bound template template-parameter. Copy its arguments into default
7910 arguments of the template template-parameter's template parameters. */
7912 static tree
7913 add_defaults_to_ttp (tree otmpl)
7915 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7916 return *c;
7918 tree ntmpl = copy_node (otmpl);
7920 tree ntype = copy_node (TREE_TYPE (otmpl));
7921 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7922 TYPE_MAIN_VARIANT (ntype) = ntype;
7923 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7924 TYPE_NAME (ntype) = ntmpl;
7925 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7927 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7928 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7929 TEMPLATE_PARM_DECL (idx) = ntmpl;
7930 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7932 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7933 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7934 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7935 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7936 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7938 tree o = TREE_VEC_ELT (vec, i);
7939 if (!template_parameter_pack_p (TREE_VALUE (o)))
7941 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7942 TREE_PURPOSE (n) = any_targ_node;
7946 tree oresult = DECL_TEMPLATE_RESULT (otmpl);
7947 tree gen_otmpl = DECL_TI_TEMPLATE (oresult);
7948 tree gen_ntmpl;
7949 if (gen_otmpl == otmpl)
7950 gen_ntmpl = ntmpl;
7951 else
7952 gen_ntmpl = add_defaults_to_ttp (gen_otmpl);
7954 tree nresult = copy_decl (oresult);
7955 DECL_TEMPLATE_INFO (nresult)
7956 = build_template_info (gen_ntmpl, TI_ARGS (DECL_TEMPLATE_INFO (oresult)));
7957 DECL_TEMPLATE_RESULT (ntmpl) = nresult;
7959 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7960 return ntmpl;
7963 /* ARG is a bound potential template template-argument, and PARGS is a list
7964 of arguments for the corresponding template template-parameter. Adjust
7965 PARGS as appropriate for application to ARG's template, and if ARG is a
7966 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7967 arguments to the template template parameter. */
7969 static tree
7970 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7972 ++processing_template_decl;
7973 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7974 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7976 /* When comparing two template template-parameters in partial ordering,
7977 rewrite the one currently being used as an argument to have default
7978 arguments for all parameters. */
7979 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7980 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7981 if (pargs != error_mark_node)
7982 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7983 TYPE_TI_ARGS (arg));
7985 else
7987 tree aparms
7988 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7989 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
7991 --processing_template_decl;
7992 return pargs;
7995 /* Subroutine of unify for the case when PARM is a
7996 BOUND_TEMPLATE_TEMPLATE_PARM. */
7998 static int
7999 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
8000 bool explain_p)
8002 tree parmvec = TYPE_TI_ARGS (parm);
8003 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
8005 /* The template template parm might be variadic and the argument
8006 not, so flatten both argument lists. */
8007 parmvec = expand_template_argument_pack (parmvec);
8008 argvec = expand_template_argument_pack (argvec);
8010 if (flag_new_ttp)
8012 /* In keeping with P0522R0, adjust P's template arguments
8013 to apply to A's template; then flatten it again. */
8014 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
8015 nparmvec = expand_template_argument_pack (nparmvec);
8017 if (unify (tparms, targs, nparmvec, argvec,
8018 UNIFY_ALLOW_NONE, explain_p))
8019 return 1;
8021 /* If the P0522 adjustment eliminated a pack expansion, deduce
8022 empty packs. */
8023 if (flag_new_ttp
8024 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8025 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8026 DEDUCE_EXACT, /*sub*/true, explain_p))
8027 return 1;
8029 else
8031 /* Deduce arguments T, i from TT<T> or TT<i>.
8032 We check each element of PARMVEC and ARGVEC individually
8033 rather than the whole TREE_VEC since they can have
8034 different number of elements, which is allowed under N2555. */
8036 int len = TREE_VEC_LENGTH (parmvec);
8038 /* Check if the parameters end in a pack, making them
8039 variadic. */
8040 int parm_variadic_p = 0;
8041 if (len > 0
8042 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8043 parm_variadic_p = 1;
8045 for (int i = 0; i < len - parm_variadic_p; ++i)
8046 /* If the template argument list of P contains a pack
8047 expansion that is not the last template argument, the
8048 entire template argument list is a non-deduced
8049 context. */
8050 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8051 return unify_success (explain_p);
8053 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8054 return unify_too_few_arguments (explain_p,
8055 TREE_VEC_LENGTH (argvec), len);
8057 for (int i = 0; i < len - parm_variadic_p; ++i)
8058 if (unify (tparms, targs,
8059 TREE_VEC_ELT (parmvec, i),
8060 TREE_VEC_ELT (argvec, i),
8061 UNIFY_ALLOW_NONE, explain_p))
8062 return 1;
8064 if (parm_variadic_p
8065 && unify_pack_expansion (tparms, targs,
8066 parmvec, argvec,
8067 DEDUCE_EXACT,
8068 /*subr=*/true, explain_p))
8069 return 1;
8072 return 0;
8075 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8076 template template parameters.
8078 Consider the example:
8079 template <class T> class A;
8080 template<template <class U> class TT> class B;
8082 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8083 and OUTER_ARGS contains A. */
8085 static int
8086 coerce_template_template_parms (tree parm_tmpl,
8087 tree arg_tmpl,
8088 tsubst_flags_t complain,
8089 tree in_decl,
8090 tree outer_args)
8092 int nparms, nargs, i;
8093 tree parm, arg;
8094 int variadic_p = 0;
8096 tree parm_parms = DECL_INNERMOST_TEMPLATE_PARMS (parm_tmpl);
8097 tree arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (arg_tmpl);
8098 tree gen_arg_tmpl = most_general_template (arg_tmpl);
8099 tree gen_arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_arg_tmpl);
8101 nparms = TREE_VEC_LENGTH (parm_parms);
8102 nargs = TREE_VEC_LENGTH (arg_parms);
8104 if (flag_new_ttp)
8106 /* P0522R0: A template template-parameter P is at least as specialized as
8107 a template template-argument A if, given the following rewrite to two
8108 function templates, the function template corresponding to P is at
8109 least as specialized as the function template corresponding to A
8110 according to the partial ordering rules for function templates
8111 ([temp.func.order]). Given an invented class template X with the
8112 template parameter list of A (including default arguments):
8114 * Each of the two function templates has the same template parameters,
8115 respectively, as P or A.
8117 * Each function template has a single function parameter whose type is
8118 a specialization of X with template arguments corresponding to the
8119 template parameters from the respective function template where, for
8120 each template parameter PP in the template parameter list of the
8121 function template, a corresponding template argument AA is formed. If
8122 PP declares a parameter pack, then AA is the pack expansion
8123 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8125 If the rewrite produces an invalid type, then P is not at least as
8126 specialized as A. */
8128 /* So coerce P's args to apply to A's parms, and then deduce between A's
8129 args and the converted args. If that succeeds, A is at least as
8130 specialized as P, so they match.*/
8131 processing_template_decl_sentinel ptds (/*reset*/false);
8132 ++processing_template_decl;
8134 tree pargs = template_parms_level_to_args (parm_parms);
8136 /* PARM and ARG might be at different template depths, and we want to
8137 pass the right additional levels of args when coercing PARGS to
8138 ARG_PARMS in case we need to do any substitution into non-type
8139 template parameter types.
8141 OUTER_ARGS are not the right outer levels in this case, as they are
8142 the args we're building up for PARM, and for the coercion we want the
8143 args for ARG. If DECL_CONTEXT isn't set for a template template
8144 parameter, we can assume that it's in the current scope. */
8145 tree ctx = DECL_CONTEXT (arg_tmpl);
8146 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8147 ctx = current_scope ();
8148 tree scope_args = NULL_TREE;
8149 if (tree tinfo = get_template_info (ctx))
8150 scope_args = TI_ARGS (tinfo);
8151 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8153 int level = TEMPLATE_TYPE_LEVEL (TREE_TYPE (gen_arg_tmpl));
8154 int scope_depth = TMPL_ARGS_DEPTH (scope_args);
8155 tree full_pargs = make_tree_vec (level + 1);
8157 /* Only use as many levels from the scope as needed
8158 (excluding the level of ARG). */
8159 for (int i = 0; i < level - 1; ++i)
8160 if (i < scope_depth)
8161 TREE_VEC_ELT (full_pargs, i) = TMPL_ARGS_LEVEL (scope_args, i + 1);
8162 else
8163 TREE_VEC_ELT (full_pargs, i) = make_tree_vec (0);
8165 /* Add the arguments that appear at the levels of ARG. */
8166 tree adjacent = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (arg_tmpl));
8167 adjacent = TMPL_ARGS_LEVEL (adjacent, TMPL_ARGS_DEPTH (adjacent) - 1);
8168 TREE_VEC_ELT (full_pargs, level - 1) = adjacent;
8170 TREE_VEC_ELT (full_pargs, level) = pargs;
8171 pargs = full_pargs;
8173 else
8174 pargs = add_to_template_args (scope_args, pargs);
8176 pargs = coerce_template_parms (gen_arg_parms, pargs,
8177 NULL_TREE, tf_none);
8178 if (pargs != error_mark_node)
8180 tree targs = make_tree_vec (nargs);
8181 tree aargs = template_parms_level_to_args (arg_parms);
8182 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8183 /*explain*/false))
8184 return 1;
8188 /* Determine whether we have a parameter pack at the end of the
8189 template template parameter's template parameter list. */
8190 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8192 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8194 if (error_operand_p (parm))
8195 return 0;
8197 switch (TREE_CODE (parm))
8199 case TEMPLATE_DECL:
8200 case TYPE_DECL:
8201 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8202 variadic_p = 1;
8203 break;
8205 case PARM_DECL:
8206 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8207 variadic_p = 1;
8208 break;
8210 default:
8211 gcc_unreachable ();
8215 if (nargs != nparms
8216 && !(variadic_p && nargs >= nparms - 1))
8217 return 0;
8219 /* Check all of the template parameters except the parameter pack at
8220 the end (if any). */
8221 for (i = 0; i < nparms - variadic_p; ++i)
8223 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8224 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8225 continue;
8227 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8228 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8230 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8231 outer_args))
8232 return 0;
8236 if (variadic_p)
8238 /* Check each of the template parameters in the template
8239 argument against the template parameter pack at the end of
8240 the template template parameter. */
8241 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8242 return 0;
8244 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8246 for (; i < nargs; ++i)
8248 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8249 continue;
8251 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8253 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8254 outer_args))
8255 return 0;
8259 return 1;
8262 /* Verifies that the deduced template arguments (in TARGS) for the
8263 template template parameters (in TPARMS) represent valid bindings,
8264 by comparing the template parameter list of each template argument
8265 to the template parameter list of its corresponding template
8266 template parameter, in accordance with DR150. This
8267 routine can only be called after all template arguments have been
8268 deduced. It will return TRUE if all of the template template
8269 parameter bindings are okay, FALSE otherwise. */
8270 bool
8271 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8273 int i, ntparms = TREE_VEC_LENGTH (tparms);
8274 bool ret = true;
8276 /* We're dealing with template parms in this process. */
8277 ++processing_template_decl;
8279 targs = INNERMOST_TEMPLATE_ARGS (targs);
8281 for (i = 0; i < ntparms; ++i)
8283 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8284 tree targ = TREE_VEC_ELT (targs, i);
8286 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8288 tree packed_args = NULL_TREE;
8289 int idx, len = 1;
8291 if (ARGUMENT_PACK_P (targ))
8293 /* Look inside the argument pack. */
8294 packed_args = ARGUMENT_PACK_ARGS (targ);
8295 len = TREE_VEC_LENGTH (packed_args);
8298 for (idx = 0; idx < len; ++idx)
8300 if (packed_args)
8301 /* Extract the next argument from the argument
8302 pack. */
8303 targ = TREE_VEC_ELT (packed_args, idx);
8305 if (PACK_EXPANSION_P (targ))
8306 /* Look at the pattern of the pack expansion. */
8307 targ = PACK_EXPANSION_PATTERN (targ);
8309 /* Extract the template parameters from the template
8310 argument. */
8311 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8312 targ = TYPE_NAME (targ);
8314 /* Verify that we can coerce the template template
8315 parameters from the template argument to the template
8316 parameter. This requires an exact match. */
8317 if (TREE_CODE (targ) == TEMPLATE_DECL
8318 && !coerce_template_template_parms
8319 (tparm,
8320 targ,
8321 tf_none,
8322 tparm,
8323 targs))
8325 ret = false;
8326 goto out;
8332 out:
8334 --processing_template_decl;
8335 return ret;
8338 /* Since type attributes aren't mangled, we need to strip them from
8339 template type arguments. */
8341 tree
8342 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8344 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8345 return arg;
8346 bool removed_attributes = false;
8347 tree canon = strip_typedefs (arg, &removed_attributes);
8348 if (removed_attributes
8349 && (complain & tf_warning))
8350 warning (OPT_Wignored_attributes,
8351 "ignoring attributes on template argument %qT", arg);
8352 return canon;
8355 /* And from inside dependent non-type arguments like sizeof(Type). */
8357 static tree
8358 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8360 if (!arg || arg == error_mark_node)
8361 return arg;
8362 bool removed_attributes = false;
8363 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8364 if (removed_attributes
8365 && (complain & tf_warning))
8366 warning (OPT_Wignored_attributes,
8367 "ignoring attributes in template argument %qE", arg);
8368 return canon;
8371 /* A template declaration can be substituted for a constrained
8372 template template parameter only when the argument is no more
8373 constrained than the parameter. */
8375 static bool
8376 is_compatible_template_arg (tree parm, tree arg)
8378 tree parm_cons = get_constraints (parm);
8380 /* For now, allow constrained template template arguments
8381 and unconstrained template template parameters. */
8382 if (parm_cons == NULL_TREE)
8383 return true;
8385 /* If the template parameter is constrained, we need to rewrite its
8386 constraints in terms of the ARG's template parameters. This ensures
8387 that all of the template parameter types will have the same depth.
8389 Note that this is only valid when coerce_template_template_parm is
8390 true for the innermost template parameters of PARM and ARG. In other
8391 words, because coercion is successful, this conversion will be valid. */
8392 tree new_args = NULL_TREE;
8393 if (parm_cons)
8395 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8396 new_args = template_parms_level_to_args (aparms);
8397 ++processing_template_decl;
8398 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8399 tf_none, NULL_TREE);
8400 --processing_template_decl;
8401 if (parm_cons == error_mark_node)
8402 return false;
8405 return weakly_subsumes (parm_cons, arg);
8408 // Convert a placeholder argument into a binding to the original
8409 // parameter. The original parameter is saved as the TREE_TYPE of
8410 // ARG.
8411 static inline tree
8412 convert_wildcard_argument (tree parm, tree arg)
8414 TREE_TYPE (arg) = parm;
8415 return arg;
8418 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8419 because one of them is dependent. But we need to represent the
8420 conversion for the benefit of cp_tree_equal. */
8422 static tree
8423 maybe_convert_nontype_argument (tree type, tree arg)
8425 /* Auto parms get no conversion. */
8426 if (type_uses_auto (type))
8427 return arg;
8428 /* We don't need or want to add this conversion now if we're going to use the
8429 argument for deduction. */
8430 if (value_dependent_expression_p (arg))
8431 return arg;
8433 type = cv_unqualified (type);
8434 tree argtype = TREE_TYPE (arg);
8435 if (same_type_p (type, argtype))
8436 return arg;
8438 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8439 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8440 return arg;
8443 /* Convert the indicated template ARG as necessary to match the
8444 indicated template PARM. Returns the converted ARG, or
8445 error_mark_node if the conversion was unsuccessful. Error and
8446 warning messages are issued under control of COMPLAIN. This
8447 conversion is for the Ith parameter in the parameter list. ARGS is
8448 the full set of template arguments deduced so far. */
8450 static tree
8451 convert_template_argument (tree parm,
8452 tree arg,
8453 tree args,
8454 tsubst_flags_t complain,
8455 int i,
8456 tree in_decl)
8458 tree orig_arg;
8459 tree val;
8460 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8462 if (parm == error_mark_node || error_operand_p (arg))
8463 return error_mark_node;
8465 /* Trivially convert placeholders. */
8466 if (TREE_CODE (arg) == WILDCARD_DECL)
8467 return convert_wildcard_argument (parm, arg);
8469 if (arg == any_targ_node)
8470 return arg;
8472 if (TREE_CODE (arg) == TREE_LIST
8473 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8475 /* The template argument was the name of some
8476 member function. That's usually
8477 invalid, but static members are OK. In any
8478 case, grab the underlying fields/functions
8479 and issue an error later if required. */
8480 TREE_TYPE (arg) = unknown_type_node;
8483 orig_arg = arg;
8485 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8486 requires_type = (TREE_CODE (parm) == TYPE_DECL
8487 || requires_tmpl_type);
8489 /* When determining whether an argument pack expansion is a template,
8490 look at the pattern. */
8491 if (PACK_EXPANSION_P (arg))
8492 arg = PACK_EXPANSION_PATTERN (arg);
8494 /* Deal with an injected-class-name used as a template template arg. */
8495 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8497 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8498 if (TREE_CODE (t) == TEMPLATE_DECL)
8500 if (cxx_dialect >= cxx11)
8501 /* OK under DR 1004. */;
8502 else if (complain & tf_warning_or_error)
8503 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8504 " used as template template argument", TYPE_NAME (arg));
8505 else if (flag_pedantic_errors)
8506 t = arg;
8508 arg = t;
8512 is_tmpl_type =
8513 ((TREE_CODE (arg) == TEMPLATE_DECL
8514 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8515 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8516 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8517 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8519 if (is_tmpl_type
8520 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8521 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8522 arg = TYPE_STUB_DECL (arg);
8524 is_type = TYPE_P (arg) || is_tmpl_type;
8526 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8527 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8529 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8531 if (complain & tf_error)
8532 error ("invalid use of destructor %qE as a type", orig_arg);
8533 return error_mark_node;
8536 permerror (input_location,
8537 "to refer to a type member of a template parameter, "
8538 "use %<typename %E%>", orig_arg);
8540 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8541 TREE_OPERAND (arg, 1),
8542 typename_type,
8543 complain);
8544 arg = orig_arg;
8545 is_type = 1;
8547 if (is_type != requires_type)
8549 if (in_decl)
8551 if (complain & tf_error)
8553 error ("type/value mismatch at argument %d in template "
8554 "parameter list for %qD",
8555 i + 1, in_decl);
8556 if (is_type)
8558 /* The template argument is a type, but we're expecting
8559 an expression. */
8560 inform (input_location,
8561 " expected a constant of type %qT, got %qT",
8562 TREE_TYPE (parm),
8563 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8564 /* [temp.arg]/2: "In a template-argument, an ambiguity
8565 between a type-id and an expression is resolved to a
8566 type-id, regardless of the form of the corresponding
8567 template-parameter." So give the user a clue. */
8568 if (TREE_CODE (arg) == FUNCTION_TYPE)
8569 inform (input_location, " ambiguous template argument "
8570 "for non-type template parameter is treated as "
8571 "function type");
8573 else if (requires_tmpl_type)
8574 inform (input_location,
8575 " expected a class template, got %qE", orig_arg);
8576 else
8577 inform (input_location,
8578 " expected a type, got %qE", orig_arg);
8581 return error_mark_node;
8583 if (is_tmpl_type ^ requires_tmpl_type)
8585 if (in_decl && (complain & tf_error))
8587 error ("type/value mismatch at argument %d in template "
8588 "parameter list for %qD",
8589 i + 1, in_decl);
8590 if (is_tmpl_type)
8591 inform (input_location,
8592 " expected a type, got %qT", DECL_NAME (arg));
8593 else
8594 inform (input_location,
8595 " expected a class template, got %qT", orig_arg);
8597 return error_mark_node;
8600 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8601 /* We already did the appropriate conversion when packing args. */
8602 val = orig_arg;
8603 else if (is_type)
8605 if (requires_tmpl_type)
8607 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8608 /* The number of argument required is not known yet.
8609 Just accept it for now. */
8610 val = orig_arg;
8611 else
8613 /* Strip alias templates that are equivalent to another
8614 template. */
8615 arg = get_underlying_template (arg);
8617 if (coerce_template_template_parms (parm, arg,
8618 complain, in_decl,
8619 args))
8621 val = arg;
8623 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8624 TEMPLATE_DECL. */
8625 if (val != error_mark_node)
8627 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8628 val = TREE_TYPE (val);
8629 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8630 val = make_pack_expansion (val, complain);
8633 else
8635 if (in_decl && (complain & tf_error))
8637 error ("type/value mismatch at argument %d in "
8638 "template parameter list for %qD",
8639 i + 1, in_decl);
8640 inform (input_location,
8641 " expected a template of type %qD, got %qT",
8642 parm, orig_arg);
8645 val = error_mark_node;
8648 // Check that the constraints are compatible before allowing the
8649 // substitution.
8650 if (val != error_mark_node)
8651 if (!is_compatible_template_arg (parm, arg))
8653 if (in_decl && (complain & tf_error))
8655 error ("constraint mismatch at argument %d in "
8656 "template parameter list for %qD",
8657 i + 1, in_decl);
8658 inform (input_location, " expected %qD but got %qD",
8659 parm, arg);
8661 val = error_mark_node;
8665 else
8666 val = orig_arg;
8667 /* We only form one instance of each template specialization.
8668 Therefore, if we use a non-canonical variant (i.e., a
8669 typedef), any future messages referring to the type will use
8670 the typedef, which is confusing if those future uses do not
8671 themselves also use the typedef. */
8672 if (TYPE_P (val))
8673 val = canonicalize_type_argument (val, complain);
8675 else
8677 tree t = TREE_TYPE (parm);
8679 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8680 > TMPL_ARGS_DEPTH (args))
8681 /* We don't have enough levels of args to do any substitution. This
8682 can happen in the context of -fnew-ttp-matching. */;
8683 else if (tree a = type_uses_auto (t))
8685 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8686 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8687 if (t == error_mark_node)
8688 return error_mark_node;
8690 else
8691 t = tsubst (t, args, complain, in_decl);
8693 /* Perform array-to-pointer and function-to-pointer conversion
8694 as per [temp.param]/10. */
8695 t = type_decays_to (t);
8697 if (invalid_nontype_parm_type_p (t, complain))
8698 return error_mark_node;
8700 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8701 this non-type template parameter, as per [temp.param]/6. */
8702 t = cv_unqualified (t);
8704 if (t != TREE_TYPE (parm))
8705 t = canonicalize_type_argument (t, complain);
8707 if (!type_dependent_expression_p (orig_arg)
8708 && !uses_template_parms (t))
8709 /* We used to call digest_init here. However, digest_init
8710 will report errors, which we don't want when complain
8711 is zero. More importantly, digest_init will try too
8712 hard to convert things: for example, `0' should not be
8713 converted to pointer type at this point according to
8714 the standard. Accepting this is not merely an
8715 extension, since deciding whether or not these
8716 conversions can occur is part of determining which
8717 function template to call, or whether a given explicit
8718 argument specification is valid. */
8719 val = convert_nontype_argument (t, orig_arg, complain);
8720 else
8722 val = canonicalize_expr_argument (orig_arg, complain);
8723 val = maybe_convert_nontype_argument (t, val);
8727 if (val == NULL_TREE)
8728 val = error_mark_node;
8729 else if (val == error_mark_node && (complain & tf_error))
8730 error_at (cp_expr_loc_or_input_loc (orig_arg),
8731 "could not convert template argument %qE from %qT to %qT",
8732 orig_arg, TREE_TYPE (orig_arg), t);
8734 if (INDIRECT_REF_P (val))
8736 /* Reject template arguments that are references to built-in
8737 functions with no library fallbacks. */
8738 const_tree inner = TREE_OPERAND (val, 0);
8739 const_tree innertype = TREE_TYPE (inner);
8740 if (innertype
8741 && TYPE_REF_P (innertype)
8742 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8743 && TREE_OPERAND_LENGTH (inner) > 0
8744 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8745 return error_mark_node;
8748 if (TREE_CODE (val) == SCOPE_REF)
8750 /* Strip typedefs from the SCOPE_REF. */
8751 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8752 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8753 complain);
8754 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8755 QUALIFIED_NAME_IS_TEMPLATE (val));
8759 return val;
8762 /* Coerces the remaining template arguments in INNER_ARGS (from
8763 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8764 Returns the coerced argument pack. PARM_IDX is the position of this
8765 parameter in the template parameter list. ARGS is the original
8766 template argument list. */
8767 static tree
8768 coerce_template_parameter_pack (tree parms,
8769 int parm_idx,
8770 tree args,
8771 tree inner_args,
8772 int arg_idx,
8773 tree new_args,
8774 int* lost,
8775 tree in_decl,
8776 tsubst_flags_t complain)
8778 tree parm = TREE_VEC_ELT (parms, parm_idx);
8779 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8780 tree packed_args;
8781 tree argument_pack;
8782 tree packed_parms = NULL_TREE;
8784 if (arg_idx > nargs)
8785 arg_idx = nargs;
8787 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8789 /* When the template parameter is a non-type template parameter pack
8790 or template template parameter pack whose type or template
8791 parameters use parameter packs, we know exactly how many arguments
8792 we are looking for. Build a vector of the instantiated decls for
8793 these template parameters in PACKED_PARMS. */
8794 /* We can't use make_pack_expansion here because it would interpret a
8795 _DECL as a use rather than a declaration. */
8796 tree decl = TREE_VALUE (parm);
8797 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8798 PACK_EXPANSION_PATTERN (exp) = decl;
8799 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8800 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8802 TREE_VEC_LENGTH (args)--;
8803 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8804 TREE_VEC_LENGTH (args)++;
8806 if (packed_parms == error_mark_node)
8807 return error_mark_node;
8809 /* If we're doing a partial instantiation of a member template,
8810 verify that all of the types used for the non-type
8811 template parameter pack are, in fact, valid for non-type
8812 template parameters. */
8813 if (arg_idx < nargs
8814 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8816 int j, len = TREE_VEC_LENGTH (packed_parms);
8817 for (j = 0; j < len; ++j)
8819 tree t = TREE_VEC_ELT (packed_parms, j);
8820 if (TREE_CODE (t) == PARM_DECL
8821 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8822 return error_mark_node;
8824 /* We don't know how many args we have yet, just
8825 use the unconverted ones for now. */
8826 return NULL_TREE;
8829 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8831 /* Check if we have a placeholder pack, which indicates we're
8832 in the context of a introduction list. In that case we want
8833 to match this pack to the single placeholder. */
8834 else if (arg_idx < nargs
8835 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8836 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8838 nargs = arg_idx + 1;
8839 packed_args = make_tree_vec (1);
8841 else
8842 packed_args = make_tree_vec (nargs - arg_idx);
8844 /* Convert the remaining arguments, which will be a part of the
8845 parameter pack "parm". */
8846 int first_pack_arg = arg_idx;
8847 for (; arg_idx < nargs; ++arg_idx)
8849 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8850 tree actual_parm = TREE_VALUE (parm);
8851 int pack_idx = arg_idx - first_pack_arg;
8853 if (packed_parms)
8855 /* Once we've packed as many args as we have types, stop. */
8856 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8857 break;
8858 else if (PACK_EXPANSION_P (arg))
8859 /* We don't know how many args we have yet, just
8860 use the unconverted ones for now. */
8861 return NULL_TREE;
8862 else
8863 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8866 if (arg == error_mark_node)
8868 if (complain & tf_error)
8869 error ("template argument %d is invalid", arg_idx + 1);
8871 else
8872 arg = convert_template_argument (actual_parm,
8873 arg, new_args, complain, parm_idx,
8874 in_decl);
8875 if (arg == error_mark_node)
8876 (*lost)++;
8877 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8880 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8881 && TREE_VEC_LENGTH (packed_args) > 0)
8883 if (complain & tf_error)
8884 error ("wrong number of template arguments (%d, should be %d)",
8885 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8886 return error_mark_node;
8889 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8890 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8891 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8892 else
8894 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8895 TREE_CONSTANT (argument_pack) = 1;
8898 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8899 if (CHECKING_P)
8900 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8901 TREE_VEC_LENGTH (packed_args));
8902 return argument_pack;
8905 /* Returns the number of pack expansions in the template argument vector
8906 ARGS. */
8908 static int
8909 pack_expansion_args_count (tree args)
8911 int i;
8912 int count = 0;
8913 if (args)
8914 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8916 tree elt = TREE_VEC_ELT (args, i);
8917 if (elt && PACK_EXPANSION_P (elt))
8918 ++count;
8920 return count;
8923 /* Convert all template arguments to their appropriate types, and
8924 return a vector containing the innermost resulting template
8925 arguments. If any error occurs, return error_mark_node. Error and
8926 warning messages are issued under control of COMPLAIN.
8928 If PARMS represents all template parameters levels, this function
8929 returns a vector of vectors representing all the resulting argument
8930 levels. Note that in this case, only the innermost arguments are
8931 coerced because the outermost ones are supposed to have been coerced
8932 already. Otherwise, if PARMS represents only (the innermost) vector
8933 of parameters, this function returns a vector containing just the
8934 innermost resulting arguments.
8936 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8937 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
8938 arguments not specified in ARGS must have default arguments which
8939 we'll use to fill in ARGS. */
8941 tree
8942 coerce_template_parms (tree parms,
8943 tree args,
8944 tree in_decl,
8945 tsubst_flags_t complain,
8946 bool require_all_args /* = true */)
8948 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8949 tree orig_inner_args;
8950 tree inner_args;
8952 /* When used as a boolean value, indicates whether this is a
8953 variadic template parameter list. Since it's an int, we can also
8954 subtract it from nparms to get the number of non-variadic
8955 parameters. */
8956 int variadic_p = 0;
8957 int variadic_args_p = 0;
8958 int post_variadic_parms = 0;
8960 /* Adjustment to nparms for fixed parameter packs. */
8961 int fixed_pack_adjust = 0;
8962 int fixed_packs = 0;
8963 int missing = 0;
8965 /* Likewise for parameters with default arguments. */
8966 int default_p = 0;
8968 if (args == error_mark_node)
8969 return error_mark_node;
8971 bool return_full_args = false;
8972 if (TREE_CODE (parms) == TREE_LIST)
8974 if (TMPL_PARMS_DEPTH (parms) > 1)
8976 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
8977 return_full_args = true;
8979 parms = INNERMOST_TEMPLATE_PARMS (parms);
8982 nparms = TREE_VEC_LENGTH (parms);
8984 /* Determine if there are any parameter packs or default arguments. */
8985 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8987 tree parm = TREE_VEC_ELT (parms, parm_idx);
8988 if (variadic_p)
8989 ++post_variadic_parms;
8990 if (template_parameter_pack_p (TREE_VALUE (parm)))
8991 ++variadic_p;
8992 if (TREE_PURPOSE (parm))
8993 ++default_p;
8996 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8997 /* If there are no parameters that follow a parameter pack, we need to
8998 expand any argument packs so that we can deduce a parameter pack from
8999 some non-packed args followed by an argument pack, as in variadic85.C.
9000 If there are such parameters, we need to leave argument packs intact
9001 so the arguments are assigned properly. This can happen when dealing
9002 with a nested class inside a partial specialization of a class
9003 template, as in variadic92.C, or when deducing a template parameter pack
9004 from a sub-declarator, as in variadic114.C. */
9005 if (!post_variadic_parms)
9006 inner_args = expand_template_argument_pack (inner_args);
9008 /* Count any pack expansion args. */
9009 variadic_args_p = pack_expansion_args_count (inner_args);
9011 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
9012 if ((nargs - variadic_args_p > nparms && !variadic_p)
9013 || (nargs < nparms - variadic_p
9014 && require_all_args
9015 && !variadic_args_p
9016 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
9017 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
9019 bad_nargs:
9020 if (complain & tf_error)
9022 if (variadic_p || default_p)
9024 nparms -= variadic_p + default_p;
9025 error ("wrong number of template arguments "
9026 "(%d, should be at least %d)", nargs, nparms);
9028 else
9029 error ("wrong number of template arguments "
9030 "(%d, should be %d)", nargs, nparms);
9032 if (in_decl)
9033 inform (DECL_SOURCE_LOCATION (in_decl),
9034 "provided for %qD", in_decl);
9037 return error_mark_node;
9039 /* We can't pass a pack expansion to a non-pack parameter of an alias
9040 template (DR 1430). */
9041 else if (in_decl
9042 && (DECL_ALIAS_TEMPLATE_P (in_decl)
9043 || concept_definition_p (in_decl))
9044 && variadic_args_p
9045 && nargs - variadic_args_p < nparms - variadic_p)
9047 if (complain & tf_error)
9049 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9051 tree arg = TREE_VEC_ELT (inner_args, i);
9052 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9054 if (PACK_EXPANSION_P (arg)
9055 && !template_parameter_pack_p (parm))
9057 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9058 error_at (location_of (arg),
9059 "pack expansion argument for non-pack parameter "
9060 "%qD of alias template %qD", parm, in_decl);
9061 else
9062 error_at (location_of (arg),
9063 "pack expansion argument for non-pack parameter "
9064 "%qD of concept %qD", parm, in_decl);
9065 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9066 goto found;
9069 gcc_unreachable ();
9070 found:;
9072 return error_mark_node;
9075 /* We need to evaluate the template arguments, even though this
9076 template-id may be nested within a "sizeof". */
9077 cp_evaluated ev;
9079 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9080 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9081 int pack_adjust = 0;
9082 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9084 tree arg;
9085 tree parm;
9087 /* Get the Ith template parameter. */
9088 parm = TREE_VEC_ELT (parms, parm_idx);
9090 if (parm == error_mark_node)
9092 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9093 continue;
9096 /* Calculate the next argument. */
9097 if (arg_idx < nargs)
9098 arg = TREE_VEC_ELT (inner_args, arg_idx);
9099 else
9100 arg = NULL_TREE;
9102 if (template_parameter_pack_p (TREE_VALUE (parm))
9103 && (arg || require_all_args || !(complain & tf_partial))
9104 && !(arg && ARGUMENT_PACK_P (arg)))
9106 /* Some arguments will be placed in the
9107 template parameter pack PARM. */
9108 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9109 inner_args, arg_idx,
9110 new_args, &lost,
9111 in_decl, complain);
9113 if (arg == NULL_TREE)
9115 /* We don't know how many args we have yet, just use the
9116 unconverted (and still packed) ones for now. */
9117 new_inner_args = orig_inner_args;
9118 arg_idx = nargs;
9119 break;
9122 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9124 /* Store this argument. */
9125 if (arg == error_mark_node)
9127 lost++;
9128 /* We are done with all of the arguments. */
9129 arg_idx = nargs;
9130 break;
9132 else
9134 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9135 arg_idx += pack_adjust;
9136 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9138 ++fixed_packs;
9139 fixed_pack_adjust += pack_adjust;
9143 continue;
9145 else if (arg)
9147 if (PACK_EXPANSION_P (arg))
9149 /* "If every valid specialization of a variadic template
9150 requires an empty template parameter pack, the template is
9151 ill-formed, no diagnostic required." So check that the
9152 pattern works with this parameter. */
9153 tree pattern = PACK_EXPANSION_PATTERN (arg);
9154 tree conv = convert_template_argument (TREE_VALUE (parm),
9155 pattern, new_args,
9156 complain, parm_idx,
9157 in_decl);
9158 if (conv == error_mark_node)
9160 if (complain & tf_error)
9161 inform (input_location, "so any instantiation with a "
9162 "non-empty parameter pack would be ill-formed");
9163 ++lost;
9165 else if (TYPE_P (conv) && !TYPE_P (pattern))
9166 /* Recover from missing typename. */
9167 TREE_VEC_ELT (inner_args, arg_idx)
9168 = make_pack_expansion (conv, complain);
9170 /* We don't know how many args we have yet, just
9171 use the unconverted ones for now. */
9172 new_inner_args = inner_args;
9173 arg_idx = nargs;
9174 break;
9177 else if (require_all_args)
9179 /* There must be a default arg in this case. */
9180 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9181 complain, in_decl);
9182 /* The position of the first default template argument,
9183 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9184 Record that. */
9185 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9186 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9187 arg_idx - pack_adjust);
9189 else
9190 break;
9192 if (arg == error_mark_node)
9194 if (complain & tf_error)
9195 error ("template argument %d is invalid", arg_idx + 1);
9197 else if (!arg)
9199 /* This can occur if there was an error in the template
9200 parameter list itself (which we would already have
9201 reported) that we are trying to recover from, e.g., a class
9202 template with a parameter list such as
9203 template<typename..., typename> (cpp0x/variadic150.C). */
9204 ++lost;
9206 /* This can also happen with a fixed parameter pack (71834). */
9207 if (arg_idx >= nargs)
9208 ++missing;
9210 else
9211 arg = convert_template_argument (TREE_VALUE (parm),
9212 arg, new_args, complain,
9213 parm_idx, in_decl);
9215 if (arg == error_mark_node)
9216 lost++;
9218 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9221 if (missing || arg_idx < nargs - variadic_args_p)
9223 /* If we had fixed parameter packs, we didn't know how many arguments we
9224 actually needed earlier; now we do. */
9225 nparms += fixed_pack_adjust;
9226 variadic_p -= fixed_packs;
9227 goto bad_nargs;
9230 if (arg_idx < nargs)
9232 /* We had some pack expansion arguments that will only work if the packs
9233 are empty, but wait until instantiation time to complain.
9234 See variadic-ttp3.C. */
9236 /* Except that we can't provide empty packs to alias templates or
9237 concepts when there are no corresponding parameters. Basically,
9238 we can get here with this:
9240 template<typename T> concept C = true;
9242 template<typename... Args>
9243 requires C<Args...>
9244 void f();
9246 When parsing C<Args...>, we try to form a concept check of
9247 C<?, Args...>. Without the extra check for substituting an empty
9248 pack past the last parameter, we can accept the check as valid.
9250 FIXME: This may be valid for alias templates (but I doubt it).
9252 FIXME: The error could be better also. */
9253 if (in_decl && concept_definition_p (in_decl))
9255 if (complain & tf_error)
9256 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9257 "too many arguments");
9258 return error_mark_node;
9261 int len = nparms + (nargs - arg_idx);
9262 tree args = make_tree_vec (len);
9263 int i = 0;
9264 for (; i < nparms; ++i)
9265 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9266 for (; i < len; ++i, ++arg_idx)
9267 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9268 arg_idx - pack_adjust);
9269 new_inner_args = args;
9272 if (lost)
9274 gcc_assert (!(complain & tf_error) || seen_error ());
9275 return error_mark_node;
9278 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9279 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9280 TREE_VEC_LENGTH (new_inner_args));
9282 return return_full_args ? new_args : new_inner_args;
9285 /* Returns true if T is a wrapper to make a C++20 template parameter
9286 object const. */
9288 static bool
9289 class_nttp_const_wrapper_p (tree t)
9291 if (cxx_dialect < cxx20)
9292 return false;
9293 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9294 && CP_TYPE_CONST_P (TREE_TYPE (t))
9295 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9298 /* Returns 1 if template args OT and NT are equivalent. */
9301 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9303 if (nt == ot)
9304 return 1;
9305 if (nt == NULL_TREE || ot == NULL_TREE)
9306 return false;
9307 if (nt == any_targ_node || ot == any_targ_node)
9308 return true;
9310 if (class_nttp_const_wrapper_p (nt))
9311 nt = TREE_OPERAND (nt, 0);
9312 if (class_nttp_const_wrapper_p (ot))
9313 ot = TREE_OPERAND (ot, 0);
9315 /* DR 1558: Don't treat an alias template specialization with dependent
9316 arguments as equivalent to its underlying type when used as a template
9317 argument; we need them to be distinct so that we substitute into the
9318 specialization arguments at instantiation time. And aliases can't be
9319 equivalent without being ==, so we don't need to look any deeper.
9321 During partial ordering, however, we need to treat them normally so we can
9322 order uses of the same alias with different cv-qualification (79960). */
9323 auto cso = make_temp_override (comparing_dependent_aliases);
9324 if (!partial_order)
9325 ++comparing_dependent_aliases;
9327 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9328 /* For member templates */
9329 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9330 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9331 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9332 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9333 PACK_EXPANSION_PATTERN (nt))
9334 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9335 PACK_EXPANSION_EXTRA_ARGS (nt)));
9336 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9337 return cp_tree_equal (ot, nt);
9338 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9339 gcc_unreachable ();
9340 else if (TYPE_P (nt) || TYPE_P (ot))
9342 if (!(TYPE_P (nt) && TYPE_P (ot)))
9343 return false;
9344 return same_type_p (ot, nt);
9346 else
9348 /* Try to treat a template non-type argument that has been converted
9349 to the parameter type as equivalent to one that hasn't yet. */
9350 for (enum tree_code code1 = TREE_CODE (ot);
9351 CONVERT_EXPR_CODE_P (code1)
9352 || code1 == NON_LVALUE_EXPR;
9353 code1 = TREE_CODE (ot))
9354 ot = TREE_OPERAND (ot, 0);
9356 for (enum tree_code code2 = TREE_CODE (nt);
9357 CONVERT_EXPR_CODE_P (code2)
9358 || code2 == NON_LVALUE_EXPR;
9359 code2 = TREE_CODE (nt))
9360 nt = TREE_OPERAND (nt, 0);
9362 return cp_tree_equal (ot, nt);
9366 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9367 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9368 NEWARG_PTR with the offending arguments if they are non-NULL. */
9370 bool
9371 comp_template_args (tree oldargs, tree newargs,
9372 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */,
9373 bool partial_order /* = false */)
9375 if (oldargs == newargs)
9376 return true;
9378 if (!oldargs || !newargs)
9379 return false;
9381 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9382 return false;
9384 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9386 tree nt = TREE_VEC_ELT (newargs, i);
9387 tree ot = TREE_VEC_ELT (oldargs, i);
9389 if (! template_args_equal (ot, nt, partial_order))
9391 if (oldarg_ptr != NULL)
9392 *oldarg_ptr = ot;
9393 if (newarg_ptr != NULL)
9394 *newarg_ptr = nt;
9395 return false;
9398 return true;
9401 inline bool
9402 comp_template_args_porder (tree oargs, tree nargs)
9404 return comp_template_args (oargs, nargs, NULL, NULL, true);
9407 /* Implement a freelist interface for objects of type T.
9409 Head is a separate object, rather than a regular member, so that we
9410 can define it as a GTY deletable pointer, which is highly
9411 desirable. A data member could be declared that way, but then the
9412 containing object would implicitly get GTY((user)), which would
9413 prevent us from instantiating freelists as global objects.
9414 Although this way we can create freelist global objects, they're
9415 such thin wrappers that instantiating temporaries at every use
9416 loses nothing and saves permanent storage for the freelist object.
9418 Member functions next, anew, poison and reinit have default
9419 implementations that work for most of the types we're interested
9420 in, but if they don't work for some type, they should be explicitly
9421 specialized. See the comments before them for requirements, and
9422 the example specializations for the tree_list_freelist. */
9423 template <typename T>
9424 class freelist
9426 /* Return the next object in a chain. We could just do type
9427 punning, but if we access the object with its underlying type, we
9428 avoid strict-aliasing trouble. This needs only work between
9429 poison and reinit. */
9430 static T *&next (T *obj) { return obj->next; }
9432 /* Return a newly allocated, uninitialized or minimally-initialized
9433 object of type T. Any initialization performed by anew should
9434 either remain across the life of the object and the execution of
9435 poison, or be redone by reinit. */
9436 static T *anew () { return ggc_alloc<T> (); }
9438 /* Optionally scribble all over the bits holding the object, so that
9439 they become (mostly?) uninitialized memory. This is called while
9440 preparing to make the object part of the free list. */
9441 static void poison (T *obj) {
9442 T *p ATTRIBUTE_UNUSED = obj;
9443 T **q ATTRIBUTE_UNUSED = &next (obj);
9445 #ifdef ENABLE_GC_CHECKING
9446 /* Poison the data, to indicate the data is garbage. */
9447 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9448 memset (p, 0xa5, sizeof (*p));
9449 #endif
9450 /* Let valgrind know the object is free. */
9451 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9453 /* Let valgrind know the next portion of the object is available,
9454 but uninitialized. */
9455 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9458 /* Bring an object that underwent at least one lifecycle after anew
9459 and before the most recent free and poison, back to a usable
9460 state, reinitializing whatever is needed for it to be
9461 functionally equivalent to an object just allocated and returned
9462 by anew. This may poison or clear the next field, used by
9463 freelist housekeeping after poison was called. */
9464 static void reinit (T *obj) {
9465 T **q ATTRIBUTE_UNUSED = &next (obj);
9467 #ifdef ENABLE_GC_CHECKING
9468 memset (q, 0xa5, sizeof (*q));
9469 #endif
9470 /* Let valgrind know the entire object is available, but
9471 uninitialized. */
9472 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9475 /* Reference a GTY-deletable pointer that points to the first object
9476 in the free list proper. */
9477 T *&head;
9478 public:
9479 /* Construct a freelist object chaining objects off of HEAD. */
9480 freelist (T *&head) : head(head) {}
9482 /* Add OBJ to the free object list. The former head becomes OBJ's
9483 successor. */
9484 void free (T *obj)
9486 poison (obj);
9487 next (obj) = head;
9488 head = obj;
9491 /* Take an object from the free list, if one is available, or
9492 allocate a new one. Objects taken from the free list should be
9493 regarded as filled with garbage, except for bits that are
9494 configured to be preserved across free and alloc. */
9495 T *alloc ()
9497 if (head)
9499 T *obj = head;
9500 head = next (head);
9501 reinit (obj);
9502 return obj;
9504 else
9505 return anew ();
9509 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9510 want to allocate a TREE_LIST using the usual interface, and ensure
9511 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9512 build_tree_list logic in reinit, so this could go out of sync. */
9513 template <>
9514 inline tree &
9515 freelist<tree_node>::next (tree obj)
9517 return TREE_CHAIN (obj);
9519 template <>
9520 inline tree
9521 freelist<tree_node>::anew ()
9523 return build_tree_list (NULL, NULL);
9525 template <>
9526 inline void
9527 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9529 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9530 tree p ATTRIBUTE_UNUSED = obj;
9531 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9532 tree *q ATTRIBUTE_UNUSED = &next (obj);
9534 #ifdef ENABLE_GC_CHECKING
9535 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9537 /* Poison the data, to indicate the data is garbage. */
9538 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9539 memset (p, 0xa5, size);
9540 #endif
9541 /* Let valgrind know the object is free. */
9542 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9543 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9544 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9545 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9547 #ifdef ENABLE_GC_CHECKING
9548 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9549 /* Keep TREE_CHAIN functional. */
9550 TREE_SET_CODE (obj, TREE_LIST);
9551 #else
9552 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9553 #endif
9555 template <>
9556 inline void
9557 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9559 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9561 #ifdef ENABLE_GC_CHECKING
9562 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9563 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9564 memset (obj, 0, sizeof (tree_list));
9565 #endif
9567 /* Let valgrind know the entire object is available, but
9568 uninitialized. */
9569 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9571 #ifdef ENABLE_GC_CHECKING
9572 TREE_SET_CODE (obj, TREE_LIST);
9573 #else
9574 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9575 #endif
9578 /* Point to the first object in the TREE_LIST freelist. */
9579 static GTY((deletable)) tree tree_list_freelist_head;
9580 /* Return the/an actual TREE_LIST freelist. */
9581 static inline freelist<tree_node>
9582 tree_list_freelist ()
9584 return tree_list_freelist_head;
9587 /* Point to the first object in the tinst_level freelist. */
9588 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9589 /* Return the/an actual tinst_level freelist. */
9590 static inline freelist<tinst_level>
9591 tinst_level_freelist ()
9593 return tinst_level_freelist_head;
9596 /* Point to the first object in the pending_template freelist. */
9597 static GTY((deletable)) pending_template *pending_template_freelist_head;
9598 /* Return the/an actual pending_template freelist. */
9599 static inline freelist<pending_template>
9600 pending_template_freelist ()
9602 return pending_template_freelist_head;
9605 /* Build the TREE_LIST object out of a split list, store it
9606 permanently, and return it. */
9607 tree
9608 tinst_level::to_list ()
9610 gcc_assert (split_list_p ());
9611 tree ret = tree_list_freelist ().alloc ();
9612 TREE_PURPOSE (ret) = tldcl;
9613 TREE_VALUE (ret) = targs;
9614 tldcl = ret;
9615 targs = NULL;
9616 gcc_assert (tree_list_p ());
9617 return ret;
9620 const unsigned short tinst_level::refcount_infinity;
9622 /* Increment OBJ's refcount unless it is already infinite. */
9623 static tinst_level *
9624 inc_refcount_use (tinst_level *obj)
9626 if (obj && obj->refcount != tinst_level::refcount_infinity)
9627 ++obj->refcount;
9628 return obj;
9631 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9632 void
9633 tinst_level::free (tinst_level *obj)
9635 if (obj->tree_list_p ())
9636 tree_list_freelist ().free (obj->get_node ());
9637 tinst_level_freelist ().free (obj);
9640 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9641 OBJ's DECL and OBJ, and start over with the tinst_level object that
9642 used to be referenced by OBJ's NEXT. */
9643 static void
9644 dec_refcount_use (tinst_level *obj)
9646 while (obj
9647 && obj->refcount != tinst_level::refcount_infinity
9648 && !--obj->refcount)
9650 tinst_level *next = obj->next;
9651 tinst_level::free (obj);
9652 obj = next;
9656 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9657 and of the former PTR. Omitting the second argument is equivalent
9658 to passing (T*)NULL; this is allowed because passing the
9659 zero-valued integral constant NULL confuses type deduction and/or
9660 overload resolution. */
9661 template <typename T>
9662 static void
9663 set_refcount_ptr (T *& ptr, T *obj = NULL)
9665 T *save = ptr;
9666 ptr = inc_refcount_use (obj);
9667 dec_refcount_use (save);
9670 static void
9671 add_pending_template (tree d)
9673 tree ti = (TYPE_P (d)
9674 ? CLASSTYPE_TEMPLATE_INFO (d)
9675 : DECL_TEMPLATE_INFO (d));
9676 struct pending_template *pt;
9677 int level;
9679 if (TI_PENDING_TEMPLATE_FLAG (ti))
9680 return;
9682 /* We are called both from instantiate_decl, where we've already had a
9683 tinst_level pushed, and instantiate_template, where we haven't.
9684 Compensate. */
9685 gcc_assert (TREE_CODE (d) != TREE_LIST);
9686 level = !current_tinst_level
9687 || current_tinst_level->maybe_get_node () != d;
9689 if (level)
9690 push_tinst_level (d);
9692 pt = pending_template_freelist ().alloc ();
9693 pt->next = NULL;
9694 pt->tinst = NULL;
9695 set_refcount_ptr (pt->tinst, current_tinst_level);
9696 if (last_pending_template)
9697 last_pending_template->next = pt;
9698 else
9699 pending_templates = pt;
9701 last_pending_template = pt;
9703 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9705 if (level)
9706 pop_tinst_level ();
9710 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9711 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9712 documentation for TEMPLATE_ID_EXPR. */
9714 tree
9715 lookup_template_function (tree fns, tree arglist)
9717 if (fns == error_mark_node || arglist == error_mark_node)
9718 return error_mark_node;
9720 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9722 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9724 error ("%q#D is not a function template", fns);
9725 return error_mark_node;
9728 if (BASELINK_P (fns))
9730 fns = copy_node (fns);
9731 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9732 unknown_type_node,
9733 BASELINK_FUNCTIONS (fns),
9734 arglist);
9735 return fns;
9738 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9741 /* Within the scope of a template class S<T>, the name S gets bound
9742 (in build_self_reference) to a TYPE_DECL for the class, not a
9743 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9744 or one of its enclosing classes, and that type is a template,
9745 return the associated TEMPLATE_DECL. Otherwise, the original
9746 DECL is returned.
9748 Also handle the case when DECL is a TREE_LIST of ambiguous
9749 injected-class-names from different bases. */
9751 tree
9752 maybe_get_template_decl_from_type_decl (tree decl)
9754 if (decl == NULL_TREE)
9755 return decl;
9757 /* DR 176: A lookup that finds an injected-class-name (10.2
9758 [class.member.lookup]) can result in an ambiguity in certain cases
9759 (for example, if it is found in more than one base class). If all of
9760 the injected-class-names that are found refer to specializations of
9761 the same class template, and if the name is followed by a
9762 template-argument-list, the reference refers to the class template
9763 itself and not a specialization thereof, and is not ambiguous. */
9764 if (TREE_CODE (decl) == TREE_LIST)
9766 tree t, tmpl = NULL_TREE;
9767 for (t = decl; t; t = TREE_CHAIN (t))
9769 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9770 if (!tmpl)
9771 tmpl = elt;
9772 else if (tmpl != elt)
9773 break;
9775 if (tmpl && t == NULL_TREE)
9776 return tmpl;
9777 else
9778 return decl;
9781 return (decl != NULL_TREE
9782 && DECL_SELF_REFERENCE_P (decl)
9783 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9784 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9787 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9788 parameters, find the desired type.
9790 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9792 IN_DECL, if non-NULL, is the template declaration we are trying to
9793 instantiate.
9795 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9796 the class we are looking up.
9798 Issue error and warning messages under control of COMPLAIN.
9800 If the template class is really a local class in a template
9801 function, then the FUNCTION_CONTEXT is the function in which it is
9802 being instantiated.
9804 ??? Note that this function is currently called *twice* for each
9805 template-id: the first time from the parser, while creating the
9806 incomplete type (finish_template_type), and the second type during the
9807 real instantiation (instantiate_template_class). This is surely something
9808 that we want to avoid. It also causes some problems with argument
9809 coercion (see convert_nontype_argument for more information on this). */
9811 tree
9812 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9813 int entering_scope, tsubst_flags_t complain)
9815 auto_timevar tv (TV_TEMPLATE_INST);
9817 tree templ = NULL_TREE, parmlist;
9818 tree t;
9819 spec_entry **slot;
9820 spec_entry *entry;
9821 spec_entry elt;
9822 hashval_t hash;
9824 if (identifier_p (d1))
9826 tree value = innermost_non_namespace_value (d1);
9827 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9828 templ = value;
9829 else
9831 if (context)
9832 push_decl_namespace (context);
9833 templ = lookup_name (d1);
9834 templ = maybe_get_template_decl_from_type_decl (templ);
9835 if (context)
9836 pop_decl_namespace ();
9839 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9841 tree type = TREE_TYPE (d1);
9843 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9844 an implicit typename for the second A. Deal with it. */
9845 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9846 type = TREE_TYPE (type);
9848 if (CLASSTYPE_TEMPLATE_INFO (type))
9850 templ = CLASSTYPE_TI_TEMPLATE (type);
9851 d1 = DECL_NAME (templ);
9854 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9855 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9857 templ = TYPE_TI_TEMPLATE (d1);
9858 d1 = DECL_NAME (templ);
9860 else if (DECL_TYPE_TEMPLATE_P (d1))
9862 templ = d1;
9863 d1 = DECL_NAME (templ);
9865 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9867 templ = d1;
9868 d1 = DECL_NAME (templ);
9871 /* Issue an error message if we didn't find a template. */
9872 if (! templ)
9874 if (complain & tf_error)
9875 error ("%qT is not a template", d1);
9876 return error_mark_node;
9879 if (TREE_CODE (templ) != TEMPLATE_DECL
9880 /* Make sure it's a user visible template, if it was named by
9881 the user. */
9882 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9883 && !PRIMARY_TEMPLATE_P (templ)))
9885 if (complain & tf_error)
9887 error ("non-template type %qT used as a template", d1);
9888 if (in_decl)
9889 error ("for template declaration %q+D", in_decl);
9891 return error_mark_node;
9894 complain &= ~tf_user;
9896 /* An alias that just changes the name of a template is equivalent to the
9897 other template, so if any of the arguments are pack expansions, strip
9898 the alias to avoid problems with a pack expansion passed to a non-pack
9899 alias template parameter (DR 1430). */
9900 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9901 templ = get_underlying_template (templ);
9903 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9905 tree parm;
9906 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9907 if (arglist2 == error_mark_node
9908 || (!uses_template_parms (arglist2)
9909 && check_instantiated_args (templ, arglist2, complain)))
9910 return error_mark_node;
9912 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9913 return parm;
9915 else
9917 tree template_type = TREE_TYPE (templ);
9918 tree gen_tmpl;
9919 tree type_decl;
9920 tree found = NULL_TREE;
9921 int arg_depth;
9922 int parm_depth;
9923 int is_dependent_type;
9924 int use_partial_inst_tmpl = false;
9926 if (template_type == error_mark_node)
9927 /* An error occurred while building the template TEMPL, and a
9928 diagnostic has most certainly been emitted for that
9929 already. Let's propagate that error. */
9930 return error_mark_node;
9932 gen_tmpl = most_general_template (templ);
9933 if (modules_p ())
9934 lazy_load_pendings (gen_tmpl);
9936 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9937 parm_depth = TMPL_PARMS_DEPTH (parmlist);
9938 arg_depth = TMPL_ARGS_DEPTH (arglist);
9940 if (arg_depth == 1 && parm_depth > 1)
9942 /* We've been given an incomplete set of template arguments.
9943 For example, given:
9945 template <class T> struct S1 {
9946 template <class U> struct S2 {};
9947 template <class U> struct S2<U*> {};
9950 we will be called with an ARGLIST of `U*', but the
9951 TEMPLATE will be `template <class T> template
9952 <class U> struct S1<T>::S2'. We must fill in the missing
9953 arguments. */
9954 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9955 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9956 arg_depth = TMPL_ARGS_DEPTH (arglist);
9959 /* Now we should have enough arguments. */
9960 gcc_assert (parm_depth == arg_depth);
9962 /* From here on, we're only interested in the most general
9963 template. */
9965 /* Shortcut looking up the current class scope again. */
9966 for (tree cur = current_nonlambda_class_type ();
9967 cur != NULL_TREE;
9968 cur = get_containing_scope (cur))
9970 if (!CLASS_TYPE_P (cur))
9971 continue;
9973 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
9974 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
9975 break;
9977 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9978 && comp_template_args (arglist, TI_ARGS (ti)))
9979 return cur;
9982 /* Calculate the BOUND_ARGS. These will be the args that are
9983 actually tsubst'd into the definition to create the
9984 instantiation. */
9985 if (PRIMARY_TEMPLATE_P (gen_tmpl))
9986 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
9988 if (arglist == error_mark_node)
9989 /* We were unable to bind the arguments. */
9990 return error_mark_node;
9992 /* In the scope of a template class, explicit references to the
9993 template class refer to the type of the template, not any
9994 instantiation of it. For example, in:
9996 template <class T> class C { void f(C<T>); }
9998 the `C<T>' is just the same as `C'. Outside of the
9999 class, however, such a reference is an instantiation. */
10000 if (entering_scope
10001 || !PRIMARY_TEMPLATE_P (gen_tmpl)
10002 || currently_open_class (template_type))
10004 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10006 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10007 return template_type;
10010 /* If we already have this specialization, return it. */
10011 elt.tmpl = gen_tmpl;
10012 elt.args = arglist;
10013 elt.spec = NULL_TREE;
10014 hash = spec_hasher::hash (&elt);
10015 entry = type_specializations->find_with_hash (&elt, hash);
10017 if (entry)
10018 return entry->spec;
10020 /* If the template's constraints are not satisfied,
10021 then we cannot form a valid type.
10023 Note that the check is deferred until after the hash
10024 lookup. This prevents redundant checks on previously
10025 instantiated specializations. */
10026 if (flag_concepts
10027 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
10028 && !constraints_satisfied_p (gen_tmpl, arglist))
10030 if (complain & tf_error)
10032 auto_diagnostic_group d;
10033 error ("template constraint failure for %qD", gen_tmpl);
10034 diagnose_constraints (input_location, gen_tmpl, arglist);
10036 return error_mark_node;
10039 is_dependent_type = uses_template_parms (arglist);
10041 /* If the deduced arguments are invalid, then the binding
10042 failed. */
10043 if (!is_dependent_type
10044 && check_instantiated_args (gen_tmpl,
10045 INNERMOST_TEMPLATE_ARGS (arglist),
10046 complain))
10047 return error_mark_node;
10049 if (!is_dependent_type
10050 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10051 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10052 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10053 /* This occurs when the user has tried to define a tagged type
10054 in a scope that forbids it. We emitted an error during the
10055 parse. We didn't complete the bail out then, so here we
10056 are. */
10057 return error_mark_node;
10059 context = DECL_CONTEXT (gen_tmpl);
10060 if (context && TYPE_P (context))
10062 if (!uses_template_parms (DECL_CONTEXT (templ)))
10063 /* If the context of the partially instantiated template is
10064 already non-dependent, then we might as well use it. */
10065 context = DECL_CONTEXT (templ);
10066 else
10068 context = tsubst_aggr_type (context, arglist,
10069 complain, in_decl, true);
10070 /* Try completing the enclosing context if it's not already so. */
10071 if (context != error_mark_node
10072 && !COMPLETE_TYPE_P (context))
10074 context = complete_type (context);
10075 if (COMPLETE_TYPE_P (context))
10077 /* Completion could have caused us to register the desired
10078 specialization already, so check the table again. */
10079 entry = type_specializations->find_with_hash (&elt, hash);
10080 if (entry)
10081 return entry->spec;
10086 else
10087 context = tsubst (context, arglist, complain, in_decl);
10089 if (context == error_mark_node)
10090 return error_mark_node;
10092 if (!context)
10093 context = global_namespace;
10095 /* Create the type. */
10096 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10098 /* The user referred to a specialization of an alias
10099 template represented by GEN_TMPL.
10101 [temp.alias]/2 says:
10103 When a template-id refers to the specialization of an
10104 alias template, it is equivalent to the associated
10105 type obtained by substitution of its
10106 template-arguments for the template-parameters in the
10107 type-id of the alias template. */
10109 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10110 /* Note that the call above (by indirectly calling
10111 register_specialization in tsubst_decl) registers the
10112 TYPE_DECL representing the specialization of the alias
10113 template. So next time someone substitutes ARGLIST for
10114 the template parms into the alias template (GEN_TMPL),
10115 she'll get that TYPE_DECL back. */
10117 if (t == error_mark_node)
10118 return t;
10120 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10122 if (!is_dependent_type)
10124 set_current_access_from_decl (TYPE_NAME (template_type));
10125 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10126 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10127 arglist, complain, in_decl),
10128 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10129 arglist, complain, in_decl),
10130 SCOPED_ENUM_P (template_type), NULL);
10132 if (t == error_mark_node)
10133 return t;
10135 else
10137 /* We don't want to call start_enum for this type, since
10138 the values for the enumeration constants may involve
10139 template parameters. And, no one should be interested
10140 in the enumeration constants for such a type. */
10141 t = cxx_make_type (ENUMERAL_TYPE);
10142 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10144 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10145 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10146 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10148 else if (CLASS_TYPE_P (template_type))
10150 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10151 instantiated here. */
10152 gcc_assert (!LAMBDA_TYPE_P (template_type));
10154 t = make_class_type (TREE_CODE (template_type));
10155 CLASSTYPE_DECLARED_CLASS (t)
10156 = CLASSTYPE_DECLARED_CLASS (template_type);
10157 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10159 /* A local class. Make sure the decl gets registered properly. */
10160 if (context == current_function_decl)
10161 if (pushtag (DECL_NAME (gen_tmpl), t)
10162 == error_mark_node)
10163 return error_mark_node;
10165 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10166 /* This instantiation is another name for the primary
10167 template type. Set the TYPE_CANONICAL field
10168 appropriately. */
10169 TYPE_CANONICAL (t) = template_type;
10170 else if (any_template_arguments_need_structural_equality_p (arglist))
10171 SET_TYPE_STRUCTURAL_EQUALITY (t);
10173 else
10174 gcc_unreachable ();
10176 /* If we called start_enum or pushtag above, this information
10177 will already be set up. */
10178 type_decl = TYPE_NAME (t);
10179 if (!type_decl)
10181 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10183 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10184 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10185 DECL_SOURCE_LOCATION (type_decl)
10186 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10189 set_instantiating_module (type_decl);
10190 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10191 of export flag. We want to propagate this because it might
10192 be a friend declaration that pushes a new hidden binding. */
10193 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10195 if (CLASS_TYPE_P (template_type))
10197 TREE_PRIVATE (type_decl)
10198 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10199 TREE_PROTECTED (type_decl)
10200 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10201 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10203 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10204 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10208 if (OVERLOAD_TYPE_P (t)
10209 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10211 static const char *tags[] = {"abi_tag", "may_alias"};
10213 for (unsigned ix = 0; ix != 2; ix++)
10215 tree attributes
10216 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10218 if (attributes)
10219 TYPE_ATTRIBUTES (t)
10220 = tree_cons (TREE_PURPOSE (attributes),
10221 TREE_VALUE (attributes),
10222 TYPE_ATTRIBUTES (t));
10226 /* Let's consider the explicit specialization of a member
10227 of a class template specialization that is implicitly instantiated,
10228 e.g.:
10229 template<class T>
10230 struct S
10232 template<class U> struct M {}; //#0
10235 template<>
10236 template<>
10237 struct S<int>::M<char> //#1
10239 int i;
10241 [temp.expl.spec]/4 says this is valid.
10243 In this case, when we write:
10244 S<int>::M<char> m;
10246 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10247 the one of #0.
10249 When we encounter #1, we want to store the partial instantiation
10250 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10252 For all cases other than this "explicit specialization of member of a
10253 class template", we just want to store the most general template into
10254 the CLASSTYPE_TI_TEMPLATE of M.
10256 This case of "explicit specialization of member of a class template"
10257 only happens when:
10258 1/ the enclosing class is an instantiation of, and therefore not
10259 the same as, the context of the most general template, and
10260 2/ we aren't looking at the partial instantiation itself, i.e.
10261 the innermost arguments are not the same as the innermost parms of
10262 the most general template.
10264 So it's only when 1/ and 2/ happens that we want to use the partial
10265 instantiation of the member template in lieu of its most general
10266 template. */
10268 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10269 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10270 /* the enclosing class must be an instantiation... */
10271 && CLASS_TYPE_P (context)
10272 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10274 TREE_VEC_LENGTH (arglist)--;
10275 ++processing_template_decl;
10276 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10277 tree partial_inst_args =
10278 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10279 arglist, complain, NULL_TREE);
10280 --processing_template_decl;
10281 TREE_VEC_LENGTH (arglist)++;
10282 if (partial_inst_args == error_mark_node)
10283 return error_mark_node;
10284 use_partial_inst_tmpl =
10285 /*...and we must not be looking at the partial instantiation
10286 itself. */
10287 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10288 partial_inst_args);
10291 if (!use_partial_inst_tmpl)
10292 /* This case is easy; there are no member templates involved. */
10293 found = gen_tmpl;
10294 else
10296 /* This is a full instantiation of a member template. Find
10297 the partial instantiation of which this is an instance. */
10299 /* Temporarily reduce by one the number of levels in the ARGLIST
10300 so as to avoid comparing the last set of arguments. */
10301 TREE_VEC_LENGTH (arglist)--;
10302 /* We don't use COMPLAIN in the following call because this isn't
10303 the immediate context of deduction. For instance, tf_partial
10304 could be set here as we might be at the beginning of template
10305 argument deduction when any explicitly specified template
10306 arguments are substituted into the function type. tf_partial
10307 could lead into trouble because we wouldn't find the partial
10308 instantiation that might have been created outside tf_partial
10309 context, because the levels of template parameters wouldn't
10310 match, because in a tf_partial context, tsubst doesn't reduce
10311 TEMPLATE_PARM_LEVEL. */
10312 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10313 TREE_VEC_LENGTH (arglist)++;
10314 /* FOUND is either a proper class type, or an alias
10315 template specialization. In the later case, it's a
10316 TYPE_DECL, resulting from the substituting of arguments
10317 for parameters in the TYPE_DECL of the alias template
10318 done earlier. So be careful while getting the template
10319 of FOUND. */
10320 found = (TREE_CODE (found) == TEMPLATE_DECL
10321 ? found
10322 : (TREE_CODE (found) == TYPE_DECL
10323 ? DECL_TI_TEMPLATE (found)
10324 : CLASSTYPE_TI_TEMPLATE (found)));
10326 if (DECL_CLASS_TEMPLATE_P (found)
10327 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10329 /* If this partial instantiation is specialized, we want to
10330 use it for hash table lookup. */
10331 elt.tmpl = found;
10332 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10333 hash = spec_hasher::hash (&elt);
10337 /* Build template info for the new specialization. */
10338 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10340 elt.spec = t;
10341 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10342 gcc_checking_assert (*slot == NULL);
10343 entry = ggc_alloc<spec_entry> ();
10344 *entry = elt;
10345 *slot = entry;
10347 /* Note this use of the partial instantiation so we can check it
10348 later in maybe_process_partial_specialization. */
10349 DECL_TEMPLATE_INSTANTIATIONS (found)
10350 = tree_cons (arglist, t,
10351 DECL_TEMPLATE_INSTANTIATIONS (found));
10353 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10354 && !uses_template_parms (current_nonlambda_scope ())
10355 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10356 /* Now that the type has been registered on the instantiations
10357 list, we set up the enumerators. Because the enumeration
10358 constants may involve the enumeration type itself, we make
10359 sure to register the type first, and then create the
10360 constants. That way, doing tsubst_expr for the enumeration
10361 constants won't result in recursive calls here; we'll find
10362 the instantiation and exit above. */
10363 tsubst_enum (template_type, t, arglist);
10365 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10366 /* If the type makes use of template parameters, the
10367 code that generates debugging information will crash. */
10368 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10370 /* Possibly limit visibility based on template args. */
10371 TREE_PUBLIC (type_decl) = 1;
10372 determine_visibility (type_decl);
10374 inherit_targ_abi_tags (t);
10376 return t;
10380 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10382 tree
10383 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
10385 if (flag_concepts && variable_concept_p (templ))
10386 return build_concept_check (templ, arglist, tf_none);
10388 tree gen_templ = most_general_template (templ);
10389 tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
10390 arglist = add_outermost_template_args (templ, arglist);
10391 arglist = coerce_template_parms (parms, arglist, templ, complain);
10392 if (arglist == error_mark_node)
10393 return error_mark_node;
10395 /* The type of the expression is NULL_TREE since the template-id could refer
10396 to an explicit or partial specialization. */
10397 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10400 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10401 not dependent. */
10403 tree
10404 finish_template_variable (tree var, tsubst_flags_t complain)
10406 tree templ = TREE_OPERAND (var, 0);
10407 tree arglist = TREE_OPERAND (var, 1);
10409 /* If the template or arguments are dependent, then we
10410 can't resolve the TEMPLATE_ID_EXPR yet. */
10411 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10412 || any_dependent_template_arguments_p (arglist))
10413 return var;
10415 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10417 if (complain & tf_error)
10419 auto_diagnostic_group d;
10420 error ("use of invalid variable template %qE", var);
10421 diagnose_constraints (location_of (var), templ, arglist);
10423 return error_mark_node;
10426 return instantiate_template (templ, arglist, complain);
10429 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10430 TARGS template args, and instantiate it if it's not dependent. */
10432 tree
10433 lookup_and_finish_template_variable (tree templ, tree targs,
10434 tsubst_flags_t complain)
10436 tree var = lookup_template_variable (templ, targs, complain);
10437 if (var == error_mark_node)
10438 return error_mark_node;
10439 var = finish_template_variable (var, complain);
10440 mark_used (var);
10441 return var;
10444 /* If the set of template parameters PARMS contains a template parameter
10445 at the given LEVEL and INDEX, then return this parameter. Otherwise
10446 return NULL_TREE. */
10448 static tree
10449 corresponding_template_parameter_list (tree parms, int level, int index)
10451 while (TMPL_PARMS_DEPTH (parms) > level)
10452 parms = TREE_CHAIN (parms);
10454 if (TMPL_PARMS_DEPTH (parms) != level
10455 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10456 return NULL_TREE;
10458 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10461 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10462 corresponds to the template parameter PARM, or else return NULL_TREE. */
10464 static tree
10465 corresponding_template_parameter_list (tree parms, tree parm)
10467 int level, index;
10468 template_parm_level_and_index (parm, &level, &index);
10469 return corresponding_template_parameter_list (parms, level, index);
10472 /* As above, but pull out the actual parameter. */
10474 static tree
10475 corresponding_template_parameter (tree parms, tree parm)
10477 tree list = corresponding_template_parameter_list (parms, parm);
10478 if (!list)
10479 return NULL_TREE;
10481 tree t = TREE_VALUE (list);
10482 /* As in template_parm_to_arg. */
10483 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10484 t = TREE_TYPE (t);
10485 else
10486 t = DECL_INITIAL (t);
10488 gcc_assert (TEMPLATE_PARM_P (t));
10489 return t;
10492 struct pair_fn_data
10494 tree_fn_t fn;
10495 tree_fn_t any_fn;
10496 void *data;
10497 /* True when we should also visit template parameters that occur in
10498 non-deduced contexts. */
10499 bool include_nondeduced_p;
10500 hash_set<tree> *visited;
10503 /* Called from for_each_template_parm via walk_tree. */
10505 static tree
10506 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10508 tree t = *tp;
10509 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10510 tree_fn_t fn = pfd->fn;
10511 void *data = pfd->data;
10512 tree result = NULL_TREE;
10514 #define WALK_SUBTREE(NODE) \
10515 do \
10517 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10518 pfd->include_nondeduced_p, \
10519 pfd->any_fn); \
10520 if (result) goto out; \
10522 while (0)
10524 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10525 return t;
10527 if (TYPE_P (t)
10528 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10529 WALK_SUBTREE (TYPE_CONTEXT (t));
10531 switch (TREE_CODE (t))
10533 case RECORD_TYPE:
10534 if (TYPE_PTRMEMFUNC_P (t))
10535 break;
10536 /* Fall through. */
10538 case UNION_TYPE:
10539 case ENUMERAL_TYPE:
10540 if (!TYPE_TEMPLATE_INFO (t))
10541 *walk_subtrees = 0;
10542 else
10543 WALK_SUBTREE (TYPE_TI_ARGS (t));
10544 break;
10546 case INTEGER_TYPE:
10547 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10548 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10549 break;
10551 case METHOD_TYPE:
10552 /* Since we're not going to walk subtrees, we have to do this
10553 explicitly here. */
10554 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10555 /* Fall through. */
10557 case FUNCTION_TYPE:
10558 /* Check the return type. */
10559 WALK_SUBTREE (TREE_TYPE (t));
10561 /* Check the parameter types. Since default arguments are not
10562 instantiated until they are needed, the TYPE_ARG_TYPES may
10563 contain expressions that involve template parameters. But,
10564 no-one should be looking at them yet. And, once they're
10565 instantiated, they don't contain template parameters, so
10566 there's no point in looking at them then, either. */
10568 tree parm;
10570 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10571 WALK_SUBTREE (TREE_VALUE (parm));
10573 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10574 want walk_tree walking into them itself. */
10575 *walk_subtrees = 0;
10578 if (flag_noexcept_type)
10580 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10581 if (spec)
10582 WALK_SUBTREE (TREE_PURPOSE (spec));
10584 break;
10586 case TYPEOF_TYPE:
10587 case DECLTYPE_TYPE:
10588 if (pfd->include_nondeduced_p
10589 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10590 pfd->visited,
10591 pfd->include_nondeduced_p,
10592 pfd->any_fn))
10593 return error_mark_node;
10594 *walk_subtrees = false;
10595 break;
10597 case TRAIT_TYPE:
10598 if (pfd->include_nondeduced_p)
10600 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10601 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10603 *walk_subtrees = false;
10604 break;
10606 case FUNCTION_DECL:
10607 case VAR_DECL:
10608 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10609 WALK_SUBTREE (DECL_TI_ARGS (t));
10610 break;
10612 case PARM_DECL:
10613 WALK_SUBTREE (TREE_TYPE (t));
10614 break;
10616 case CONST_DECL:
10617 if (DECL_TEMPLATE_PARM_P (t))
10618 WALK_SUBTREE (DECL_INITIAL (t));
10619 if (DECL_CONTEXT (t)
10620 && pfd->include_nondeduced_p)
10621 WALK_SUBTREE (DECL_CONTEXT (t));
10622 break;
10624 case BOUND_TEMPLATE_TEMPLATE_PARM:
10625 /* Record template parameters such as `T' inside `TT<T>'. */
10626 WALK_SUBTREE (TYPE_TI_ARGS (t));
10627 /* Fall through. */
10629 case TEMPLATE_TEMPLATE_PARM:
10630 case TEMPLATE_TYPE_PARM:
10631 case TEMPLATE_PARM_INDEX:
10632 if (fn && (*fn)(t, data))
10633 return t;
10634 else if (!fn)
10635 return t;
10636 break;
10638 case TEMPLATE_DECL:
10639 /* A template template parameter is encountered. */
10640 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10641 WALK_SUBTREE (TREE_TYPE (t));
10643 /* Already substituted template template parameter */
10644 *walk_subtrees = 0;
10645 break;
10647 case TYPENAME_TYPE:
10648 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10649 partial instantiation. */
10650 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10651 *walk_subtrees = 0;
10652 break;
10654 case INDIRECT_REF:
10655 case COMPONENT_REF:
10656 /* If there's no type, then this thing must be some expression
10657 involving template parameters. */
10658 if (!fn && !TREE_TYPE (t))
10659 return error_mark_node;
10660 break;
10662 case CONSTRUCTOR:
10663 case TRAIT_EXPR:
10664 case PLUS_EXPR:
10665 case MULT_EXPR:
10666 case SCOPE_REF:
10667 /* These are non-deduced contexts. */
10668 if (!pfd->include_nondeduced_p)
10669 *walk_subtrees = 0;
10670 break;
10672 case MODOP_EXPR:
10673 case CAST_EXPR:
10674 case IMPLICIT_CONV_EXPR:
10675 case REINTERPRET_CAST_EXPR:
10676 case CONST_CAST_EXPR:
10677 case STATIC_CAST_EXPR:
10678 case DYNAMIC_CAST_EXPR:
10679 case ARROW_EXPR:
10680 case DOTSTAR_EXPR:
10681 case TYPEID_EXPR:
10682 case PSEUDO_DTOR_EXPR:
10683 if (!fn)
10684 return error_mark_node;
10685 break;
10687 default:
10688 break;
10691 #undef WALK_SUBTREE
10693 /* We didn't find any template parameters we liked. */
10694 out:
10695 return result;
10698 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10699 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10700 call FN with the parameter and the DATA.
10701 If FN returns nonzero, the iteration is terminated, and
10702 for_each_template_parm returns 1. Otherwise, the iteration
10703 continues. If FN never returns a nonzero value, the value
10704 returned by for_each_template_parm is 0. If FN is NULL, it is
10705 considered to be the function which always returns 1.
10707 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10708 parameters that occur in non-deduced contexts. When false, only
10709 visits those template parameters that can be deduced. */
10711 static tree
10712 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10713 hash_set<tree> *visited,
10714 bool include_nondeduced_p,
10715 tree_fn_t any_fn)
10717 struct pair_fn_data pfd;
10718 tree result;
10720 /* Set up. */
10721 pfd.fn = fn;
10722 pfd.any_fn = any_fn;
10723 pfd.data = data;
10724 pfd.include_nondeduced_p = include_nondeduced_p;
10726 /* Walk the tree. (Conceptually, we would like to walk without
10727 duplicates, but for_each_template_parm_r recursively calls
10728 for_each_template_parm, so we would need to reorganize a fair
10729 bit to use walk_tree_without_duplicates, so we keep our own
10730 visited list.) */
10731 if (visited)
10732 pfd.visited = visited;
10733 else
10734 pfd.visited = new hash_set<tree>;
10735 result = cp_walk_tree (&t,
10736 for_each_template_parm_r,
10737 &pfd,
10738 pfd.visited);
10740 /* Clean up. */
10741 if (!visited)
10743 delete pfd.visited;
10744 pfd.visited = 0;
10747 return result;
10750 struct find_template_parameter_info
10752 explicit find_template_parameter_info (tree ctx_parms)
10753 : ctx_parms (ctx_parms),
10754 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10757 hash_set<tree> visited;
10758 hash_set<tree> parms;
10759 tree parm_list = NULL_TREE;
10760 tree *parm_list_tail = &parm_list;
10761 tree ctx_parms;
10762 int max_depth;
10764 tree find_in (tree);
10765 tree find_in_recursive (tree);
10766 bool found (tree);
10767 unsigned num_found () { return parms.elements (); }
10770 /* Appends the declaration of T to the list in DATA. */
10772 static int
10773 keep_template_parm (tree t, void* data)
10775 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10777 /* Template parameters declared within the expression are not part of
10778 the parameter mapping. For example, in this concept:
10780 template<typename T>
10781 concept C = requires { <expr> } -> same_as<int>;
10783 the return specifier same_as<int> declares a new decltype parameter
10784 that must not be part of the parameter mapping. The same is true
10785 for generic lambda parameters, lambda template parameters, etc. */
10786 int level;
10787 int index;
10788 template_parm_level_and_index (t, &level, &index);
10789 if (level == 0 || level > ftpi->max_depth)
10790 return 0;
10792 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10793 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10794 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10795 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10797 /* This template parameter might be an argument to a cached dependent
10798 specalization that was formed earlier inside some other template, in
10799 which case the parameter is not among the ones that are in-scope.
10800 Look in CTX_PARMS to find the corresponding in-scope template
10801 parameter, and use it instead. */
10802 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10803 t = in_scope;
10805 /* Arguments like const T yield parameters like const T. This means that
10806 a template-id like X<T, const T> would yield two distinct parameters:
10807 T and const T. Adjust types to their unqualified versions. */
10808 if (TYPE_P (t))
10809 t = TYPE_MAIN_VARIANT (t);
10810 if (!ftpi->parms.add (t))
10812 /* Append T to PARM_LIST. */
10813 tree node = build_tree_list (NULL_TREE, t);
10814 *ftpi->parm_list_tail = node;
10815 ftpi->parm_list_tail = &TREE_CHAIN (node);
10818 /* Verify the parameter we found has a valid index. */
10819 if (flag_checking)
10821 tree parms = ftpi->ctx_parms;
10822 while (TMPL_PARMS_DEPTH (parms) > level)
10823 parms = TREE_CHAIN (parms);
10824 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10825 gcc_assert (index < len);
10828 return 0;
10831 /* Ensure that we recursively examine certain terms that are not normally
10832 visited in for_each_template_parm_r. */
10834 static int
10835 any_template_parm_r (tree t, void *data)
10837 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10839 #define WALK_SUBTREE(NODE) \
10840 do \
10842 for_each_template_parm (NODE, keep_template_parm, data, \
10843 &ftpi->visited, true, \
10844 any_template_parm_r); \
10846 while (0)
10848 /* A mention of a member alias/typedef is a use of all of its template
10849 arguments, including those from the enclosing class, so we don't use
10850 alias_template_specialization_p here. */
10851 if (TYPE_P (t) && typedef_variant_p (t))
10852 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10853 WALK_SUBTREE (TI_ARGS (tinfo));
10855 switch (TREE_CODE (t))
10857 case TEMPLATE_TYPE_PARM:
10858 /* Type constraints of a placeholder type may contain parameters. */
10859 if (is_auto (t))
10860 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10861 WALK_SUBTREE (constr);
10862 break;
10864 case TEMPLATE_ID_EXPR:
10865 /* Search through references to variable templates. */
10866 WALK_SUBTREE (TREE_OPERAND (t, 0));
10867 WALK_SUBTREE (TREE_OPERAND (t, 1));
10868 break;
10870 case TEMPLATE_PARM_INDEX:
10871 WALK_SUBTREE (TREE_TYPE (t));
10872 break;
10874 case TEMPLATE_DECL:
10875 /* If T is a member template that shares template parameters with
10876 ctx_parms, we need to mark all those parameters for mapping.
10877 To that end, it should suffice to just walk the DECL_CONTEXT of
10878 the template (assuming the template is not overly general). */
10879 WALK_SUBTREE (DECL_CONTEXT (t));
10880 break;
10882 case LAMBDA_EXPR:
10884 /* Look in the parms and body. */
10885 tree fn = lambda_function (t);
10886 WALK_SUBTREE (TREE_TYPE (fn));
10887 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10889 break;
10891 case IDENTIFIER_NODE:
10892 if (IDENTIFIER_CONV_OP_P (t))
10893 /* The conversion-type-id of a conversion operator may be dependent. */
10894 WALK_SUBTREE (TREE_TYPE (t));
10895 break;
10897 case CONVERT_EXPR:
10898 if (is_dummy_object (t))
10899 WALK_SUBTREE (TREE_TYPE (t));
10900 break;
10902 default:
10903 break;
10906 /* Keep walking. */
10907 return 0;
10910 /* Look through T for template parameters. */
10912 tree
10913 find_template_parameter_info::find_in (tree t)
10915 return for_each_template_parm (t, keep_template_parm, this, &visited,
10916 /*include_nondeduced*/true,
10917 any_template_parm_r);
10920 /* As above, but also recursively look into the default arguments of template
10921 parameters we found. Used for alias CTAD. */
10923 tree
10924 find_template_parameter_info::find_in_recursive (tree t)
10926 if (tree r = find_in (t))
10927 return r;
10928 /* Since newly found parms are added to the end of the list, we
10929 can just walk it until we reach the end. */
10930 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
10932 tree parm = TREE_VALUE (pl);
10933 tree list = corresponding_template_parameter_list (ctx_parms, parm);
10934 if (tree r = find_in (TREE_PURPOSE (list)))
10935 return r;
10937 return NULL_TREE;
10940 /* True if PARM was found by a previous call to find_in. PARM can be a
10941 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
10943 bool
10944 find_template_parameter_info::found (tree parm)
10946 if (TREE_CODE (parm) == TREE_LIST)
10947 parm = TREE_VALUE (parm);
10948 if (TREE_CODE (parm) == TYPE_DECL)
10949 parm = TREE_TYPE (parm);
10950 else
10951 parm = DECL_INITIAL (parm);
10952 gcc_checking_assert (TEMPLATE_PARM_P (parm));
10953 return parms.contains (parm);
10956 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10957 are the template parameters in scope. */
10959 tree
10960 find_template_parameters (tree t, tree ctx_parms)
10962 if (!ctx_parms)
10963 return NULL_TREE;
10965 find_template_parameter_info ftpi (ctx_parms);
10966 ftpi.find_in (t);
10967 return ftpi.parm_list;
10970 /* Returns true if T depends on any template parameter. */
10972 bool
10973 uses_template_parms (tree t)
10975 if (t == NULL_TREE || t == error_mark_node)
10976 return false;
10978 /* Namespaces can't depend on any template parameters. */
10979 if (TREE_CODE (t) == NAMESPACE_DECL)
10980 return false;
10982 processing_template_decl_sentinel ptds (/*reset*/false);
10983 ++processing_template_decl;
10985 if (TYPE_P (t))
10986 return dependent_type_p (t);
10987 else if (TREE_CODE (t) == TREE_VEC)
10988 return any_dependent_template_arguments_p (t);
10989 else if (TREE_CODE (t) == TREE_LIST)
10990 return (uses_template_parms (TREE_VALUE (t))
10991 || uses_template_parms (TREE_CHAIN (t)));
10992 else if (TREE_CODE (t) == TYPE_DECL)
10993 return dependent_type_p (TREE_TYPE (t));
10994 else
10995 return instantiation_dependent_expression_p (t);
10998 /* Returns true if T depends on any template parameter with level LEVEL. */
11000 bool
11001 uses_template_parms_level (tree t, int level)
11003 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
11004 /*include_nondeduced_p=*/true);
11007 /* Returns true if the signature of DECL depends on any template parameter from
11008 its enclosing class. */
11010 static bool
11011 uses_outer_template_parms (tree decl)
11013 int depth;
11014 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11015 depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
11016 else
11017 depth = template_class_depth (CP_DECL_CONTEXT (decl));
11018 if (depth == 0)
11019 return false;
11020 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
11021 &depth, NULL, /*include_nondeduced_p=*/true))
11022 return true;
11023 if (PRIMARY_TEMPLATE_P (decl)
11024 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
11026 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
11027 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
11029 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
11030 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
11031 if (TREE_CODE (parm) == PARM_DECL
11032 && for_each_template_parm (TREE_TYPE (parm),
11033 template_parm_outer_level,
11034 &depth, NULL, /*nondeduced*/true))
11035 return true;
11036 if (TREE_CODE (parm) == TEMPLATE_DECL
11037 && uses_outer_template_parms (parm))
11038 return true;
11039 if (defarg
11040 && for_each_template_parm (defarg, template_parm_outer_level,
11041 &depth, NULL, /*nondeduced*/true))
11042 return true;
11045 if (uses_outer_template_parms_in_constraints (decl))
11046 return true;
11047 return false;
11050 /* Returns true if the constraints of DECL depend on any template parameters
11051 from its enclosing scope. */
11053 bool
11054 uses_outer_template_parms_in_constraints (tree decl, tree ctx/*=NULL_TREE*/)
11056 tree ci = get_constraints (decl);
11057 if (ci)
11058 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11059 if (!ci)
11060 return false;
11061 if (!ctx)
11063 if (tree fc = DECL_FRIEND_CONTEXT (decl))
11064 ctx = fc;
11065 else
11066 ctx = CP_DECL_CONTEXT (decl);
11068 int depth = template_class_depth (ctx);
11069 if (depth == 0)
11070 return false;
11071 return for_each_template_parm (ci, template_parm_outer_level,
11072 &depth, NULL, /*nondeduced*/true);
11075 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11076 ill-formed translation unit, i.e. a variable or function that isn't
11077 usable in a constant expression. */
11079 static inline bool
11080 neglectable_inst_p (tree d)
11082 return (d && DECL_P (d)
11083 && !undeduced_auto_decl (d)
11084 && !(TREE_CODE (d) == FUNCTION_DECL
11085 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11086 : decl_maybe_constant_var_p (d)));
11089 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11090 neglectable and instantiated from within an erroneous instantiation. */
11092 static bool
11093 limit_bad_template_recursion (tree decl)
11095 struct tinst_level *lev = current_tinst_level;
11096 int errs = errorcount + sorrycount;
11097 if (errs == 0 || !neglectable_inst_p (decl))
11098 return false;
11100 /* Avoid instantiating members of an ill-formed class. */
11101 bool refuse
11102 = (DECL_CLASS_SCOPE_P (decl)
11103 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11105 if (!refuse)
11107 for (; lev; lev = lev->next)
11108 if (neglectable_inst_p (lev->maybe_get_node ()))
11109 break;
11110 refuse = (lev && errs > lev->errors);
11113 if (refuse)
11115 /* Don't warn about it not being defined. */
11116 suppress_warning (decl, OPT_Wunused);
11117 tree clone;
11118 FOR_EACH_CLONE (clone, decl)
11119 suppress_warning (clone, OPT_Wunused);
11121 return refuse;
11124 static int tinst_depth;
11125 extern int max_tinst_depth;
11126 int depth_reached;
11128 static GTY(()) struct tinst_level *last_error_tinst_level;
11130 /* We're starting to instantiate D; record the template instantiation context
11131 at LOC for diagnostics and to restore it later. */
11133 bool
11134 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11136 struct tinst_level *new_level;
11138 if (tinst_depth >= max_tinst_depth)
11140 /* Tell error.cc not to try to instantiate any templates. */
11141 at_eof = 2;
11142 fatal_error (input_location,
11143 "template instantiation depth exceeds maximum of %d"
11144 " (use %<-ftemplate-depth=%> to increase the maximum)",
11145 max_tinst_depth);
11146 return false;
11149 /* If the current instantiation caused problems, don't let it instantiate
11150 anything else. Do allow deduction substitution and decls usable in
11151 constant expressions. */
11152 if (!targs && limit_bad_template_recursion (tldcl))
11154 /* Avoid no_linkage_errors and unused function (and all other)
11155 warnings for this decl. */
11156 suppress_warning (tldcl);
11157 return false;
11160 /* When not -quiet, dump template instantiations other than functions, since
11161 announce_function will take care of those. */
11162 if (!quiet_flag && !targs
11163 && TREE_CODE (tldcl) != TREE_LIST
11164 && TREE_CODE (tldcl) != FUNCTION_DECL)
11165 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11167 new_level = tinst_level_freelist ().alloc ();
11168 new_level->tldcl = tldcl;
11169 new_level->targs = targs;
11170 new_level->locus = loc;
11171 new_level->errors = errorcount + sorrycount;
11172 new_level->next = NULL;
11173 new_level->refcount = 0;
11174 new_level->path = new_level->visible = nullptr;
11175 set_refcount_ptr (new_level->next, current_tinst_level);
11176 set_refcount_ptr (current_tinst_level, new_level);
11178 ++tinst_depth;
11179 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11180 depth_reached = tinst_depth;
11182 return true;
11185 /* We're starting substitution of TMPL<ARGS>; record the template
11186 substitution context for diagnostics and to restore it later. */
11188 bool
11189 push_tinst_level (tree tmpl, tree args)
11191 return push_tinst_level_loc (tmpl, args, input_location);
11194 /* We're starting to instantiate D; record INPUT_LOCATION and the
11195 template instantiation context for diagnostics and to restore it
11196 later. */
11198 bool
11199 push_tinst_level (tree d)
11201 return push_tinst_level_loc (d, input_location);
11204 /* Likewise, but record LOC as the program location. */
11206 bool
11207 push_tinst_level_loc (tree d, location_t loc)
11209 gcc_assert (TREE_CODE (d) != TREE_LIST);
11210 return push_tinst_level_loc (d, NULL, loc);
11213 /* We're done instantiating this template; return to the instantiation
11214 context. */
11216 void
11217 pop_tinst_level (void)
11219 /* Restore the filename and line number stashed away when we started
11220 this instantiation. */
11221 input_location = current_tinst_level->locus;
11222 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11223 --tinst_depth;
11226 /* We're instantiating a deferred template; restore the template
11227 instantiation context in which the instantiation was requested, which
11228 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11230 static tree
11231 reopen_tinst_level (struct tinst_level *level)
11233 struct tinst_level *t;
11235 tinst_depth = 0;
11236 for (t = level; t; t = t->next)
11237 ++tinst_depth;
11239 set_refcount_ptr (current_tinst_level, level);
11240 pop_tinst_level ();
11241 if (current_tinst_level)
11242 current_tinst_level->errors = errorcount+sorrycount;
11243 return level->maybe_get_node ();
11246 /* Returns the TINST_LEVEL which gives the original instantiation
11247 context. */
11249 struct tinst_level *
11250 outermost_tinst_level (void)
11252 struct tinst_level *level = current_tinst_level;
11253 if (level)
11254 while (level->next)
11255 level = level->next;
11256 return level;
11259 /* True iff T is a friend function declaration that is not itself a template
11260 and is not defined in a class template. */
11262 bool
11263 non_templated_friend_p (tree t)
11265 if (t && TREE_CODE (t) == FUNCTION_DECL
11266 && DECL_UNIQUE_FRIEND_P (t))
11268 tree ti = DECL_TEMPLATE_INFO (t);
11269 if (!ti)
11270 return true;
11271 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11272 if (DECL_FRIEND_CONTEXT (t))
11273 return false;
11274 /* Non-templated friends in a class template are still represented with a
11275 TEMPLATE_DECL; check that its primary template is the befriending
11276 class. Note that DECL_PRIMARY_TEMPLATE is null for
11277 template <class T> friend A<T>::f(); */
11278 tree tmpl = TI_TEMPLATE (ti);
11279 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11280 return (primary && primary != tmpl);
11282 else
11283 return false;
11286 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11287 vector of template arguments, as for tsubst.
11289 Returns an appropriate tsubst'd friend declaration. */
11291 static tree
11292 tsubst_friend_function (tree decl, tree args)
11294 tree new_friend;
11296 if (TREE_CODE (decl) == FUNCTION_DECL
11297 && DECL_TEMPLATE_INSTANTIATION (decl)
11298 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11299 /* This was a friend declared with an explicit template
11300 argument list, e.g.:
11302 friend void f<>(T);
11304 to indicate that f was a template instantiation, not a new
11305 function declaration. Now, we have to figure out what
11306 instantiation of what template. */
11308 tree template_id, arglist, fns;
11309 tree new_args;
11310 tree tmpl;
11311 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11313 /* Friend functions are looked up in the containing namespace scope.
11314 We must enter that scope, to avoid finding member functions of the
11315 current class with same name. */
11316 push_nested_namespace (ns);
11317 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11318 tf_warning_or_error, NULL_TREE);
11319 pop_nested_namespace (ns);
11320 arglist = tsubst (DECL_TI_ARGS (decl), args,
11321 tf_warning_or_error, NULL_TREE);
11322 template_id = lookup_template_function (fns, arglist);
11324 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11325 tmpl = determine_specialization (template_id, new_friend,
11326 &new_args,
11327 /*need_member_template=*/0,
11328 TREE_VEC_LENGTH (args),
11329 tsk_none);
11330 return instantiate_template (tmpl, new_args, tf_error);
11333 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11334 if (new_friend == error_mark_node)
11335 return error_mark_node;
11337 /* The NEW_FRIEND will look like an instantiation, to the
11338 compiler, but is not an instantiation from the point of view of
11339 the language. For example, we might have had:
11341 template <class T> struct S {
11342 template <class U> friend void f(T, U);
11345 Then, in S<int>, template <class U> void f(int, U) is not an
11346 instantiation of anything. */
11348 DECL_USE_TEMPLATE (new_friend) = 0;
11349 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11351 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11352 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11353 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11354 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11356 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11357 match in decls_match. */
11358 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11359 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11360 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11361 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11363 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11364 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11365 tsubst_each_template_parm_constraints (parms, args,
11366 tf_warning_or_error);
11370 /* The mangled name for the NEW_FRIEND is incorrect. The function
11371 is not a template instantiation and should not be mangled like
11372 one. Therefore, we forget the mangling here; we'll recompute it
11373 later if we need it. */
11374 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11376 SET_DECL_RTL (new_friend, NULL);
11377 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11380 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11382 tree old_decl;
11383 tree ns;
11385 /* We must save some information from NEW_FRIEND before calling
11386 duplicate decls since that function will free NEW_FRIEND if
11387 possible. */
11388 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11389 tree new_friend_result_template_info = NULL_TREE;
11390 bool new_friend_is_defn =
11391 (new_friend_template_info
11392 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11393 (template_for_substitution (new_friend)))
11394 != NULL_TREE));
11395 tree not_tmpl = new_friend;
11397 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11399 /* This declaration is a `primary' template. */
11400 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11402 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11403 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11406 /* Inside pushdecl_namespace_level, we will push into the
11407 current namespace. However, the friend function should go
11408 into the namespace of the template. */
11409 ns = decl_namespace_context (new_friend);
11410 push_nested_namespace (ns);
11411 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11412 pop_nested_namespace (ns);
11414 if (old_decl == error_mark_node)
11415 return error_mark_node;
11417 if (old_decl != new_friend)
11419 /* This new friend declaration matched an existing
11420 declaration. For example, given:
11422 template <class T> void f(T);
11423 template <class U> class C {
11424 template <class T> friend void f(T) {}
11427 the friend declaration actually provides the definition
11428 of `f', once C has been instantiated for some type. So,
11429 old_decl will be the out-of-class template declaration,
11430 while new_friend is the in-class definition.
11432 But, if `f' was called before this point, the
11433 instantiation of `f' will have DECL_TI_ARGS corresponding
11434 to `T' but not to `U', references to which might appear
11435 in the definition of `f'. Previously, the most general
11436 template for an instantiation of `f' was the out-of-class
11437 version; now it is the in-class version. Therefore, we
11438 run through all specialization of `f', adding to their
11439 DECL_TI_ARGS appropriately. In particular, they need a
11440 new set of outer arguments, corresponding to the
11441 arguments for this class instantiation.
11443 The same situation can arise with something like this:
11445 friend void f(int);
11446 template <class T> class C {
11447 friend void f(T) {}
11450 when `C<int>' is instantiated. Now, `f(int)' is defined
11451 in the class. */
11453 if (!new_friend_is_defn)
11454 /* On the other hand, if the in-class declaration does
11455 *not* provide a definition, then we don't want to alter
11456 existing definitions. We can just leave everything
11457 alone. */
11459 else
11461 tree new_template = TI_TEMPLATE (new_friend_template_info);
11462 tree new_args = TI_ARGS (new_friend_template_info);
11464 /* Overwrite whatever template info was there before, if
11465 any, with the new template information pertaining to
11466 the declaration. */
11467 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11469 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11471 /* We should have called reregister_specialization in
11472 duplicate_decls. */
11473 gcc_assert (retrieve_specialization (new_template,
11474 new_args, 0)
11475 == old_decl);
11477 /* Instantiate it if the global has already been used. */
11478 if (DECL_ODR_USED (old_decl))
11479 instantiate_decl (old_decl, /*defer_ok=*/true,
11480 /*expl_inst_class_mem_p=*/false);
11482 else
11484 tree t;
11486 /* Indicate that the old function template is a partial
11487 instantiation. */
11488 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11489 = new_friend_result_template_info;
11491 gcc_assert (new_template
11492 == most_general_template (new_template));
11493 gcc_assert (new_template != old_decl);
11495 /* Reassign any specializations already in the hash table
11496 to the new more general template, and add the
11497 additional template args. */
11498 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11499 t != NULL_TREE;
11500 t = TREE_CHAIN (t))
11502 tree spec = TREE_VALUE (t);
11503 spec_entry elt;
11505 elt.tmpl = old_decl;
11506 elt.args = DECL_TI_ARGS (spec);
11507 elt.spec = NULL_TREE;
11509 decl_specializations->remove_elt (&elt);
11511 DECL_TI_ARGS (spec)
11512 = add_outermost_template_args (new_args,
11513 DECL_TI_ARGS (spec));
11515 register_specialization
11516 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11519 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11523 /* The information from NEW_FRIEND has been merged into OLD_DECL
11524 by duplicate_decls. */
11525 new_friend = old_decl;
11528 /* We've just introduced a namespace-scope function in the purview
11529 without necessarily having opened the enclosing namespace, so
11530 make sure the namespace is in the purview now too. */
11531 if (modules_p ()
11532 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11533 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11534 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11536 else
11538 tree context = DECL_CONTEXT (new_friend);
11539 bool dependent_p;
11541 /* In the code
11542 template <class T> class C {
11543 template <class U> friend void C1<U>::f (); // case 1
11544 friend void C2<T>::f (); // case 2
11546 we only need to make sure CONTEXT is a complete type for
11547 case 2. To distinguish between the two cases, we note that
11548 CONTEXT of case 1 remains dependent type after tsubst while
11549 this isn't true for case 2. */
11550 ++processing_template_decl;
11551 dependent_p = dependent_type_p (context);
11552 --processing_template_decl;
11554 if (!dependent_p
11555 && !complete_type_or_else (context, NULL_TREE))
11556 return error_mark_node;
11558 if (COMPLETE_TYPE_P (context))
11560 tree fn = new_friend;
11561 /* do_friend adds the TEMPLATE_DECL for any member friend
11562 template even if it isn't a member template, i.e.
11563 template <class T> friend A<T>::f();
11564 Look through it in that case. */
11565 if (TREE_CODE (fn) == TEMPLATE_DECL
11566 && !PRIMARY_TEMPLATE_P (fn))
11567 fn = DECL_TEMPLATE_RESULT (fn);
11568 /* Check to see that the declaration is really present, and,
11569 possibly obtain an improved declaration. */
11570 fn = check_classfn (context, fn, NULL_TREE);
11572 if (fn)
11573 new_friend = fn;
11577 return new_friend;
11580 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11581 template arguments, as for tsubst.
11583 Returns an appropriate tsubst'd friend type or error_mark_node on
11584 failure. */
11586 static tree
11587 tsubst_friend_class (tree friend_tmpl, tree args)
11589 tree tmpl;
11591 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11593 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11594 return TREE_TYPE (tmpl);
11597 tree context = CP_DECL_CONTEXT (friend_tmpl);
11598 if (TREE_CODE (context) == NAMESPACE_DECL)
11599 push_nested_namespace (context);
11600 else
11602 context = tsubst (context, args, tf_error, NULL_TREE);
11603 push_nested_class (context);
11606 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11607 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11609 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11611 /* The friend template has already been declared. Just
11612 check to see that the declarations match, and install any new
11613 default parameters. We must tsubst the default parameters,
11614 of course. We only need the innermost template parameters
11615 because that is all that redeclare_class_template will look
11616 at. */
11617 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11618 > TMPL_ARGS_DEPTH (args))
11620 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11621 args, tf_warning_or_error);
11622 tsubst_each_template_parm_constraints (parms, args,
11623 tf_warning_or_error);
11624 location_t saved_input_location = input_location;
11625 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11626 tree cons = get_constraints (friend_tmpl);
11627 ++processing_template_decl;
11628 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11629 DECL_FRIEND_CONTEXT (friend_tmpl));
11630 --processing_template_decl;
11631 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11632 input_location = saved_input_location;
11635 else
11637 /* The friend template has not already been declared. In this
11638 case, the instantiation of the template class will cause the
11639 injection of this template into the namespace scope. */
11640 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11642 if (tmpl != error_mark_node)
11644 /* The new TMPL is not an instantiation of anything, so we
11645 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11646 for the new type because that is supposed to be the
11647 corresponding template decl, i.e., TMPL. */
11648 DECL_USE_TEMPLATE (tmpl) = 0;
11649 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11650 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11651 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11652 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11654 /* Substitute into and set the constraints on the new declaration. */
11655 if (tree ci = get_constraints (friend_tmpl))
11657 ++processing_template_decl;
11658 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11659 DECL_FRIEND_CONTEXT (friend_tmpl));
11660 --processing_template_decl;
11661 set_constraints (tmpl, ci);
11662 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11663 args, tf_warning_or_error);
11666 /* Inject this template into the enclosing namspace scope. */
11667 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11671 if (TREE_CODE (context) == NAMESPACE_DECL)
11672 pop_nested_namespace (context);
11673 else
11674 pop_nested_class ();
11676 return TREE_TYPE (tmpl);
11679 /* Returns zero if TYPE cannot be completed later due to circularity.
11680 Otherwise returns one. */
11682 static int
11683 can_complete_type_without_circularity (tree type)
11685 if (type == NULL_TREE || type == error_mark_node)
11686 return 0;
11687 else if (COMPLETE_TYPE_P (type))
11688 return 1;
11689 else if (TREE_CODE (type) == ARRAY_TYPE)
11690 return can_complete_type_without_circularity (TREE_TYPE (type));
11691 else if (CLASS_TYPE_P (type)
11692 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11693 return 0;
11694 else
11695 return 1;
11698 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11699 tsubst_flags_t, tree);
11701 /* Instantiate the contract statement. */
11703 static tree
11704 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11705 tree in_decl)
11707 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11708 bool auto_p = type_uses_auto (type);
11710 tree r = copy_node (t);
11712 /* Rebuild the result variable. */
11713 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11715 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11717 tree newvar = copy_node (oldvar);
11718 TREE_TYPE (newvar) = type;
11719 DECL_CONTEXT (newvar) = decl;
11720 POSTCONDITION_IDENTIFIER (r) = newvar;
11722 /* Make sure the postcondition is valid. */
11723 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11724 if (!auto_p)
11725 if (!check_postcondition_result (decl, type, loc))
11726 return invalidate_contract (r);
11728 /* Make the variable available for lookup. */
11729 register_local_specialization (newvar, oldvar);
11732 /* Instantiate the condition. If the return type is undeduced, process
11733 the expression as if inside a template to avoid spurious type errors. */
11734 if (auto_p)
11735 ++processing_template_decl;
11736 ++processing_contract_condition;
11737 CONTRACT_CONDITION (r)
11738 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11739 --processing_contract_condition;
11740 if (auto_p)
11741 --processing_template_decl;
11743 /* And the comment. */
11744 CONTRACT_COMMENT (r)
11745 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11747 return r;
11750 /* Update T by instantiating its contract attribute. */
11752 static void
11753 tsubst_contract_attribute (tree decl, tree t, tree args,
11754 tsubst_flags_t complain, tree in_decl)
11756 /* For non-specializations, adjust the current declaration to the most general
11757 version of in_decl. Because we defer the instantiation of contracts as long
11758 as possible, they are still written in terms of the parameters (and return
11759 type) of the most general template. */
11760 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11761 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11762 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11763 local_specialization_stack specs (lss_copy);
11764 register_parameter_specializations (in_decl, decl);
11766 /* Get the contract to be instantiated. */
11767 tree contract = CONTRACT_STATEMENT (t);
11769 /* Use the complete set of template arguments for instantiation. The
11770 contract may not have been instantiated and still refer to outer levels
11771 of template parameters. */
11772 args = DECL_TI_ARGS (decl);
11774 /* For member functions, make this available for semantic analysis. */
11775 tree save_ccp = current_class_ptr;
11776 tree save_ccr = current_class_ref;
11777 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11779 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11780 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11781 inject_this_parameter (this_type, cp_type_quals (this_type));
11784 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11786 current_class_ptr = save_ccp;
11787 current_class_ref = save_ccr;
11789 /* Rebuild the attribute. */
11790 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11793 /* Rebuild the attribute list for DECL, substituting into contracts
11794 as needed. */
11796 void
11797 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11799 tree list = copy_list (DECL_ATTRIBUTES (decl));
11800 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11802 if (cxx_contract_attribute_p (attr))
11803 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11805 DECL_ATTRIBUTES (decl) = list;
11808 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11809 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11811 static tree
11812 tsubst_attribute (tree t, tree *decl_p, tree args,
11813 tsubst_flags_t complain, tree in_decl)
11815 gcc_assert (ATTR_IS_DEPENDENT (t));
11817 /* Note that contract attributes are never substituted from this function.
11818 Their instantiation is triggered by regenerate_from_template_decl when
11819 we instantiate the body of the function. */
11821 tree val = TREE_VALUE (t);
11822 if (val == NULL_TREE)
11823 /* Nothing to do. */;
11824 else if ((flag_openmp || flag_openmp_simd)
11825 && is_attribute_p ("omp declare simd",
11826 get_attribute_name (t)))
11828 tree clauses = TREE_VALUE (val);
11829 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11830 complain, in_decl);
11831 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11832 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11833 tree parms = DECL_ARGUMENTS (*decl_p);
11834 clauses
11835 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11836 if (clauses)
11837 val = build_tree_list (NULL_TREE, clauses);
11838 else
11839 val = NULL_TREE;
11841 else if (flag_openmp
11842 && is_attribute_p ("omp declare variant base",
11843 get_attribute_name (t)))
11845 ++cp_unevaluated_operand;
11846 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11847 --cp_unevaluated_operand;
11848 tree chain = TREE_CHAIN (val);
11849 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11850 tree ctx = copy_list (TREE_VALUE (val));
11851 tree simd = get_identifier ("simd");
11852 tree score = get_identifier (" score");
11853 tree condition = get_identifier ("condition");
11854 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11856 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11857 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11858 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11860 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11862 tree clauses = TREE_VALUE (t2);
11863 clauses = tsubst_omp_clauses (clauses,
11864 C_ORT_OMP_DECLARE_SIMD, args,
11865 complain, in_decl);
11866 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11867 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11868 TREE_VALUE (t2) = clauses;
11870 else
11872 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11873 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11874 if (TREE_VALUE (t3))
11876 bool allow_string
11877 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11878 && TREE_PURPOSE (t3) != score);
11879 tree v = TREE_VALUE (t3);
11880 if (TREE_CODE (v) == STRING_CST && allow_string)
11881 continue;
11882 v = tsubst_expr (v, args, complain, in_decl);
11883 v = fold_non_dependent_expr (v);
11884 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11885 || (TREE_PURPOSE (t3) == score
11886 ? TREE_CODE (v) != INTEGER_CST
11887 : !tree_fits_shwi_p (v)))
11889 location_t loc
11890 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11891 match_loc);
11892 if (TREE_PURPOSE (t3) == score)
11893 error_at (loc, "score argument must be "
11894 "constant integer expression");
11895 else if (allow_string)
11896 error_at (loc, "property must be constant "
11897 "integer expression or string "
11898 "literal");
11899 else
11900 error_at (loc, "property must be constant "
11901 "integer expression");
11902 return NULL_TREE;
11904 else if (TREE_PURPOSE (t3) == score
11905 && tree_int_cst_sgn (v) < 0)
11907 location_t loc
11908 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11909 match_loc);
11910 error_at (loc, "score argument must be "
11911 "non-negative");
11912 return NULL_TREE;
11914 TREE_VALUE (t3) = v;
11919 val = tree_cons (varid, ctx, chain);
11921 /* If the first attribute argument is an identifier, don't
11922 pass it through tsubst. Attributes like mode, format,
11923 cleanup and several target specific attributes expect it
11924 unmodified. */
11925 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11927 tree chain
11928 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
11929 if (chain != TREE_CHAIN (val))
11930 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11932 else if (PACK_EXPANSION_P (val))
11934 /* An attribute pack expansion. */
11935 tree purp = TREE_PURPOSE (t);
11936 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11937 if (pack == error_mark_node)
11938 return error_mark_node;
11939 int len = TREE_VEC_LENGTH (pack);
11940 tree list = NULL_TREE;
11941 tree *q = &list;
11942 for (int i = 0; i < len; ++i)
11944 tree elt = TREE_VEC_ELT (pack, i);
11945 *q = build_tree_list (purp, elt);
11946 q = &TREE_CHAIN (*q);
11948 return list;
11950 else
11951 val = tsubst_expr (val, args, complain, in_decl);
11953 if (val == error_mark_node)
11954 return error_mark_node;
11955 if (val != TREE_VALUE (t))
11956 return build_tree_list (TREE_PURPOSE (t), val);
11957 return t;
11960 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11961 unchanged or a new TREE_LIST chain. */
11963 static tree
11964 tsubst_attributes (tree attributes, tree args,
11965 tsubst_flags_t complain, tree in_decl)
11967 tree last_dep = NULL_TREE;
11969 for (tree t = attributes; t; t = TREE_CHAIN (t))
11970 if (ATTR_IS_DEPENDENT (t))
11972 last_dep = t;
11973 attributes = copy_list (attributes);
11974 break;
11977 if (last_dep)
11978 for (tree *p = &attributes; *p; )
11980 tree t = *p;
11981 if (ATTR_IS_DEPENDENT (t))
11983 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11984 if (subst != t)
11986 *p = subst;
11987 while (*p)
11988 p = &TREE_CHAIN (*p);
11989 *p = TREE_CHAIN (t);
11990 continue;
11993 p = &TREE_CHAIN (*p);
11996 return attributes;
11999 /* Apply any attributes which had to be deferred until instantiation
12000 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
12001 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
12002 false on error. */
12004 static bool
12005 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
12006 tree args, tsubst_flags_t complain, tree in_decl)
12008 tree t;
12009 tree *p;
12011 if (attributes == NULL_TREE)
12012 return true;
12014 if (DECL_P (*decl_p))
12016 if (TREE_TYPE (*decl_p) == error_mark_node)
12017 return false;
12018 p = &DECL_ATTRIBUTES (*decl_p);
12019 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
12020 to our attributes parameter. */
12021 gcc_assert (*p == attributes);
12023 else
12025 p = &TYPE_ATTRIBUTES (*decl_p);
12026 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
12027 lookup_template_class_1, and should be preserved. */
12028 gcc_assert (*p != attributes);
12029 while (*p)
12030 p = &TREE_CHAIN (*p);
12033 /* save_template_attributes puts the dependent attributes at the beginning of
12034 the list; find the non-dependent ones. */
12035 for (t = attributes; t; t = TREE_CHAIN (t))
12036 if (!ATTR_IS_DEPENDENT (t))
12037 break;
12038 tree nondep = t;
12040 /* Apply any non-dependent attributes. */
12041 *p = nondep;
12043 if (nondep == attributes)
12044 return true;
12046 /* And then any dependent ones. */
12047 tree late_attrs = NULL_TREE;
12048 tree *q = &late_attrs;
12049 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12051 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12052 if (*q == error_mark_node)
12053 return false;
12054 if (*q == t)
12056 *q = copy_node (t);
12057 TREE_CHAIN (*q) = NULL_TREE;
12059 while (*q)
12060 q = &TREE_CHAIN (*q);
12063 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12064 those attributes should have been added already when those templates were
12065 parsed, and shouldn't be added based on from which context they are
12066 first time instantiated. */
12067 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12068 auto o2 = make_temp_override (optimization_current_node,
12069 optimization_default_node);
12070 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12071 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12072 NULL);
12073 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12075 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12077 return true;
12080 /* The template TMPL is being instantiated with the template arguments TARGS.
12081 Perform the access checks that we deferred when parsing the template. */
12083 static void
12084 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12086 unsigned i;
12087 deferred_access_check *chk;
12089 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12090 return;
12092 if (vec<deferred_access_check, va_gc> *access_checks
12093 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12094 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12096 tree decl = chk->decl;
12097 tree diag_decl = chk->diag_decl;
12098 tree type_scope = TREE_TYPE (chk->binfo);
12100 if (uses_template_parms (type_scope))
12101 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12103 /* Make access check error messages point to the location
12104 of the use of the typedef. */
12105 iloc_sentinel ils (chk->loc);
12106 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12107 decl, diag_decl, tf_warning_or_error);
12111 tree
12112 instantiate_class_template (tree type)
12114 auto_timevar tv (TV_TEMPLATE_INST);
12116 tree templ, args, pattern, t, member;
12117 tree typedecl;
12118 tree pbinfo;
12119 tree base_list;
12120 unsigned int saved_maximum_field_alignment;
12121 tree fn_context;
12123 if (type == error_mark_node)
12124 return error_mark_node;
12126 if (COMPLETE_OR_OPEN_TYPE_P (type)
12127 || (uses_template_parms (type)
12128 && !TYPE_FUNCTION_SCOPE_P (type)))
12129 return type;
12131 /* Figure out which template is being instantiated. */
12132 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12133 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12135 /* Mark the type as in the process of being defined. */
12136 TYPE_BEING_DEFINED (type) = 1;
12138 /* We may be in the middle of deferred access check. Disable
12139 it now. */
12140 deferring_access_check_sentinel acs (dk_no_deferred);
12142 /* Determine what specialization of the original template to
12143 instantiate. */
12144 t = most_specialized_partial_spec (type, tf_warning_or_error);
12145 if (t == error_mark_node)
12146 return error_mark_node;
12147 else if (t)
12149 /* This TYPE is actually an instantiation of a partial
12150 specialization. We replace the innermost set of ARGS with
12151 the arguments appropriate for substitution. For example,
12152 given:
12154 template <class T> struct S {};
12155 template <class T> struct S<T*> {};
12157 and supposing that we are instantiating S<int*>, ARGS will
12158 presently be {int*} -- but we need {int}. */
12159 pattern = TREE_TYPE (TI_TEMPLATE (t));
12160 args = TI_ARGS (t);
12162 else
12164 pattern = TREE_TYPE (templ);
12165 args = CLASSTYPE_TI_ARGS (type);
12168 /* If the template we're instantiating is incomplete, then clearly
12169 there's nothing we can do. */
12170 if (!COMPLETE_TYPE_P (pattern))
12172 /* We can try again later. */
12173 TYPE_BEING_DEFINED (type) = 0;
12174 return type;
12177 /* If we've recursively instantiated too many templates, stop. */
12178 if (! push_tinst_level (type))
12179 return type;
12181 int saved_unevaluated_operand = cp_unevaluated_operand;
12182 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12184 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12185 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12186 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12187 fn_context = error_mark_node;
12188 if (!fn_context)
12189 push_to_top_level ();
12190 else
12192 cp_unevaluated_operand = 0;
12193 c_inhibit_evaluation_warnings = 0;
12196 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12198 /* Use #pragma pack from the template context. */
12199 saved_maximum_field_alignment = maximum_field_alignment;
12200 maximum_field_alignment = TYPE_PRECISION (pattern);
12202 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12204 /* Set the input location to the most specialized template definition.
12205 This is needed if tsubsting causes an error. */
12206 typedecl = TYPE_MAIN_DECL (pattern);
12207 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12208 DECL_SOURCE_LOCATION (typedecl);
12210 set_instantiating_module (TYPE_NAME (type));
12212 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12213 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12214 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12215 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12216 if (ANON_AGGR_TYPE_P (pattern))
12217 SET_ANON_AGGR_TYPE_P (type);
12218 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12220 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12221 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12222 /* Adjust visibility for template arguments. */
12223 determine_visibility (TYPE_MAIN_DECL (type));
12225 if (CLASS_TYPE_P (type))
12226 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12228 pbinfo = TYPE_BINFO (pattern);
12230 /* We should never instantiate a nested class before its enclosing
12231 class; we need to look up the nested class by name before we can
12232 instantiate it, and that lookup should instantiate the enclosing
12233 class. */
12234 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12235 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12237 base_list = NULL_TREE;
12238 /* Defer access checking while we substitute into the types named in
12239 the base-clause. */
12240 push_deferring_access_checks (dk_deferred);
12241 if (BINFO_N_BASE_BINFOS (pbinfo))
12243 tree pbase_binfo;
12244 int i;
12246 /* Substitute into each of the bases to determine the actual
12247 basetypes. */
12248 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12250 tree base;
12251 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12252 tree expanded_bases = NULL_TREE;
12253 int idx, len = 1;
12255 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12257 expanded_bases =
12258 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12259 args, tf_error, NULL_TREE);
12260 if (expanded_bases == error_mark_node)
12261 continue;
12263 len = TREE_VEC_LENGTH (expanded_bases);
12266 for (idx = 0; idx < len; idx++)
12268 if (expanded_bases)
12269 /* Extract the already-expanded base class. */
12270 base = TREE_VEC_ELT (expanded_bases, idx);
12271 else
12272 /* Substitute to figure out the base class. */
12273 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12274 NULL_TREE);
12276 if (base == error_mark_node)
12277 continue;
12279 base_list = tree_cons (access, base, base_list);
12280 if (BINFO_VIRTUAL_P (pbase_binfo))
12281 TREE_TYPE (base_list) = integer_type_node;
12285 /* The list is now in reverse order; correct that. */
12286 base_list = nreverse (base_list);
12288 /* Now call xref_basetypes to set up all the base-class
12289 information. */
12290 xref_basetypes (type, base_list);
12292 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12293 (int) ATTR_FLAG_TYPE_IN_PLACE,
12294 args, tf_error, NULL_TREE);
12295 fixup_attribute_variants (type);
12297 /* Now that our base classes are set up, enter the scope of the
12298 class, so that name lookups into base classes, etc. will work
12299 correctly. This is precisely analogous to what we do in
12300 begin_class_definition when defining an ordinary non-template
12301 class, except we also need to push the enclosing classes. */
12302 push_nested_class (type);
12304 /* Now check accessibility of the types named in its base-clause,
12305 relative to the scope of the class. */
12306 pop_to_parent_deferring_access_checks ();
12308 /* A vector to hold members marked with attribute used. */
12309 auto_vec<tree> used;
12311 /* Now members are processed in the order of declaration. */
12312 for (member = CLASSTYPE_DECL_LIST (pattern);
12313 member; member = TREE_CHAIN (member))
12315 tree t = TREE_VALUE (member);
12317 if (TREE_PURPOSE (member))
12319 if (TYPE_P (t))
12321 if (LAMBDA_TYPE_P (t))
12322 /* A closure type for a lambda in an NSDMI or default argument.
12323 Ignore it; it will be regenerated when needed. */
12324 continue;
12326 /* If the member is a class template, we've
12327 already substituted its type. */
12328 if (CLASS_TYPE_P (t)
12329 && CLASSTYPE_IS_TEMPLATE (t))
12330 continue;
12332 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12333 if (newtag == error_mark_node)
12334 continue;
12336 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12338 tree name = TYPE_IDENTIFIER (t);
12340 /* Now, install the tag. We don't use pushtag
12341 because that does too much work -- creating an
12342 implicit typedef, which we've already done. */
12343 set_identifier_type_value (name, TYPE_NAME (newtag));
12344 maybe_add_class_template_decl_list (type, newtag, false);
12345 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12346 determine_visibility (TYPE_NAME (newtag));
12349 else if (DECL_DECLARES_FUNCTION_P (t))
12351 tree r;
12353 if (TREE_CODE (t) == TEMPLATE_DECL)
12354 ++processing_template_decl;
12355 r = tsubst (t, args, tf_error, NULL_TREE);
12356 if (TREE_CODE (t) == TEMPLATE_DECL)
12357 --processing_template_decl;
12359 set_current_access_from_decl (r);
12360 finish_member_declaration (r);
12361 /* Instantiate members marked with attribute used. */
12362 if (r != error_mark_node && DECL_PRESERVE_P (r))
12363 used.safe_push (r);
12364 if (TREE_CODE (r) == FUNCTION_DECL
12365 && DECL_OMP_DECLARE_REDUCTION_P (r))
12366 cp_check_omp_declare_reduction (r);
12368 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12369 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12370 /* A closure type for a lambda in an NSDMI or default argument.
12371 Ignore it; it will be regenerated when needed. */;
12372 else
12374 /* Build new TYPE_FIELDS. */
12375 if (TREE_CODE (t) == STATIC_ASSERT)
12376 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE);
12377 else if (TREE_CODE (t) != CONST_DECL)
12379 tree r;
12380 tree vec = NULL_TREE;
12381 int len = 1;
12383 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12384 /* The file and line for this declaration, to
12385 assist in error message reporting. Since we
12386 called push_tinst_level above, we don't need to
12387 restore these. */
12388 input_location = DECL_SOURCE_LOCATION (t);
12390 if (TREE_CODE (t) == TEMPLATE_DECL)
12391 ++processing_template_decl;
12392 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12393 if (TREE_CODE (t) == TEMPLATE_DECL)
12394 --processing_template_decl;
12396 if (TREE_CODE (r) == TREE_VEC)
12398 /* A capture pack became multiple fields. */
12399 vec = r;
12400 len = TREE_VEC_LENGTH (vec);
12403 for (int i = 0; i < len; ++i)
12405 if (vec)
12406 r = TREE_VEC_ELT (vec, i);
12407 if (VAR_P (r))
12409 /* In [temp.inst]:
12411 [t]he initialization (and any associated
12412 side-effects) of a static data member does
12413 not occur unless the static data member is
12414 itself used in a way that requires the
12415 definition of the static data member to
12416 exist.
12418 Therefore, we do not substitute into the
12419 initialized for the static data member here. */
12420 finish_static_data_member_decl
12422 /*init=*/NULL_TREE,
12423 /*init_const_expr_p=*/false,
12424 /*asmspec_tree=*/NULL_TREE,
12425 /*flags=*/0);
12426 /* Instantiate members marked with attribute used. */
12427 if (r != error_mark_node && DECL_PRESERVE_P (r))
12428 used.safe_push (r);
12430 else if (TREE_CODE (r) == FIELD_DECL)
12432 /* Determine whether R has a valid type and can be
12433 completed later. If R is invalid, then its type
12434 is replaced by error_mark_node. */
12435 tree rtype = TREE_TYPE (r);
12436 if (can_complete_type_without_circularity (rtype))
12437 complete_type (rtype);
12439 if (!complete_or_array_type_p (rtype))
12441 /* If R's type couldn't be completed and
12442 it isn't a flexible array member (whose
12443 type is incomplete by definition) give
12444 an error. */
12445 cxx_incomplete_type_error (r, rtype);
12446 TREE_TYPE (r) = error_mark_node;
12448 else if (TREE_CODE (rtype) == ARRAY_TYPE
12449 && TYPE_DOMAIN (rtype) == NULL_TREE
12450 && (TREE_CODE (type) == UNION_TYPE
12451 || TREE_CODE (type) == QUAL_UNION_TYPE))
12453 error ("flexible array member %qD in union", r);
12454 TREE_TYPE (r) = error_mark_node;
12456 else if (!verify_type_context (input_location,
12457 TCTX_FIELD, rtype))
12458 TREE_TYPE (r) = error_mark_node;
12461 /* If it is a TYPE_DECL for a class-scoped
12462 ENUMERAL_TYPE, such a thing will already have
12463 been added to the field list by tsubst_enum
12464 in finish_member_declaration case above. */
12465 if (!(TREE_CODE (r) == TYPE_DECL
12466 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12467 && DECL_ARTIFICIAL (r)))
12469 set_current_access_from_decl (r);
12470 finish_member_declaration (r);
12476 else
12478 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12479 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12481 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12483 tree friend_type = t;
12484 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12486 /* template <class T> friend class C; */
12487 friend_type = tsubst_friend_class (friend_type, args);
12489 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12491 /* template <class T> friend class C::D; */
12492 friend_type = tsubst (friend_type, args,
12493 tf_warning_or_error, NULL_TREE);
12494 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12495 friend_type = TREE_TYPE (friend_type);
12497 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12498 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12500 /* This could be either
12502 friend class T::C;
12504 when dependent_type_p is false or
12506 template <class U> friend class T::C;
12508 otherwise. */
12509 /* Bump processing_template_decl in case this is something like
12510 template <class T> friend struct A<T>::B. */
12511 ++processing_template_decl;
12512 friend_type = tsubst (friend_type, args,
12513 tf_warning_or_error, NULL_TREE);
12514 --processing_template_decl;
12516 else if (uses_template_parms (friend_type))
12517 /* friend class C<T>; */
12518 friend_type = tsubst (friend_type, args,
12519 tf_warning_or_error, NULL_TREE);
12521 /* Otherwise it's
12523 friend class C;
12525 where C is already declared or
12527 friend class C<int>;
12529 We don't have to do anything in these cases. */
12531 if (friend_type != error_mark_node)
12532 make_friend_class (type, friend_type, /*complain=*/false);
12534 else
12536 /* Build new DECL_FRIENDLIST. */
12537 tree r;
12539 /* The file and line for this declaration, to
12540 assist in error message reporting. Since we
12541 called push_tinst_level above, we don't need to
12542 restore these. */
12543 input_location = DECL_SOURCE_LOCATION (t);
12545 if (TREE_CODE (t) == TEMPLATE_DECL)
12547 ++processing_template_decl;
12548 push_deferring_access_checks (dk_no_check);
12551 r = tsubst_friend_function (t, args);
12552 add_friend (type, r, /*complain=*/false);
12553 if (TREE_CODE (t) == TEMPLATE_DECL)
12555 pop_deferring_access_checks ();
12556 --processing_template_decl;
12562 if (fn_context)
12564 /* Restore these before substituting into the lambda capture
12565 initializers. */
12566 cp_unevaluated_operand = saved_unevaluated_operand;
12567 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12570 /* Set the file and line number information to whatever is given for
12571 the class itself. This puts error messages involving generated
12572 implicit functions at a predictable point, and the same point
12573 that would be used for non-template classes. */
12574 input_location = DECL_SOURCE_LOCATION (typedecl);
12576 unreverse_member_declarations (type);
12577 finish_struct_1 (type);
12578 TYPE_BEING_DEFINED (type) = 0;
12580 /* Remember if instantiating this class ran into errors, so we can avoid
12581 instantiating member functions in limit_bad_template_recursion. We set
12582 this flag even if the problem was in another instantiation triggered by
12583 this one, as that will likely also cause trouble for member functions. */
12584 if (errorcount + sorrycount > current_tinst_level->errors)
12585 CLASSTYPE_ERRONEOUS (type) = true;
12587 /* We don't instantiate default arguments for member functions. 14.7.1:
12589 The implicit instantiation of a class template specialization causes
12590 the implicit instantiation of the declarations, but not of the
12591 definitions or default arguments, of the class member functions,
12592 member classes, static data members and member templates.... */
12594 perform_instantiation_time_access_checks (pattern, args);
12595 perform_deferred_access_checks (tf_warning_or_error);
12597 /* Now that we've gone through all the members, instantiate those
12598 marked with attribute used. We must do this in the context of
12599 the class -- not the context we pushed from, as that might be
12600 inside a template and change the behaviour of mark_used. */
12601 for (tree x : used)
12602 mark_used (x);
12604 pop_nested_class ();
12605 maximum_field_alignment = saved_maximum_field_alignment;
12606 if (!fn_context)
12607 pop_from_top_level ();
12608 pop_tinst_level ();
12610 /* The vtable for a template class can be emitted in any translation
12611 unit in which the class is instantiated. When there is no key
12612 method, however, finish_struct_1 will already have added TYPE to
12613 the keyed_classes. */
12614 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12615 vec_safe_push (keyed_classes, type);
12617 return type;
12620 tree
12621 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12623 tree r;
12625 if (!t)
12626 r = t;
12627 else if (TYPE_P (t))
12628 r = tsubst (t, args, complain, in_decl);
12629 else
12631 if (!(complain & tf_warning))
12632 ++c_inhibit_evaluation_warnings;
12633 r = tsubst_expr (t, args, complain, in_decl);
12634 if (!(complain & tf_warning))
12635 --c_inhibit_evaluation_warnings;
12638 return r;
12641 /* Given a function parameter pack TMPL_PARM and some function parameters
12642 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12643 and set *SPEC_P to point at the next point in the list. */
12645 tree
12646 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12648 /* Collect all of the extra "packed" parameters into an
12649 argument pack. */
12650 tree argpack;
12651 tree spec_parm = *spec_p;
12652 int len;
12654 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12655 if (tmpl_parm
12656 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12657 break;
12659 spec_parm = *spec_p;
12660 if (len == 1 && DECL_PACK_P (spec_parm))
12662 /* The instantiation is still a parameter pack; don't wrap it in a
12663 NONTYPE_ARGUMENT_PACK. */
12664 argpack = spec_parm;
12665 spec_parm = DECL_CHAIN (spec_parm);
12667 else
12669 /* Fill in PARMVEC with all of the parameters. */
12670 tree parmvec = make_tree_vec (len);
12671 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12672 for (int i = 0; i < len; i++)
12674 tree elt = spec_parm;
12675 if (DECL_PACK_P (elt))
12676 elt = make_pack_expansion (elt);
12677 TREE_VEC_ELT (parmvec, i) = elt;
12678 spec_parm = DECL_CHAIN (spec_parm);
12681 /* Build the argument packs. */
12682 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12684 *spec_p = spec_parm;
12686 return argpack;
12689 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12690 NONTYPE_ARGUMENT_PACK. */
12692 static tree
12693 make_fnparm_pack (tree spec_parm)
12695 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12698 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12699 pack expansion with no extra args, 2 if it has extra args, or 0
12700 if it is not a pack expansion. */
12702 static int
12703 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12705 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12706 /* We're being called before this happens in tsubst_pack_expansion. */
12707 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12708 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12709 if (i >= TREE_VEC_LENGTH (vec))
12710 return 0;
12711 tree elt = TREE_VEC_ELT (vec, i);
12712 if (DECL_P (elt))
12713 /* A decl pack is itself an expansion. */
12714 elt = TREE_TYPE (elt);
12715 if (!PACK_EXPANSION_P (elt))
12716 return 0;
12717 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12718 return 2;
12719 return 1;
12723 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12725 static tree
12726 make_argument_pack_select (tree arg_pack, unsigned index)
12728 tree aps = make_node (ARGUMENT_PACK_SELECT);
12730 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12731 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12733 return aps;
12736 /* This is a subroutine of tsubst_pack_expansion.
12738 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12739 mechanism to store the (non complete list of) arguments of the
12740 substitution and return a non substituted pack expansion, in order
12741 to wait for when we have enough arguments to really perform the
12742 substitution. */
12744 static bool
12745 use_pack_expansion_extra_args_p (tree t,
12746 tree parm_packs,
12747 int arg_pack_len,
12748 bool has_empty_arg)
12750 if (has_empty_arg
12751 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12752 return true;
12754 /* If one pack has an expansion and another pack has a normal
12755 argument or if one pack has an empty argument and an another
12756 one hasn't then tsubst_pack_expansion cannot perform the
12757 substitution and need to fall back on the
12758 PACK_EXPANSION_EXTRA mechanism. */
12759 if (parm_packs == NULL_TREE)
12760 return false;
12761 else if (has_empty_arg)
12763 /* If all the actual packs are pack expansions, we can still
12764 subsitute directly. */
12765 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12767 tree a = TREE_VALUE (p);
12768 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12769 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12770 a = ARGUMENT_PACK_ARGS (a);
12771 if (TREE_VEC_LENGTH (a) == 1)
12772 a = TREE_VEC_ELT (a, 0);
12773 if (PACK_EXPANSION_P (a))
12774 continue;
12775 return true;
12777 return false;
12780 for (int i = 0 ; i < arg_pack_len; ++i)
12782 bool has_expansion_arg = false;
12783 bool has_non_expansion_arg = false;
12784 for (tree parm_pack = parm_packs;
12785 parm_pack;
12786 parm_pack = TREE_CHAIN (parm_pack))
12788 tree arg = TREE_VALUE (parm_pack);
12790 int exp = argument_pack_element_is_expansion_p (arg, i);
12791 if (exp == 2)
12792 /* We can't substitute a pack expansion with extra args into
12793 our pattern. */
12794 return true;
12795 else if (exp)
12796 has_expansion_arg = true;
12797 else
12798 has_non_expansion_arg = true;
12801 if (has_expansion_arg && has_non_expansion_arg)
12803 gcc_checking_assert (false);
12804 return true;
12807 return false;
12810 /* [temp.variadic]/6 says that:
12812 The instantiation of a pack expansion [...]
12813 produces a list E1,E2, ..., En, where N is the number of elements
12814 in the pack expansion parameters.
12816 This subroutine of tsubst_pack_expansion produces one of these Ei.
12818 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12819 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12820 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12821 INDEX is the index 'i' of the element Ei to produce. ARGS,
12822 COMPLAIN, and IN_DECL are the same parameters as for the
12823 tsubst_pack_expansion function.
12825 The function returns the resulting Ei upon successful completion,
12826 or error_mark_node.
12828 Note that this function possibly modifies the ARGS parameter, so
12829 it's the responsibility of the caller to restore it. */
12831 static tree
12832 gen_elem_of_pack_expansion_instantiation (tree pattern,
12833 tree parm_packs,
12834 unsigned index,
12835 tree args /* This parm gets
12836 modified. */,
12837 tsubst_flags_t complain,
12838 tree in_decl)
12840 tree t;
12841 bool ith_elem_is_expansion = false;
12843 /* For each parameter pack, change the substitution of the parameter
12844 pack to the ith argument in its argument pack, then expand the
12845 pattern. */
12846 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12848 tree parm = TREE_PURPOSE (pack);
12849 tree arg_pack = TREE_VALUE (pack);
12850 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12852 ith_elem_is_expansion |=
12853 argument_pack_element_is_expansion_p (arg_pack, index);
12855 /* Select the Ith argument from the pack. */
12856 if (TREE_CODE (parm) == PARM_DECL
12857 || VAR_P (parm)
12858 || TREE_CODE (parm) == FIELD_DECL)
12860 if (index == 0)
12862 aps = make_argument_pack_select (arg_pack, index);
12863 if (!mark_used (parm, complain) && !(complain & tf_error))
12864 return error_mark_node;
12865 register_local_specialization (aps, parm);
12867 else
12868 aps = retrieve_local_specialization (parm);
12870 else
12872 int idx, level;
12873 template_parm_level_and_index (parm, &level, &idx);
12875 if (index == 0)
12877 aps = make_argument_pack_select (arg_pack, index);
12878 /* Update the corresponding argument. */
12879 TMPL_ARG (args, level, idx) = aps;
12881 else
12882 /* Re-use the ARGUMENT_PACK_SELECT. */
12883 aps = TMPL_ARG (args, level, idx);
12885 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12888 /* Substitute into the PATTERN with the (possibly altered)
12889 arguments. */
12890 if (pattern == in_decl)
12891 /* Expanding a fixed parameter pack from
12892 coerce_template_parameter_pack. */
12893 t = tsubst_decl (pattern, args, complain);
12894 else if (pattern == error_mark_node)
12895 t = error_mark_node;
12896 else if (!TYPE_P (pattern))
12897 t = tsubst_expr (pattern, args, complain, in_decl);
12898 else
12900 t = tsubst (pattern, args, complain, in_decl);
12901 if (is_auto (t) && !ith_elem_is_expansion)
12902 /* When expanding the fake auto... pack expansion from add_capture, we
12903 need to mark that the expansion is no longer a pack. */
12904 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12907 /* If the Ith argument pack element is a pack expansion, then
12908 the Ith element resulting from the substituting is going to
12909 be a pack expansion as well. */
12910 if (ith_elem_is_expansion)
12911 t = make_pack_expansion (t, complain);
12913 return t;
12916 /* When the unexpanded parameter pack in a fold expression expands to an empty
12917 sequence, the value of the expression is as follows; the program is
12918 ill-formed if the operator is not listed in this table.
12920 && true
12921 || false
12922 , void() */
12924 tree
12925 expand_empty_fold (tree t, tsubst_flags_t complain)
12927 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12928 if (!FOLD_EXPR_MODIFY_P (t))
12929 switch (code)
12931 case TRUTH_ANDIF_EXPR:
12932 return boolean_true_node;
12933 case TRUTH_ORIF_EXPR:
12934 return boolean_false_node;
12935 case COMPOUND_EXPR:
12936 return void_node;
12937 default:
12938 break;
12941 if (complain & tf_error)
12942 error_at (location_of (t),
12943 "fold of empty expansion over %O", code);
12944 return error_mark_node;
12947 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12948 form an expression that combines the two terms using the
12949 operator of T. */
12951 static tree
12952 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12954 tree_code code = FOLD_EXPR_OP (t);
12956 tree lookups = templated_operator_saved_lookups (t);
12958 // Handle compound assignment operators.
12959 if (FOLD_EXPR_MODIFY_P (t))
12960 return build_x_modify_expr (input_location, left, code, right,
12961 lookups, complain);
12963 warning_sentinel s(warn_parentheses);
12964 switch (code)
12966 case COMPOUND_EXPR:
12967 return build_x_compound_expr (input_location, left, right,
12968 lookups, complain);
12969 default:
12970 return build_x_binary_op (input_location, code,
12971 left, TREE_CODE (left),
12972 right, TREE_CODE (right),
12973 lookups, /*overload=*/NULL,
12974 complain);
12978 /* Substitute ARGS into the pack of a fold expression T. */
12980 static inline tree
12981 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12983 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12986 /* Substitute ARGS into the pack of a fold expression T. */
12988 static inline tree
12989 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12991 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
12994 /* Expand a PACK of arguments into a grouped as left fold.
12995 Given a pack containing elements A0, A1, ..., An and an
12996 operator @, this builds the expression:
12998 ((A0 @ A1) @ A2) ... @ An
13000 Note that PACK must not be empty.
13002 The operator is defined by the original fold expression T. */
13004 static tree
13005 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
13007 tree left = TREE_VEC_ELT (pack, 0);
13008 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
13010 tree right = TREE_VEC_ELT (pack, i);
13011 left = fold_expression (t, left, right, complain);
13013 return left;
13016 /* Substitute into a unary left fold expression. */
13018 static tree
13019 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
13020 tree in_decl)
13022 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13023 if (pack == error_mark_node)
13024 return error_mark_node;
13025 if (PACK_EXPANSION_P (pack))
13027 tree r = copy_node (t);
13028 FOLD_EXPR_PACK (r) = pack;
13029 return r;
13031 if (TREE_VEC_LENGTH (pack) == 0)
13032 return expand_empty_fold (t, complain);
13033 else
13034 return expand_left_fold (t, pack, complain);
13037 /* Substitute into a binary left fold expression.
13039 Do ths by building a single (non-empty) vector of argumnts and
13040 building the expression from those elements. */
13042 static tree
13043 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
13044 tree in_decl)
13046 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13047 if (pack == error_mark_node)
13048 return error_mark_node;
13049 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13050 if (init == error_mark_node)
13051 return error_mark_node;
13053 if (PACK_EXPANSION_P (pack))
13055 tree r = copy_node (t);
13056 FOLD_EXPR_PACK (r) = pack;
13057 FOLD_EXPR_INIT (r) = init;
13058 return r;
13061 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13062 TREE_VEC_ELT (vec, 0) = init;
13063 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13064 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13066 return expand_left_fold (t, vec, complain);
13069 /* Expand a PACK of arguments into a grouped as right fold.
13070 Given a pack containing elementns A0, A1, ..., and an
13071 operator @, this builds the expression:
13073 A0@ ... (An-2 @ (An-1 @ An))
13075 Note that PACK must not be empty.
13077 The operator is defined by the original fold expression T. */
13079 tree
13080 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13082 // Build the expression.
13083 int n = TREE_VEC_LENGTH (pack);
13084 tree right = TREE_VEC_ELT (pack, n - 1);
13085 for (--n; n != 0; --n)
13087 tree left = TREE_VEC_ELT (pack, n - 1);
13088 right = fold_expression (t, left, right, complain);
13090 return right;
13093 /* Substitute into a unary right fold expression. */
13095 static tree
13096 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13097 tree in_decl)
13099 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13100 if (pack == error_mark_node)
13101 return error_mark_node;
13102 if (PACK_EXPANSION_P (pack))
13104 tree r = copy_node (t);
13105 FOLD_EXPR_PACK (r) = pack;
13106 return r;
13108 if (TREE_VEC_LENGTH (pack) == 0)
13109 return expand_empty_fold (t, complain);
13110 else
13111 return expand_right_fold (t, pack, complain);
13114 /* Substitute into a binary right fold expression.
13116 Do ths by building a single (non-empty) vector of arguments and
13117 building the expression from those elements. */
13119 static tree
13120 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13121 tree in_decl)
13123 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13124 if (pack == error_mark_node)
13125 return error_mark_node;
13126 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13127 if (init == error_mark_node)
13128 return error_mark_node;
13130 if (PACK_EXPANSION_P (pack))
13132 tree r = copy_node (t);
13133 FOLD_EXPR_PACK (r) = pack;
13134 FOLD_EXPR_INIT (r) = init;
13135 return r;
13138 int n = TREE_VEC_LENGTH (pack);
13139 tree vec = make_tree_vec (n + 1);
13140 for (int i = 0; i < n; ++i)
13141 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13142 TREE_VEC_ELT (vec, n) = init;
13144 return expand_right_fold (t, vec, complain);
13147 /* Walk through the pattern of a pack expansion, adding everything in
13148 local_specializations to a list. */
13150 class el_data
13152 public:
13153 /* Set of variables declared within the pattern. */
13154 hash_set<tree> internal;
13155 /* Set of AST nodes that have been visited by the traversal. */
13156 hash_set<tree> visited;
13157 /* List of local_specializations used within the pattern. */
13158 tree extra;
13159 tsubst_flags_t complain;
13160 /* True iff we don't want to walk into unevaluated contexts. */
13161 bool skip_unevaluated_operands = false;
13162 /* The unevaluated contexts that we avoided walking. */
13163 auto_vec<tree> skipped_trees;
13165 el_data (tsubst_flags_t c)
13166 : extra (NULL_TREE), complain (c) {}
13168 static tree
13169 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13171 el_data &data = *reinterpret_cast<el_data*>(data_);
13172 tree *extra = &data.extra;
13173 tsubst_flags_t complain = data.complain;
13175 if (data.skip_unevaluated_operands
13176 && unevaluated_p (TREE_CODE (*tp)))
13178 data.skipped_trees.safe_push (*tp);
13179 *walk_subtrees = 0;
13180 return NULL_TREE;
13183 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13184 /* Remember local typedefs (85214). */
13185 tp = &TYPE_NAME (*tp);
13187 if (TREE_CODE (*tp) == DECL_EXPR)
13189 tree decl = DECL_EXPR_DECL (*tp);
13190 data.internal.add (decl);
13191 if (VAR_P (decl)
13192 && DECL_DECOMPOSITION_P (decl)
13193 && TREE_TYPE (decl) != error_mark_node)
13195 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13196 for (tree decl2 = DECL_CHAIN (decl);
13197 decl2
13198 && VAR_P (decl2)
13199 && DECL_DECOMPOSITION_P (decl2)
13200 && DECL_NAME (decl2)
13201 && TREE_TYPE (decl2) != error_mark_node;
13202 decl2 = DECL_CHAIN (decl2))
13204 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13205 data.internal.add (decl2);
13209 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13211 /* Since we defer implicit capture, look in the parms and body. */
13212 tree fn = lambda_function (*tp);
13213 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13214 &data.visited);
13215 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13216 &data.visited);
13218 else if (tree spec = retrieve_local_specialization (*tp))
13220 if (data.internal.contains (*tp))
13221 /* Don't mess with variables declared within the pattern. */
13222 return NULL_TREE;
13223 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13225 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13226 tree args = ARGUMENT_PACK_ARGS (spec);
13227 if (TREE_VEC_LENGTH (args) == 1)
13229 tree elt = TREE_VEC_ELT (args, 0);
13230 if (PACK_EXPANSION_P (elt))
13231 elt = PACK_EXPANSION_PATTERN (elt);
13232 if (DECL_PACK_P (elt))
13233 spec = elt;
13235 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13237 /* Handle lambda capture here, since we aren't doing any
13238 substitution now, and so tsubst_copy won't call
13239 process_outer_var_ref. */
13240 tree args = ARGUMENT_PACK_ARGS (spec);
13241 int len = TREE_VEC_LENGTH (args);
13242 for (int i = 0; i < len; ++i)
13244 tree arg = TREE_VEC_ELT (args, i);
13245 tree carg = arg;
13246 if (outer_automatic_var_p (arg))
13247 carg = process_outer_var_ref (arg, complain);
13248 if (carg != arg)
13250 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13251 proxies. */
13252 if (i == 0)
13254 spec = copy_node (spec);
13255 args = copy_node (args);
13256 ARGUMENT_PACK_ARGS (spec) = args;
13257 register_local_specialization (spec, *tp);
13259 TREE_VEC_ELT (args, i) = carg;
13264 if (outer_automatic_var_p (spec))
13265 spec = process_outer_var_ref (spec, complain);
13266 *extra = tree_cons (*tp, spec, *extra);
13268 return NULL_TREE;
13270 static tree
13271 extract_local_specs (tree pattern, tsubst_flags_t complain)
13273 el_data data (complain);
13274 /* Walk the pattern twice, ignoring unevaluated operands the first time
13275 around, so that if a local specialization appears in both an evaluated
13276 and unevaluated context we prefer to process it in the evaluated context
13277 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13278 context). */
13279 data.skip_unevaluated_operands = true;
13280 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13281 /* Now walk the unevaluated contexts we skipped the first time around. */
13282 data.skip_unevaluated_operands = false;
13283 for (tree t : data.skipped_trees)
13285 data.visited.remove (t);
13286 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13288 return data.extra;
13291 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13292 for use in PACK_EXPANSION_EXTRA_ARGS. */
13294 tree
13295 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13297 /* Make a copy of the extra arguments so that they won't get changed
13298 out from under us. */
13299 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13300 if (local_specializations)
13301 if (tree locals = extract_local_specs (pattern, complain))
13302 extra = tree_cons (NULL_TREE, extra, locals);
13303 return extra;
13306 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13307 normal template args to ARGS. */
13309 tree
13310 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13312 if (extra && TREE_CODE (extra) == TREE_LIST)
13314 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13316 /* The partial instantiation involved local declarations collected in
13317 extract_local_specs; map from the general template to our local
13318 context. */
13319 tree gen = TREE_PURPOSE (elt);
13320 tree inst = TREE_VALUE (elt);
13321 if (DECL_P (inst))
13322 if (tree local = retrieve_local_specialization (inst))
13323 inst = local;
13324 /* else inst is already a full instantiation of the pack. */
13325 register_local_specialization (inst, gen);
13327 gcc_assert (!TREE_PURPOSE (extra));
13328 extra = TREE_VALUE (extra);
13330 if (uses_template_parms (extra))
13332 /* This can happen after dependent substitution into a
13333 requires-expr or a lambda that uses constexpr if. */
13334 extra = tsubst_template_args (extra, args, complain, in_decl);
13335 args = add_outermost_template_args (args, extra);
13337 else
13338 args = add_to_template_args (extra, args);
13339 return args;
13342 /* Substitute ARGS into T, which is an pack expansion
13343 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13344 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13345 (if only a partial substitution could be performed) or
13346 ERROR_MARK_NODE if there was an error. */
13347 tree
13348 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13349 tree in_decl)
13351 tree pattern;
13352 tree pack, packs = NULL_TREE;
13353 bool unsubstituted_packs = false;
13354 int i, len = -1;
13355 tree result;
13356 bool need_local_specializations = false;
13357 int levels;
13359 gcc_assert (PACK_EXPANSION_P (t));
13360 pattern = PACK_EXPANSION_PATTERN (t);
13362 /* Add in any args remembered from an earlier partial instantiation. */
13363 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13365 levels = TMPL_ARGS_DEPTH (args);
13367 /* Determine the argument packs that will instantiate the parameter
13368 packs used in the expansion expression. While we're at it,
13369 compute the number of arguments to be expanded and make sure it
13370 is consistent. */
13371 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13372 pack = TREE_CHAIN (pack))
13374 tree parm_pack = TREE_VALUE (pack);
13375 tree arg_pack = NULL_TREE;
13376 tree orig_arg = NULL_TREE;
13377 int level = 0;
13379 if (TREE_CODE (parm_pack) == BASES)
13381 gcc_assert (parm_pack == pattern);
13382 if (BASES_DIRECT (parm_pack))
13383 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13384 args, complain,
13385 in_decl),
13386 complain);
13387 else
13388 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13389 args, complain, in_decl),
13390 complain);
13392 else if (builtin_pack_call_p (parm_pack))
13394 if (parm_pack != pattern)
13396 if (complain & tf_error)
13397 sorry ("%qE is not the entire pattern of the pack expansion",
13398 parm_pack);
13399 return error_mark_node;
13401 return expand_builtin_pack_call (parm_pack, args,
13402 complain, in_decl);
13404 else if (TREE_CODE (parm_pack) == PARM_DECL)
13406 /* We know we have correct local_specializations if this
13407 expansion is at function scope, or if we're dealing with a
13408 local parameter in a requires expression; for the latter,
13409 tsubst_requires_expr set it up appropriately. */
13410 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13411 arg_pack = retrieve_local_specialization (parm_pack);
13412 else
13413 /* We can't rely on local_specializations for a parameter
13414 name used later in a function declaration (such as in a
13415 late-specified return type). Even if it exists, it might
13416 have the wrong value for a recursive call. */
13417 need_local_specializations = true;
13419 if (!arg_pack)
13421 /* This parameter pack was used in an unevaluated context. Just
13422 make a dummy decl, since it's only used for its type. */
13423 ++cp_unevaluated_operand;
13424 arg_pack = tsubst_decl (parm_pack, args, complain);
13425 --cp_unevaluated_operand;
13426 if (arg_pack && DECL_PACK_P (arg_pack))
13427 /* Partial instantiation of the parm_pack, we can't build
13428 up an argument pack yet. */
13429 arg_pack = NULL_TREE;
13430 else
13431 arg_pack = make_fnparm_pack (arg_pack);
13433 else if (DECL_PACK_P (arg_pack))
13434 /* This argument pack isn't fully instantiated yet. */
13435 arg_pack = NULL_TREE;
13437 else if (is_capture_proxy (parm_pack))
13439 arg_pack = retrieve_local_specialization (parm_pack);
13440 if (DECL_PACK_P (arg_pack))
13441 arg_pack = NULL_TREE;
13443 else
13445 int idx;
13446 template_parm_level_and_index (parm_pack, &level, &idx);
13447 if (level <= levels)
13448 arg_pack = TMPL_ARG (args, level, idx);
13450 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13451 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13452 arg_pack = NULL_TREE;
13455 orig_arg = arg_pack;
13456 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13457 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13459 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13460 /* This can only happen if we forget to expand an argument
13461 pack somewhere else. Just return an error, silently. */
13463 result = make_tree_vec (1);
13464 TREE_VEC_ELT (result, 0) = error_mark_node;
13465 return result;
13468 if (arg_pack)
13470 int my_len =
13471 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13473 /* Don't bother trying to do a partial substitution with
13474 incomplete packs; we'll try again after deduction. */
13475 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13476 return t;
13478 if (len < 0)
13479 len = my_len;
13480 else if (len != my_len)
13482 if (!(complain & tf_error))
13483 /* Fail quietly. */;
13484 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13485 error ("mismatched argument pack lengths while expanding %qT",
13486 pattern);
13487 else
13488 error ("mismatched argument pack lengths while expanding %qE",
13489 pattern);
13490 return error_mark_node;
13493 /* Keep track of the parameter packs and their corresponding
13494 argument packs. */
13495 packs = tree_cons (parm_pack, arg_pack, packs);
13496 TREE_TYPE (packs) = orig_arg;
13498 else
13500 /* We can't substitute for this parameter pack. We use a flag as
13501 well as the missing_level counter because function parameter
13502 packs don't have a level. */
13503 gcc_assert (processing_template_decl || is_auto (parm_pack));
13504 unsubstituted_packs = true;
13508 /* If the expansion is just T..., return the matching argument pack, unless
13509 we need to call convert_from_reference on all the elements. This is an
13510 important optimization; see c++/68422. */
13511 if (!unsubstituted_packs
13512 && TREE_PURPOSE (packs) == pattern)
13514 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13516 /* If the argument pack is a single pack expansion, pull it out. */
13517 if (TREE_VEC_LENGTH (args) == 1
13518 && pack_expansion_args_count (args))
13519 return TREE_VEC_ELT (args, 0);
13521 /* Types need no adjustment, nor does sizeof..., and if we still have
13522 some pack expansion args we won't do anything yet. */
13523 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13524 || PACK_EXPANSION_SIZEOF_P (t)
13525 || pack_expansion_args_count (args))
13526 return args;
13527 /* Also optimize expression pack expansions if we can tell that the
13528 elements won't have reference type. */
13529 tree type = TREE_TYPE (pattern);
13530 if (type && !TYPE_REF_P (type)
13531 && !PACK_EXPANSION_P (type)
13532 && !WILDCARD_TYPE_P (type))
13533 return args;
13534 /* Otherwise use the normal path so we get convert_from_reference. */
13537 /* We cannot expand this expansion expression, because we don't have
13538 all of the argument packs we need. */
13539 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13541 /* We got some full packs, but we can't substitute them in until we
13542 have values for all the packs. So remember these until then. */
13544 t = make_pack_expansion (pattern, complain);
13545 PACK_EXPANSION_EXTRA_ARGS (t)
13546 = build_extra_args (pattern, args, complain);
13547 return t;
13550 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13551 type, so create our own local specializations map; the current map is
13552 either NULL or (in the case of recursive unification) might have
13553 bindings that we don't want to use or alter. */
13554 local_specialization_stack lss (need_local_specializations
13555 ? lss_blank : lss_nop);
13557 if (unsubstituted_packs)
13559 /* There were no real arguments, we're just replacing a parameter
13560 pack with another version of itself. Substitute into the
13561 pattern and return a PACK_EXPANSION_*. The caller will need to
13562 deal with that. */
13563 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13564 result = tsubst_expr (pattern, args, complain, in_decl);
13565 else
13566 result = tsubst (pattern, args, complain, in_decl);
13567 result = make_pack_expansion (result, complain);
13568 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13569 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13570 if (PACK_EXPANSION_AUTO_P (t))
13572 /* This is a fake auto... pack expansion created in add_capture with
13573 _PACKS that don't appear in the pattern. Copy one over. */
13574 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13575 pack = retrieve_local_specialization (TREE_VALUE (packs));
13576 gcc_checking_assert (DECL_PACK_P (pack));
13577 PACK_EXPANSION_PARAMETER_PACKS (result)
13578 = build_tree_list (NULL_TREE, pack);
13579 PACK_EXPANSION_AUTO_P (result) = true;
13581 return result;
13584 gcc_assert (len >= 0);
13586 /* For each argument in each argument pack, substitute into the
13587 pattern. */
13588 result = make_tree_vec (len);
13589 tree elem_args = copy_template_args (args);
13590 for (i = 0; i < len; ++i)
13592 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13594 elem_args, complain,
13595 in_decl);
13596 TREE_VEC_ELT (result, i) = t;
13597 if (t == error_mark_node)
13599 result = error_mark_node;
13600 break;
13604 /* Update ARGS to restore the substitution from parameter packs to
13605 their argument packs. */
13606 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13608 tree parm = TREE_PURPOSE (pack);
13610 if (TREE_CODE (parm) == PARM_DECL
13611 || VAR_P (parm)
13612 || TREE_CODE (parm) == FIELD_DECL)
13613 register_local_specialization (TREE_TYPE (pack), parm);
13614 else
13616 int idx, level;
13618 if (TREE_VALUE (pack) == NULL_TREE)
13619 continue;
13621 template_parm_level_and_index (parm, &level, &idx);
13623 /* Update the corresponding argument. */
13624 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13625 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13626 TREE_TYPE (pack);
13627 else
13628 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13632 /* If the dependent pack arguments were such that we end up with only a
13633 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13634 if (len == 1 && TREE_CODE (result) == TREE_VEC
13635 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13636 return TREE_VEC_ELT (result, 0);
13638 return result;
13641 /* Make an argument pack out of the TREE_VEC VEC. */
13643 static tree
13644 make_argument_pack (tree vec)
13646 tree pack;
13648 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13649 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13650 else
13652 pack = make_node (NONTYPE_ARGUMENT_PACK);
13653 TREE_CONSTANT (pack) = 1;
13655 ARGUMENT_PACK_ARGS (pack) = vec;
13656 return pack;
13659 /* Return an exact copy of template args T that can be modified
13660 independently. */
13662 static tree
13663 copy_template_args (tree t)
13665 if (t == error_mark_node)
13666 return t;
13668 int len = TREE_VEC_LENGTH (t);
13669 tree new_vec = make_tree_vec (len);
13671 for (int i = 0; i < len; ++i)
13673 tree elt = TREE_VEC_ELT (t, i);
13674 if (elt && TREE_CODE (elt) == TREE_VEC)
13675 elt = copy_template_args (elt);
13676 TREE_VEC_ELT (new_vec, i) = elt;
13679 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13680 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13682 return new_vec;
13685 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13687 tree
13688 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13689 tree in_decl)
13691 /* This flag is used only during deduction, and we don't expect to
13692 substitute such ARGUMENT_PACKs. */
13693 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13695 /* Substitute into each of the arguments. */
13696 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13697 args, complain, in_decl);
13698 if (pack_args == error_mark_node)
13699 return error_mark_node;
13701 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13702 return orig_arg;
13704 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13705 template parameter, we might be able to avoid allocating a new
13706 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13707 if the substituted result is identical to it. */
13708 if (tree parm = template_arg_to_parm (orig_arg))
13710 int level, index;
13711 template_parm_level_and_index (parm, &level, &index);
13712 if (TMPL_ARGS_DEPTH (args) >= level)
13713 if (tree arg = TMPL_ARG (args, level, index))
13714 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13715 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13717 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13718 return arg;
13722 tree new_arg;
13723 if (TYPE_P (orig_arg))
13725 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13726 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13728 else
13730 new_arg = make_node (TREE_CODE (orig_arg));
13731 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13733 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13734 return new_arg;
13737 /* Substitute ARGS into the vector or list of template arguments T. */
13739 tree
13740 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13742 if (t == error_mark_node)
13743 return error_mark_node;
13745 /* In "sizeof(X<I>)" we need to evaluate "I". */
13746 cp_evaluated ev;
13748 const int len = TREE_VEC_LENGTH (t);
13749 tree *elts = XALLOCAVEC (tree, len);
13750 int expanded_len_adjust = 0;
13752 /* True iff the substituted result is identical to T. */
13753 bool const_subst_p = true;
13755 for (int i = 0; i < len; i++)
13757 tree orig_arg = TREE_VEC_ELT (t, i);
13758 tree new_arg;
13760 if (!orig_arg)
13761 new_arg = NULL_TREE;
13762 else if (TREE_CODE (orig_arg) == TREE_VEC)
13763 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13764 else if (PACK_EXPANSION_P (orig_arg))
13766 /* Substitute into an expansion expression. */
13767 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13769 if (TREE_CODE (new_arg) == TREE_VEC)
13770 /* Add to the expanded length adjustment the number of
13771 expanded arguments. We subtract one from this
13772 measurement, because the argument pack expression
13773 itself is already counted as 1 in
13774 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13775 the argument pack is empty. */
13776 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13778 else if (ARGUMENT_PACK_P (orig_arg))
13779 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13780 else
13781 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13783 if (new_arg == error_mark_node)
13784 return error_mark_node;
13786 elts[i] = new_arg;
13787 if (new_arg != orig_arg)
13788 const_subst_p = false;
13791 if (const_subst_p)
13792 return t;
13794 tree maybe_reuse = NULL_TREE;
13796 /* If ARGS and T are both multi-level, the substituted result may be
13797 identical to ARGS. */
13798 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13799 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13800 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13801 maybe_reuse = args;
13802 /* If T appears to be a vector of generic template arguments, the
13803 substituted result may be identical to the corresponding level
13804 from ARGS. */
13805 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13807 int level, index;
13808 template_parm_level_and_index (parm, &level, &index);
13809 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13810 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13813 /* If the substituted result is identical to MAYBE_REUSE, return
13814 it and avoid allocating a new TREE_VEC, as an optimization. */
13815 if (maybe_reuse != NULL_TREE
13816 && TREE_VEC_LENGTH (maybe_reuse) == len
13817 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13818 return maybe_reuse;
13820 /* If T consists of only a pack expansion for which substitution yielded
13821 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13822 of effectively making a copy. */
13823 if (len == 1
13824 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13825 && TREE_CODE (elts[0]) == TREE_VEC)
13826 return elts[0];
13828 /* Make space for the expanded arguments coming from template
13829 argument packs. */
13830 tree r = make_tree_vec (len + expanded_len_adjust);
13831 /* T can contain TREE_VECs. That happens if T contains the
13832 arguments for a member template.
13833 In that case each TREE_VEC in T represents a level of template
13834 arguments, and T won't carry any non defaulted argument count.
13835 It will rather be the nested TREE_VECs that will carry one.
13836 In other words, T carries a non defaulted argument count only
13837 if it doesn't contain any nested TREE_VEC. */
13838 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13840 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13841 count += expanded_len_adjust;
13842 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13845 int out = 0;
13846 for (int i = 0; i < len; i++)
13848 tree orig_arg = TREE_VEC_ELT (t, i);
13849 if (orig_arg
13850 && PACK_EXPANSION_P (orig_arg)
13851 && TREE_CODE (elts[i]) == TREE_VEC)
13853 /* Now expand the template argument pack "in place". */
13854 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13855 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13857 else
13859 TREE_VEC_ELT (r, out) = elts[i];
13860 out++;
13863 gcc_assert (out == TREE_VEC_LENGTH (r));
13865 return r;
13868 /* Substitute ARGS into one level PARMS of template parameters. */
13870 static tree
13871 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13873 if (parms == error_mark_node)
13874 return error_mark_node;
13876 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13878 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13880 tree tuple = TREE_VEC_ELT (parms, i);
13882 if (tuple == error_mark_node)
13883 continue;
13885 TREE_VEC_ELT (new_vec, i) =
13886 tsubst_template_parm (tuple, args, complain);
13889 return new_vec;
13892 /* Return the result of substituting ARGS into the template parameters
13893 given by PARMS. If there are m levels of ARGS and m + n levels of
13894 PARMS, then the result will contain n levels of PARMS. For
13895 example, if PARMS is `template <class T> template <class U>
13896 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13897 result will be `template <int*, double, class V>'. */
13899 static tree
13900 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13902 tree r = NULL_TREE;
13903 tree* new_parms;
13905 /* When substituting into a template, we must set
13906 PROCESSING_TEMPLATE_DECL as the template parameters may be
13907 dependent if they are based on one-another, and the dependency
13908 predicates are short-circuit outside of templates. */
13909 ++processing_template_decl;
13911 for (new_parms = &r;
13912 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13913 new_parms = &(TREE_CHAIN (*new_parms)),
13914 parms = TREE_CHAIN (parms))
13916 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13917 args, complain);
13918 *new_parms =
13919 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13920 - TMPL_ARGS_DEPTH (args)),
13921 new_vec, NULL_TREE);
13922 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13923 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13926 --processing_template_decl;
13928 return r;
13931 /* Return the result of substituting ARGS into one template parameter
13932 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13933 parameter and which TREE_PURPOSE is the default argument of the
13934 template parameter. */
13936 static tree
13937 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13939 tree default_value, parm_decl;
13941 if (args == NULL_TREE
13942 || t == NULL_TREE
13943 || t == error_mark_node)
13944 return t;
13946 gcc_assert (TREE_CODE (t) == TREE_LIST);
13948 default_value = TREE_PURPOSE (t);
13949 parm_decl = TREE_VALUE (t);
13951 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13952 if (TREE_CODE (parm_decl) == PARM_DECL
13953 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13954 parm_decl = error_mark_node;
13955 default_value = tsubst_template_arg (default_value, args,
13956 complain, NULL_TREE);
13958 tree r = build_tree_list (default_value, parm_decl);
13959 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13960 return r;
13963 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13964 parameter in PARMS for sake of declaration matching. */
13966 static void
13967 tsubst_each_template_parm_constraints (tree parms, tree args,
13968 tsubst_flags_t complain)
13970 ++processing_template_decl;
13971 for (; parms; parms = TREE_CHAIN (parms))
13973 tree level = TREE_VALUE (parms);
13974 for (tree parm : tree_vec_range (level))
13975 TEMPLATE_PARM_CONSTRAINTS (parm)
13976 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13977 complain, NULL_TREE);
13979 --processing_template_decl;
13982 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13983 type T. If T is not an aggregate or enumeration type, it is
13984 handled as if by tsubst. IN_DECL is as for tsubst. If
13985 ENTERING_SCOPE is nonzero, T is the context for a template which
13986 we are presently tsubst'ing. Return the substituted value. */
13988 static tree
13989 tsubst_aggr_type (tree t,
13990 tree args,
13991 tsubst_flags_t complain,
13992 tree in_decl,
13993 int entering_scope)
13995 if (t == NULL_TREE)
13996 return NULL_TREE;
13998 /* Handle typedefs via tsubst so that they get consistently reused. */
13999 if (typedef_variant_p (t))
14001 t = tsubst (t, args, complain, in_decl);
14002 if (t == error_mark_node)
14003 return error_mark_node;
14005 /* The effect of entering_scope is that for a dependent specialization
14006 A<T>, lookup_template_class prefers to return A's primary template
14007 type instead of the implicit instantiation. So when entering_scope,
14008 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
14009 taking advantage of the fact that lookup_template_class links the two
14010 types by setting TYPE_CANONICAL of the latter to the former. */
14011 if (entering_scope
14012 && CLASS_TYPE_P (t)
14013 && dependent_type_p (t)
14014 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
14015 t = TYPE_CANONICAL (t);
14017 return t;
14020 switch (TREE_CODE (t))
14022 case RECORD_TYPE:
14023 case ENUMERAL_TYPE:
14024 case UNION_TYPE:
14025 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
14027 default:
14028 return tsubst (t, args, complain, in_decl);
14032 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
14033 and ENUMERAL_TYPE cases of tsubst. */
14035 static tree
14036 tsubst_aggr_type_1 (tree t,
14037 tree args,
14038 tsubst_flags_t complain,
14039 tree in_decl,
14040 int entering_scope)
14042 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
14044 complain &= ~tf_qualifying_scope;
14046 /* Figure out what arguments are appropriate for the
14047 type we are trying to find. For example, given:
14049 template <class T> struct S;
14050 template <class T, class U> void f(T, U) { S<U> su; }
14052 and supposing that we are instantiating f<int, double>,
14053 then our ARGS will be {int, double}, but, when looking up
14054 S we only want {double}. */
14055 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14056 complain, in_decl);
14057 if (argvec == error_mark_node)
14058 return error_mark_node;
14060 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14061 entering_scope, complain);
14062 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14064 else
14065 /* This is not a template type, so there's nothing to do. */
14066 return t;
14069 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14070 indexed in reverse order of the parameters. */
14072 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14074 /* Return a reference to the vec* of defarg insts for FN. */
14076 static vec<tree,va_gc> *&
14077 defarg_insts_for (tree fn)
14079 if (!defarg_inst)
14080 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14081 tree_vec_map in = { { fn }, nullptr };
14082 tree_vec_map **slot
14083 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14084 if (!*slot)
14086 *slot = ggc_alloc<tree_vec_map> ();
14087 **slot = in;
14089 return (*slot)->to;
14092 /* Substitute into the default argument ARG (a default argument for
14093 FN), which has the indicated TYPE. */
14095 tree
14096 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14097 tsubst_flags_t complain)
14099 int errs = errorcount + sorrycount;
14101 /* This can happen in invalid code. */
14102 if (TREE_CODE (arg) == DEFERRED_PARSE)
14103 return arg;
14105 /* Shortcut {}. */
14106 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14107 && CONSTRUCTOR_NELTS (arg) == 0)
14108 return arg;
14110 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14111 parm = chain_index (parmnum, parm);
14112 tree parmtype = TREE_TYPE (parm);
14113 if (DECL_BY_REFERENCE (parm))
14114 parmtype = TREE_TYPE (parmtype);
14115 if (parmtype == error_mark_node)
14116 return error_mark_node;
14118 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14120 /* Remember the location of the pointer to the vec rather than the location
14121 of the particular element, in case the vec grows in tsubst_expr. */
14122 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14123 /* Index in reverse order to avoid allocating space for initial parameters
14124 that don't have default arguments. */
14125 unsigned ridx = list_length (parm);
14126 if (vec_safe_length (defs) < ridx)
14127 vec_safe_grow_cleared (defs, ridx);
14128 else if (tree inst = (*defs)[ridx - 1])
14129 return inst;
14131 /* This default argument came from a template. Instantiate the
14132 default argument here, not in tsubst. In the case of
14133 something like:
14135 template <class T>
14136 struct S {
14137 static T t();
14138 void f(T = t());
14141 we must be careful to do name lookup in the scope of S<T>,
14142 rather than in the current class. */
14143 push_to_top_level ();
14144 push_access_scope (fn);
14145 push_deferring_access_checks (dk_no_deferred);
14146 /* So in_immediate_context knows this is a default argument. */
14147 begin_scope (sk_function_parms, fn);
14148 start_lambda_scope (parm);
14150 /* The default argument expression may cause implicitly defined
14151 member functions to be synthesized, which will result in garbage
14152 collection. We must treat this situation as if we were within
14153 the body of function so as to avoid collecting live data on the
14154 stack. */
14155 ++function_depth;
14156 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14157 --function_depth;
14159 finish_lambda_scope ();
14161 /* Make sure the default argument is reasonable. */
14162 arg = check_default_argument (type, arg, complain);
14164 if (errorcount+sorrycount > errs
14165 && (complain & tf_warning_or_error))
14166 inform (input_location,
14167 " when instantiating default argument for call to %qD", fn);
14169 leave_scope ();
14170 pop_deferring_access_checks ();
14171 pop_access_scope (fn);
14172 pop_from_top_level ();
14174 if (arg != error_mark_node && !cp_unevaluated_operand)
14175 (*defs)[ridx - 1] = arg;
14177 return arg;
14180 /* Substitute into all the default arguments for FN. */
14182 static void
14183 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14185 tree arg;
14186 tree tmpl_args;
14188 tmpl_args = DECL_TI_ARGS (fn);
14190 /* If this function is not yet instantiated, we certainly don't need
14191 its default arguments. */
14192 if (uses_template_parms (tmpl_args))
14193 return;
14194 /* Don't do this again for clones. */
14195 if (DECL_CLONED_FUNCTION_P (fn))
14196 return;
14198 int i = 0;
14199 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14200 arg;
14201 arg = TREE_CHAIN (arg), ++i)
14202 if (TREE_PURPOSE (arg))
14203 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14204 TREE_VALUE (arg),
14205 TREE_PURPOSE (arg),
14206 complain);
14209 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14210 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14212 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14214 void
14215 store_explicit_specifier (tree v, tree t)
14217 if (!explicit_specifier_map)
14218 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14219 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14220 explicit_specifier_map->put (v, t);
14223 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14225 tree
14226 lookup_explicit_specifier (tree v)
14228 return *explicit_specifier_map->get (v);
14231 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14232 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14233 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14234 identical to T. */
14236 static tree
14237 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14238 tree raises, tsubst_flags_t complain)
14240 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14242 tree new_type;
14243 if (TREE_CODE (t) == FUNCTION_TYPE)
14245 new_type = build_function_type (return_type, arg_types);
14246 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14248 else
14250 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14251 /* Don't pick up extra function qualifiers from the basetype. */
14252 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14253 if (! MAYBE_CLASS_TYPE_P (r))
14255 /* [temp.deduct]
14257 Type deduction may fail for any of the following
14258 reasons:
14260 -- Attempting to create "pointer to member of T" when T
14261 is not a class type. */
14262 if (complain & tf_error)
14263 error ("creating pointer to member function of non-class type %qT",
14265 return error_mark_node;
14268 new_type = build_method_type_directly (r, return_type,
14269 TREE_CHAIN (arg_types));
14271 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14273 cp_ref_qualifier rqual = type_memfn_rqual (t);
14274 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14275 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14278 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14279 each of its formal parameters. If there is a disagreement then rebuild
14280 DECL's function type according to its formal parameter types, as part of a
14281 resolution for Core issues 1001/1322. */
14283 static void
14284 maybe_rebuild_function_decl_type (tree decl)
14286 bool function_type_needs_rebuilding = false;
14287 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14289 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14290 while (parm_type_list && parm_type_list != void_list_node)
14292 tree parm_type = TREE_VALUE (parm_type_list);
14293 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14294 if (!same_type_p (parm_type, formal_parm_type_unqual))
14296 function_type_needs_rebuilding = true;
14297 break;
14300 parm_list = DECL_CHAIN (parm_list);
14301 parm_type_list = TREE_CHAIN (parm_type_list);
14305 if (!function_type_needs_rebuilding)
14306 return;
14308 const tree fntype = TREE_TYPE (decl);
14309 tree parm_list = DECL_ARGUMENTS (decl);
14310 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14311 tree new_parm_type_list = NULL_TREE;
14312 tree *q = &new_parm_type_list;
14313 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14315 *q = copy_node (old_parm_type_list);
14316 parm_list = DECL_CHAIN (parm_list);
14317 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14318 q = &TREE_CHAIN (*q);
14320 while (old_parm_type_list && old_parm_type_list != void_list_node)
14322 *q = copy_node (old_parm_type_list);
14323 tree *new_parm_type = &TREE_VALUE (*q);
14324 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14325 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14326 *new_parm_type = formal_parm_type_unqual;
14328 parm_list = DECL_CHAIN (parm_list);
14329 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14330 q = &TREE_CHAIN (*q);
14332 if (old_parm_type_list == void_list_node)
14333 *q = void_list_node;
14335 TREE_TYPE (decl)
14336 = rebuild_function_or_method_type (fntype,
14337 TREE_TYPE (fntype), new_parm_type_list,
14338 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14341 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14343 static tree
14344 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14345 tree lambda_fntype, bool use_spec_table = true)
14347 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14348 hashval_t hash = 0;
14349 tree in_decl = t;
14351 /* Nobody should be tsubst'ing into non-template functions. */
14352 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14353 || DECL_LOCAL_DECL_P (t));
14355 if (DECL_LOCAL_DECL_P (t))
14357 if (tree spec = retrieve_local_specialization (t))
14358 return spec;
14360 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14362 /* If T is not dependent, just return it. */
14363 if (!uses_template_parms (DECL_TI_ARGS (t))
14364 && !LAMBDA_FUNCTION_P (t))
14365 return t;
14367 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14368 if (non_templated_friend_p (t))
14369 goto friend_case;
14371 /* Calculate the most general template of which R is a
14372 specialization. */
14373 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14375 /* We're substituting a lambda function under tsubst_lambda_expr but not
14376 directly from it; find the matching function we're already inside.
14377 But don't do this if T is a generic lambda with a single level of
14378 template parms, as in that case we're doing a normal instantiation. */
14379 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14380 && (!generic_lambda_fn_p (t)
14381 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14382 return enclosing_instantiation_of (t);
14384 /* Calculate the complete set of arguments used to
14385 specialize R. */
14386 if (use_spec_table)
14388 argvec = tsubst_template_args (DECL_TI_ARGS
14389 (DECL_TEMPLATE_RESULT
14390 (DECL_TI_TEMPLATE (t))),
14391 args, complain, in_decl);
14392 if (argvec == error_mark_node)
14393 return error_mark_node;
14395 /* Check to see if we already have this specialization. */
14396 if (!lambda_fntype)
14398 hash = spec_hasher::hash (gen_tmpl, argvec);
14399 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14400 /* The spec for these args might be a partial instantiation of the
14401 template, but here what we want is the FUNCTION_DECL. */
14402 return STRIP_TEMPLATE (spec);
14405 else
14406 argvec = args;
14408 else
14410 /* This special case arises when we have something like this:
14412 template <class T> struct S {
14413 friend void f<int>(int, double);
14416 Here, the DECL_TI_TEMPLATE for the friend declaration
14417 will be an IDENTIFIER_NODE. We are being called from
14418 tsubst_friend_function, and we want only to create a
14419 new decl (R) with appropriate types so that we can call
14420 determine_specialization. */
14421 friend_case:
14422 gen_tmpl = NULL_TREE;
14423 argvec = NULL_TREE;
14426 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14427 : NULL_TREE);
14428 tree ctx = closure ? closure : DECL_CONTEXT (t);
14429 bool member = ctx && TYPE_P (ctx);
14431 /* If this is a static lambda, remove the 'this' pointer added in
14432 tsubst_lambda_expr now that we know the closure type. */
14433 if (lambda_fntype && DECL_STATIC_FUNCTION_P (t))
14434 lambda_fntype = static_fn_type (lambda_fntype);
14436 if (member && !closure)
14437 ctx = tsubst_aggr_type (ctx, args,
14438 complain, t, /*entering_scope=*/1);
14440 tree type = (lambda_fntype ? lambda_fntype
14441 : tsubst (TREE_TYPE (t), args,
14442 complain | tf_fndecl_type, in_decl));
14443 if (type == error_mark_node)
14444 return error_mark_node;
14446 /* If we hit excessive deduction depth, the type is bogus even if
14447 it isn't error_mark_node, so don't build a decl. */
14448 if (excessive_deduction_depth)
14449 return error_mark_node;
14451 /* We do NOT check for matching decls pushed separately at this
14452 point, as they may not represent instantiations of this
14453 template, and in any case are considered separate under the
14454 discrete model. */
14455 tree r = copy_decl (t);
14456 DECL_USE_TEMPLATE (r) = 0;
14457 TREE_TYPE (r) = type;
14458 /* Clear out the mangled name and RTL for the instantiation. */
14459 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14460 SET_DECL_RTL (r, NULL);
14461 /* Leave DECL_INITIAL set on deleted instantiations. */
14462 if (!DECL_DELETED_FN (r))
14463 DECL_INITIAL (r) = NULL_TREE;
14464 DECL_CONTEXT (r) = ctx;
14465 set_instantiating_module (r);
14467 /* Handle explicit(dependent-expr). */
14468 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14470 tree spec = lookup_explicit_specifier (t);
14471 spec = tsubst_copy_and_build (spec, args, complain, in_decl);
14472 spec = build_explicit_specifier (spec, complain);
14473 if (spec == error_mark_node)
14474 return error_mark_node;
14475 if (instantiation_dependent_expression_p (spec))
14476 store_explicit_specifier (r, spec);
14477 else
14479 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14480 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14484 /* OpenMP UDRs have the only argument a reference to the declared
14485 type. We want to diagnose if the declared type is a reference,
14486 which is invalid, but as references to references are usually
14487 quietly merged, diagnose it here. */
14488 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14490 tree argtype
14491 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14492 argtype = tsubst (argtype, args, complain, in_decl);
14493 if (TYPE_REF_P (argtype))
14494 error_at (DECL_SOURCE_LOCATION (t),
14495 "reference type %qT in "
14496 "%<#pragma omp declare reduction%>", argtype);
14497 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14498 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14499 argtype);
14502 if (member && DECL_CONV_FN_P (r))
14503 /* Type-conversion operator. Reconstruct the name, in
14504 case it's the name of one of the template's parameters. */
14505 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14507 tree parms = DECL_ARGUMENTS (t);
14508 if (closure && !DECL_STATIC_FUNCTION_P (t))
14509 parms = DECL_CHAIN (parms);
14510 parms = tsubst (parms, args, complain, t);
14511 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14512 DECL_CONTEXT (parm) = r;
14513 if (closure && !DECL_STATIC_FUNCTION_P (t))
14515 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14516 DECL_NAME (tparm) = closure_identifier;
14517 DECL_CHAIN (tparm) = parms;
14518 parms = tparm;
14520 DECL_ARGUMENTS (r) = parms;
14521 DECL_RESULT (r) = NULL_TREE;
14523 maybe_rebuild_function_decl_type (r);
14525 TREE_STATIC (r) = 0;
14526 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14527 DECL_EXTERNAL (r) = 1;
14528 /* If this is an instantiation of a function with internal
14529 linkage, we already know what object file linkage will be
14530 assigned to the instantiation. */
14531 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14532 DECL_DEFER_OUTPUT (r) = 0;
14533 DECL_CHAIN (r) = NULL_TREE;
14534 DECL_PENDING_INLINE_INFO (r) = 0;
14535 DECL_PENDING_INLINE_P (r) = 0;
14536 DECL_SAVED_TREE (r) = NULL_TREE;
14537 DECL_STRUCT_FUNCTION (r) = NULL;
14538 TREE_USED (r) = 0;
14539 /* We'll re-clone as appropriate in instantiate_template. */
14540 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14542 /* If we aren't complaining now, return on error before we register
14543 the specialization so that we'll complain eventually. */
14544 if ((complain & tf_error) == 0
14545 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14546 && !grok_op_properties (r, /*complain=*/false))
14547 return error_mark_node;
14549 /* Associate the constraints directly with the instantiation. We
14550 don't substitute through the constraints; that's only done when
14551 they are checked. */
14552 if (tree ci = get_constraints (t))
14553 set_constraints (r, ci);
14555 if (DECL_FRIEND_CONTEXT (t))
14556 SET_DECL_FRIEND_CONTEXT (r,
14557 tsubst (DECL_FRIEND_CONTEXT (t),
14558 args, complain, in_decl));
14560 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14561 args, complain, in_decl))
14562 return error_mark_node;
14564 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14565 this in the special friend case mentioned above where
14566 GEN_TMPL is NULL. */
14567 if (gen_tmpl && !closure)
14569 DECL_TEMPLATE_INFO (r)
14570 = build_template_info (gen_tmpl, argvec);
14571 SET_DECL_IMPLICIT_INSTANTIATION (r);
14573 if (use_spec_table)
14575 tree new_r
14576 = register_specialization (r, gen_tmpl, argvec, false, hash);
14577 if (new_r != r)
14578 /* We instantiated this while substituting into
14579 the type earlier (template/friend54.C). */
14580 return new_r;
14583 /* We're not supposed to instantiate default arguments
14584 until they are called, for a template. But, for a
14585 declaration like:
14587 template <class T> void f ()
14588 { extern void g(int i = T()); }
14590 we should do the substitution when the template is
14591 instantiated. We handle the member function case in
14592 instantiate_class_template since the default arguments
14593 might refer to other members of the class. */
14594 if (!member
14595 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14596 && !uses_template_parms (argvec))
14597 tsubst_default_arguments (r, complain);
14599 else if (DECL_LOCAL_DECL_P (r))
14601 if (!cp_unevaluated_operand)
14602 register_local_specialization (r, t);
14604 else
14605 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14607 /* Copy the list of befriending classes. */
14608 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14609 *friends;
14610 friends = &TREE_CHAIN (*friends))
14612 *friends = copy_node (*friends);
14613 TREE_VALUE (*friends)
14614 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14617 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14619 maybe_retrofit_in_chrg (r);
14620 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14621 return error_mark_node;
14622 /* If this is an instantiation of a member template, clone it.
14623 If it isn't, that'll be handled by
14624 clone_constructors_and_destructors. */
14625 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14626 clone_cdtor (r, /*update_methods=*/false);
14628 else if ((complain & tf_error) != 0
14629 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14630 && !grok_op_properties (r, /*complain=*/true))
14631 return error_mark_node;
14633 /* Possibly limit visibility based on template args. */
14634 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14635 if (DECL_VISIBILITY_SPECIFIED (t))
14637 DECL_VISIBILITY_SPECIFIED (r) = 0;
14638 DECL_ATTRIBUTES (r)
14639 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14641 determine_visibility (r);
14642 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14643 && !processing_template_decl)
14644 defaulted_late_check (r);
14646 if (flag_openmp)
14647 if (tree attr = lookup_attribute ("omp declare variant base",
14648 DECL_ATTRIBUTES (r)))
14649 omp_declare_variant_finalize (r, attr);
14651 return r;
14654 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14656 static tree
14657 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14658 tree lambda_fntype, tree lambda_tparms)
14660 /* We can get here when processing a member function template,
14661 member class template, or template template parameter. */
14662 tree decl = DECL_TEMPLATE_RESULT (t);
14663 tree in_decl = t;
14664 tree spec;
14665 tree tmpl_args;
14666 tree full_args;
14667 tree r;
14668 hashval_t hash = 0;
14670 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14672 /* Template template parameter is treated here. */
14673 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14674 if (new_type == error_mark_node)
14675 r = error_mark_node;
14676 /* If we get a real template back, return it. This can happen in
14677 the context of most_specialized_partial_spec. */
14678 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14679 r = new_type;
14680 else
14681 /* The new TEMPLATE_DECL was built in
14682 reduce_template_parm_level. */
14683 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14684 return r;
14687 if (!lambda_fntype)
14689 /* We might already have an instance of this template.
14690 The ARGS are for the surrounding class type, so the
14691 full args contain the tsubst'd args for the context,
14692 plus the innermost args from the template decl. */
14693 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14694 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14695 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14696 /* Because this is a template, the arguments will still be
14697 dependent, even after substitution. If
14698 PROCESSING_TEMPLATE_DECL is not set, the dependency
14699 predicates will short-circuit. */
14700 ++processing_template_decl;
14701 full_args = tsubst_template_args (tmpl_args, args,
14702 complain, in_decl);
14703 --processing_template_decl;
14704 if (full_args == error_mark_node)
14705 return error_mark_node;
14707 /* If this is a default template template argument,
14708 tsubst might not have changed anything. */
14709 if (full_args == tmpl_args)
14710 return t;
14712 hash = spec_hasher::hash (t, full_args);
14713 spec = retrieve_specialization (t, full_args, hash);
14714 if (spec != NULL_TREE)
14716 if (TYPE_P (spec))
14717 /* Type partial instantiations are stored as the type by
14718 lookup_template_class_1, not here as the template. */
14719 spec = CLASSTYPE_TI_TEMPLATE (spec);
14720 return spec;
14724 /* Make a new template decl. It will be similar to the
14725 original, but will record the current template arguments.
14726 We also create a new function declaration, which is just
14727 like the old one, but points to this new template, rather
14728 than the old one. */
14729 r = copy_decl (t);
14730 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14731 DECL_CHAIN (r) = NULL_TREE;
14733 // Build new template info linking to the original template decl.
14734 if (!lambda_fntype)
14736 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14737 SET_DECL_IMPLICIT_INSTANTIATION (r);
14739 else
14740 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14742 /* The template parameters for this new template are all the
14743 template parameters for the old template, except the
14744 outermost level of parameters. */
14745 auto tparm_guard = make_temp_override (current_template_parms);
14746 DECL_TEMPLATE_PARMS (r)
14747 = current_template_parms
14748 = (lambda_tparms
14749 ? lambda_tparms
14750 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14751 complain));
14753 bool class_p = false;
14754 tree inner = decl;
14755 ++processing_template_decl;
14756 if (TREE_CODE (inner) == FUNCTION_DECL)
14757 inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14758 else
14760 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14762 class_p = true;
14763 inner = TREE_TYPE (inner);
14765 if (class_p)
14766 inner = tsubst_aggr_type (inner, args, complain,
14767 in_decl, /*entering*/1);
14768 else
14769 inner = tsubst (inner, args, complain, in_decl);
14771 --processing_template_decl;
14772 if (inner == error_mark_node)
14773 return error_mark_node;
14775 if (class_p)
14777 /* For a partial specialization, we need to keep pointing to
14778 the primary template. */
14779 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14781 CLASSTYPE_TI_TEMPLATE (inner) = r;
14782 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14785 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14786 inner = TYPE_MAIN_DECL (inner);
14788 else if (lambda_fntype)
14790 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14791 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14793 else
14795 DECL_TI_TEMPLATE (inner) = r;
14796 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14799 DECL_TEMPLATE_RESULT (r) = inner;
14800 TREE_TYPE (r) = TREE_TYPE (inner);
14801 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14803 if (modules_p ())
14805 /* Propagate module information from the decl. */
14806 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14807 if (DECL_LANG_SPECIFIC (inner))
14808 /* If this is a constrained template, the above tsubst of
14809 inner can find the unconstrained template, which may have
14810 come from an import. This is ok, because we don't
14811 register this instantiation (see below). */
14812 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14813 || (TEMPLATE_PARMS_CONSTRAINTS
14814 (DECL_TEMPLATE_PARMS (t))));
14817 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14818 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14820 if (PRIMARY_TEMPLATE_P (t))
14821 DECL_PRIMARY_TEMPLATE (r) = r;
14823 if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14824 /* Record this non-type partial instantiation. */
14825 register_specialization (r, t,
14826 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14827 false, hash);
14829 return r;
14832 /* True if FN is the op() for a lambda in an uninstantiated template. */
14834 bool
14835 lambda_fn_in_template_p (tree fn)
14837 if (!fn || !LAMBDA_FUNCTION_P (fn))
14838 return false;
14839 tree closure = DECL_CONTEXT (fn);
14840 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14843 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14844 which the above is true. */
14846 bool
14847 regenerated_lambda_fn_p (tree fn)
14849 if (!fn || !LAMBDA_FUNCTION_P (fn))
14850 return false;
14851 tree closure = DECL_CONTEXT (fn);
14852 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14853 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14856 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14857 If T is not a regenerated LAMBDA_EXPR, return T. */
14859 tree
14860 most_general_lambda (tree t)
14862 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14863 t = TI_TEMPLATE (ti);
14864 return t;
14867 /* Return the set of template arguments used to regenerate the lambda T
14868 from its most general lambda. */
14870 tree
14871 lambda_regenerating_args (tree t)
14873 if (LAMBDA_FUNCTION_P (t))
14874 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14875 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14876 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14877 return TI_ARGS (ti);
14878 else
14879 return NULL_TREE;
14882 /* We're instantiating a variable from template function TCTX. Return the
14883 corresponding current enclosing scope. We can match them up using
14884 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14885 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14886 the template definition in regenerate_decl_from_template. */
14888 static tree
14889 enclosing_instantiation_of (tree tctx)
14891 tree fn = current_function_decl;
14893 /* We shouldn't ever need to do this for other artificial functions. */
14894 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14896 for (; fn; fn = decl_function_context (fn))
14897 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14898 return fn;
14899 gcc_unreachable ();
14902 /* Substitute the ARGS into the T, which is a _DECL. Return the
14903 result of the substitution. Issue error and warning messages under
14904 control of COMPLAIN. The flag USE_SPEC_TABLE controls if we look up
14905 and insert into the specializations table or if we can assume it's
14906 the caller's responsibility; this is used by instantiate_template
14907 to avoid doing some redundant work. */
14909 static tree
14910 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
14911 bool use_spec_table /* = true */)
14913 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14914 location_t saved_loc;
14915 tree r = NULL_TREE;
14916 tree in_decl = t;
14917 hashval_t hash = 0;
14919 if (t == error_mark_node)
14920 return error_mark_node;
14922 /* Set the filename and linenumber to improve error-reporting. */
14923 saved_loc = input_location;
14924 input_location = DECL_SOURCE_LOCATION (t);
14926 switch (TREE_CODE (t))
14928 case TEMPLATE_DECL:
14929 r = tsubst_template_decl (t, args, complain,
14930 /*lambda_fntype=*/NULL_TREE,
14931 /*lambda_tparms=*/NULL_TREE);
14932 break;
14934 case FUNCTION_DECL:
14935 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
14936 use_spec_table);
14937 break;
14939 case PARM_DECL:
14941 tree type = NULL_TREE;
14942 int i, len = 1;
14943 tree expanded_types = NULL_TREE;
14944 tree prev_r = NULL_TREE;
14945 tree first_r = NULL_TREE;
14947 if (DECL_PACK_P (t))
14949 /* If there is a local specialization that isn't a
14950 parameter pack, it means that we're doing a "simple"
14951 substitution from inside tsubst_pack_expansion. Just
14952 return the local specialization (which will be a single
14953 parm). */
14954 tree spec = retrieve_local_specialization (t);
14955 if (spec
14956 && TREE_CODE (spec) == PARM_DECL
14957 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14958 RETURN (spec);
14960 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14961 the parameters in this function parameter pack. */
14962 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14963 complain, in_decl);
14964 if (TREE_CODE (expanded_types) == TREE_VEC)
14966 len = TREE_VEC_LENGTH (expanded_types);
14968 /* Zero-length parameter packs are boring. Just substitute
14969 into the chain. */
14970 if (len == 0 && !cp_unevaluated_operand)
14971 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14972 TREE_CHAIN (t)));
14974 else
14976 /* All we did was update the type. Make a note of that. */
14977 type = expanded_types;
14978 expanded_types = NULL_TREE;
14982 /* Loop through all of the parameters we'll build. When T is
14983 a function parameter pack, LEN is the number of expanded
14984 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14985 r = NULL_TREE;
14986 for (i = 0; i < len; ++i)
14988 prev_r = r;
14989 r = copy_node (t);
14990 if (DECL_TEMPLATE_PARM_P (t))
14991 SET_DECL_TEMPLATE_PARM_P (r);
14993 if (expanded_types)
14994 /* We're on the Ith parameter of the function parameter
14995 pack. */
14997 /* Get the Ith type. */
14998 type = TREE_VEC_ELT (expanded_types, i);
15000 /* Rename the parameter to include the index. */
15001 DECL_NAME (r)
15002 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15004 else if (!type)
15005 /* We're dealing with a normal parameter. */
15006 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15008 type = type_decays_to (type);
15009 TREE_TYPE (r) = type;
15010 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15012 if (DECL_INITIAL (r))
15014 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
15015 DECL_INITIAL (r) = TREE_TYPE (r);
15016 else
15017 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
15018 complain, in_decl);
15021 DECL_CONTEXT (r) = NULL_TREE;
15023 if (!DECL_TEMPLATE_PARM_P (r))
15024 DECL_ARG_TYPE (r) = type_passed_as (type);
15026 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15027 args, complain, in_decl))
15028 return error_mark_node;
15030 /* Keep track of the first new parameter we
15031 generate. That's what will be returned to the
15032 caller. */
15033 if (!first_r)
15034 first_r = r;
15036 /* Build a proper chain of parameters when substituting
15037 into a function parameter pack. */
15038 if (prev_r)
15039 DECL_CHAIN (prev_r) = r;
15042 /* If cp_unevaluated_operand is set, we're just looking for a
15043 single dummy parameter, so don't keep going. */
15044 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
15045 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
15046 complain, DECL_CHAIN (t));
15048 /* FIRST_R contains the start of the chain we've built. */
15049 r = first_r;
15051 break;
15053 case FIELD_DECL:
15055 tree type = NULL_TREE;
15056 tree vec = NULL_TREE;
15057 tree expanded_types = NULL_TREE;
15058 int len = 1;
15060 if (PACK_EXPANSION_P (TREE_TYPE (t)))
15062 /* This field is a lambda capture pack. Return a TREE_VEC of
15063 the expanded fields to instantiate_class_template_1. */
15064 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
15065 complain, in_decl);
15066 if (TREE_CODE (expanded_types) == TREE_VEC)
15068 len = TREE_VEC_LENGTH (expanded_types);
15069 vec = make_tree_vec (len);
15071 else
15073 /* All we did was update the type. Make a note of that. */
15074 type = expanded_types;
15075 expanded_types = NULL_TREE;
15079 for (int i = 0; i < len; ++i)
15081 r = copy_decl (t);
15082 if (expanded_types)
15084 type = TREE_VEC_ELT (expanded_types, i);
15085 DECL_NAME (r)
15086 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15088 else if (!type)
15089 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15091 if (type == error_mark_node)
15092 RETURN (error_mark_node);
15093 TREE_TYPE (r) = type;
15094 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15096 if (DECL_C_BIT_FIELD (r))
15097 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15098 number of bits. */
15099 DECL_BIT_FIELD_REPRESENTATIVE (r)
15100 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15101 complain, in_decl);
15102 if (DECL_INITIAL (t))
15104 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15105 NSDMI in perform_member_init. Still set DECL_INITIAL
15106 so that we know there is one. */
15107 DECL_INITIAL (r) = void_node;
15108 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15109 retrofit_lang_decl (r);
15110 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15112 /* We don't have to set DECL_CONTEXT here; it is set by
15113 finish_member_declaration. */
15114 DECL_CHAIN (r) = NULL_TREE;
15116 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15117 args, complain, in_decl))
15118 return error_mark_node;
15120 if (vec)
15121 TREE_VEC_ELT (vec, i) = r;
15124 if (vec)
15125 r = vec;
15127 break;
15129 case USING_DECL:
15130 /* We reach here only for member using decls. We also need to check
15131 uses_template_parms because DECL_DEPENDENT_P is not set for a
15132 using-declaration that designates a member of the current
15133 instantiation (c++/53549). */
15134 if (DECL_DEPENDENT_P (t)
15135 || uses_template_parms (USING_DECL_SCOPE (t)))
15137 /* True iff this using-decl was written as a pack expansion
15138 (and a pack appeared in its scope or name). If a pack
15139 appeared in both, we expand the packs separately and
15140 manually merge them. */
15141 bool variadic_p = false;
15143 tree scope = USING_DECL_SCOPE (t);
15144 if (PACK_EXPANSION_P (scope))
15146 scope = tsubst_pack_expansion (scope, args,
15147 complain | tf_qualifying_scope,
15148 in_decl);
15149 variadic_p = true;
15151 else
15152 scope = tsubst_scope (scope, args, complain, in_decl);
15154 tree name = DECL_NAME (t);
15155 if (IDENTIFIER_CONV_OP_P (name)
15156 && PACK_EXPANSION_P (TREE_TYPE (name)))
15158 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15159 complain, in_decl);
15160 if (name == error_mark_node)
15162 r = error_mark_node;
15163 break;
15165 for (tree& elt : tree_vec_range (name))
15166 elt = make_conv_op_name (elt);
15167 variadic_p = true;
15169 else
15170 name = tsubst_copy (name, args, complain, in_decl);
15172 int len;
15173 if (!variadic_p)
15174 len = 1;
15175 else if (TREE_CODE (scope) == TREE_VEC
15176 && TREE_CODE (name) == TREE_VEC)
15178 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15180 error ("mismatched argument pack lengths (%d vs %d)",
15181 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15182 r = error_mark_node;
15183 break;
15185 len = TREE_VEC_LENGTH (scope);
15187 else if (TREE_CODE (scope) == TREE_VEC)
15188 len = TREE_VEC_LENGTH (scope);
15189 else /* TREE_CODE (name) == TREE_VEC */
15190 len = TREE_VEC_LENGTH (name);
15192 r = make_tree_vec (len);
15193 for (int i = 0; i < len; ++i)
15195 tree escope = (TREE_CODE (scope) == TREE_VEC
15196 ? TREE_VEC_ELT (scope, i)
15197 : scope);
15198 tree ename = (TREE_CODE (name) == TREE_VEC
15199 ? TREE_VEC_ELT (name, i)
15200 : name);
15201 tree elt = do_class_using_decl (escope, ename);
15202 if (!elt)
15204 r = error_mark_node;
15205 break;
15207 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15208 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15209 TREE_VEC_ELT (r, i) = elt;
15212 if (!variadic_p && r != error_mark_node)
15213 r = TREE_VEC_ELT (r, 0);
15215 else
15217 r = copy_node (t);
15218 DECL_CHAIN (r) = NULL_TREE;
15220 break;
15222 case TYPE_DECL:
15223 case VAR_DECL:
15225 tree argvec = NULL_TREE;
15226 tree gen_tmpl = NULL_TREE;
15227 tree tmpl = NULL_TREE;
15228 tree type = NULL_TREE;
15230 if (TREE_TYPE (t) == error_mark_node)
15231 RETURN (error_mark_node);
15233 if (TREE_CODE (t) == TYPE_DECL
15234 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15236 /* If this is the canonical decl, we don't have to
15237 mess with instantiations, and often we can't (for
15238 typename, template type parms and such). Note that
15239 TYPE_NAME is not correct for the above test if
15240 we've copied the type for a typedef. */
15241 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15242 if (type == error_mark_node)
15243 RETURN (error_mark_node);
15244 r = TYPE_NAME (type);
15245 break;
15248 /* Check to see if we already have the specialization we
15249 need. */
15250 tree spec = NULL_TREE;
15251 bool local_p = false;
15252 tree ctx = DECL_CONTEXT (t);
15253 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15254 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15256 local_p = false;
15257 if (DECL_CLASS_SCOPE_P (t))
15259 ctx = tsubst_aggr_type (ctx, args,
15260 complain,
15261 in_decl, /*entering_scope=*/1);
15262 if (DECL_SELF_REFERENCE_P (t))
15263 /* The context and type of an injected-class-name are
15264 the same, so we don't need to substitute both. */
15265 type = ctx;
15266 /* If CTX is unchanged, then T is in fact the
15267 specialization we want. That situation occurs when
15268 referencing a static data member within in its own
15269 class. We can use pointer equality, rather than
15270 same_type_p, because DECL_CONTEXT is always
15271 canonical... */
15272 if (ctx == DECL_CONTEXT (t)
15273 /* ... unless T is a member template; in which
15274 case our caller can be willing to create a
15275 specialization of that template represented
15276 by T. */
15277 && !(DECL_TI_TEMPLATE (t)
15278 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15279 spec = t;
15282 if (!spec)
15284 tmpl = DECL_TI_TEMPLATE (t);
15285 if (use_spec_table)
15287 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15288 if (argvec == error_mark_node)
15289 RETURN (error_mark_node);
15290 gen_tmpl = most_general_template (tmpl);
15291 hash = spec_hasher::hash (gen_tmpl, argvec);
15292 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15294 else
15295 argvec = args;
15298 else
15300 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15301 /* Subsequent calls to pushdecl will fill this in. */
15302 ctx = NULL_TREE;
15303 /* A local variable. */
15304 local_p = true;
15305 /* Unless this is a reference to a static variable from an
15306 enclosing function, in which case we need to fill it in now. */
15307 if (TREE_STATIC (t))
15309 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15310 if (fn != current_function_decl)
15311 ctx = fn;
15313 spec = retrieve_local_specialization (t);
15315 /* If we already have the specialization we need, there is
15316 nothing more to do. */
15317 if (spec)
15319 r = spec;
15320 break;
15323 /* Create a new node for the specialization we need. */
15324 if (type == NULL_TREE)
15326 if (is_typedef_decl (t))
15327 type = DECL_ORIGINAL_TYPE (t);
15328 else
15329 type = TREE_TYPE (t);
15330 if (VAR_P (t)
15331 && VAR_HAD_UNKNOWN_BOUND (t)
15332 && type != error_mark_node)
15333 type = strip_array_domain (type);
15334 tsubst_flags_t tcomplain = complain;
15335 if (VAR_P (t))
15336 tcomplain |= tf_tst_ok;
15337 type = tsubst (type, args, tcomplain, in_decl);
15338 /* Substituting the type might have recursively instantiated this
15339 same alias (c++/86171). */
15340 if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15341 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15343 r = spec;
15344 break;
15347 if (type == error_mark_node && !(complain & tf_error))
15348 RETURN (error_mark_node);
15349 r = copy_decl (t);
15350 if (VAR_P (r))
15352 DECL_INITIALIZED_P (r) = 0;
15353 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15354 if (TREE_CODE (type) == FUNCTION_TYPE)
15356 /* It may seem that this case cannot occur, since:
15358 typedef void f();
15359 void g() { f x; }
15361 declares a function, not a variable. However:
15363 typedef void f();
15364 template <typename T> void g() { T t; }
15365 template void g<f>();
15367 is an attempt to declare a variable with function
15368 type. */
15369 error ("variable %qD has function type",
15370 /* R is not yet sufficiently initialized, so we
15371 just use its name. */
15372 DECL_NAME (r));
15373 RETURN (error_mark_node);
15375 type = complete_type (type);
15376 /* Wait until cp_finish_decl to set this again, to handle
15377 circular dependency (template/instantiate6.C). */
15378 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15379 type = check_var_type (DECL_NAME (r), type,
15380 DECL_SOURCE_LOCATION (r));
15381 if (DECL_HAS_VALUE_EXPR_P (t))
15383 tree ve = DECL_VALUE_EXPR (t);
15384 /* If the DECL_VALUE_EXPR is converted to the declared type,
15385 preserve the identity so that gimplify_type_sizes works. */
15386 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15387 if (nop)
15388 ve = TREE_OPERAND (ve, 0);
15389 ve = tsubst_expr (ve, args, complain, in_decl);
15390 if (REFERENCE_REF_P (ve))
15392 gcc_assert (TYPE_REF_P (type));
15393 ve = TREE_OPERAND (ve, 0);
15395 if (nop)
15396 ve = build_nop (type, ve);
15397 else if (DECL_LANG_SPECIFIC (t)
15398 && DECL_OMP_PRIVATIZED_MEMBER (t)
15399 && TREE_CODE (ve) == COMPONENT_REF
15400 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15401 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15402 type = TREE_TYPE (ve);
15403 else
15404 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15405 == TYPE_MAIN_VARIANT (type));
15406 SET_DECL_VALUE_EXPR (r, ve);
15408 if (CP_DECL_THREAD_LOCAL_P (r)
15409 && !processing_template_decl)
15410 set_decl_tls_model (r, decl_default_tls_model (r));
15412 else if (DECL_SELF_REFERENCE_P (t))
15413 SET_DECL_SELF_REFERENCE_P (r);
15414 TREE_TYPE (r) = type;
15415 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15416 DECL_CONTEXT (r) = ctx;
15417 /* Clear out the mangled name and RTL for the instantiation. */
15418 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15419 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15420 SET_DECL_RTL (r, NULL);
15421 set_instantiating_module (r);
15423 /* The initializer must not be expanded until it is required;
15424 see [temp.inst]. */
15425 DECL_INITIAL (r) = NULL_TREE;
15426 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15427 if (VAR_P (r))
15429 if (DECL_LANG_SPECIFIC (r))
15430 SET_DECL_DEPENDENT_INIT_P (r, false);
15432 SET_DECL_MODE (r, VOIDmode);
15434 /* Possibly limit visibility based on template args. */
15435 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15436 if (DECL_VISIBILITY_SPECIFIED (t))
15438 DECL_VISIBILITY_SPECIFIED (r) = 0;
15439 DECL_ATTRIBUTES (r)
15440 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15442 determine_visibility (r);
15445 if (!local_p)
15447 /* A static data member declaration is always marked
15448 external when it is declared in-class, even if an
15449 initializer is present. We mimic the non-template
15450 processing here. */
15451 DECL_EXTERNAL (r) = 1;
15452 if (DECL_NAMESPACE_SCOPE_P (t))
15453 DECL_NOT_REALLY_EXTERN (r) = 1;
15455 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15456 SET_DECL_IMPLICIT_INSTANTIATION (r);
15457 if (use_spec_table)
15458 register_specialization (r, gen_tmpl, argvec, false, hash);
15460 else
15462 if (DECL_LANG_SPECIFIC (r))
15463 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15464 if (!cp_unevaluated_operand)
15465 register_local_specialization (r, t);
15468 DECL_CHAIN (r) = NULL_TREE;
15470 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15471 /*flags=*/0,
15472 args, complain, in_decl))
15473 return error_mark_node;
15475 /* Preserve a typedef that names a type. */
15476 if (is_typedef_decl (r) && type != error_mark_node)
15478 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15479 set_underlying_type (r);
15481 /* common_handle_aligned_attribute doesn't apply the alignment
15482 to DECL_ORIGINAL_TYPE. */
15483 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15484 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15485 TYPE_ALIGN (TREE_TYPE (t)));
15488 layout_decl (r, 0);
15490 break;
15492 default:
15493 gcc_unreachable ();
15495 #undef RETURN
15497 out:
15498 /* Restore the file and line information. */
15499 input_location = saved_loc;
15501 return r;
15504 /* Substitute into the complete parameter type list PARMS. */
15506 tree
15507 tsubst_function_parms (tree parms,
15508 tree args,
15509 tsubst_flags_t complain,
15510 tree in_decl)
15512 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15515 /* Substitute into the ARG_TYPES of a function type.
15516 If END is a TREE_CHAIN, leave it and any following types
15517 un-substituted. */
15519 static tree
15520 tsubst_arg_types (tree arg_types,
15521 tree args,
15522 tree end,
15523 tsubst_flags_t complain,
15524 tree in_decl)
15526 tree type = NULL_TREE;
15527 int len = 1;
15528 tree expanded_args = NULL_TREE;
15530 if (!arg_types || arg_types == void_list_node || arg_types == end)
15531 return arg_types;
15533 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15535 /* For a pack expansion, perform substitution on the
15536 entire expression. Later on, we'll handle the arguments
15537 one-by-one. */
15538 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15539 args, complain, in_decl);
15541 if (TREE_CODE (expanded_args) == TREE_VEC)
15542 /* So that we'll spin through the parameters, one by one. */
15543 len = TREE_VEC_LENGTH (expanded_args);
15544 else
15546 /* We only partially substituted into the parameter
15547 pack. Our type is TYPE_PACK_EXPANSION. */
15548 type = expanded_args;
15549 expanded_args = NULL_TREE;
15552 else
15553 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15555 /* Check if a substituted type is erroneous before substituting into
15556 the rest of the chain. */
15557 for (int i = 0; i < len; i++)
15559 if (expanded_args)
15560 type = TREE_VEC_ELT (expanded_args, i);
15562 if (type == error_mark_node)
15563 return error_mark_node;
15564 if (VOID_TYPE_P (type))
15566 if (complain & tf_error)
15568 error ("invalid parameter type %qT", type);
15569 if (in_decl)
15570 error ("in declaration %q+D", in_decl);
15572 return error_mark_node;
15576 /* We do not substitute into default arguments here. The standard
15577 mandates that they be instantiated only when needed, which is
15578 done in build_over_call. */
15579 tree default_arg = TREE_PURPOSE (arg_types);
15581 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15582 since the new op() won't have any associated template arguments for us
15583 to refer to later. */
15584 if (lambda_fn_in_template_p (in_decl)
15585 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15586 && DECL_LOCAL_DECL_P (in_decl)))
15587 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl);
15589 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15590 args, end, complain, in_decl);
15591 if (remaining_arg_types == error_mark_node)
15592 return error_mark_node;
15594 for (int i = len-1; i >= 0; i--)
15596 if (expanded_args)
15597 type = TREE_VEC_ELT (expanded_args, i);
15599 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15600 top-level qualifiers as required. */
15601 type = cv_unqualified (type_decays_to (type));
15603 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15605 /* We've instantiated a template before its default arguments
15606 have been parsed. This can happen for a nested template
15607 class, and is not an error unless we require the default
15608 argument in a call of this function. */
15609 remaining_arg_types
15610 = tree_cons (default_arg, type, remaining_arg_types);
15611 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15612 remaining_arg_types);
15614 else
15615 remaining_arg_types
15616 = hash_tree_cons (default_arg, type, remaining_arg_types);
15619 return remaining_arg_types;
15622 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15623 *not* handle the exception-specification for FNTYPE, because the
15624 initial substitution of explicitly provided template parameters
15625 during argument deduction forbids substitution into the
15626 exception-specification:
15628 [temp.deduct]
15630 All references in the function type of the function template to the
15631 corresponding template parameters are replaced by the specified tem-
15632 plate argument values. If a substitution in a template parameter or
15633 in the function type of the function template results in an invalid
15634 type, type deduction fails. [Note: The equivalent substitution in
15635 exception specifications is done only when the function is instanti-
15636 ated, at which point a program is ill-formed if the substitution
15637 results in an invalid type.] */
15639 static tree
15640 tsubst_function_type (tree t,
15641 tree args,
15642 tsubst_flags_t complain,
15643 tree in_decl)
15645 tree return_type;
15646 tree arg_types = NULL_TREE;
15648 /* The TYPE_CONTEXT is not used for function/method types. */
15649 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15651 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15652 failure. */
15653 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15655 if (late_return_type_p)
15657 /* Substitute the argument types. */
15658 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15659 complain, in_decl);
15660 if (arg_types == error_mark_node)
15661 return error_mark_node;
15663 tree save_ccp = current_class_ptr;
15664 tree save_ccr = current_class_ref;
15665 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15666 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15667 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15668 if (do_inject)
15670 /* DR 1207: 'this' is in scope in the trailing return type. */
15671 inject_this_parameter (this_type, cp_type_quals (this_type));
15674 /* Substitute the return type. */
15675 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15677 if (do_inject)
15679 current_class_ptr = save_ccp;
15680 current_class_ref = save_ccr;
15683 else
15684 /* Substitute the return type. */
15685 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15687 if (return_type == error_mark_node)
15688 return error_mark_node;
15689 /* DR 486 clarifies that creation of a function type with an
15690 invalid return type is a deduction failure. */
15691 if (TREE_CODE (return_type) == ARRAY_TYPE
15692 || TREE_CODE (return_type) == FUNCTION_TYPE)
15694 if (complain & tf_error)
15696 if (TREE_CODE (return_type) == ARRAY_TYPE)
15697 error ("function returning an array");
15698 else
15699 error ("function returning a function");
15701 return error_mark_node;
15704 if (!late_return_type_p)
15706 /* Substitute the argument types. */
15707 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15708 complain, in_decl);
15709 if (arg_types == error_mark_node)
15710 return error_mark_node;
15713 /* Construct a new type node and return it. */
15714 return rebuild_function_or_method_type (t, return_type, arg_types,
15715 /*raises=*/NULL_TREE, complain);
15718 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15719 ARGS into that specification, and return the substituted
15720 specification. If there is no specification, return NULL_TREE. */
15722 static tree
15723 tsubst_exception_specification (tree fntype,
15724 tree args,
15725 tsubst_flags_t complain,
15726 tree in_decl,
15727 bool defer_ok)
15729 tree specs;
15730 tree new_specs;
15732 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15733 new_specs = NULL_TREE;
15734 if (specs && TREE_PURPOSE (specs))
15736 /* A noexcept-specifier. */
15737 tree expr = TREE_PURPOSE (specs);
15738 if (TREE_CODE (expr) == INTEGER_CST)
15739 new_specs = expr;
15740 else if (defer_ok)
15742 /* Defer instantiation of noexcept-specifiers to avoid
15743 excessive instantiations (c++/49107). */
15744 new_specs = make_node (DEFERRED_NOEXCEPT);
15745 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15747 /* We already partially instantiated this member template,
15748 so combine the new args with the old. */
15749 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15750 = DEFERRED_NOEXCEPT_PATTERN (expr);
15751 DEFERRED_NOEXCEPT_ARGS (new_specs)
15752 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15754 else
15756 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15757 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15760 else
15762 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15764 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15765 args);
15766 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15768 new_specs = tsubst_copy_and_build (expr, args, complain, in_decl);
15770 new_specs = build_noexcept_spec (new_specs, complain);
15771 /* We've instantiated a template before a noexcept-specifier
15772 contained therein has been parsed. This can happen for
15773 a nested template class:
15775 struct S {
15776 template<typename> struct B { B() noexcept(...); };
15777 struct A : B<int> { ... use B() ... };
15780 where completing B<int> will trigger instantiating the
15781 noexcept, even though we only parse it at the end of S. */
15782 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15784 gcc_checking_assert (defer_ok);
15785 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15788 else if (specs)
15790 if (! TREE_VALUE (specs))
15791 new_specs = specs;
15792 else
15793 while (specs)
15795 tree spec;
15796 int i, len = 1;
15797 tree expanded_specs = NULL_TREE;
15799 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15801 /* Expand the pack expansion type. */
15802 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15803 args, complain,
15804 in_decl);
15806 if (expanded_specs == error_mark_node)
15807 return error_mark_node;
15808 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15809 len = TREE_VEC_LENGTH (expanded_specs);
15810 else
15812 /* We're substituting into a member template, so
15813 we got a TYPE_PACK_EXPANSION back. Add that
15814 expansion and move on. */
15815 gcc_assert (TREE_CODE (expanded_specs)
15816 == TYPE_PACK_EXPANSION);
15817 new_specs = add_exception_specifier (new_specs,
15818 expanded_specs,
15819 complain);
15820 specs = TREE_CHAIN (specs);
15821 continue;
15825 for (i = 0; i < len; ++i)
15827 if (expanded_specs)
15828 spec = TREE_VEC_ELT (expanded_specs, i);
15829 else
15830 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15831 if (spec == error_mark_node)
15832 return spec;
15833 new_specs = add_exception_specifier (new_specs, spec,
15834 complain);
15837 specs = TREE_CHAIN (specs);
15840 return new_specs;
15843 /* Substitute through a TREE_LIST of types or expressions, handling pack
15844 expansions. */
15846 tree
15847 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15849 if (t == void_list_node)
15850 return t;
15852 tree purpose = TREE_PURPOSE (t);
15853 tree purposevec = NULL_TREE;
15854 if (!purpose)
15856 else if (PACK_EXPANSION_P (purpose))
15858 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15859 if (TREE_CODE (purpose) == TREE_VEC)
15860 purposevec = purpose;
15862 else if (TYPE_P (purpose))
15863 purpose = tsubst (purpose, args, complain, in_decl);
15864 else
15865 purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15866 if (purpose == error_mark_node || purposevec == error_mark_node)
15867 return error_mark_node;
15869 tree value = TREE_VALUE (t);
15870 tree valuevec = NULL_TREE;
15871 if (!value)
15873 else if (PACK_EXPANSION_P (value))
15875 value = tsubst_pack_expansion (value, args, complain, in_decl);
15876 if (TREE_CODE (value) == TREE_VEC)
15877 valuevec = value;
15879 else if (TYPE_P (value))
15880 value = tsubst (value, args, complain, in_decl);
15881 else
15882 value = tsubst_copy_and_build (value, args, complain, in_decl);
15883 if (value == error_mark_node || valuevec == error_mark_node)
15884 return error_mark_node;
15886 tree chain = TREE_CHAIN (t);
15887 if (!chain)
15889 else if (TREE_CODE (chain) == TREE_LIST)
15890 chain = tsubst_tree_list (chain, args, complain, in_decl);
15891 else if (TYPE_P (chain))
15892 chain = tsubst (chain, args, complain, in_decl);
15893 else
15894 chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15895 if (chain == error_mark_node)
15896 return error_mark_node;
15898 if (purpose == TREE_PURPOSE (t)
15899 && value == TREE_VALUE (t)
15900 && chain == TREE_CHAIN (t))
15901 return t;
15903 int len;
15904 /* Determine the number of arguments. */
15905 if (purposevec)
15907 len = TREE_VEC_LENGTH (purposevec);
15908 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15910 else if (valuevec)
15911 len = TREE_VEC_LENGTH (valuevec);
15912 else
15913 len = 1;
15915 for (int i = len; i-- > 0; )
15917 if (purposevec)
15918 purpose = TREE_VEC_ELT (purposevec, i);
15919 if (valuevec)
15920 value = TREE_VEC_ELT (valuevec, i);
15922 if (value && TYPE_P (value))
15923 chain = hash_tree_cons (purpose, value, chain);
15924 else
15925 chain = tree_cons (purpose, value, chain);
15928 return chain;
15931 /* Take the tree structure T and replace template parameters used
15932 therein with the argument vector ARGS. IN_DECL is an associated
15933 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15934 Issue error and warning messages under control of COMPLAIN. Note
15935 that we must be relatively non-tolerant of extensions here, in
15936 order to preserve conformance; if we allow substitutions that
15937 should not be allowed, we may allow argument deductions that should
15938 not succeed, and therefore report ambiguous overload situations
15939 where there are none. In theory, we could allow the substitution,
15940 but indicate that it should have failed, and allow our caller to
15941 make sure that the right thing happens, but we don't try to do this
15942 yet.
15944 This function is used for dealing with types, decls and the like;
15945 for expressions, use tsubst_expr or tsubst_copy. */
15947 tree
15948 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15950 enum tree_code code;
15951 tree type, r = NULL_TREE;
15953 if (t == NULL_TREE || t == error_mark_node
15954 || t == integer_type_node
15955 || t == void_type_node
15956 || t == char_type_node
15957 || t == unknown_type_node
15958 || TREE_CODE (t) == NAMESPACE_DECL
15959 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15960 return t;
15962 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
15963 complain &= ~tf_tst_ok;
15965 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
15966 complain &= ~tf_qualifying_scope;
15968 if (DECL_P (t))
15969 return tsubst_decl (t, args, complain);
15971 if (args == NULL_TREE)
15972 return t;
15974 code = TREE_CODE (t);
15976 gcc_assert (code != IDENTIFIER_NODE);
15977 type = TREE_TYPE (t);
15979 gcc_assert (type != unknown_type_node);
15981 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15982 return d;
15984 /* Reuse typedefs. We need to do this to handle dependent attributes,
15985 such as attribute aligned. */
15986 if (TYPE_P (t)
15987 && typedef_variant_p (t))
15989 tree decl = TYPE_NAME (t);
15991 if (alias_template_specialization_p (t, nt_opaque))
15993 /* DECL represents an alias template and we want to
15994 instantiate it. */
15995 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15996 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15997 r = instantiate_alias_template (tmpl, gen_args, complain);
15999 else if (DECL_CLASS_SCOPE_P (decl)
16000 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
16001 && uses_template_parms (DECL_CONTEXT (decl)))
16003 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16004 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
16005 r = retrieve_specialization (tmpl, gen_args, 0);
16007 else if (DECL_FUNCTION_SCOPE_P (decl)
16008 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
16009 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
16010 r = retrieve_local_specialization (decl);
16011 else
16012 /* The typedef is from a non-template context. */
16013 return t;
16015 if (r)
16017 r = TREE_TYPE (r);
16018 r = cp_build_qualified_type
16019 (r, cp_type_quals (t) | cp_type_quals (r),
16020 complain | tf_ignore_bad_quals);
16021 return r;
16023 else
16025 /* We don't have an instantiation yet, so drop the typedef. */
16026 int quals = cp_type_quals (t);
16027 t = DECL_ORIGINAL_TYPE (decl);
16028 t = cp_build_qualified_type (t, quals,
16029 complain | tf_ignore_bad_quals);
16033 bool fndecl_type = (complain & tf_fndecl_type);
16034 complain &= ~tf_fndecl_type;
16036 if (type
16037 && code != TYPENAME_TYPE
16038 && code != TEMPLATE_TYPE_PARM
16039 && code != TEMPLATE_PARM_INDEX
16040 && code != IDENTIFIER_NODE
16041 && code != FUNCTION_TYPE
16042 && code != METHOD_TYPE)
16043 type = tsubst (type, args, complain, in_decl);
16044 if (type == error_mark_node)
16045 return error_mark_node;
16047 switch (code)
16049 case RECORD_TYPE:
16050 if (TYPE_PTRMEMFUNC_P (t))
16051 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
16052 /* Fall through. */
16053 case UNION_TYPE:
16054 case ENUMERAL_TYPE:
16055 return tsubst_aggr_type_1 (t, args, complain, in_decl,
16056 /*entering_scope=*/0);
16058 case ERROR_MARK:
16059 case IDENTIFIER_NODE:
16060 case VOID_TYPE:
16061 case OPAQUE_TYPE:
16062 case REAL_TYPE:
16063 case COMPLEX_TYPE:
16064 case VECTOR_TYPE:
16065 case BOOLEAN_TYPE:
16066 case NULLPTR_TYPE:
16067 case LANG_TYPE:
16068 return t;
16070 case INTEGER_TYPE:
16071 if (t == integer_type_node)
16072 return t;
16074 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16075 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16076 return t;
16079 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16081 max = tsubst_expr (omax, args, complain, in_decl);
16083 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16084 needed. */
16085 if (TREE_CODE (max) == NOP_EXPR
16086 && TREE_SIDE_EFFECTS (omax)
16087 && !TREE_TYPE (max))
16088 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16090 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16091 with TREE_SIDE_EFFECTS that indicates this is not an integral
16092 constant expression. */
16093 if (processing_template_decl
16094 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16096 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16097 TREE_SIDE_EFFECTS (max) = 1;
16100 return compute_array_index_type (NULL_TREE, max, complain);
16103 case TEMPLATE_TYPE_PARM:
16104 if (template_placeholder_p (t))
16106 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16107 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
16108 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16109 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16111 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16112 return make_template_placeholder (tmpl);
16113 else
16114 return t;
16116 /* Fall through. */
16117 case TEMPLATE_TEMPLATE_PARM:
16118 case BOUND_TEMPLATE_TEMPLATE_PARM:
16119 case TEMPLATE_PARM_INDEX:
16121 int idx;
16122 int level;
16123 int levels;
16124 tree arg = NULL_TREE;
16126 r = NULL_TREE;
16128 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16129 template_parm_level_and_index (t, &level, &idx);
16131 levels = TMPL_ARGS_DEPTH (args);
16132 if (level <= levels
16133 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16135 arg = TMPL_ARG (args, level, idx);
16137 /* See through ARGUMENT_PACK_SELECT arguments. */
16138 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16139 arg = argument_pack_select_arg (arg);
16142 if (arg == error_mark_node)
16143 return error_mark_node;
16144 else if (arg != NULL_TREE)
16146 if (ARGUMENT_PACK_P (arg))
16147 /* If ARG is an argument pack, we don't actually want to
16148 perform a substitution here, because substitutions
16149 for argument packs are only done
16150 element-by-element. We can get to this point when
16151 substituting the type of a non-type template
16152 parameter pack, when that type actually contains
16153 template parameter packs from an outer template, e.g.,
16155 template<typename... Types> struct A {
16156 template<Types... Values> struct B { };
16157 }; */
16158 return t;
16160 if (code == TEMPLATE_TYPE_PARM)
16162 int quals;
16164 /* When building concept checks for the purpose of
16165 deducing placeholders, we can end up with wildcards
16166 where types are expected. Adjust this to the deduced
16167 value. */
16168 if (TREE_CODE (arg) == WILDCARD_DECL)
16169 arg = TREE_TYPE (TREE_TYPE (arg));
16171 gcc_assert (TYPE_P (arg));
16173 quals = cp_type_quals (arg) | cp_type_quals (t);
16175 return cp_build_qualified_type
16176 (arg, quals, complain | tf_ignore_bad_quals);
16178 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16180 /* We are processing a type constructed from a
16181 template template parameter. */
16182 tree argvec = tsubst (TYPE_TI_ARGS (t),
16183 args, complain, in_decl);
16184 if (argvec == error_mark_node)
16185 return error_mark_node;
16187 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16188 || TREE_CODE (arg) == TEMPLATE_DECL
16189 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16191 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16192 /* Consider this code:
16194 template <template <class> class Template>
16195 struct Internal {
16196 template <class Arg> using Bind = Template<Arg>;
16199 template <template <class> class Template, class Arg>
16200 using Instantiate = Template<Arg>; //#0
16202 template <template <class> class Template,
16203 class Argument>
16204 using Bind =
16205 Instantiate<Internal<Template>::template Bind,
16206 Argument>; //#1
16208 When #1 is parsed, the
16209 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16210 parameter `Template' in #0 matches the
16211 UNBOUND_CLASS_TEMPLATE representing the argument
16212 `Internal<Template>::template Bind'; We then want
16213 to assemble the type `Bind<Argument>' that can't
16214 be fully created right now, because
16215 `Internal<Template>' not being complete, the Bind
16216 template cannot be looked up in that context. So
16217 we need to "store" `Bind<Argument>' for later
16218 when the context of Bind becomes complete. Let's
16219 store that in a TYPENAME_TYPE. */
16220 return make_typename_type (TYPE_CONTEXT (arg),
16221 build_nt (TEMPLATE_ID_EXPR,
16222 TYPE_IDENTIFIER (arg),
16223 argvec),
16224 typename_type,
16225 complain);
16227 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16228 are resolving nested-types in the signature of a
16229 member function templates. Otherwise ARG is a
16230 TEMPLATE_DECL and is the real template to be
16231 instantiated. */
16232 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16233 arg = TYPE_NAME (arg);
16235 r = lookup_template_class (arg,
16236 argvec, in_decl,
16237 DECL_CONTEXT (arg),
16238 /*entering_scope=*/0,
16239 complain);
16240 return cp_build_qualified_type
16241 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16243 else if (code == TEMPLATE_TEMPLATE_PARM)
16244 return arg;
16245 else
16246 /* TEMPLATE_PARM_INDEX. */
16247 return convert_from_reference (unshare_expr (arg));
16250 if (level == 1)
16251 /* This can happen during the attempted tsubst'ing in
16252 unify. This means that we don't yet have any information
16253 about the template parameter in question. */
16254 return t;
16256 /* Early in template argument deduction substitution, we don't
16257 want to reduce the level of 'auto', or it will be confused
16258 with a normal template parm in subsequent deduction.
16259 Similarly, don't reduce the level of template parameters to
16260 avoid mismatches when deducing their types. */
16261 if (complain & tf_partial)
16262 return t;
16264 /* If we get here, we must have been looking at a parm for a
16265 more deeply nested template. Make a new version of this
16266 template parameter, but with a lower level. */
16267 int quals;
16268 switch (code)
16270 case TEMPLATE_TYPE_PARM:
16271 case TEMPLATE_TEMPLATE_PARM:
16272 quals = cp_type_quals (t);
16273 if (quals)
16275 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16276 t = TYPE_MAIN_VARIANT (t);
16279 if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
16280 if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
16281 && (code == TEMPLATE_TYPE_PARM
16282 || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
16283 /* Cache lowering a type parameter or a simple template
16284 template parameter. */
16285 r = TREE_TYPE (d);
16287 if (!r)
16289 r = copy_type (t);
16290 TEMPLATE_TYPE_PARM_INDEX (r)
16291 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16292 r, levels, args, complain);
16293 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16294 TYPE_MAIN_VARIANT (r) = r;
16295 TYPE_POINTER_TO (r) = NULL_TREE;
16296 TYPE_REFERENCE_TO (r) = NULL_TREE;
16298 if (code == TEMPLATE_TYPE_PARM)
16299 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16300 /* Propagate constraints on placeholders since they are
16301 only instantiated during satisfaction. */
16302 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16304 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16305 SET_TYPE_STRUCTURAL_EQUALITY (r);
16306 else
16307 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16310 if (quals)
16311 r = cp_build_qualified_type (r, quals,
16312 complain | tf_ignore_bad_quals);
16313 break;
16315 case BOUND_TEMPLATE_TEMPLATE_PARM:
16317 tree tinfo = TYPE_TEMPLATE_INFO (t);
16318 /* We might need to substitute into the types of non-type
16319 template parameters. This also lowers the level of
16320 the ttp appropriately. */
16321 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16322 complain, in_decl);
16323 if (tmpl == error_mark_node)
16324 return error_mark_node;
16325 tree argvec = tsubst (TI_ARGS (tinfo), args,
16326 complain, in_decl);
16327 if (argvec == error_mark_node)
16328 return error_mark_node;
16329 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16330 /*entering_scope=*/false, complain);
16331 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16332 break;
16335 case TEMPLATE_PARM_INDEX:
16336 /* OK, now substitute the type of the non-type parameter. We
16337 couldn't do it earlier because it might be an auto parameter,
16338 and we wouldn't need to if we had an argument. */
16339 type = tsubst (type, args, complain, in_decl);
16340 if (type == error_mark_node)
16341 return error_mark_node;
16342 r = reduce_template_parm_level (t, type, levels, args, complain);
16343 break;
16345 default:
16346 gcc_unreachable ();
16349 return r;
16352 case TREE_LIST:
16353 return tsubst_tree_list (t, args, complain, in_decl);
16355 case TREE_BINFO:
16356 /* We should never be tsubsting a binfo. */
16357 gcc_unreachable ();
16359 case TREE_VEC:
16360 /* A vector of template arguments. */
16361 gcc_assert (!type);
16362 return tsubst_template_args (t, args, complain, in_decl);
16364 case POINTER_TYPE:
16365 case REFERENCE_TYPE:
16367 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16368 return t;
16370 /* [temp.deduct]
16372 Type deduction may fail for any of the following
16373 reasons:
16375 -- Attempting to create a pointer to reference type.
16376 -- Attempting to create a reference to a reference type or
16377 a reference to void.
16379 Core issue 106 says that creating a reference to a reference
16380 during instantiation is no longer a cause for failure. We
16381 only enforce this check in strict C++98 mode. */
16382 if ((TYPE_REF_P (type)
16383 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16384 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16386 static location_t last_loc;
16388 /* We keep track of the last time we issued this error
16389 message to avoid spewing a ton of messages during a
16390 single bad template instantiation. */
16391 if (complain & tf_error
16392 && last_loc != input_location)
16394 if (VOID_TYPE_P (type))
16395 error ("forming reference to void");
16396 else if (code == POINTER_TYPE)
16397 error ("forming pointer to reference type %qT", type);
16398 else
16399 error ("forming reference to reference type %qT", type);
16400 last_loc = input_location;
16403 return error_mark_node;
16405 else if (TREE_CODE (type) == FUNCTION_TYPE
16406 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16407 || type_memfn_rqual (type) != REF_QUAL_NONE))
16409 if (complain & tf_error)
16411 if (code == POINTER_TYPE)
16412 error ("forming pointer to qualified function type %qT",
16413 type);
16414 else
16415 error ("forming reference to qualified function type %qT",
16416 type);
16418 return error_mark_node;
16420 else if (code == POINTER_TYPE)
16422 r = build_pointer_type (type);
16423 if (TREE_CODE (type) == METHOD_TYPE)
16424 r = build_ptrmemfunc_type (r);
16426 else if (TYPE_REF_P (type))
16427 /* In C++0x, during template argument substitution, when there is an
16428 attempt to create a reference to a reference type, reference
16429 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16431 "If a template-argument for a template-parameter T names a type
16432 that is a reference to a type A, an attempt to create the type
16433 'lvalue reference to cv T' creates the type 'lvalue reference to
16434 A,' while an attempt to create the type type rvalue reference to
16435 cv T' creates the type T"
16437 r = cp_build_reference_type
16438 (TREE_TYPE (type),
16439 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16440 else
16441 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16442 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16444 if (r != error_mark_node)
16445 /* Will this ever be needed for TYPE_..._TO values? */
16446 layout_type (r);
16448 return r;
16450 case OFFSET_TYPE:
16452 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16453 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16455 /* [temp.deduct]
16457 Type deduction may fail for any of the following
16458 reasons:
16460 -- Attempting to create "pointer to member of T" when T
16461 is not a class type. */
16462 if (complain & tf_error)
16463 error ("creating pointer to member of non-class type %qT", r);
16464 return error_mark_node;
16466 if (TYPE_REF_P (type))
16468 if (complain & tf_error)
16469 error ("creating pointer to member reference type %qT", type);
16470 return error_mark_node;
16472 if (VOID_TYPE_P (type))
16474 if (complain & tf_error)
16475 error ("creating pointer to member of type void");
16476 return error_mark_node;
16478 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16479 if (TREE_CODE (type) == FUNCTION_TYPE)
16481 /* The type of the implicit object parameter gets its
16482 cv-qualifiers from the FUNCTION_TYPE. */
16483 tree memptr;
16484 tree method_type
16485 = build_memfn_type (type, r, type_memfn_quals (type),
16486 type_memfn_rqual (type));
16487 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16488 return cp_build_qualified_type (memptr, cp_type_quals (t),
16489 complain);
16491 else
16492 return cp_build_qualified_type (build_ptrmem_type (r, type),
16493 cp_type_quals (t),
16494 complain);
16496 case FUNCTION_TYPE:
16497 case METHOD_TYPE:
16499 tree fntype;
16500 tree specs;
16501 fntype = tsubst_function_type (t, args, complain, in_decl);
16502 if (fntype == error_mark_node)
16503 return error_mark_node;
16505 /* Substitute the exception specification. */
16506 specs = tsubst_exception_specification (t, args, complain, in_decl,
16507 /*defer_ok*/fndecl_type);
16508 if (specs == error_mark_node)
16509 return error_mark_node;
16510 if (specs)
16511 fntype = build_exception_variant (fntype, specs);
16512 return fntype;
16514 case ARRAY_TYPE:
16516 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16517 if (domain == error_mark_node)
16518 return error_mark_node;
16520 /* As an optimization, we avoid regenerating the array type if
16521 it will obviously be the same as T. */
16522 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16523 return t;
16525 /* These checks should match the ones in create_array_type_for_decl.
16527 [temp.deduct]
16529 The deduction may fail for any of the following reasons:
16531 -- Attempting to create an array with an element type that
16532 is void, a function type, or a reference type, or [DR337]
16533 an abstract class type. */
16534 if (VOID_TYPE_P (type)
16535 || TREE_CODE (type) == FUNCTION_TYPE
16536 || (TREE_CODE (type) == ARRAY_TYPE
16537 && TYPE_DOMAIN (type) == NULL_TREE)
16538 || TYPE_REF_P (type))
16540 if (complain & tf_error)
16541 error ("creating array of %qT", type);
16542 return error_mark_node;
16545 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16546 !(complain & tf_error)))
16547 return error_mark_node;
16549 r = build_cplus_array_type (type, domain);
16551 if (!valid_array_size_p (input_location, r, in_decl,
16552 (complain & tf_error)))
16553 return error_mark_node;
16555 if (TYPE_USER_ALIGN (t))
16557 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16558 TYPE_USER_ALIGN (r) = 1;
16561 return r;
16564 case TYPENAME_TYPE:
16566 tree ctx = TYPE_CONTEXT (t);
16567 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16569 ctx = tsubst_pack_expansion (ctx, args,
16570 complain | tf_qualifying_scope,
16571 in_decl);
16572 if (ctx == error_mark_node
16573 || TREE_VEC_LENGTH (ctx) > 1)
16574 return error_mark_node;
16575 if (TREE_VEC_LENGTH (ctx) == 0)
16577 if (complain & tf_error)
16578 error ("%qD is instantiated for an empty pack",
16579 TYPENAME_TYPE_FULLNAME (t));
16580 return error_mark_node;
16582 ctx = TREE_VEC_ELT (ctx, 0);
16584 else
16585 ctx = tsubst_aggr_type (ctx, args,
16586 complain | tf_qualifying_scope,
16587 in_decl, /*entering_scope=*/1);
16588 if (ctx == error_mark_node)
16589 return error_mark_node;
16591 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16592 complain, in_decl);
16593 if (f == error_mark_node)
16594 return error_mark_node;
16596 if (!MAYBE_CLASS_TYPE_P (ctx))
16598 if (complain & tf_error)
16599 error ("%qT is not a class, struct, or union type", ctx);
16600 return error_mark_node;
16602 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16604 /* Normally, make_typename_type does not require that the CTX
16605 have complete type in order to allow things like:
16607 template <class T> struct S { typename S<T>::X Y; };
16609 But, such constructs have already been resolved by this
16610 point, so here CTX really should have complete type, unless
16611 it's a partial instantiation. */
16612 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16613 return error_mark_node;
16616 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16617 tags. TYPENAME_TYPE should probably remember the exact tag that
16618 was written. */
16619 enum tag_types tag_type
16620 = TYPENAME_IS_CLASS_P (t) ? class_type
16621 : TYPENAME_IS_ENUM_P (t) ? enum_type
16622 : typename_type;
16623 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16624 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16625 f = make_typename_type (ctx, f, tag_type, tcomplain);
16626 if (f == error_mark_node)
16627 return f;
16628 if (TREE_CODE (f) == TYPE_DECL)
16630 complain |= tf_ignore_bad_quals;
16631 f = TREE_TYPE (f);
16634 if (TREE_CODE (f) != TYPENAME_TYPE)
16636 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16638 if (complain & tf_error)
16639 error ("%qT resolves to %qT, which is not an enumeration type",
16640 t, f);
16641 else
16642 return error_mark_node;
16644 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16646 if (complain & tf_error)
16647 error ("%qT resolves to %qT, which is not a class type",
16648 t, f);
16649 else
16650 return error_mark_node;
16654 return cp_build_qualified_type
16655 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16658 case UNBOUND_CLASS_TEMPLATE:
16660 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16661 in_decl, /*entering_scope=*/1);
16662 tree name = TYPE_IDENTIFIER (t);
16663 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16665 if (ctx == error_mark_node || name == error_mark_node)
16666 return error_mark_node;
16668 if (parm_list)
16669 parm_list = tsubst_template_parms (parm_list, args, complain);
16670 return make_unbound_class_template (ctx, name, parm_list, complain);
16673 case TYPEOF_TYPE:
16675 tree type;
16677 ++cp_unevaluated_operand;
16678 ++c_inhibit_evaluation_warnings;
16680 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16682 --cp_unevaluated_operand;
16683 --c_inhibit_evaluation_warnings;
16685 type = finish_typeof (type);
16686 return cp_build_qualified_type (type,
16687 cp_type_quals (t)
16688 | cp_type_quals (type),
16689 complain);
16692 case DECLTYPE_TYPE:
16694 tree type;
16696 ++cp_unevaluated_operand;
16697 ++c_inhibit_evaluation_warnings;
16699 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16700 complain|tf_decltype, in_decl);
16702 --cp_unevaluated_operand;
16703 --c_inhibit_evaluation_warnings;
16705 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16706 type = lambda_capture_field_type (type,
16707 false /*explicit_init*/,
16708 DECLTYPE_FOR_REF_CAPTURE (t));
16709 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16710 type = lambda_proxy_type (type);
16711 else
16713 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16714 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16715 && EXPR_P (type))
16716 /* In a template ~id could be either a complement expression
16717 or an unqualified-id naming a destructor; if instantiating
16718 it produces an expression, it's not an id-expression or
16719 member access. */
16720 id = false;
16721 type = finish_decltype_type (type, id, complain);
16723 return cp_build_qualified_type (type,
16724 cp_type_quals (t)
16725 | cp_type_quals (type),
16726 complain | tf_ignore_bad_quals);
16729 case TRAIT_TYPE:
16731 tree type1 = TRAIT_TYPE_TYPE1 (t);
16732 if (TYPE_P (type1))
16733 type1 = tsubst (type1, args, complain, in_decl);
16734 else
16735 type1 = tsubst_copy_and_build (type1, args, complain, in_decl);
16736 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16737 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16738 return cp_build_qualified_type (type,
16739 cp_type_quals (t) | cp_type_quals (type),
16740 complain | tf_ignore_bad_quals);
16743 case TYPE_ARGUMENT_PACK:
16744 case NONTYPE_ARGUMENT_PACK:
16745 return tsubst_argument_pack (t, args, complain, in_decl);
16747 case VOID_CST:
16748 case INTEGER_CST:
16749 case REAL_CST:
16750 case STRING_CST:
16751 case PLUS_EXPR:
16752 case MINUS_EXPR:
16753 case NEGATE_EXPR:
16754 case NOP_EXPR:
16755 case INDIRECT_REF:
16756 case ADDR_EXPR:
16757 case CALL_EXPR:
16758 case ARRAY_REF:
16759 case SCOPE_REF:
16760 /* We should use one of the expression tsubsts for these codes. */
16761 gcc_unreachable ();
16763 default:
16764 sorry ("use of %qs in template", get_tree_code_name (code));
16765 return error_mark_node;
16769 /* Convenience wrapper over tsubst for substituting into the LHS
16770 of the :: scope resolution operator. */
16772 static tree
16773 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16775 gcc_checking_assert (TYPE_P (t));
16776 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16779 /* OLDFNS is a lookup set of member functions from some class template, and
16780 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16781 of that class template. Return the subset of NEWFNS which are
16782 specializations of a function from OLDFNS. */
16784 static tree
16785 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16787 /* Record all member functions from the old lookup set OLDFNS into
16788 VISIBLE_SET. */
16789 hash_set<tree> visible_set;
16790 bool seen_dep_using = false;
16791 for (tree fn : lkp_range (oldfns))
16793 if (TREE_CODE (fn) == USING_DECL)
16795 /* Imprecisely handle dependent using-decl by keeping all members
16796 in the new lookup set that are defined in a base class, i.e.
16797 members that could plausibly have been introduced by this
16798 dependent using-decl.
16799 FIXME: Track which members are introduced by a dependent
16800 using-decl precisely, perhaps by performing another lookup
16801 from the substituted USING_DECL_SCOPE. */
16802 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16803 seen_dep_using = true;
16805 else
16806 visible_set.add (fn);
16809 /* Returns true iff (a less specialized version of) FN appeared in
16810 the old lookup set OLDFNS. */
16811 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16812 if (DECL_CONTEXT (fn) != newtype)
16813 /* FN is a member function from a base class, introduced via a
16814 using-decl; if it might have been introduced by a dependent
16815 using-decl then just conservatively keep it, otherwise look
16816 in the old lookup set for FN exactly. */
16817 return seen_dep_using || visible_set.contains (fn);
16818 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16819 /* FN is a member function template from the current class;
16820 look in the old lookup set for the TEMPLATE_DECL from which
16821 it was specialized. */
16822 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16823 else
16824 /* FN is a non-template member function from the current class;
16825 look in the old lookup set for the FUNCTION_DECL from which
16826 it was specialized. */
16827 return visible_set.contains (DECL_TEMPLATE_RESULT
16828 (DECL_TI_TEMPLATE (fn)));
16831 bool lookup_changed_p = false;
16832 for (tree fn : lkp_range (newfns))
16833 if (!visible_p (fn))
16835 lookup_changed_p = true;
16836 break;
16838 if (!lookup_changed_p)
16839 return newfns;
16841 /* Filter out from NEWFNS the member functions that weren't
16842 previously visible according to OLDFNS. */
16843 tree filtered_fns = NULL_TREE;
16844 unsigned filtered_size = 0;
16845 for (tree fn : lkp_range (newfns))
16846 if (visible_p (fn))
16848 filtered_fns = lookup_add (fn, filtered_fns);
16849 filtered_size++;
16851 gcc_checking_assert (seen_dep_using
16852 ? filtered_size >= visible_set.elements ()
16853 : filtered_size == visible_set.elements ());
16855 return filtered_fns;
16858 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16859 expression on the left-hand side of the "." or "->" operator. We
16860 only do the lookup if we had a dependent BASELINK. Otherwise we
16861 adjust it onto the instantiated heirarchy. */
16863 static tree
16864 tsubst_baselink (tree baselink, tree object_type,
16865 tree args, tsubst_flags_t complain, tree in_decl)
16867 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16868 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16869 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16871 tree optype = BASELINK_OPTYPE (baselink);
16872 optype = tsubst (optype, args, complain, in_decl);
16874 tree template_args = NULL_TREE;
16875 bool template_id_p = false;
16876 tree fns = BASELINK_FUNCTIONS (baselink);
16877 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16879 template_id_p = true;
16880 template_args = TREE_OPERAND (fns, 1);
16881 fns = TREE_OPERAND (fns, 0);
16882 if (template_args)
16883 template_args = tsubst_template_args (template_args, args,
16884 complain, in_decl);
16887 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16888 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16889 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16890 || optype != BASELINK_OPTYPE (baselink));
16892 if (dependent_p)
16894 tree name = OVL_NAME (fns);
16895 if (IDENTIFIER_CONV_OP_P (name))
16896 name = make_conv_op_name (optype);
16898 /* See maybe_dependent_member_ref. */
16899 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16901 if (template_id_p)
16902 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16903 template_args);
16904 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16905 /* ::template */false);
16908 if (name == complete_dtor_identifier)
16909 /* Treat as-if non-dependent below. */
16910 dependent_p = false;
16912 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16913 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16914 complain);
16915 if (maybe_incomplete)
16917 /* Filter out from the new lookup set those functions which didn't
16918 appear in the original lookup set (in a less specialized form).
16919 This is needed to preserve the consistency of member lookup
16920 performed in an incomplete-class context, within which
16921 later-declared members ought to remain invisible. */
16922 BASELINK_FUNCTIONS (baselink)
16923 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16924 binfo_type);
16925 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16928 if (!baselink)
16930 if ((complain & tf_error)
16931 && constructor_name_p (name, qualifying_scope))
16932 error ("cannot call constructor %<%T::%D%> directly",
16933 qualifying_scope, name);
16934 return error_mark_node;
16937 fns = BASELINK_FUNCTIONS (baselink);
16939 else
16941 /* We're going to overwrite pieces below, make a duplicate. */
16942 baselink = copy_node (baselink);
16944 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16946 /* The decl we found was from non-dependent scope, but we still need
16947 to update the binfos for the instantiated qualifying_scope. */
16948 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16949 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16950 ba_unique, nullptr, complain);
16954 /* If lookup found a single function, mark it as used at this point.
16955 (If lookup found multiple functions the one selected later by
16956 overload resolution will be marked as used at that point.) */
16957 if (!template_id_p && !really_overloaded_fn (fns))
16959 tree fn = OVL_FIRST (fns);
16960 bool ok = mark_used (fn, complain);
16961 if (!ok && !(complain & tf_error))
16962 return error_mark_node;
16963 if (ok && BASELINK_P (baselink))
16964 /* We might have instantiated an auto function. */
16965 TREE_TYPE (baselink) = TREE_TYPE (fn);
16968 if (BASELINK_P (baselink))
16970 /* Add back the template arguments, if present. */
16971 if (template_id_p)
16972 BASELINK_FUNCTIONS (baselink)
16973 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16975 /* Update the conversion operator type. */
16976 BASELINK_OPTYPE (baselink) = optype;
16979 if (!object_type)
16980 object_type = current_class_type;
16982 if (qualified_p || !dependent_p)
16984 baselink = adjust_result_of_qualified_name_lookup (baselink,
16985 qualifying_scope,
16986 object_type);
16987 if (!qualified_p)
16988 /* We need to call adjust_result_of_qualified_name_lookup in case the
16989 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16990 so that we still get virtual function binding. */
16991 BASELINK_QUALIFIED_P (baselink) = false;
16994 return baselink;
16997 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16998 true if the qualified-id will be a postfix-expression in-and-of
16999 itself; false if more of the postfix-expression follows the
17000 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
17001 of "&". */
17003 static tree
17004 tsubst_qualified_id (tree qualified_id, tree args,
17005 tsubst_flags_t complain, tree in_decl,
17006 bool done, bool address_p)
17008 tree expr;
17009 tree scope;
17010 tree name;
17011 bool is_template;
17012 tree template_args;
17013 location_t loc = EXPR_LOCATION (qualified_id);
17015 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
17017 /* Figure out what name to look up. */
17018 name = TREE_OPERAND (qualified_id, 1);
17019 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
17021 is_template = true;
17022 template_args = TREE_OPERAND (name, 1);
17023 if (template_args)
17024 template_args = tsubst_template_args (template_args, args,
17025 complain, in_decl);
17026 if (template_args == error_mark_node)
17027 return error_mark_node;
17028 name = TREE_OPERAND (name, 0);
17030 else
17032 is_template = false;
17033 template_args = NULL_TREE;
17036 /* Substitute into the qualifying scope. When there are no ARGS, we
17037 are just trying to simplify a non-dependent expression. In that
17038 case the qualifying scope may be dependent, and, in any case,
17039 substituting will not help. */
17040 scope = TREE_OPERAND (qualified_id, 0);
17041 if (args)
17043 scope = tsubst_scope (scope, args, complain, in_decl);
17044 expr = tsubst_copy (name, args, complain, in_decl);
17046 else
17047 expr = name;
17049 if (dependent_scope_p (scope))
17051 if (TREE_CODE (expr) == SCOPE_REF)
17052 /* We built one in tsubst_baselink. */
17053 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
17054 else
17056 if (is_template)
17057 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
17058 template_args);
17059 expr = build_qualified_name (NULL_TREE, scope, expr,
17060 QUALIFIED_NAME_IS_TEMPLATE
17061 (qualified_id));
17063 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17064 return expr;
17067 if (!BASELINK_P (name) && !DECL_P (expr))
17069 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17071 /* A BIT_NOT_EXPR is used to represent a destructor. */
17072 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17074 error ("qualifying type %qT does not match destructor name ~%qT",
17075 scope, TREE_OPERAND (expr, 0));
17076 expr = error_mark_node;
17078 else
17079 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17080 LOOK_want::NORMAL, false);
17082 else
17083 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17084 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17085 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17087 if (complain & tf_error)
17089 error ("dependent-name %qE is parsed as a non-type, but "
17090 "instantiation yields a type", qualified_id);
17091 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17093 return error_mark_node;
17097 if (DECL_P (expr))
17099 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17100 scope, complain))
17101 return error_mark_node;
17102 /* Remember that there was a reference to this entity. */
17103 if (!mark_used (expr, complain) && !(complain & tf_error))
17104 return error_mark_node;
17107 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17109 if (complain & tf_error)
17110 qualified_name_lookup_error (scope,
17111 TREE_OPERAND (qualified_id, 1),
17112 expr, input_location);
17113 return error_mark_node;
17116 if (is_template)
17118 /* We may be repeating a check already done during parsing, but
17119 if it was well-formed and passed then, it will pass again
17120 now, and if it didn't, we wouldn't have got here. The case
17121 we want to catch is when we couldn't tell then, and can now,
17122 namely when templ prior to substitution was an
17123 identifier. */
17124 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17125 return error_mark_node;
17127 if (variable_template_p (expr))
17128 expr = lookup_and_finish_template_variable (expr, template_args,
17129 complain);
17130 else
17131 expr = lookup_template_function (expr, template_args);
17134 if (expr == error_mark_node && complain & tf_error)
17135 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17136 expr, input_location);
17137 else if (TYPE_P (scope))
17139 expr = (adjust_result_of_qualified_name_lookup
17140 (expr, scope, current_nonlambda_class_type ()));
17141 expr = (finish_qualified_id_expr
17142 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17143 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17144 /*template_arg_p=*/false, complain));
17147 /* Expressions do not generally have reference type. */
17148 if (TREE_CODE (expr) != SCOPE_REF
17149 /* However, if we're about to form a pointer-to-member, we just
17150 want the referenced member referenced. */
17151 && TREE_CODE (expr) != OFFSET_REF)
17152 expr = convert_from_reference (expr);
17154 if (REF_PARENTHESIZED_P (qualified_id))
17155 expr = force_paren_expr (expr);
17157 expr = maybe_wrap_with_location (expr, loc);
17159 return expr;
17162 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17163 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17164 for tsubst. */
17166 static tree
17167 tsubst_init (tree init, tree decl, tree args,
17168 tsubst_flags_t complain, tree in_decl)
17170 if (!init)
17171 return NULL_TREE;
17173 init = tsubst_expr (init, args, complain, in_decl);
17175 tree type = TREE_TYPE (decl);
17177 if (!init && type != error_mark_node)
17179 if (tree auto_node = type_uses_auto (type))
17181 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17183 if (complain & tf_error)
17184 error ("initializer for %q#D expands to an empty list "
17185 "of expressions", decl);
17186 return error_mark_node;
17189 else if (!dependent_type_p (type))
17191 /* If we had an initializer but it
17192 instantiated to nothing,
17193 value-initialize the object. This will
17194 only occur when the initializer was a
17195 pack expansion where the parameter packs
17196 used in that expansion were of length
17197 zero. */
17198 init = build_value_init (type, complain);
17199 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17200 init = get_target_expr (init, complain);
17201 if (TREE_CODE (init) == TARGET_EXPR)
17202 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17206 return init;
17209 /* If T is a reference to a dependent member of the current instantiation C and
17210 we are trying to refer to that member in a partial instantiation of C,
17211 return a SCOPE_REF; otherwise, return NULL_TREE.
17213 This can happen when forming a C++17 deduction guide, as in PR96199. */
17215 static tree
17216 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17217 tree in_decl)
17219 if (!(complain & tf_dguide))
17220 return NULL_TREE;
17222 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17223 if (!decl || !DECL_P (decl))
17224 return NULL_TREE;
17226 tree ctx = context_for_name_lookup (decl);
17227 if (!CLASS_TYPE_P (ctx))
17228 return NULL_TREE;
17230 ctx = tsubst (ctx, args, complain, in_decl);
17231 if (!dependent_scope_p (ctx))
17232 return NULL_TREE;
17234 if (TYPE_P (t))
17236 if (typedef_variant_p (t))
17237 t = strip_typedefs (t);
17238 tree decl = TYPE_NAME (t);
17239 if (decl)
17240 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17241 if (!decl)
17242 return NULL_TREE;
17243 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17244 complain);
17247 tree name = DECL_NAME (t);
17248 tree fullname = name;
17249 if (instantiates_primary_template_p (t))
17251 tree tinfo = get_template_info (t);
17252 name = DECL_NAME (TI_TEMPLATE (tinfo));
17253 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17254 targs = tsubst_template_args (targs, args, complain, in_decl);
17255 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17258 if (TREE_CODE (t) == TYPE_DECL)
17260 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17261 && TYPE_NAME (TREE_TYPE (t)) == t)
17262 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17263 scope, but it doesn't need to be rewritten again. */
17264 return NULL_TREE;
17265 tree type = build_typename_type (ctx, name, fullname, typename_type);
17266 return TYPE_NAME (type);
17268 else if (DECL_TYPE_TEMPLATE_P (t))
17269 return make_unbound_class_template (ctx, name,
17270 NULL_TREE, complain);
17271 else
17272 return build_qualified_name (NULL_TREE, ctx, fullname,
17273 TREE_CODE (t) == TEMPLATE_DECL);
17276 /* Like tsubst, but deals with expressions. This function just replaces
17277 template parms; to finish processing the resultant expression, use
17278 tsubst_copy_and_build or tsubst_expr. */
17280 static tree
17281 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17283 enum tree_code code;
17284 tree r;
17286 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
17287 return t;
17289 if (TYPE_P (t))
17290 return tsubst (t, args, complain, in_decl);
17292 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
17293 return d;
17295 code = TREE_CODE (t);
17297 switch (code)
17299 case PARM_DECL:
17300 r = retrieve_local_specialization (t);
17302 if (r == NULL_TREE)
17304 /* We get here for a use of 'this' in an NSDMI. */
17305 if (DECL_NAME (t) == this_identifier && current_class_ptr)
17306 return current_class_ptr;
17308 /* This can happen for a parameter name used later in a function
17309 declaration (such as in a late-specified return type). Just
17310 make a dummy decl, since it's only used for its type. */
17311 gcc_assert (cp_unevaluated_operand);
17312 r = tsubst_decl (t, args, complain);
17313 /* Give it the template pattern as its context; its true context
17314 hasn't been instantiated yet and this is good enough for
17315 mangling. */
17316 DECL_CONTEXT (r) = DECL_CONTEXT (t);
17319 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17320 r = argument_pack_select_arg (r);
17321 if (!mark_used (r, complain) && !(complain & tf_error))
17322 return error_mark_node;
17323 return r;
17325 case CONST_DECL:
17327 tree enum_type;
17328 tree v;
17330 if (DECL_TEMPLATE_PARM_P (t))
17331 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17332 if (!uses_template_parms (DECL_CONTEXT (t)))
17333 return t;
17335 /* Unfortunately, we cannot just call lookup_name here.
17336 Consider:
17338 template <int I> int f() {
17339 enum E { a = I };
17340 struct S { void g() { E e = a; } };
17343 When we instantiate f<7>::S::g(), say, lookup_name is not
17344 clever enough to find f<7>::a. */
17345 enum_type
17346 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17347 /*entering_scope=*/0);
17349 for (v = TYPE_VALUES (enum_type);
17350 v != NULL_TREE;
17351 v = TREE_CHAIN (v))
17352 if (TREE_PURPOSE (v) == DECL_NAME (t))
17353 return TREE_VALUE (v);
17355 /* We didn't find the name. That should never happen; if
17356 name-lookup found it during preliminary parsing, we
17357 should find it again here during instantiation. */
17358 gcc_unreachable ();
17360 return t;
17362 case FIELD_DECL:
17363 if (DECL_CONTEXT (t))
17365 tree ctx;
17367 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17368 /*entering_scope=*/1);
17369 if (ctx != DECL_CONTEXT (t))
17371 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17372 if (!r)
17374 if (complain & tf_error)
17375 error ("using invalid field %qD", t);
17376 return error_mark_node;
17378 return r;
17382 return t;
17384 case VAR_DECL:
17385 case FUNCTION_DECL:
17386 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17387 r = tsubst (t, args, complain, in_decl);
17388 else if (DECL_LOCAL_DECL_P (t))
17390 /* Local specialization will usually have been created when
17391 we instantiated the DECL_EXPR_DECL. */
17392 r = retrieve_local_specialization (t);
17393 if (!r)
17395 /* We're in a generic lambda referencing a local extern
17396 from an outer block-scope of a non-template. */
17397 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17398 r = t;
17401 else if (local_variable_p (t)
17402 && uses_template_parms (DECL_CONTEXT (t)))
17404 r = retrieve_local_specialization (t);
17405 if (r == NULL_TREE)
17407 /* First try name lookup to find the instantiation. */
17408 r = lookup_name (DECL_NAME (t));
17409 if (r)
17411 if (!VAR_P (r))
17413 /* During error-recovery we may find a non-variable,
17414 even an OVERLOAD: just bail out and avoid ICEs and
17415 duplicate diagnostics (c++/62207). */
17416 gcc_assert (seen_error ());
17417 return error_mark_node;
17419 if (!is_capture_proxy (r))
17421 /* Make sure the one we found is the one we want. */
17422 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17423 if (ctx != DECL_CONTEXT (r))
17424 r = NULL_TREE;
17428 if (r)
17429 /* OK */;
17430 else
17432 /* This can happen for a variable used in a
17433 late-specified return type of a local lambda, or for a
17434 local static or constant. Building a new VAR_DECL
17435 should be OK in all those cases. */
17436 r = tsubst_decl (t, args, complain);
17437 if (local_specializations)
17438 /* Avoid infinite recursion (79640). */
17439 register_local_specialization (r, t);
17440 if (decl_maybe_constant_var_p (r))
17442 /* We can't call cp_finish_decl, so handle the
17443 initializer by hand. */
17444 tree init = tsubst_init (DECL_INITIAL (t), r, args,
17445 complain, in_decl);
17446 if (!processing_template_decl)
17447 init = maybe_constant_init (init);
17448 if (processing_template_decl
17449 ? potential_constant_expression (init)
17450 : reduced_constant_expression_p (init))
17451 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17452 = TREE_CONSTANT (r) = true;
17453 DECL_INITIAL (r) = init;
17454 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17455 TREE_TYPE (r)
17456 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17457 complain, adc_variable_type);
17459 gcc_assert (cp_unevaluated_operand
17460 || processing_contract_condition
17461 || TREE_STATIC (r)
17462 || decl_constant_var_p (r)
17463 || seen_error ());
17464 if (!processing_template_decl
17465 && !TREE_STATIC (r))
17466 r = process_outer_var_ref (r, complain);
17468 /* Remember this for subsequent uses. */
17469 if (local_specializations)
17470 register_local_specialization (r, t);
17472 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17473 r = argument_pack_select_arg (r);
17475 else
17476 r = t;
17477 if (!mark_used (r, complain))
17478 return error_mark_node;
17479 return r;
17481 case NAMESPACE_DECL:
17482 return t;
17484 case OVERLOAD:
17485 return t;
17487 case BASELINK:
17488 return tsubst_baselink (t, current_nonlambda_class_type (),
17489 args, complain, in_decl);
17491 case TEMPLATE_DECL:
17492 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17493 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17494 args, complain, in_decl);
17495 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17496 return tsubst (t, args, complain, in_decl);
17497 else if (DECL_CLASS_SCOPE_P (t)
17498 && uses_template_parms (DECL_CONTEXT (t)))
17500 /* Template template argument like the following example need
17501 special treatment:
17503 template <template <class> class TT> struct C {};
17504 template <class T> struct D {
17505 template <class U> struct E {};
17506 C<E> c; // #1
17508 D<int> d; // #2
17510 We are processing the template argument `E' in #1 for
17511 the template instantiation #2. Originally, `E' is a
17512 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
17513 have to substitute this with one having context `D<int>'. */
17515 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
17516 in_decl, /*entering_scope=*/true);
17517 return lookup_field (context, DECL_NAME(t), 0, false);
17519 else
17520 /* Ordinary template template argument. */
17521 return t;
17523 case NON_LVALUE_EXPR:
17524 case VIEW_CONVERT_EXPR:
17526 /* Handle location wrappers by substituting the wrapped node
17527 first, *then* reusing the resulting type. Doing the type
17528 first ensures that we handle template parameters and
17529 parameter pack expansions. */
17530 if (location_wrapper_p (t))
17532 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17533 complain, in_decl);
17534 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17536 tree op = TREE_OPERAND (t, 0);
17537 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
17538 if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17540 op = tsubst_copy (op, args, complain, in_decl);
17541 op = build1 (code, TREE_TYPE (op), op);
17542 REF_PARENTHESIZED_P (op) = true;
17543 return op;
17545 /* We shouldn't see any other uses of these in templates
17546 (tsubst_copy_and_build handles C++20 tparm object wrappers). */
17547 gcc_unreachable ();
17550 case CAST_EXPR:
17551 case REINTERPRET_CAST_EXPR:
17552 case CONST_CAST_EXPR:
17553 case STATIC_CAST_EXPR:
17554 case DYNAMIC_CAST_EXPR:
17555 case IMPLICIT_CONV_EXPR:
17556 CASE_CONVERT:
17558 tsubst_flags_t tcomplain = complain;
17559 if (code == CAST_EXPR)
17560 tcomplain |= tf_tst_ok;
17561 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17562 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17563 return build1 (code, type, op0);
17566 case BIT_CAST_EXPR:
17568 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17569 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17570 r = build_min (BIT_CAST_EXPR, type, op0);
17571 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17572 return r;
17575 case SIZEOF_EXPR:
17576 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17577 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17579 tree expanded, op = TREE_OPERAND (t, 0);
17580 int len = 0;
17582 if (SIZEOF_EXPR_TYPE_P (t))
17583 op = TREE_TYPE (op);
17585 ++cp_unevaluated_operand;
17586 ++c_inhibit_evaluation_warnings;
17587 /* We only want to compute the number of arguments. */
17588 if (PACK_EXPANSION_P (op))
17589 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17590 else
17591 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17592 args, complain, in_decl);
17593 --cp_unevaluated_operand;
17594 --c_inhibit_evaluation_warnings;
17596 if (TREE_CODE (expanded) == TREE_VEC)
17598 len = TREE_VEC_LENGTH (expanded);
17599 /* Set TREE_USED for the benefit of -Wunused. */
17600 for (int i = 0; i < len; i++)
17601 if (DECL_P (TREE_VEC_ELT (expanded, i)))
17602 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17605 if (expanded == error_mark_node)
17606 return error_mark_node;
17607 else if (PACK_EXPANSION_P (expanded)
17608 || (TREE_CODE (expanded) == TREE_VEC
17609 && pack_expansion_args_count (expanded)))
17612 if (PACK_EXPANSION_P (expanded))
17613 /* OK. */;
17614 else if (TREE_VEC_LENGTH (expanded) == 1)
17615 expanded = TREE_VEC_ELT (expanded, 0);
17616 else
17617 expanded = make_argument_pack (expanded);
17619 if (TYPE_P (expanded))
17620 return cxx_sizeof_or_alignof_type (input_location,
17621 expanded, SIZEOF_EXPR,
17622 false,
17623 complain & tf_error);
17624 else
17625 return cxx_sizeof_or_alignof_expr (input_location,
17626 expanded, SIZEOF_EXPR,
17627 false,
17628 complain & tf_error);
17630 else
17631 return build_int_cst (size_type_node, len);
17633 if (SIZEOF_EXPR_TYPE_P (t))
17635 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17636 args, complain, in_decl);
17637 r = build1 (NOP_EXPR, r, error_mark_node);
17638 r = build1 (SIZEOF_EXPR,
17639 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17640 SIZEOF_EXPR_TYPE_P (r) = 1;
17641 return r;
17643 /* Fall through */
17645 case INDIRECT_REF:
17646 case NEGATE_EXPR:
17647 case TRUTH_NOT_EXPR:
17648 case BIT_NOT_EXPR:
17649 case ADDR_EXPR:
17650 case UNARY_PLUS_EXPR: /* Unary + */
17651 case ALIGNOF_EXPR:
17652 case AT_ENCODE_EXPR:
17653 case ARROW_EXPR:
17654 case THROW_EXPR:
17655 case TYPEID_EXPR:
17656 case REALPART_EXPR:
17657 case IMAGPART_EXPR:
17658 case PAREN_EXPR:
17660 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17661 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17662 r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17663 if (code == ALIGNOF_EXPR)
17664 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17665 /* For addresses of immediate functions ensure we have EXPR_LOCATION
17666 set for possible later diagnostics. */
17667 if (code == ADDR_EXPR
17668 && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17669 && TREE_CODE (op0) == FUNCTION_DECL
17670 && DECL_IMMEDIATE_FUNCTION_P (op0))
17671 SET_EXPR_LOCATION (r, input_location);
17672 return r;
17675 case EXCESS_PRECISION_EXPR:
17677 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17678 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17679 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
17681 gcc_checking_assert (same_type_p (type, TREE_TYPE (op0)));
17682 return op0;
17684 return build1_loc (EXPR_LOCATION (t), code, type, op0);
17687 case COMPONENT_REF:
17689 tree object;
17690 tree name;
17692 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17693 name = TREE_OPERAND (t, 1);
17694 if (TREE_CODE (name) == BIT_NOT_EXPR)
17696 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17697 complain, in_decl);
17698 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17700 else if (TREE_CODE (name) == SCOPE_REF
17701 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17703 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17704 complain, in_decl);
17705 name = TREE_OPERAND (name, 1);
17706 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17707 complain, in_decl);
17708 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17709 name = build_qualified_name (/*type=*/NULL_TREE,
17710 base, name,
17711 /*template_p=*/false);
17713 else if (BASELINK_P (name))
17714 name = tsubst_baselink (name,
17715 non_reference (TREE_TYPE (object)),
17716 args, complain,
17717 in_decl);
17718 else
17719 name = tsubst_copy (name, args, complain, in_decl);
17720 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17723 case PLUS_EXPR:
17724 case MINUS_EXPR:
17725 case MULT_EXPR:
17726 case TRUNC_DIV_EXPR:
17727 case CEIL_DIV_EXPR:
17728 case FLOOR_DIV_EXPR:
17729 case ROUND_DIV_EXPR:
17730 case EXACT_DIV_EXPR:
17731 case BIT_AND_EXPR:
17732 case BIT_IOR_EXPR:
17733 case BIT_XOR_EXPR:
17734 case TRUNC_MOD_EXPR:
17735 case FLOOR_MOD_EXPR:
17736 case TRUTH_ANDIF_EXPR:
17737 case TRUTH_ORIF_EXPR:
17738 case TRUTH_AND_EXPR:
17739 case TRUTH_OR_EXPR:
17740 case RSHIFT_EXPR:
17741 case LSHIFT_EXPR:
17742 case EQ_EXPR:
17743 case NE_EXPR:
17744 case MAX_EXPR:
17745 case MIN_EXPR:
17746 case LE_EXPR:
17747 case GE_EXPR:
17748 case LT_EXPR:
17749 case GT_EXPR:
17750 case COMPOUND_EXPR:
17751 case DOTSTAR_EXPR:
17752 case MEMBER_REF:
17753 case PREDECREMENT_EXPR:
17754 case PREINCREMENT_EXPR:
17755 case POSTDECREMENT_EXPR:
17756 case POSTINCREMENT_EXPR:
17758 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17759 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17760 return build_nt (code, op0, op1);
17763 case SCOPE_REF:
17765 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
17766 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17767 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17768 QUALIFIED_NAME_IS_TEMPLATE (t));
17771 case ARRAY_REF:
17773 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17774 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17775 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17778 case CALL_EXPR:
17780 int n = VL_EXP_OPERAND_LENGTH (t);
17781 tree result = build_vl_exp (CALL_EXPR, n);
17782 int i;
17783 for (i = 0; i < n; i++)
17784 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17785 complain, in_decl);
17786 return result;
17789 case COND_EXPR:
17790 case MODOP_EXPR:
17791 case PSEUDO_DTOR_EXPR:
17792 case VEC_PERM_EXPR:
17794 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17795 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17796 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17797 r = build_nt (code, op0, op1, op2);
17798 copy_warning (r, t);
17799 return r;
17802 case NEW_EXPR:
17804 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17805 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17806 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17807 r = build_nt (code, op0, op1, op2);
17808 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17809 return r;
17812 case DELETE_EXPR:
17814 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17815 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17816 r = build_nt (code, op0, op1);
17817 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17818 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17819 return r;
17822 case TEMPLATE_ID_EXPR:
17824 /* Substituted template arguments */
17825 tree tmpl = TREE_OPERAND (t, 0);
17826 tree targs = TREE_OPERAND (t, 1);
17828 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17829 if (targs)
17830 targs = tsubst_template_args (targs, args, complain, in_decl);
17832 if (variable_template_p (tmpl))
17833 return lookup_template_variable (tmpl, targs, complain);
17834 else
17835 return lookup_template_function (tmpl, targs);
17838 case TREE_LIST:
17840 tree purpose, value, chain;
17842 if (t == void_list_node)
17843 return t;
17845 purpose = TREE_PURPOSE (t);
17846 if (purpose)
17847 purpose = tsubst_copy (purpose, args, complain, in_decl);
17848 value = TREE_VALUE (t);
17849 if (value)
17850 value = tsubst_copy (value, args, complain, in_decl);
17851 chain = TREE_CHAIN (t);
17852 if (chain && chain != void_type_node)
17853 chain = tsubst_copy (chain, args, complain, in_decl);
17854 if (purpose == TREE_PURPOSE (t)
17855 && value == TREE_VALUE (t)
17856 && chain == TREE_CHAIN (t))
17857 return t;
17858 return tree_cons (purpose, value, chain);
17861 case TEMPLATE_PARM_INDEX:
17862 case TYPE_DECL:
17863 return tsubst (t, args, complain, in_decl);
17865 case USING_DECL:
17866 t = DECL_NAME (t);
17867 /* Fall through. */
17868 case IDENTIFIER_NODE:
17869 if (IDENTIFIER_CONV_OP_P (t))
17871 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17872 return make_conv_op_name (new_type);
17874 else
17875 return t;
17877 case CONSTRUCTOR:
17878 /* This is handled by tsubst_copy_and_build. */
17879 gcc_unreachable ();
17881 case VA_ARG_EXPR:
17883 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17884 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17885 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17888 case CLEANUP_POINT_EXPR:
17889 /* We shouldn't have built any of these during initial template
17890 generation. Instead, they should be built during instantiation
17891 in response to the saved STMT_IS_FULL_EXPR_P setting. */
17892 gcc_unreachable ();
17894 case OFFSET_REF:
17896 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17897 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17898 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17899 r = build2 (code, type, op0, op1);
17900 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17901 if (!mark_used (TREE_OPERAND (r, 1), complain)
17902 && !(complain & tf_error))
17903 return error_mark_node;
17904 return r;
17907 case EXPR_PACK_EXPANSION:
17908 error ("invalid use of pack expansion expression");
17909 return error_mark_node;
17911 case NONTYPE_ARGUMENT_PACK:
17912 error ("use %<...%> to expand argument pack");
17913 return error_mark_node;
17915 case VOID_CST:
17916 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17917 return t;
17919 case INTEGER_CST:
17920 case REAL_CST:
17921 case COMPLEX_CST:
17922 case VECTOR_CST:
17924 /* Instantiate any typedefs in the type. */
17925 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17926 r = fold_convert (type, t);
17927 gcc_assert (TREE_CODE (r) == code);
17928 return r;
17931 case STRING_CST:
17933 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17934 r = t;
17935 if (type != TREE_TYPE (t))
17937 r = copy_node (t);
17938 TREE_TYPE (r) = type;
17940 return r;
17943 case PTRMEM_CST:
17944 /* These can sometimes show up in a partial instantiation, but never
17945 involve template parms. */
17946 gcc_assert (!uses_template_parms (t));
17947 return t;
17949 case UNARY_LEFT_FOLD_EXPR:
17950 return tsubst_unary_left_fold (t, args, complain, in_decl);
17951 case UNARY_RIGHT_FOLD_EXPR:
17952 return tsubst_unary_right_fold (t, args, complain, in_decl);
17953 case BINARY_LEFT_FOLD_EXPR:
17954 return tsubst_binary_left_fold (t, args, complain, in_decl);
17955 case BINARY_RIGHT_FOLD_EXPR:
17956 return tsubst_binary_right_fold (t, args, complain, in_decl);
17957 case PREDICT_EXPR:
17958 return t;
17960 case DEBUG_BEGIN_STMT:
17961 /* ??? There's no point in copying it for now, but maybe some
17962 day it will contain more information, such as a pointer back
17963 to the containing function, inlined copy or so. */
17964 return t;
17966 case CO_AWAIT_EXPR:
17967 return tsubst_expr (t, args, complain, in_decl);
17969 default:
17970 /* We shouldn't get here, but keep going if !flag_checking. */
17971 if (flag_checking)
17972 gcc_unreachable ();
17973 return t;
17977 /* Helper function for tsubst_omp_clauses, used for instantiation of
17978 OMP_CLAUSE_DECL of clauses. */
17980 static tree
17981 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17982 tree in_decl, tree *iterator_cache)
17984 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17985 return decl;
17987 /* Handle OpenMP iterators. */
17988 if (TREE_CODE (decl) == TREE_LIST
17989 && TREE_PURPOSE (decl)
17990 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17992 tree ret;
17993 if (iterator_cache[0] == TREE_PURPOSE (decl))
17994 ret = iterator_cache[1];
17995 else
17997 tree *tp = &ret;
17998 begin_scope (sk_omp, NULL);
17999 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
18001 *tp = copy_node (it);
18002 TREE_VEC_ELT (*tp, 0)
18003 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
18004 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
18005 pushdecl (TREE_VEC_ELT (*tp, 0));
18006 TREE_VEC_ELT (*tp, 1)
18007 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl);
18008 TREE_VEC_ELT (*tp, 2)
18009 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl);
18010 TREE_VEC_ELT (*tp, 3)
18011 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl);
18012 TREE_CHAIN (*tp) = NULL_TREE;
18013 tp = &TREE_CHAIN (*tp);
18015 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
18016 iterator_cache[0] = TREE_PURPOSE (decl);
18017 iterator_cache[1] = ret;
18019 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
18020 args, complain,
18021 in_decl, NULL));
18024 /* Handle an OpenMP array section represented as a TREE_LIST (or
18025 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
18026 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
18027 TREE_LIST. We can handle it exactly the same as an array section
18028 (purpose, value, and a chain), even though the nomenclature
18029 (low_bound, length, etc) is different. */
18030 if (TREE_CODE (decl) == TREE_LIST)
18032 tree low_bound
18033 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl);
18034 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl);
18035 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
18036 in_decl, NULL);
18037 if (TREE_PURPOSE (decl) == low_bound
18038 && TREE_VALUE (decl) == length
18039 && TREE_CHAIN (decl) == chain)
18040 return decl;
18041 tree ret = tree_cons (low_bound, length, chain);
18042 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
18043 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
18044 return ret;
18046 tree ret = tsubst_expr (decl, args, complain, in_decl);
18047 /* Undo convert_from_reference tsubst_expr could have called. */
18048 if (decl
18049 && REFERENCE_REF_P (ret)
18050 && !REFERENCE_REF_P (decl))
18051 ret = TREE_OPERAND (ret, 0);
18052 return ret;
18055 /* Like tsubst_copy, but specifically for OpenMP clauses. */
18057 static tree
18058 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
18059 tree args, tsubst_flags_t complain, tree in_decl)
18061 tree new_clauses = NULL_TREE, nc, oc;
18062 tree linear_no_step = NULL_TREE;
18063 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
18065 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
18067 nc = copy_node (oc);
18068 OMP_CLAUSE_CHAIN (nc) = new_clauses;
18069 new_clauses = nc;
18071 switch (OMP_CLAUSE_CODE (nc))
18073 case OMP_CLAUSE_LASTPRIVATE:
18074 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
18076 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
18077 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
18078 complain, in_decl);
18079 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
18080 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
18082 /* FALLTHRU */
18083 case OMP_CLAUSE_PRIVATE:
18084 case OMP_CLAUSE_SHARED:
18085 case OMP_CLAUSE_FIRSTPRIVATE:
18086 case OMP_CLAUSE_COPYIN:
18087 case OMP_CLAUSE_COPYPRIVATE:
18088 case OMP_CLAUSE_UNIFORM:
18089 case OMP_CLAUSE_DEPEND:
18090 case OMP_CLAUSE_DOACROSS:
18091 case OMP_CLAUSE_AFFINITY:
18092 case OMP_CLAUSE_FROM:
18093 case OMP_CLAUSE_TO:
18094 case OMP_CLAUSE_MAP:
18095 case OMP_CLAUSE__CACHE_:
18096 case OMP_CLAUSE_NONTEMPORAL:
18097 case OMP_CLAUSE_USE_DEVICE_PTR:
18098 case OMP_CLAUSE_USE_DEVICE_ADDR:
18099 case OMP_CLAUSE_IS_DEVICE_PTR:
18100 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18101 case OMP_CLAUSE_INCLUSIVE:
18102 case OMP_CLAUSE_EXCLUSIVE:
18103 OMP_CLAUSE_DECL (nc)
18104 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18105 in_decl, iterator_cache);
18106 break;
18107 case OMP_CLAUSE_NUM_TEAMS:
18108 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
18109 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
18110 = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
18111 complain, in_decl);
18112 /* FALLTHRU */
18113 case OMP_CLAUSE_TILE:
18114 case OMP_CLAUSE_IF:
18115 case OMP_CLAUSE_NUM_THREADS:
18116 case OMP_CLAUSE_SCHEDULE:
18117 case OMP_CLAUSE_COLLAPSE:
18118 case OMP_CLAUSE_FINAL:
18119 case OMP_CLAUSE_DEVICE:
18120 case OMP_CLAUSE_DIST_SCHEDULE:
18121 case OMP_CLAUSE_THREAD_LIMIT:
18122 case OMP_CLAUSE_SAFELEN:
18123 case OMP_CLAUSE_SIMDLEN:
18124 case OMP_CLAUSE_NUM_TASKS:
18125 case OMP_CLAUSE_GRAINSIZE:
18126 case OMP_CLAUSE_PRIORITY:
18127 case OMP_CLAUSE_ORDERED:
18128 case OMP_CLAUSE_HINT:
18129 case OMP_CLAUSE_FILTER:
18130 case OMP_CLAUSE_NUM_GANGS:
18131 case OMP_CLAUSE_NUM_WORKERS:
18132 case OMP_CLAUSE_VECTOR_LENGTH:
18133 case OMP_CLAUSE_WORKER:
18134 case OMP_CLAUSE_VECTOR:
18135 case OMP_CLAUSE_ASYNC:
18136 case OMP_CLAUSE_WAIT:
18137 case OMP_CLAUSE_DETACH:
18138 OMP_CLAUSE_OPERAND (nc, 0)
18139 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
18140 break;
18141 case OMP_CLAUSE_REDUCTION:
18142 case OMP_CLAUSE_IN_REDUCTION:
18143 case OMP_CLAUSE_TASK_REDUCTION:
18144 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
18146 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
18147 if (TREE_CODE (placeholder) == SCOPE_REF)
18149 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
18150 complain, in_decl);
18151 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
18152 = build_qualified_name (NULL_TREE, scope,
18153 TREE_OPERAND (placeholder, 1),
18154 false);
18156 else
18157 gcc_assert (identifier_p (placeholder));
18159 OMP_CLAUSE_DECL (nc)
18160 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18161 in_decl, NULL);
18162 break;
18163 case OMP_CLAUSE_GANG:
18164 case OMP_CLAUSE_ALIGNED:
18165 OMP_CLAUSE_DECL (nc)
18166 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18167 in_decl, NULL);
18168 OMP_CLAUSE_OPERAND (nc, 1)
18169 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18170 break;
18171 case OMP_CLAUSE_ALLOCATE:
18172 OMP_CLAUSE_DECL (nc)
18173 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18174 in_decl, NULL);
18175 OMP_CLAUSE_OPERAND (nc, 1)
18176 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18177 OMP_CLAUSE_OPERAND (nc, 2)
18178 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
18179 break;
18180 case OMP_CLAUSE_LINEAR:
18181 OMP_CLAUSE_DECL (nc)
18182 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18183 in_decl, NULL);
18184 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
18186 gcc_assert (!linear_no_step);
18187 linear_no_step = nc;
18189 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
18190 OMP_CLAUSE_LINEAR_STEP (nc)
18191 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
18192 complain, in_decl, NULL);
18193 else
18194 OMP_CLAUSE_LINEAR_STEP (nc)
18195 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args,
18196 complain, in_decl);
18197 break;
18198 case OMP_CLAUSE_NOWAIT:
18199 case OMP_CLAUSE_DEFAULT:
18200 case OMP_CLAUSE_UNTIED:
18201 case OMP_CLAUSE_MERGEABLE:
18202 case OMP_CLAUSE_INBRANCH:
18203 case OMP_CLAUSE_NOTINBRANCH:
18204 case OMP_CLAUSE_PROC_BIND:
18205 case OMP_CLAUSE_FOR:
18206 case OMP_CLAUSE_PARALLEL:
18207 case OMP_CLAUSE_SECTIONS:
18208 case OMP_CLAUSE_TASKGROUP:
18209 case OMP_CLAUSE_NOGROUP:
18210 case OMP_CLAUSE_THREADS:
18211 case OMP_CLAUSE_SIMD:
18212 case OMP_CLAUSE_DEFAULTMAP:
18213 case OMP_CLAUSE_ORDER:
18214 case OMP_CLAUSE_BIND:
18215 case OMP_CLAUSE_INDEPENDENT:
18216 case OMP_CLAUSE_AUTO:
18217 case OMP_CLAUSE_SEQ:
18218 case OMP_CLAUSE_IF_PRESENT:
18219 case OMP_CLAUSE_FINALIZE:
18220 case OMP_CLAUSE_NOHOST:
18221 break;
18222 default:
18223 gcc_unreachable ();
18225 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
18226 switch (OMP_CLAUSE_CODE (nc))
18228 case OMP_CLAUSE_SHARED:
18229 case OMP_CLAUSE_PRIVATE:
18230 case OMP_CLAUSE_FIRSTPRIVATE:
18231 case OMP_CLAUSE_LASTPRIVATE:
18232 case OMP_CLAUSE_COPYPRIVATE:
18233 case OMP_CLAUSE_LINEAR:
18234 case OMP_CLAUSE_REDUCTION:
18235 case OMP_CLAUSE_IN_REDUCTION:
18236 case OMP_CLAUSE_TASK_REDUCTION:
18237 case OMP_CLAUSE_USE_DEVICE_PTR:
18238 case OMP_CLAUSE_USE_DEVICE_ADDR:
18239 case OMP_CLAUSE_IS_DEVICE_PTR:
18240 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18241 case OMP_CLAUSE_INCLUSIVE:
18242 case OMP_CLAUSE_EXCLUSIVE:
18243 case OMP_CLAUSE_ALLOCATE:
18244 /* tsubst_expr on SCOPE_REF results in returning
18245 finish_non_static_data_member result. Undo that here. */
18246 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
18247 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
18248 == IDENTIFIER_NODE))
18250 tree t = OMP_CLAUSE_DECL (nc);
18251 tree v = t;
18252 while (v)
18253 switch (TREE_CODE (v))
18255 case COMPONENT_REF:
18256 case MEM_REF:
18257 case INDIRECT_REF:
18258 CASE_CONVERT:
18259 case POINTER_PLUS_EXPR:
18260 v = TREE_OPERAND (v, 0);
18261 continue;
18262 case PARM_DECL:
18263 if (DECL_CONTEXT (v) == current_function_decl
18264 && DECL_ARTIFICIAL (v)
18265 && DECL_NAME (v) == this_identifier)
18266 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18267 /* FALLTHRU */
18268 default:
18269 v = NULL_TREE;
18270 break;
18273 else if (VAR_P (OMP_CLAUSE_DECL (oc))
18274 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18275 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18276 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18277 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18279 tree decl = OMP_CLAUSE_DECL (nc);
18280 if (VAR_P (decl))
18282 retrofit_lang_decl (decl);
18283 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18286 break;
18287 default:
18288 break;
18292 new_clauses = nreverse (new_clauses);
18293 if (ort != C_ORT_OMP_DECLARE_SIMD)
18295 new_clauses = finish_omp_clauses (new_clauses, ort);
18296 if (linear_no_step)
18297 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18298 if (nc == linear_no_step)
18300 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18301 break;
18304 return new_clauses;
18307 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
18309 static tree
18310 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18311 tree in_decl)
18313 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18315 tree purpose, value, chain;
18317 if (t == NULL)
18318 return t;
18320 if (TREE_CODE (t) != TREE_LIST)
18321 return tsubst_copy_and_build (t, args, complain, in_decl);
18323 if (t == void_list_node)
18324 return t;
18326 purpose = TREE_PURPOSE (t);
18327 if (purpose)
18328 purpose = RECUR (purpose);
18329 value = TREE_VALUE (t);
18330 if (value)
18332 if (TREE_CODE (value) != LABEL_DECL)
18333 value = RECUR (value);
18334 else
18336 value = lookup_label (DECL_NAME (value));
18337 gcc_assert (TREE_CODE (value) == LABEL_DECL);
18338 TREE_USED (value) = 1;
18341 chain = TREE_CHAIN (t);
18342 if (chain && chain != void_type_node)
18343 chain = RECUR (chain);
18344 return tree_cons (purpose, value, chain);
18345 #undef RECUR
18348 /* Used to temporarily communicate the list of #pragma omp parallel
18349 clauses to #pragma omp for instantiation if they are combined
18350 together. */
18352 static tree *omp_parallel_combined_clauses;
18354 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18355 tree *, unsigned int *);
18357 /* Substitute one OMP_FOR iterator. */
18359 static bool
18360 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18361 tree initv, tree condv, tree incrv, tree *clauses,
18362 tree args, tsubst_flags_t complain, tree in_decl)
18364 #define RECUR(NODE) \
18365 tsubst_expr ((NODE), args, complain, in_decl)
18366 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18367 bool ret = false;
18369 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18370 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18372 decl = TREE_OPERAND (init, 0);
18373 init = TREE_OPERAND (init, 1);
18374 tree decl_expr = NULL_TREE;
18375 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18376 if (range_for)
18378 bool decomp = false;
18379 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18381 tree v = DECL_VALUE_EXPR (decl);
18382 if (TREE_CODE (v) == ARRAY_REF
18383 && VAR_P (TREE_OPERAND (v, 0))
18384 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18386 tree decomp_first = NULL_TREE;
18387 unsigned decomp_cnt = 0;
18388 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18389 maybe_push_decl (d);
18390 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18391 in_decl, &decomp_first, &decomp_cnt);
18392 decomp = true;
18393 if (d == error_mark_node)
18394 decl = error_mark_node;
18395 else
18396 for (unsigned int i = 0; i < decomp_cnt; i++)
18398 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18400 tree v = build_nt (ARRAY_REF, d,
18401 size_int (decomp_cnt - i - 1),
18402 NULL_TREE, NULL_TREE);
18403 SET_DECL_VALUE_EXPR (decomp_first, v);
18404 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18406 fit_decomposition_lang_decl (decomp_first, d);
18407 decomp_first = DECL_CHAIN (decomp_first);
18411 decl = tsubst_decl (decl, args, complain);
18412 if (!decomp)
18413 maybe_push_decl (decl);
18415 else if (init && TREE_CODE (init) == DECL_EXPR)
18417 /* We need to jump through some hoops to handle declarations in the
18418 init-statement, since we might need to handle auto deduction,
18419 but we need to keep control of initialization. */
18420 decl_expr = init;
18421 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18422 decl = tsubst_decl (decl, args, complain);
18424 else
18426 if (TREE_CODE (decl) == SCOPE_REF)
18428 decl = RECUR (decl);
18429 if (TREE_CODE (decl) == COMPONENT_REF)
18431 tree v = decl;
18432 while (v)
18433 switch (TREE_CODE (v))
18435 case COMPONENT_REF:
18436 case MEM_REF:
18437 case INDIRECT_REF:
18438 CASE_CONVERT:
18439 case POINTER_PLUS_EXPR:
18440 v = TREE_OPERAND (v, 0);
18441 continue;
18442 case PARM_DECL:
18443 if (DECL_CONTEXT (v) == current_function_decl
18444 && DECL_ARTIFICIAL (v)
18445 && DECL_NAME (v) == this_identifier)
18447 decl = TREE_OPERAND (decl, 1);
18448 decl = omp_privatize_field (decl, false);
18450 /* FALLTHRU */
18451 default:
18452 v = NULL_TREE;
18453 break;
18457 else
18458 decl = RECUR (decl);
18460 if (init && TREE_CODE (init) == TREE_VEC)
18462 init = copy_node (init);
18463 TREE_VEC_ELT (init, 0)
18464 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18465 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18466 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18468 else
18469 init = RECUR (init);
18471 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18473 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18474 if (TREE_CODE (o) == TREE_LIST)
18475 TREE_VEC_ELT (orig_declv, i)
18476 = tree_cons (RECUR (TREE_PURPOSE (o)),
18477 RECUR (TREE_VALUE (o)),
18478 NULL_TREE);
18479 else
18480 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18483 if (range_for)
18485 tree this_pre_body = NULL_TREE;
18486 tree orig_init = NULL_TREE;
18487 tree orig_decl = NULL_TREE;
18488 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18489 orig_init, cond, incr);
18490 if (orig_decl)
18492 if (orig_declv == NULL_TREE)
18493 orig_declv = copy_node (declv);
18494 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18495 ret = true;
18497 else if (orig_declv)
18498 TREE_VEC_ELT (orig_declv, i) = decl;
18501 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18502 if (!range_for && auto_node && init)
18503 TREE_TYPE (decl)
18504 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18506 gcc_assert (!type_dependent_expression_p (decl));
18508 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18510 if (decl_expr)
18512 /* Declare the variable, but don't let that initialize it. */
18513 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18514 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18515 RECUR (decl_expr);
18516 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18519 if (!range_for)
18521 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18522 if (COMPARISON_CLASS_P (cond)
18523 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18525 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18526 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18527 TREE_VEC_ELT (rhs, 0)
18528 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18529 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18530 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18531 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18532 lhs, rhs);
18534 else
18535 cond = RECUR (cond);
18536 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18537 if (TREE_CODE (incr) == MODIFY_EXPR)
18539 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18540 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18541 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18542 NOP_EXPR, rhs, NULL_TREE, complain);
18544 else
18545 incr = RECUR (incr);
18546 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18547 TREE_VEC_ELT (orig_declv, i) = decl;
18549 TREE_VEC_ELT (declv, i) = decl;
18550 TREE_VEC_ELT (initv, i) = init;
18551 TREE_VEC_ELT (condv, i) = cond;
18552 TREE_VEC_ELT (incrv, i) = incr;
18553 return ret;
18556 if (decl_expr)
18558 /* Declare and initialize the variable. */
18559 RECUR (decl_expr);
18560 init = NULL_TREE;
18562 else if (init)
18564 tree *pc;
18565 int j;
18566 for (j = ((omp_parallel_combined_clauses == NULL
18567 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18569 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18571 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18572 && OMP_CLAUSE_DECL (*pc) == decl)
18573 break;
18574 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18575 && OMP_CLAUSE_DECL (*pc) == decl)
18577 if (j)
18578 break;
18579 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18580 tree c = *pc;
18581 *pc = OMP_CLAUSE_CHAIN (c);
18582 OMP_CLAUSE_CHAIN (c) = *clauses;
18583 *clauses = c;
18585 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18586 && OMP_CLAUSE_DECL (*pc) == decl)
18588 error ("iteration variable %qD should not be firstprivate",
18589 decl);
18590 *pc = OMP_CLAUSE_CHAIN (*pc);
18592 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18593 && OMP_CLAUSE_DECL (*pc) == decl)
18595 error ("iteration variable %qD should not be reduction",
18596 decl);
18597 *pc = OMP_CLAUSE_CHAIN (*pc);
18599 else
18600 pc = &OMP_CLAUSE_CHAIN (*pc);
18602 if (*pc)
18603 break;
18605 if (*pc == NULL_TREE)
18607 tree c = build_omp_clause (input_location,
18608 TREE_CODE (t) == OMP_LOOP
18609 ? OMP_CLAUSE_LASTPRIVATE
18610 : OMP_CLAUSE_PRIVATE);
18611 OMP_CLAUSE_DECL (c) = decl;
18612 c = finish_omp_clauses (c, C_ORT_OMP);
18613 if (c)
18615 OMP_CLAUSE_CHAIN (c) = *clauses;
18616 *clauses = c;
18620 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18621 if (COMPARISON_CLASS_P (cond))
18623 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18624 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18625 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18627 else
18628 cond = RECUR (cond);
18629 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18630 switch (TREE_CODE (incr))
18632 case PREINCREMENT_EXPR:
18633 case PREDECREMENT_EXPR:
18634 case POSTINCREMENT_EXPR:
18635 case POSTDECREMENT_EXPR:
18636 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18637 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18638 break;
18639 case MODIFY_EXPR:
18640 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18641 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18643 tree rhs = TREE_OPERAND (incr, 1);
18644 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18645 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18646 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18647 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18648 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18649 rhs0, rhs1));
18651 else
18652 incr = RECUR (incr);
18653 break;
18654 case MODOP_EXPR:
18655 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18656 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18658 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18659 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18660 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18661 TREE_TYPE (decl), lhs,
18662 RECUR (TREE_OPERAND (incr, 2))));
18664 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18665 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18666 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18668 tree rhs = TREE_OPERAND (incr, 2);
18669 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18670 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18671 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18672 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18673 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18674 rhs0, rhs1));
18676 else
18677 incr = RECUR (incr);
18678 break;
18679 default:
18680 incr = RECUR (incr);
18681 break;
18684 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18685 TREE_VEC_ELT (orig_declv, i) = decl;
18686 TREE_VEC_ELT (declv, i) = decl;
18687 TREE_VEC_ELT (initv, i) = init;
18688 TREE_VEC_ELT (condv, i) = cond;
18689 TREE_VEC_ELT (incrv, i) = incr;
18690 return false;
18691 #undef RECUR
18694 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18695 of OMP_TARGET's body. */
18697 static tree
18698 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18700 *walk_subtrees = 0;
18701 switch (TREE_CODE (*tp))
18703 case OMP_TEAMS:
18704 return *tp;
18705 case BIND_EXPR:
18706 case STATEMENT_LIST:
18707 *walk_subtrees = 1;
18708 break;
18709 default:
18710 break;
18712 return NULL_TREE;
18715 /* Helper function for tsubst_expr. For decomposition declaration
18716 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18717 also the corresponding decls representing the identifiers
18718 of the decomposition declaration. Return DECL if successful
18719 or error_mark_node otherwise, set *FIRST to the first decl
18720 in the list chained through DECL_CHAIN and *CNT to the number
18721 of such decls. */
18723 static tree
18724 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18725 tsubst_flags_t complain, tree in_decl, tree *first,
18726 unsigned int *cnt)
18728 tree decl2, decl3, prev = decl;
18729 *cnt = 0;
18730 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18731 for (decl2 = DECL_CHAIN (pattern_decl);
18732 decl2
18733 && VAR_P (decl2)
18734 && DECL_DECOMPOSITION_P (decl2)
18735 && DECL_NAME (decl2);
18736 decl2 = DECL_CHAIN (decl2))
18738 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18740 gcc_assert (errorcount);
18741 return error_mark_node;
18743 (*cnt)++;
18744 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18745 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18746 tree v = DECL_VALUE_EXPR (decl2);
18747 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18748 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18749 decl3 = tsubst (decl2, args, complain, in_decl);
18750 SET_DECL_VALUE_EXPR (decl2, v);
18751 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18752 if (VAR_P (decl3))
18753 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18754 else
18756 gcc_assert (errorcount);
18757 decl = error_mark_node;
18758 continue;
18760 maybe_push_decl (decl3);
18761 if (error_operand_p (decl3))
18762 decl = error_mark_node;
18763 else if (decl != error_mark_node
18764 && DECL_CHAIN (decl3) != prev
18765 && decl != prev)
18767 gcc_assert (errorcount);
18768 decl = error_mark_node;
18770 else
18771 prev = decl3;
18773 *first = prev;
18774 return decl;
18777 /* Return the proper local_specialization for init-capture pack DECL. */
18779 static tree
18780 lookup_init_capture_pack (tree decl)
18782 /* We handle normal pack captures by forwarding to the specialization of the
18783 captured parameter. We can't do that for pack init-captures; we need them
18784 to have their own local_specialization. We created the individual
18785 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18786 when we process the DECL_EXPR for the pack init-capture in the template.
18787 So, how do we find them? We don't know the capture proxy pack when
18788 building the individual resulting proxies, and we don't know the
18789 individual proxies when instantiating the pack. What we have in common is
18790 the FIELD_DECL.
18792 So...when we instantiate the FIELD_DECL, we stick the result in
18793 local_specializations. Then at the DECL_EXPR we look up that result, see
18794 how many elements it has, synthesize the names, and look them up. */
18796 tree cname = DECL_NAME (decl);
18797 tree val = DECL_VALUE_EXPR (decl);
18798 tree field = TREE_OPERAND (val, 1);
18799 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18800 tree fpack = retrieve_local_specialization (field);
18801 if (fpack == error_mark_node)
18802 return error_mark_node;
18804 int len = 1;
18805 tree vec = NULL_TREE;
18806 tree r = NULL_TREE;
18807 if (TREE_CODE (fpack) == TREE_VEC)
18809 len = TREE_VEC_LENGTH (fpack);
18810 vec = make_tree_vec (len);
18811 r = make_node (NONTYPE_ARGUMENT_PACK);
18812 ARGUMENT_PACK_ARGS (r) = vec;
18814 for (int i = 0; i < len; ++i)
18816 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18817 tree elt = lookup_name (ename);
18818 if (vec)
18819 TREE_VEC_ELT (vec, i) = elt;
18820 else
18821 r = elt;
18823 return r;
18826 /* T is an operand of a template tree being substituted. Return whether
18827 T is dependent such that we should suppress some warnings that would
18828 make sense if the substituted expression were written directly, like
18829 template <int I> bool f() { return I == 2; }
18830 We don't want to warn when instantiating f that comparing two constants
18831 always has the same value.
18833 This is a more limited concept of dependence than instantiation-dependent;
18834 here we don't care whether substitution could fail. */
18836 static bool
18837 dependent_operand_p (tree t)
18839 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18840 t = TREE_OPERAND (t, 0);
18841 ++processing_template_decl;
18842 bool r = (potential_constant_expression (t)
18843 ? value_dependent_expression_p (t)
18844 : type_dependent_expression_p (t));
18845 --processing_template_decl;
18846 return r;
18849 /* Like tsubst_copy for expressions, etc. but also does semantic
18850 processing. */
18852 tree
18853 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18855 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18856 #define RECUR(NODE) \
18857 tsubst_expr ((NODE), args, complain, in_decl)
18859 tree stmt, tmp;
18860 tree r;
18861 location_t loc;
18863 if (t == NULL_TREE || t == error_mark_node)
18864 return t;
18866 loc = input_location;
18867 if (location_t eloc = cp_expr_location (t))
18868 input_location = eloc;
18869 if (STATEMENT_CODE_P (TREE_CODE (t)))
18870 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18872 switch (TREE_CODE (t))
18874 case STATEMENT_LIST:
18876 for (tree stmt : tsi_range (t))
18877 RECUR (stmt);
18878 break;
18881 case CTOR_INITIALIZER:
18882 finish_mem_initializers (tsubst_initializer_list
18883 (TREE_OPERAND (t, 0), args));
18884 break;
18886 case RETURN_EXPR:
18887 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18888 break;
18890 case CO_RETURN_EXPR:
18891 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18892 break;
18894 case CO_YIELD_EXPR:
18895 stmt = finish_co_yield_expr (input_location,
18896 RECUR (TREE_OPERAND (t, 0)));
18897 RETURN (stmt);
18899 case CO_AWAIT_EXPR:
18900 stmt = finish_co_await_expr (input_location,
18901 RECUR (TREE_OPERAND (t, 0)));
18902 RETURN (stmt);
18904 case EXPR_STMT:
18905 tmp = RECUR (EXPR_STMT_EXPR (t));
18906 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18907 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18908 else
18909 finish_expr_stmt (tmp);
18910 break;
18912 case USING_STMT:
18913 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18914 break;
18916 case PRECONDITION_STMT:
18917 case POSTCONDITION_STMT:
18918 gcc_unreachable ();
18920 case ASSERTION_STMT:
18922 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18923 if (r != error_mark_node)
18924 add_stmt (r);
18925 RETURN (r);
18927 break;
18929 case DECL_EXPR:
18931 tree decl, pattern_decl;
18932 tree init;
18934 pattern_decl = decl = DECL_EXPR_DECL (t);
18935 if (TREE_CODE (decl) == LABEL_DECL)
18936 finish_label_decl (DECL_NAME (decl));
18937 else if (TREE_CODE (decl) == USING_DECL)
18939 tree scope = USING_DECL_SCOPE (decl);
18940 if (DECL_DEPENDENT_P (decl))
18942 scope = tsubst (scope, args, complain, in_decl);
18943 if (!MAYBE_CLASS_TYPE_P (scope)
18944 && TREE_CODE (scope) != ENUMERAL_TYPE)
18946 if (complain & tf_error)
18947 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18948 "class, namespace, or enumeration", scope);
18949 return error_mark_node;
18951 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18953 else
18955 /* This is a non-dependent using-decl, and we'll have
18956 used the names it found during template parsing. We do
18957 not want to do the lookup again, because we might not
18958 find the things we found then. */
18959 gcc_checking_assert (scope == tsubst (scope, args,
18960 complain, in_decl));
18961 /* We still need to push the bindings so that we can look up
18962 this name later. */
18963 push_using_decl_bindings (DECL_NAME (decl),
18964 USING_DECL_DECLS (decl));
18967 else if (is_capture_proxy (decl)
18968 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18970 /* We're in tsubst_lambda_expr, we've already inserted a new
18971 capture proxy, so look it up and register it. */
18972 tree inst;
18973 if (!DECL_PACK_P (decl))
18975 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18976 LOOK_want::HIDDEN_LAMBDA);
18977 gcc_assert (inst != decl && is_capture_proxy (inst));
18979 else if (is_normal_capture_proxy (decl))
18981 inst = (retrieve_local_specialization
18982 (DECL_CAPTURED_VARIABLE (decl)));
18983 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18984 || DECL_PACK_P (inst));
18986 else
18987 inst = lookup_init_capture_pack (decl);
18989 register_local_specialization (inst, decl);
18990 break;
18992 else if (DECL_PRETTY_FUNCTION_P (decl))
18993 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18994 DECL_NAME (decl),
18995 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18996 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18997 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18998 /* Don't copy the old closure; we'll create a new one in
18999 tsubst_lambda_expr. */
19000 break;
19001 else
19003 init = DECL_INITIAL (decl);
19004 decl = tsubst (decl, args, complain, in_decl);
19005 if (decl != error_mark_node)
19007 /* By marking the declaration as instantiated, we avoid
19008 trying to instantiate it. Since instantiate_decl can't
19009 handle local variables, and since we've already done
19010 all that needs to be done, that's the right thing to
19011 do. */
19012 if (VAR_P (decl))
19013 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19014 if (VAR_P (decl) && !DECL_NAME (decl)
19015 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
19016 /* Anonymous aggregates are a special case. */
19017 finish_anon_union (decl);
19018 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
19020 DECL_CONTEXT (decl) = current_function_decl;
19021 if (DECL_NAME (decl) == this_identifier)
19023 tree lam = DECL_CONTEXT (current_function_decl);
19024 lam = CLASSTYPE_LAMBDA_EXPR (lam);
19025 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
19027 insert_capture_proxy (decl);
19029 else if (DECL_IMPLICIT_TYPEDEF_P (t))
19030 /* We already did a pushtag. */;
19031 else if (VAR_OR_FUNCTION_DECL_P (decl)
19032 && DECL_LOCAL_DECL_P (decl))
19034 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
19035 DECL_CONTEXT (decl) = NULL_TREE;
19036 decl = pushdecl (decl);
19037 if (TREE_CODE (decl) == FUNCTION_DECL
19038 && DECL_OMP_DECLARE_REDUCTION_P (decl)
19039 && cp_check_omp_declare_reduction (decl))
19040 instantiate_body (pattern_decl, args, decl, true);
19042 else
19044 bool const_init = false;
19045 unsigned int cnt = 0;
19046 tree first = NULL_TREE, ndecl = error_mark_node;
19047 tree asmspec_tree = NULL_TREE;
19048 maybe_push_decl (decl);
19050 if (VAR_P (decl)
19051 && DECL_LANG_SPECIFIC (decl)
19052 && DECL_OMP_PRIVATIZED_MEMBER (decl))
19053 break;
19055 if (VAR_P (decl)
19056 && DECL_DECOMPOSITION_P (decl)
19057 && TREE_TYPE (pattern_decl) != error_mark_node)
19058 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
19059 complain, in_decl, &first,
19060 &cnt);
19062 init = tsubst_init (init, decl, args, complain, in_decl);
19064 if (VAR_P (decl))
19065 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
19066 (pattern_decl));
19068 if (ndecl != error_mark_node)
19069 cp_maybe_mangle_decomp (ndecl, first, cnt);
19071 /* In a non-template function, VLA type declarations are
19072 handled in grokdeclarator; for templates, handle them
19073 now. */
19074 predeclare_vla (decl);
19076 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
19078 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
19079 const char *asmspec = IDENTIFIER_POINTER (id);
19080 gcc_assert (asmspec[0] == '*');
19081 asmspec_tree
19082 = build_string (IDENTIFIER_LENGTH (id) - 1,
19083 asmspec + 1);
19084 TREE_TYPE (asmspec_tree) = char_array_type_node;
19087 cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
19089 if (ndecl != error_mark_node)
19090 cp_finish_decomp (ndecl, first, cnt);
19095 break;
19098 case FOR_STMT:
19099 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
19100 RECUR (FOR_INIT_STMT (t));
19101 finish_init_stmt (stmt);
19102 tmp = RECUR (FOR_COND (t));
19103 finish_for_cond (tmp, stmt, false, 0, false);
19104 tmp = RECUR (FOR_EXPR (t));
19105 finish_for_expr (tmp, stmt);
19107 bool prev = note_iteration_stmt_body_start ();
19108 RECUR (FOR_BODY (t));
19109 note_iteration_stmt_body_end (prev);
19111 finish_for_stmt (stmt);
19112 break;
19114 case RANGE_FOR_STMT:
19116 /* Construct another range_for, if this is not a final
19117 substitution (for inside a generic lambda of a
19118 template). Otherwise convert to a regular for. */
19119 tree decl, expr;
19120 stmt = (processing_template_decl
19121 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
19122 : begin_for_stmt (NULL_TREE, NULL_TREE));
19123 RECUR (RANGE_FOR_INIT_STMT (t));
19124 decl = RANGE_FOR_DECL (t);
19125 decl = tsubst (decl, args, complain, in_decl);
19126 maybe_push_decl (decl);
19127 expr = RECUR (RANGE_FOR_EXPR (t));
19129 tree decomp_first = NULL_TREE;
19130 unsigned decomp_cnt = 0;
19131 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
19132 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
19133 complain, in_decl,
19134 &decomp_first, &decomp_cnt);
19136 if (processing_template_decl)
19138 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
19139 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
19140 RANGE_FOR_NOVECTOR (stmt) = RANGE_FOR_NOVECTOR (t);
19141 finish_range_for_decl (stmt, decl, expr);
19142 if (decomp_first && decl != error_mark_node)
19143 cp_finish_decomp (decl, decomp_first, decomp_cnt);
19145 else
19147 unsigned short unroll = (RANGE_FOR_UNROLL (t)
19148 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
19149 stmt = cp_convert_range_for (stmt, decl, expr,
19150 decomp_first, decomp_cnt,
19151 RANGE_FOR_IVDEP (t), unroll,
19152 RANGE_FOR_NOVECTOR (t));
19155 bool prev = note_iteration_stmt_body_start ();
19156 RECUR (RANGE_FOR_BODY (t));
19157 note_iteration_stmt_body_end (prev);
19158 finish_for_stmt (stmt);
19160 break;
19162 case WHILE_STMT:
19163 stmt = begin_while_stmt ();
19164 tmp = RECUR (WHILE_COND (t));
19165 finish_while_stmt_cond (tmp, stmt, false, 0, false);
19167 bool prev = note_iteration_stmt_body_start ();
19168 RECUR (WHILE_BODY (t));
19169 note_iteration_stmt_body_end (prev);
19171 finish_while_stmt (stmt);
19172 break;
19174 case DO_STMT:
19175 stmt = begin_do_stmt ();
19177 bool prev = note_iteration_stmt_body_start ();
19178 RECUR (DO_BODY (t));
19179 note_iteration_stmt_body_end (prev);
19181 finish_do_body (stmt);
19182 tmp = RECUR (DO_COND (t));
19183 finish_do_stmt (tmp, stmt, false, 0, false);
19184 break;
19186 case IF_STMT:
19187 stmt = begin_if_stmt ();
19188 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
19189 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
19190 if (IF_STMT_CONSTEXPR_P (t))
19191 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
19193 tree cond = IF_COND (t);
19194 bool was_dep = dependent_operand_p (cond);
19195 cond = RECUR (cond);
19196 warning_sentinel s1(warn_address, was_dep);
19197 tmp = finish_if_stmt_cond (cond, stmt);
19199 if (IF_STMT_CONSTEXPR_P (t)
19200 && instantiation_dependent_expression_p (tmp))
19202 /* We're partially instantiating a generic lambda, but the condition
19203 of the constexpr if is still dependent. Don't substitute into the
19204 branches now, just remember the template arguments. */
19205 do_poplevel (IF_SCOPE (stmt));
19206 IF_COND (stmt) = IF_COND (t);
19207 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
19208 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
19209 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
19210 add_stmt (stmt);
19211 break;
19213 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
19214 /* Don't instantiate the THEN_CLAUSE. */;
19215 else if (IF_STMT_CONSTEVAL_P (t))
19217 bool save_in_consteval_if_p = in_consteval_if_p;
19218 in_consteval_if_p = true;
19219 RECUR (THEN_CLAUSE (t));
19220 in_consteval_if_p = save_in_consteval_if_p;
19222 else
19224 tree folded = fold_non_dependent_expr (tmp, complain);
19225 bool inhibit = integer_zerop (folded);
19226 if (inhibit)
19227 ++c_inhibit_evaluation_warnings;
19228 RECUR (THEN_CLAUSE (t));
19229 if (inhibit)
19230 --c_inhibit_evaluation_warnings;
19232 finish_then_clause (stmt);
19234 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
19235 /* Don't instantiate the ELSE_CLAUSE. */;
19236 else if (ELSE_CLAUSE (t))
19238 tree folded = fold_non_dependent_expr (tmp, complain);
19239 bool inhibit = integer_nonzerop (folded);
19240 begin_else_clause (stmt);
19241 if (inhibit)
19242 ++c_inhibit_evaluation_warnings;
19243 RECUR (ELSE_CLAUSE (t));
19244 if (inhibit)
19245 --c_inhibit_evaluation_warnings;
19246 finish_else_clause (stmt);
19249 finish_if_stmt (stmt);
19250 break;
19252 case BIND_EXPR:
19253 if (BIND_EXPR_BODY_BLOCK (t))
19254 stmt = begin_function_body ();
19255 else
19256 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
19257 ? BCS_TRY_BLOCK : 0);
19259 RECUR (BIND_EXPR_BODY (t));
19261 if (BIND_EXPR_BODY_BLOCK (t))
19262 finish_function_body (stmt);
19263 else
19264 finish_compound_stmt (stmt);
19265 break;
19267 case BREAK_STMT:
19268 finish_break_stmt ();
19269 break;
19271 case CONTINUE_STMT:
19272 finish_continue_stmt ();
19273 break;
19275 case SWITCH_STMT:
19276 stmt = begin_switch_stmt ();
19277 tmp = RECUR (SWITCH_STMT_COND (t));
19278 finish_switch_cond (tmp, stmt);
19279 RECUR (SWITCH_STMT_BODY (t));
19280 finish_switch_stmt (stmt);
19281 break;
19283 case CASE_LABEL_EXPR:
19285 tree decl = CASE_LABEL (t);
19286 tree low = RECUR (CASE_LOW (t));
19287 tree high = RECUR (CASE_HIGH (t));
19288 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
19289 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
19291 tree label = CASE_LABEL (l);
19292 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19293 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19294 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19297 break;
19299 case LABEL_EXPR:
19301 tree decl = LABEL_EXPR_LABEL (t);
19302 tree label;
19304 label = finish_label_stmt (DECL_NAME (decl));
19305 if (TREE_CODE (label) == LABEL_DECL)
19306 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19307 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19308 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19310 break;
19312 case GOTO_EXPR:
19313 tmp = GOTO_DESTINATION (t);
19314 if (TREE_CODE (tmp) != LABEL_DECL)
19315 /* Computed goto's must be tsubst'd into. On the other hand,
19316 non-computed gotos must not be; the identifier in question
19317 will have no binding. */
19318 tmp = RECUR (tmp);
19319 else
19320 tmp = DECL_NAME (tmp);
19321 finish_goto_stmt (tmp);
19322 break;
19324 case ASM_EXPR:
19326 tree string = RECUR (ASM_STRING (t));
19327 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19328 complain, in_decl);
19329 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19330 complain, in_decl);
19331 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19332 complain, in_decl);
19333 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19334 complain, in_decl);
19335 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19336 outputs, inputs, clobbers, labels,
19337 ASM_INLINE_P (t));
19338 tree asm_expr = tmp;
19339 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19340 asm_expr = TREE_OPERAND (asm_expr, 0);
19341 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19343 break;
19345 case TRY_BLOCK:
19346 if (CLEANUP_P (t))
19348 stmt = begin_try_block ();
19349 RECUR (TRY_STMTS (t));
19350 finish_cleanup_try_block (stmt);
19351 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19353 else
19355 tree compound_stmt = NULL_TREE;
19357 if (FN_TRY_BLOCK_P (t))
19358 stmt = begin_function_try_block (&compound_stmt);
19359 else
19360 stmt = begin_try_block ();
19362 RECUR (TRY_STMTS (t));
19364 if (FN_TRY_BLOCK_P (t))
19365 finish_function_try_block (stmt);
19366 else
19367 finish_try_block (stmt);
19369 RECUR (TRY_HANDLERS (t));
19370 if (FN_TRY_BLOCK_P (t))
19371 finish_function_handler_sequence (stmt, compound_stmt);
19372 else
19373 finish_handler_sequence (stmt);
19375 break;
19377 case HANDLER:
19379 tree decl = HANDLER_PARMS (t);
19381 if (decl)
19383 decl = tsubst (decl, args, complain, in_decl);
19384 /* Prevent instantiate_decl from trying to instantiate
19385 this variable. We've already done all that needs to be
19386 done. */
19387 if (decl != error_mark_node)
19388 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19390 stmt = begin_handler ();
19391 finish_handler_parms (decl, stmt);
19392 RECUR (HANDLER_BODY (t));
19393 finish_handler (stmt);
19395 break;
19397 case TAG_DEFN:
19398 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19399 if (CLASS_TYPE_P (tmp))
19401 /* Local classes are not independent templates; they are
19402 instantiated along with their containing function. And this
19403 way we don't have to deal with pushing out of one local class
19404 to instantiate a member of another local class. */
19405 /* Closures are handled by the LAMBDA_EXPR. */
19406 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19407 complete_type (tmp);
19408 if (dependent_type_p (tmp))
19410 /* This is a partial instantiation, try again when full. */
19411 add_stmt (build_min (TAG_DEFN, tmp));
19412 break;
19414 tree save_ccp = current_class_ptr;
19415 tree save_ccr = current_class_ref;
19416 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19417 if ((VAR_P (fld)
19418 || (TREE_CODE (fld) == FUNCTION_DECL
19419 && !DECL_ARTIFICIAL (fld)))
19420 && DECL_TEMPLATE_INSTANTIATION (fld))
19421 instantiate_decl (fld, /*defer_ok=*/false,
19422 /*expl_inst_class=*/false);
19423 else if (TREE_CODE (fld) == FIELD_DECL)
19424 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19425 current_class_ptr = save_ccp;
19426 current_class_ref = save_ccr;
19428 break;
19430 case STATIC_ASSERT:
19432 tree condition;
19434 ++c_inhibit_evaluation_warnings;
19435 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
19436 complain, in_decl);
19437 --c_inhibit_evaluation_warnings;
19439 finish_static_assert (condition,
19440 STATIC_ASSERT_MESSAGE (t),
19441 STATIC_ASSERT_SOURCE_LOCATION (t),
19442 /*member_p=*/false, /*show_expr_p=*/true);
19444 break;
19446 case OACC_KERNELS:
19447 case OACC_PARALLEL:
19448 case OACC_SERIAL:
19449 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19450 in_decl);
19451 stmt = begin_omp_parallel ();
19452 RECUR (OMP_BODY (t));
19453 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19454 break;
19456 case OMP_PARALLEL:
19457 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19458 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19459 complain, in_decl);
19460 if (OMP_PARALLEL_COMBINED (t))
19461 omp_parallel_combined_clauses = &tmp;
19462 stmt = begin_omp_parallel ();
19463 RECUR (OMP_PARALLEL_BODY (t));
19464 gcc_assert (omp_parallel_combined_clauses == NULL);
19465 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19466 = OMP_PARALLEL_COMBINED (t);
19467 pop_omp_privatization_clauses (r);
19468 break;
19470 case OMP_TASK:
19471 if (OMP_TASK_BODY (t) == NULL_TREE)
19473 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19474 complain, in_decl);
19475 t = copy_node (t);
19476 OMP_TASK_CLAUSES (t) = tmp;
19477 add_stmt (t);
19478 break;
19480 r = push_omp_privatization_clauses (false);
19481 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19482 complain, in_decl);
19483 stmt = begin_omp_task ();
19484 RECUR (OMP_TASK_BODY (t));
19485 finish_omp_task (tmp, stmt);
19486 pop_omp_privatization_clauses (r);
19487 break;
19489 case OMP_FOR:
19490 case OMP_LOOP:
19491 case OMP_SIMD:
19492 case OMP_DISTRIBUTE:
19493 case OMP_TASKLOOP:
19494 case OACC_LOOP:
19496 tree clauses, body, pre_body;
19497 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19498 tree orig_declv = NULL_TREE;
19499 tree incrv = NULL_TREE;
19500 enum c_omp_region_type ort = C_ORT_OMP;
19501 bool any_range_for = false;
19502 int i;
19504 if (TREE_CODE (t) == OACC_LOOP)
19505 ort = C_ORT_ACC;
19507 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19508 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19509 in_decl);
19510 if (OMP_FOR_INIT (t) != NULL_TREE)
19512 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19513 if (OMP_FOR_ORIG_DECLS (t))
19514 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19515 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19516 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19517 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19520 keep_next_level (true);
19521 stmt = begin_omp_structured_block ();
19523 pre_body = push_stmt_list ();
19524 RECUR (OMP_FOR_PRE_BODY (t));
19525 pre_body = pop_stmt_list (pre_body);
19527 if (OMP_FOR_INIT (t) != NULL_TREE)
19528 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19529 any_range_for
19530 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19531 condv, incrv, &clauses, args,
19532 complain, in_decl);
19533 omp_parallel_combined_clauses = NULL;
19535 if (any_range_for)
19537 gcc_assert (orig_declv);
19538 body = begin_omp_structured_block ();
19539 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19540 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19541 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19542 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19543 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19544 TREE_VEC_ELT (declv, i));
19546 else
19547 body = push_stmt_list ();
19548 RECUR (OMP_FOR_BODY (t));
19549 if (any_range_for)
19550 body = finish_omp_structured_block (body);
19551 else
19552 body = pop_stmt_list (body);
19554 if (OMP_FOR_INIT (t) != NULL_TREE)
19555 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19556 orig_declv, initv, condv, incrv, body, pre_body,
19557 NULL, clauses);
19558 else
19560 t = make_node (TREE_CODE (t));
19561 TREE_TYPE (t) = void_type_node;
19562 OMP_FOR_BODY (t) = body;
19563 OMP_FOR_PRE_BODY (t) = pre_body;
19564 OMP_FOR_CLAUSES (t) = clauses;
19565 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19566 add_stmt (t);
19569 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19570 t));
19571 pop_omp_privatization_clauses (r);
19573 break;
19575 case OMP_SECTIONS:
19576 case OMP_MASKED:
19577 omp_parallel_combined_clauses = NULL;
19578 /* FALLTHRU */
19579 case OMP_SINGLE:
19580 case OMP_SCOPE:
19581 case OMP_TEAMS:
19582 case OMP_CRITICAL:
19583 case OMP_TASKGROUP:
19584 case OMP_SCAN:
19585 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19586 && OMP_TEAMS_COMBINED (t));
19587 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19588 in_decl);
19589 if (TREE_CODE (t) == OMP_TEAMS)
19591 keep_next_level (true);
19592 stmt = begin_omp_structured_block ();
19593 RECUR (OMP_BODY (t));
19594 stmt = finish_omp_structured_block (stmt);
19596 else
19598 stmt = push_stmt_list ();
19599 RECUR (OMP_BODY (t));
19600 stmt = pop_stmt_list (stmt);
19603 if (TREE_CODE (t) == OMP_CRITICAL
19604 && tmp != NULL_TREE
19605 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19607 error_at (OMP_CLAUSE_LOCATION (tmp),
19608 "%<#pragma omp critical%> with %<hint%> clause requires "
19609 "a name, except when %<omp_sync_hint_none%> is used");
19610 RETURN (error_mark_node);
19612 t = copy_node (t);
19613 OMP_BODY (t) = stmt;
19614 OMP_CLAUSES (t) = tmp;
19615 add_stmt (t);
19616 pop_omp_privatization_clauses (r);
19617 break;
19619 case OMP_DEPOBJ:
19620 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19621 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19623 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19624 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19626 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19627 args, complain, in_decl);
19628 if (tmp == NULL_TREE)
19629 tmp = error_mark_node;
19631 else
19633 kind = (enum omp_clause_depend_kind)
19634 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19635 tmp = NULL_TREE;
19637 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19639 else
19640 finish_omp_depobj (EXPR_LOCATION (t), r,
19641 OMP_CLAUSE_DEPEND_INVALID,
19642 OMP_DEPOBJ_CLAUSES (t));
19643 break;
19645 case OACC_DATA:
19646 case OMP_TARGET_DATA:
19647 case OMP_TARGET:
19648 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19649 TREE_CODE (t) == OACC_DATA
19650 ? C_ORT_ACC
19651 : TREE_CODE (t) == OMP_TARGET
19652 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19653 args, complain, in_decl);
19654 keep_next_level (true);
19655 stmt = begin_omp_structured_block ();
19657 RECUR (OMP_BODY (t));
19658 stmt = finish_omp_structured_block (stmt);
19660 t = copy_node (t);
19661 OMP_BODY (t) = stmt;
19662 OMP_CLAUSES (t) = tmp;
19664 if (TREE_CODE (t) == OMP_TARGET)
19665 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19666 &OMP_CLAUSES (t));
19668 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19670 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19671 if (teams)
19672 /* For combined target teams, ensure the num_teams and
19673 thread_limit clause expressions are evaluated on the host,
19674 before entering the target construct. */
19675 for (tree c = OMP_TEAMS_CLAUSES (teams);
19676 c; c = OMP_CLAUSE_CHAIN (c))
19677 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19678 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19679 for (int i = 0;
19680 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19681 if (OMP_CLAUSE_OPERAND (c, i)
19682 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19684 tree expr = OMP_CLAUSE_OPERAND (c, i);
19685 expr = force_target_expr (TREE_TYPE (expr), expr,
19686 tf_none);
19687 if (expr == error_mark_node)
19688 continue;
19689 tmp = TARGET_EXPR_SLOT (expr);
19690 add_stmt (expr);
19691 OMP_CLAUSE_OPERAND (c, i) = expr;
19692 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19693 OMP_CLAUSE_FIRSTPRIVATE);
19694 OMP_CLAUSE_DECL (tc) = tmp;
19695 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19696 OMP_TARGET_CLAUSES (t) = tc;
19699 add_stmt (t);
19700 break;
19702 case OACC_DECLARE:
19703 t = copy_node (t);
19704 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19705 complain, in_decl);
19706 OACC_DECLARE_CLAUSES (t) = tmp;
19707 add_stmt (t);
19708 break;
19710 case OMP_TARGET_UPDATE:
19711 case OMP_TARGET_ENTER_DATA:
19712 case OMP_TARGET_EXIT_DATA:
19713 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19714 complain, in_decl);
19715 t = copy_node (t);
19716 OMP_STANDALONE_CLAUSES (t) = tmp;
19717 add_stmt (t);
19718 break;
19720 case OACC_CACHE:
19721 case OACC_ENTER_DATA:
19722 case OACC_EXIT_DATA:
19723 case OACC_UPDATE:
19724 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19725 complain, in_decl);
19726 t = copy_node (t);
19727 OMP_STANDALONE_CLAUSES (t) = tmp;
19728 add_stmt (t);
19729 break;
19731 case OMP_ORDERED:
19732 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19733 complain, in_decl);
19734 if (OMP_BODY (t))
19736 stmt = push_stmt_list ();
19737 RECUR (OMP_BODY (t));
19738 stmt = pop_stmt_list (stmt);
19740 else
19741 stmt = NULL_TREE;
19743 t = copy_node (t);
19744 OMP_BODY (t) = stmt;
19745 OMP_ORDERED_CLAUSES (t) = tmp;
19746 add_stmt (t);
19747 break;
19749 case OMP_MASTER:
19750 omp_parallel_combined_clauses = NULL;
19751 /* FALLTHRU */
19752 case OMP_SECTION:
19753 stmt = push_stmt_list ();
19754 RECUR (OMP_BODY (t));
19755 stmt = pop_stmt_list (stmt);
19757 t = copy_node (t);
19758 OMP_BODY (t) = stmt;
19759 add_stmt (t);
19760 break;
19762 case OMP_ATOMIC:
19763 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19764 tmp = NULL_TREE;
19765 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19766 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19767 complain, in_decl);
19768 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19770 tree op1 = TREE_OPERAND (t, 1);
19771 tree rhs1 = NULL_TREE;
19772 tree r = NULL_TREE;
19773 tree lhs, rhs;
19774 if (TREE_CODE (op1) == COMPOUND_EXPR)
19776 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19777 op1 = TREE_OPERAND (op1, 1);
19779 if (TREE_CODE (op1) == COND_EXPR)
19781 gcc_assert (rhs1 == NULL_TREE);
19782 tree c = TREE_OPERAND (op1, 0);
19783 if (TREE_CODE (c) == MODIFY_EXPR)
19785 r = RECUR (TREE_OPERAND (c, 0));
19786 c = TREE_OPERAND (c, 1);
19788 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19789 rhs = RECUR (TREE_OPERAND (c, 1));
19790 lhs = RECUR (TREE_OPERAND (op1, 2));
19791 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19793 else
19795 lhs = RECUR (TREE_OPERAND (op1, 0));
19796 rhs = RECUR (TREE_OPERAND (op1, 1));
19798 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19799 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19800 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19801 OMP_ATOMIC_WEAK (t));
19803 else
19805 tree op1 = TREE_OPERAND (t, 1);
19806 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19807 tree rhs1 = NULL_TREE, r = NULL_TREE;
19808 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19809 enum tree_code opcode = NOP_EXPR;
19810 if (code == OMP_ATOMIC_READ)
19812 v = RECUR (TREE_OPERAND (op1, 0));
19813 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19815 else if (code == OMP_ATOMIC_CAPTURE_OLD
19816 || code == OMP_ATOMIC_CAPTURE_NEW)
19818 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19819 v = RECUR (TREE_OPERAND (op1, 0));
19820 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19821 if (TREE_CODE (op11) == COMPOUND_EXPR)
19823 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19824 op11 = TREE_OPERAND (op11, 1);
19826 if (TREE_CODE (op11) == COND_EXPR)
19828 gcc_assert (rhs1 == NULL_TREE);
19829 tree c = TREE_OPERAND (op11, 0);
19830 if (TREE_CODE (c) == MODIFY_EXPR)
19832 r = RECUR (TREE_OPERAND (c, 0));
19833 c = TREE_OPERAND (c, 1);
19835 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19836 rhs = RECUR (TREE_OPERAND (c, 1));
19837 lhs = RECUR (TREE_OPERAND (op11, 2));
19838 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19840 else
19842 lhs = RECUR (TREE_OPERAND (op11, 0));
19843 rhs = RECUR (TREE_OPERAND (op11, 1));
19845 opcode = TREE_CODE (op11);
19846 if (opcode == MODIFY_EXPR)
19847 opcode = NOP_EXPR;
19849 else
19851 code = OMP_ATOMIC;
19852 lhs = RECUR (TREE_OPERAND (op1, 0));
19853 rhs = RECUR (TREE_OPERAND (op1, 1));
19855 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19856 lhs1, rhs1, r, tmp,
19857 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19859 break;
19861 case TRANSACTION_EXPR:
19863 int flags = 0;
19864 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19865 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19867 if (TRANSACTION_EXPR_IS_STMT (t))
19869 tree body = TRANSACTION_EXPR_BODY (t);
19870 tree noex = NULL_TREE;
19871 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19873 noex = MUST_NOT_THROW_COND (body);
19874 if (noex == NULL_TREE)
19875 noex = boolean_true_node;
19876 body = TREE_OPERAND (body, 0);
19878 stmt = begin_transaction_stmt (input_location, NULL, flags);
19879 RECUR (body);
19880 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19882 else
19884 stmt = build_transaction_expr (EXPR_LOCATION (t),
19885 RECUR (TRANSACTION_EXPR_BODY (t)),
19886 flags, NULL_TREE);
19887 RETURN (stmt);
19890 break;
19892 case MUST_NOT_THROW_EXPR:
19894 tree op0 = RECUR (TREE_OPERAND (t, 0));
19895 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19896 RETURN (build_must_not_throw_expr (op0, cond));
19899 case EXPR_PACK_EXPANSION:
19900 error ("invalid use of pack expansion expression");
19901 RETURN (error_mark_node);
19903 case NONTYPE_ARGUMENT_PACK:
19904 error ("use %<...%> to expand argument pack");
19905 RETURN (error_mark_node);
19907 case COMPOUND_EXPR:
19908 tmp = RECUR (TREE_OPERAND (t, 0));
19909 if (tmp == NULL_TREE)
19910 /* If the first operand was a statement, we're done with it. */
19911 RETURN (RECUR (TREE_OPERAND (t, 1)));
19912 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19913 RECUR (TREE_OPERAND (t, 1)),
19914 templated_operator_saved_lookups (t),
19915 complain));
19917 case ANNOTATE_EXPR:
19918 tmp = RECUR (TREE_OPERAND (t, 0));
19919 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19920 TREE_TYPE (tmp), tmp,
19921 RECUR (TREE_OPERAND (t, 1)),
19922 RECUR (TREE_OPERAND (t, 2))));
19924 case PREDICT_EXPR:
19925 RETURN (add_stmt (copy_node (t)));
19927 default:
19928 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19930 RETURN (tsubst_copy_and_build (t, args, complain, in_decl));
19933 RETURN (NULL_TREE);
19934 out:
19935 input_location = loc;
19936 return r;
19937 #undef RECUR
19938 #undef RETURN
19941 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19942 function. For description of the body see comment above
19943 cp_parser_omp_declare_reduction_exprs. */
19945 static void
19946 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19948 if (t == NULL_TREE || t == error_mark_node)
19949 return;
19951 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19953 tree_stmt_iterator tsi;
19954 int i;
19955 tree stmts[7];
19956 memset (stmts, 0, sizeof stmts);
19957 for (i = 0, tsi = tsi_start (t);
19958 i < 7 && !tsi_end_p (tsi);
19959 i++, tsi_next (&tsi))
19960 stmts[i] = tsi_stmt (tsi);
19961 gcc_assert (tsi_end_p (tsi));
19963 if (i >= 3)
19965 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19966 && TREE_CODE (stmts[1]) == DECL_EXPR);
19967 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19968 args, complain, in_decl);
19969 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19970 args, complain, in_decl);
19971 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19972 expect to be pushing it. */
19973 DECL_CONTEXT (omp_out) = current_function_decl;
19974 DECL_CONTEXT (omp_in) = current_function_decl;
19975 keep_next_level (true);
19976 tree block = begin_omp_structured_block ();
19977 tsubst_expr (stmts[2], args, complain, in_decl);
19978 block = finish_omp_structured_block (block);
19979 block = maybe_cleanup_point_expr_void (block);
19980 add_decl_expr (omp_out);
19981 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19982 add_decl_expr (omp_in);
19983 finish_expr_stmt (block);
19985 if (i >= 6)
19987 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19988 && TREE_CODE (stmts[4]) == DECL_EXPR);
19989 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19990 args, complain, in_decl);
19991 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19992 args, complain, in_decl);
19993 DECL_CONTEXT (omp_priv) = current_function_decl;
19994 DECL_CONTEXT (omp_orig) = current_function_decl;
19995 keep_next_level (true);
19996 tree block = begin_omp_structured_block ();
19997 tsubst_expr (stmts[5], args, complain, in_decl);
19998 block = finish_omp_structured_block (block);
19999 block = maybe_cleanup_point_expr_void (block);
20000 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
20001 add_decl_expr (omp_priv);
20002 add_decl_expr (omp_orig);
20003 finish_expr_stmt (block);
20004 if (i == 7)
20005 add_decl_expr (omp_orig);
20009 /* T is a postfix-expression that is not being used in a function
20010 call. Return the substituted version of T. */
20012 static tree
20013 tsubst_non_call_postfix_expression (tree t, tree args,
20014 tsubst_flags_t complain,
20015 tree in_decl)
20017 if (TREE_CODE (t) == SCOPE_REF)
20018 t = tsubst_qualified_id (t, args, complain, in_decl,
20019 /*done=*/false, /*address_p=*/false);
20020 else
20021 t = tsubst_copy_and_build (t, args, complain, in_decl);
20023 return t;
20026 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
20027 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
20028 dependent init-capture. EXPLICIT_P is true if the original list had
20029 explicit captures. */
20031 static void
20032 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
20033 tsubst_flags_t complain)
20035 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
20037 tree type = NULL_TREE;
20038 if (!init)
20040 if (complain & tf_error)
20041 error ("empty initializer in lambda init-capture");
20042 init = error_mark_node;
20044 else if (TREE_CODE (init) == TREE_LIST)
20045 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
20046 if (!type)
20047 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
20048 TREE_TYPE (field) = type;
20049 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
20051 list = tree_cons (field, init, list);
20052 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
20055 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
20056 instantiation context. Instantiating a pack expansion containing a lambda
20057 might result in multiple lambdas all based on the same lambda in the
20058 template. */
20060 tree
20061 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
20063 tree oldfn = lambda_function (t);
20064 in_decl = oldfn;
20066 tree r = build_lambda_expr ();
20068 LAMBDA_EXPR_LOCATION (r)
20069 = LAMBDA_EXPR_LOCATION (t);
20070 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
20071 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
20072 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
20073 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
20074 LAMBDA_EXPR_REGEN_INFO (r)
20075 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
20076 preserve_args (args)));
20077 else
20078 LAMBDA_EXPR_REGEN_INFO (r)
20079 = build_template_info (t, preserve_args (args));
20081 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
20082 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
20084 vec<tree,va_gc>* field_packs = NULL;
20086 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
20087 cap = TREE_CHAIN (cap))
20089 tree ofield = TREE_PURPOSE (cap);
20090 tree init = TREE_VALUE (cap);
20091 if (PACK_EXPANSION_P (init))
20092 init = tsubst_pack_expansion (init, args, complain, in_decl);
20093 else
20094 init = tsubst_copy_and_build (init, args, complain, in_decl);
20096 if (init == error_mark_node)
20097 return error_mark_node;
20099 if (init && TREE_CODE (init) == TREE_LIST)
20100 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
20102 if (!processing_template_decl
20103 && init && TREE_CODE (init) != TREE_VEC
20104 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
20106 /* For a VLA, simply tsubsting the field type won't work, we need to
20107 go through add_capture again. XXX do we want to do this for all
20108 captures? */
20109 tree name = (get_identifier
20110 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
20111 tree ftype = TREE_TYPE (ofield);
20112 bool by_ref = (TYPE_REF_P (ftype)
20113 || (TREE_CODE (ftype) == DECLTYPE_TYPE
20114 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
20115 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
20116 continue;
20119 if (PACK_EXPANSION_P (ofield))
20120 ofield = PACK_EXPANSION_PATTERN (ofield);
20121 tree field = tsubst_decl (ofield, args, complain);
20123 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
20125 /* Remember these for when we've pushed local_specializations. */
20126 vec_safe_push (field_packs, ofield);
20127 vec_safe_push (field_packs, field);
20130 if (field == error_mark_node)
20131 return error_mark_node;
20133 if (TREE_CODE (field) == TREE_VEC)
20135 int len = TREE_VEC_LENGTH (field);
20136 gcc_assert (TREE_CODE (init) == TREE_VEC
20137 && TREE_VEC_LENGTH (init) == len);
20138 for (int i = 0; i < len; ++i)
20139 prepend_one_capture (TREE_VEC_ELT (field, i),
20140 TREE_VEC_ELT (init, i),
20141 LAMBDA_EXPR_CAPTURE_LIST (r),
20142 LAMBDA_CAPTURE_EXPLICIT_P (cap),
20143 complain);
20145 else
20147 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
20148 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
20150 if (id_equal (DECL_NAME (field), "__this"))
20151 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
20155 tree type = begin_lambda_type (r);
20156 if (type == error_mark_node)
20157 return error_mark_node;
20159 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
20160 record_lambda_scope (r);
20161 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
20162 /* If we're pushed into another scope (PR105652), fix it. */
20163 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
20164 = TYPE_CONTEXT (TREE_TYPE (t));
20165 record_lambda_scope_discriminator (r);
20167 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
20168 determine_visibility (TYPE_NAME (type));
20170 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
20172 tree oldtmpl = (generic_lambda_fn_p (oldfn)
20173 ? DECL_TI_TEMPLATE (oldfn)
20174 : NULL_TREE);
20176 tree tparms = NULL_TREE;
20177 if (oldtmpl)
20178 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
20180 tree fntype = static_fn_type (oldfn);
20182 tree saved_ctp = current_template_parms;
20183 if (oldtmpl)
20185 ++processing_template_decl;
20186 current_template_parms = tparms;
20188 fntype = tsubst (fntype, args, complain, in_decl);
20189 if (oldtmpl)
20191 current_template_parms = saved_ctp;
20192 --processing_template_decl;
20195 if (fntype == error_mark_node)
20196 r = error_mark_node;
20197 else
20199 /* The body of a lambda-expression is not a subexpression of the
20200 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
20201 which would be skipped if cp_unevaluated_operand. */
20202 cp_evaluated ev;
20204 /* Fix the type of 'this'. */
20205 fntype = build_memfn_type (fntype, type,
20206 type_memfn_quals (fntype),
20207 type_memfn_rqual (fntype));
20208 tree inst = (oldtmpl
20209 ? tsubst_template_decl (oldtmpl, args, complain,
20210 fntype, tparms)
20211 : tsubst_function_decl (oldfn, args, complain, fntype));
20212 if (inst == error_mark_node)
20214 r = error_mark_node;
20215 goto out;
20217 finish_member_declaration (inst);
20218 record_lambda_scope_sig_discriminator (r, inst);
20220 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
20222 /* Let finish_function set this. */
20223 DECL_DECLARED_CONSTEXPR_P (fn) = false;
20225 bool nested = cfun;
20226 if (nested)
20227 push_function_context ();
20228 else
20229 /* Still increment function_depth so that we don't GC in the
20230 middle of an expression. */
20231 ++function_depth;
20233 local_specialization_stack s (lss_copy);
20235 bool save_in_consteval_if_p = in_consteval_if_p;
20236 in_consteval_if_p = false;
20238 tree body = start_lambda_function (fn, r);
20240 /* Now record them for lookup_init_capture_pack. */
20241 int fplen = vec_safe_length (field_packs);
20242 for (int i = 0; i < fplen; )
20244 tree pack = (*field_packs)[i++];
20245 tree inst = (*field_packs)[i++];
20246 register_local_specialization (inst, pack);
20248 release_tree_vector (field_packs);
20250 register_parameter_specializations (oldfn, fn);
20252 if (oldtmpl)
20254 /* We might not partially instantiate some parts of the function, so
20255 copy these flags from the original template. */
20256 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
20257 current_function_returns_value = ol->returns_value;
20258 current_function_returns_null = ol->returns_null;
20259 current_function_returns_abnormally = ol->returns_abnormally;
20260 current_function_infinite_loop = ol->infinite_loop;
20263 /* [temp.deduct] A lambda-expression appearing in a function type or a
20264 template parameter is not considered part of the immediate context for
20265 the purposes of template argument deduction. */
20266 complain = tf_warning_or_error;
20268 tree saved = DECL_SAVED_TREE (oldfn);
20269 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20270 /* We already have a body block from start_lambda_function, we don't
20271 need another to confuse NRV (91217). */
20272 saved = BIND_EXPR_BODY (saved);
20274 tsubst_expr (saved, args, complain, r);
20276 finish_lambda_function (body);
20278 in_consteval_if_p = save_in_consteval_if_p;
20280 if (nested)
20281 pop_function_context ();
20282 else
20283 --function_depth;
20285 /* The capture list was built up in reverse order; fix that now. */
20286 LAMBDA_EXPR_CAPTURE_LIST (r)
20287 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20289 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20291 maybe_add_lambda_conv_op (type);
20294 out:
20295 finish_struct (type, /*attr*/NULL_TREE);
20297 insert_pending_capture_proxies ();
20299 return r;
20302 /* Subroutine of maybe_fold_fn_template_args. */
20304 static bool
20305 fold_targs_r (tree targs, tsubst_flags_t complain)
20307 int len = TREE_VEC_LENGTH (targs);
20308 for (int i = 0; i < len; ++i)
20310 tree &elt = TREE_VEC_ELT (targs, i);
20311 if (!elt || TYPE_P (elt)
20312 || TREE_CODE (elt) == TEMPLATE_DECL)
20313 continue;
20314 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20316 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20317 return false;
20319 else if (/* We can only safely preevaluate scalar prvalues. */
20320 SCALAR_TYPE_P (TREE_TYPE (elt))
20321 && !glvalue_p (elt)
20322 && !TREE_CONSTANT (elt))
20324 elt = cxx_constant_value (elt, complain);
20325 if (elt == error_mark_node)
20326 return false;
20330 return true;
20333 /* Try to do constant evaluation of any explicit template arguments in FN
20334 before overload resolution, to get any errors only once. Return true iff
20335 we didn't have any problems folding. */
20337 static bool
20338 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20340 if (processing_template_decl || fn == NULL_TREE)
20341 return true;
20342 if (fn == error_mark_node)
20343 return false;
20344 if (TREE_CODE (fn) == OFFSET_REF
20345 || TREE_CODE (fn) == COMPONENT_REF)
20346 fn = TREE_OPERAND (fn, 1);
20347 if (BASELINK_P (fn))
20348 fn = BASELINK_FUNCTIONS (fn);
20349 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20350 return true;
20351 tree targs = TREE_OPERAND (fn, 1);
20352 if (targs == NULL_TREE)
20353 return true;
20354 if (targs == error_mark_node)
20355 return false;
20356 return fold_targs_r (targs, complain);
20359 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20360 handling. */
20362 static void
20363 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20364 tree in_decl, releasing_vec &call_args)
20366 unsigned int nargs = call_expr_nargs (t);
20367 for (unsigned int i = 0; i < nargs; ++i)
20369 tree arg = CALL_EXPR_ARG (t, i);
20371 if (!PACK_EXPANSION_P (arg))
20372 vec_safe_push (call_args,
20373 tsubst_copy_and_build (arg, args, complain, in_decl));
20374 else
20376 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20377 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20378 if (TREE_CODE (arg) == TREE_VEC)
20380 unsigned int len, j;
20382 len = TREE_VEC_LENGTH (arg);
20383 for (j = 0; j < len; ++j)
20385 tree value = TREE_VEC_ELT (arg, j);
20386 if (value != NULL_TREE)
20387 value = convert_from_reference (value);
20388 vec_safe_push (call_args, value);
20391 else
20392 /* A partial substitution. Add one entry. */
20393 vec_safe_push (call_args, arg);
20398 /* Like tsubst but deals with expressions and performs semantic
20399 analysis. */
20401 tree
20402 tsubst_copy_and_build (tree t,
20403 tree args,
20404 tsubst_flags_t complain,
20405 tree in_decl)
20407 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20408 #define RECUR(NODE) \
20409 tsubst_copy_and_build (NODE, args, complain, in_decl)
20411 tree retval, op1;
20412 location_t save_loc;
20414 if (t == NULL_TREE || t == error_mark_node)
20415 return t;
20417 save_loc = input_location;
20418 if (location_t eloc = cp_expr_location (t))
20419 input_location = eloc;
20421 /* N3276 decltype magic only applies to calls at the top level or on the
20422 right side of a comma. */
20423 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20424 complain &= ~tf_decltype;
20426 switch (TREE_CODE (t))
20428 case USING_DECL:
20429 t = DECL_NAME (t);
20430 /* Fall through. */
20431 case IDENTIFIER_NODE:
20433 tree decl;
20434 cp_id_kind idk;
20435 const char *error_msg;
20437 if (IDENTIFIER_CONV_OP_P (t))
20439 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20440 t = make_conv_op_name (new_type);
20443 /* Look up the name. */
20444 decl = lookup_name (t);
20446 /* By convention, expressions use ERROR_MARK_NODE to indicate
20447 failure, not NULL_TREE. */
20448 if (decl == NULL_TREE)
20449 decl = error_mark_node;
20451 decl = finish_id_expression (t, decl, NULL_TREE,
20452 &idk,
20453 /*i_c_e_p=*/false,
20454 /*allow_i_c_e_p=*/true,
20455 /*non_i_c_e_p=*/nullptr,
20456 /*template_p=*/false,
20457 /*done=*/true,
20458 /*address_p=*/false,
20459 /*template_arg_p=*/false,
20460 &error_msg,
20461 input_location);
20462 if (error_msg)
20463 error (error_msg);
20464 if (identifier_p (decl))
20466 if (complain & tf_error)
20467 unqualified_name_lookup_error (decl);
20468 decl = error_mark_node;
20470 RETURN (decl);
20473 case TEMPLATE_ID_EXPR:
20475 tree object;
20476 tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20477 complain, in_decl);
20478 tree targs = TREE_OPERAND (t, 1);
20480 if (targs)
20481 targs = tsubst_template_args (targs, args, complain, in_decl);
20482 if (targs == error_mark_node)
20483 RETURN (error_mark_node);
20485 if (TREE_CODE (templ) == SCOPE_REF)
20487 tree name = TREE_OPERAND (templ, 1);
20488 tree tid = lookup_template_function (name, targs);
20489 TREE_OPERAND (templ, 1) = tid;
20490 RETURN (templ);
20493 if (concept_definition_p (templ))
20495 tree check = build_concept_check (templ, targs, complain);
20496 if (check == error_mark_node)
20497 RETURN (error_mark_node);
20499 tree id = unpack_concept_check (check);
20501 /* If we built a function concept check, return the underlying
20502 template-id. So we can evaluate it as a function call. */
20503 if (function_concept_p (TREE_OPERAND (id, 0)))
20504 RETURN (id);
20506 RETURN (check);
20509 if (variable_template_p (templ))
20511 tree r = lookup_and_finish_template_variable (templ, targs,
20512 complain);
20513 r = convert_from_reference (r);
20514 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20515 RETURN (r);
20518 if (TREE_CODE (templ) == COMPONENT_REF)
20520 object = TREE_OPERAND (templ, 0);
20521 templ = TREE_OPERAND (templ, 1);
20523 else
20524 object = NULL_TREE;
20526 tree tid = lookup_template_function (templ, targs);
20527 protected_set_expr_location (tid, EXPR_LOCATION (t));
20529 if (object)
20530 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20531 object, tid, NULL_TREE));
20532 else if (identifier_p (templ))
20534 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20535 name lookup found nothing when parsing the template name. */
20536 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20537 RETURN (tid);
20539 else
20540 RETURN (baselink_for_fns (tid));
20543 case INDIRECT_REF:
20545 tree r = RECUR (TREE_OPERAND (t, 0));
20547 if (REFERENCE_REF_P (t))
20549 /* A type conversion to reference type will be enclosed in
20550 such an indirect ref, but the substitution of the cast
20551 will have also added such an indirect ref. */
20552 r = convert_from_reference (r);
20554 else
20555 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20556 templated_operator_saved_lookups (t),
20557 complain|decltype_flag);
20559 if (REF_PARENTHESIZED_P (t))
20560 r = force_paren_expr (r);
20562 RETURN (r);
20565 case NOP_EXPR:
20567 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20568 tree op0 = RECUR (TREE_OPERAND (t, 0));
20569 RETURN (build_nop (type, op0));
20572 case IMPLICIT_CONV_EXPR:
20574 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20575 tree expr = RECUR (TREE_OPERAND (t, 0));
20576 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20578 retval = copy_node (t);
20579 TREE_TYPE (retval) = type;
20580 TREE_OPERAND (retval, 0) = expr;
20581 RETURN (retval);
20583 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20584 /* We'll pass this to convert_nontype_argument again, we don't need
20585 to actually perform any conversion here. */
20586 RETURN (expr);
20587 int flags = LOOKUP_IMPLICIT;
20588 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20589 flags = LOOKUP_NORMAL;
20590 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20591 flags |= LOOKUP_NO_NARROWING;
20592 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20593 flags));
20596 case CONVERT_EXPR:
20598 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20599 tree op0 = RECUR (TREE_OPERAND (t, 0));
20600 if (op0 == error_mark_node)
20601 RETURN (error_mark_node);
20602 RETURN (build1 (CONVERT_EXPR, type, op0));
20605 case CAST_EXPR:
20606 case REINTERPRET_CAST_EXPR:
20607 case CONST_CAST_EXPR:
20608 case DYNAMIC_CAST_EXPR:
20609 case STATIC_CAST_EXPR:
20611 tree type;
20612 tree op, r = NULL_TREE;
20614 tsubst_flags_t tcomplain = complain;
20615 if (TREE_CODE (t) == CAST_EXPR)
20616 tcomplain |= tf_tst_ok;
20617 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20619 op = RECUR (TREE_OPERAND (t, 0));
20621 warning_sentinel s(warn_useless_cast);
20622 warning_sentinel s2(warn_ignored_qualifiers);
20623 warning_sentinel s3(warn_int_in_bool_context);
20624 switch (TREE_CODE (t))
20626 case CAST_EXPR:
20627 r = build_functional_cast (input_location, type, op, complain);
20628 break;
20629 case REINTERPRET_CAST_EXPR:
20630 r = build_reinterpret_cast (input_location, type, op, complain);
20631 break;
20632 case CONST_CAST_EXPR:
20633 r = build_const_cast (input_location, type, op, complain);
20634 break;
20635 case DYNAMIC_CAST_EXPR:
20636 r = build_dynamic_cast (input_location, type, op, complain);
20637 break;
20638 case STATIC_CAST_EXPR:
20639 r = build_static_cast (input_location, type, op, complain);
20640 if (IMPLICIT_RVALUE_P (t))
20641 set_implicit_rvalue_p (r);
20642 break;
20643 default:
20644 gcc_unreachable ();
20647 RETURN (r);
20650 case BIT_CAST_EXPR:
20652 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20653 tree op0 = RECUR (TREE_OPERAND (t, 0));
20654 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20657 case POSTDECREMENT_EXPR:
20658 case POSTINCREMENT_EXPR:
20659 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20660 args, complain, in_decl);
20661 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20662 templated_operator_saved_lookups (t),
20663 complain|decltype_flag));
20665 case PREDECREMENT_EXPR:
20666 case PREINCREMENT_EXPR:
20667 case NEGATE_EXPR:
20668 case BIT_NOT_EXPR:
20669 case ABS_EXPR:
20670 case TRUTH_NOT_EXPR:
20671 case UNARY_PLUS_EXPR: /* Unary + */
20672 case REALPART_EXPR:
20673 case IMAGPART_EXPR:
20674 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20675 RECUR (TREE_OPERAND (t, 0)),
20676 templated_operator_saved_lookups (t),
20677 complain|decltype_flag));
20679 case EXCESS_PRECISION_EXPR:
20681 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20682 tree op0 = RECUR (TREE_OPERAND (t, 0));
20683 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20684 RETURN (op0);
20685 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20686 type, op0));
20689 case FIX_TRUNC_EXPR:
20690 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20691 gcc_unreachable ();
20693 case ADDR_EXPR:
20694 op1 = TREE_OPERAND (t, 0);
20695 if (TREE_CODE (op1) == LABEL_DECL)
20696 RETURN (finish_label_address_expr (DECL_NAME (op1),
20697 EXPR_LOCATION (op1)));
20698 if (TREE_CODE (op1) == SCOPE_REF)
20699 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20700 /*done=*/true, /*address_p=*/true);
20701 else
20702 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20703 in_decl);
20704 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20705 templated_operator_saved_lookups (t),
20706 complain|decltype_flag));
20708 case PLUS_EXPR:
20709 case MINUS_EXPR:
20710 case MULT_EXPR:
20711 case TRUNC_DIV_EXPR:
20712 case CEIL_DIV_EXPR:
20713 case FLOOR_DIV_EXPR:
20714 case ROUND_DIV_EXPR:
20715 case EXACT_DIV_EXPR:
20716 case BIT_AND_EXPR:
20717 case BIT_IOR_EXPR:
20718 case BIT_XOR_EXPR:
20719 case TRUNC_MOD_EXPR:
20720 case FLOOR_MOD_EXPR:
20721 case TRUTH_ANDIF_EXPR:
20722 case TRUTH_ORIF_EXPR:
20723 case TRUTH_AND_EXPR:
20724 case TRUTH_OR_EXPR:
20725 case RSHIFT_EXPR:
20726 case LSHIFT_EXPR:
20727 case EQ_EXPR:
20728 case NE_EXPR:
20729 case MAX_EXPR:
20730 case MIN_EXPR:
20731 case LE_EXPR:
20732 case GE_EXPR:
20733 case LT_EXPR:
20734 case GT_EXPR:
20735 case SPACESHIP_EXPR:
20736 case MEMBER_REF:
20737 case DOTSTAR_EXPR:
20739 /* If either OP0 or OP1 was value- or type-dependent, suppress
20740 warnings that depend on the range of the types involved. */
20741 tree op0 = TREE_OPERAND (t, 0);
20742 tree op1 = TREE_OPERAND (t, 1);
20743 const bool was_dep = (dependent_operand_p (op0)
20744 || dependent_operand_p (op1));
20745 op0 = RECUR (op0);
20746 op1 = RECUR (op1);
20748 warning_sentinel s1(warn_type_limits, was_dep);
20749 warning_sentinel s2(warn_div_by_zero, was_dep);
20750 warning_sentinel s3(warn_logical_op, was_dep);
20751 warning_sentinel s4(warn_tautological_compare, was_dep);
20752 warning_sentinel s5(warn_address, was_dep);
20754 tree r = build_x_binary_op
20755 (input_location, TREE_CODE (t),
20756 op0,
20757 (warning_suppressed_p (TREE_OPERAND (t, 0))
20758 ? ERROR_MARK
20759 : TREE_CODE (TREE_OPERAND (t, 0))),
20760 op1,
20761 (warning_suppressed_p (TREE_OPERAND (t, 1))
20762 ? ERROR_MARK
20763 : TREE_CODE (TREE_OPERAND (t, 1))),
20764 templated_operator_saved_lookups (t),
20765 /*overload=*/NULL,
20766 complain|decltype_flag);
20767 if (EXPR_P (r))
20768 copy_warning (r, t);
20770 RETURN (r);
20773 case POINTER_PLUS_EXPR:
20775 tree op0 = RECUR (TREE_OPERAND (t, 0));
20776 if (op0 == error_mark_node)
20777 RETURN (error_mark_node);
20778 tree op1 = RECUR (TREE_OPERAND (t, 1));
20779 if (op1 == error_mark_node)
20780 RETURN (error_mark_node);
20781 RETURN (fold_build_pointer_plus (op0, op1));
20784 case SCOPE_REF:
20785 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20786 /*address_p=*/false));
20788 case BASELINK:
20789 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20790 args, complain, in_decl));
20792 case ARRAY_REF:
20793 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20794 args, complain, in_decl);
20795 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20796 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20797 == ovl_op_identifier (ARRAY_REF)))
20799 tree c = TREE_OPERAND (t, 1);
20800 releasing_vec index_exp_list;
20801 tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20802 index_exp_list);
20804 tree r;
20805 if (vec_safe_length (index_exp_list) == 1
20806 && !PACK_EXPANSION_P (index_exp_list[0]))
20807 r = grok_array_decl (EXPR_LOCATION (t), op1,
20808 index_exp_list[0], NULL,
20809 complain | decltype_flag);
20810 else
20811 r = grok_array_decl (EXPR_LOCATION (t), op1,
20812 NULL_TREE, &index_exp_list,
20813 complain | decltype_flag);
20814 RETURN (r);
20816 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20817 RECUR (TREE_OPERAND (t, 1)),
20818 complain|decltype_flag));
20820 case SIZEOF_EXPR:
20821 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20822 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20823 RETURN (tsubst_copy (t, args, complain, in_decl));
20824 /* Fall through */
20826 case ALIGNOF_EXPR:
20828 tree r;
20830 op1 = TREE_OPERAND (t, 0);
20831 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20832 op1 = TREE_TYPE (op1);
20833 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20834 && ALIGNOF_EXPR_STD_P (t));
20835 if (!args)
20837 /* When there are no ARGS, we are trying to evaluate a
20838 non-dependent expression from the parser. Trying to do
20839 the substitutions may not work. */
20840 if (!TYPE_P (op1))
20841 op1 = TREE_TYPE (op1);
20843 else
20845 ++cp_unevaluated_operand;
20846 ++c_inhibit_evaluation_warnings;
20847 if (TYPE_P (op1))
20848 op1 = tsubst (op1, args, complain, in_decl);
20849 else
20850 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20851 --cp_unevaluated_operand;
20852 --c_inhibit_evaluation_warnings;
20854 if (TYPE_P (op1))
20855 r = cxx_sizeof_or_alignof_type (input_location,
20856 op1, TREE_CODE (t), std_alignof,
20857 complain & tf_error);
20858 else
20859 r = cxx_sizeof_or_alignof_expr (input_location,
20860 op1, TREE_CODE (t), std_alignof,
20861 complain & tf_error);
20862 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20864 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20866 if (!processing_template_decl && TYPE_P (op1))
20868 r = build_min (SIZEOF_EXPR, size_type_node,
20869 build1 (NOP_EXPR, op1, error_mark_node));
20870 SIZEOF_EXPR_TYPE_P (r) = 1;
20872 else
20873 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20874 TREE_SIDE_EFFECTS (r) = 0;
20875 TREE_READONLY (r) = 1;
20877 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20879 RETURN (r);
20882 case AT_ENCODE_EXPR:
20884 op1 = TREE_OPERAND (t, 0);
20885 ++cp_unevaluated_operand;
20886 ++c_inhibit_evaluation_warnings;
20887 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20888 --cp_unevaluated_operand;
20889 --c_inhibit_evaluation_warnings;
20890 RETURN (objc_build_encode_expr (op1));
20893 case NOEXCEPT_EXPR:
20894 op1 = TREE_OPERAND (t, 0);
20895 ++cp_unevaluated_operand;
20896 ++c_inhibit_evaluation_warnings;
20897 ++cp_noexcept_operand;
20898 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20899 --cp_unevaluated_operand;
20900 --c_inhibit_evaluation_warnings;
20901 --cp_noexcept_operand;
20902 RETURN (finish_noexcept_expr (op1, complain));
20904 case MODOP_EXPR:
20906 warning_sentinel s(warn_div_by_zero);
20907 tree lhs = RECUR (TREE_OPERAND (t, 0));
20908 tree rhs = RECUR (TREE_OPERAND (t, 2));
20910 tree r = build_x_modify_expr
20911 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20912 templated_operator_saved_lookups (t),
20913 complain|decltype_flag);
20914 /* TREE_NO_WARNING must be set if either the expression was
20915 parenthesized or it uses an operator such as >>= rather
20916 than plain assignment. In the former case, it was already
20917 set and must be copied. In the latter case,
20918 build_x_modify_expr sets it and it must not be reset
20919 here. */
20920 if (warning_suppressed_p (t, OPT_Wparentheses))
20921 suppress_warning (r, OPT_Wparentheses);
20923 RETURN (r);
20926 case ARROW_EXPR:
20927 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20928 args, complain, in_decl);
20929 /* Remember that there was a reference to this entity. */
20930 if (DECL_P (op1)
20931 && !mark_used (op1, complain) && !(complain & tf_error))
20932 RETURN (error_mark_node);
20933 RETURN (build_x_arrow (input_location, op1, complain));
20935 case NEW_EXPR:
20937 tree placement = RECUR (TREE_OPERAND (t, 0));
20938 tree init = RECUR (TREE_OPERAND (t, 3));
20939 vec<tree, va_gc> *placement_vec;
20940 vec<tree, va_gc> *init_vec;
20941 tree ret;
20942 location_t loc = EXPR_LOCATION (t);
20944 if (placement == NULL_TREE)
20945 placement_vec = NULL;
20946 else if (placement == error_mark_node)
20947 RETURN (error_mark_node);
20948 else
20950 placement_vec = make_tree_vector ();
20951 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20952 vec_safe_push (placement_vec, TREE_VALUE (placement));
20955 /* If there was an initializer in the original tree, but it
20956 instantiated to an empty list, then we should pass a
20957 non-NULL empty vector to tell build_new that it was an
20958 empty initializer() rather than no initializer. This can
20959 only happen when the initializer is a pack expansion whose
20960 parameter packs are of length zero. */
20961 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20962 init_vec = NULL;
20963 else if (init == error_mark_node)
20964 RETURN (error_mark_node);
20965 else
20967 init_vec = make_tree_vector ();
20968 if (init == void_node)
20969 gcc_assert (init_vec != NULL);
20970 else
20972 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20973 vec_safe_push (init_vec, TREE_VALUE (init));
20977 /* Avoid passing an enclosing decl to valid_array_size_p. */
20978 in_decl = NULL_TREE;
20980 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20981 tree op2 = RECUR (TREE_OPERAND (t, 2));
20982 ret = build_new (loc, &placement_vec, op1, op2,
20983 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20984 complain);
20986 if (placement_vec != NULL)
20987 release_tree_vector (placement_vec);
20988 if (init_vec != NULL)
20989 release_tree_vector (init_vec);
20991 RETURN (ret);
20994 case DELETE_EXPR:
20996 tree op0 = RECUR (TREE_OPERAND (t, 0));
20997 tree op1 = RECUR (TREE_OPERAND (t, 1));
20998 RETURN (delete_sanity (input_location, op0, op1,
20999 DELETE_EXPR_USE_VEC (t),
21000 DELETE_EXPR_USE_GLOBAL (t),
21001 complain));
21004 case COMPOUND_EXPR:
21006 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
21007 complain & ~tf_decltype, in_decl);
21008 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
21009 op0,
21010 RECUR (TREE_OPERAND (t, 1)),
21011 templated_operator_saved_lookups (t),
21012 complain|decltype_flag));
21015 case CALL_EXPR:
21017 tree function;
21018 unsigned int nargs;
21019 bool qualified_p;
21020 bool koenig_p;
21021 tree ret;
21023 function = CALL_EXPR_FN (t);
21024 /* Internal function with no arguments. */
21025 if (function == NULL_TREE && call_expr_nargs (t) == 0)
21026 RETURN (t);
21028 /* When we parsed the expression, we determined whether or
21029 not Koenig lookup should be performed. */
21030 koenig_p = KOENIG_LOOKUP_P (t);
21031 if (function == NULL_TREE)
21033 koenig_p = false;
21034 qualified_p = false;
21036 else if (TREE_CODE (function) == SCOPE_REF)
21038 qualified_p = true;
21039 function = tsubst_qualified_id (function, args, complain, in_decl,
21040 /*done=*/false,
21041 /*address_p=*/false);
21043 else if (koenig_p
21044 && (identifier_p (function)
21045 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21046 && identifier_p (TREE_OPERAND (function, 0)))))
21048 /* Do nothing; calling tsubst_copy_and_build on an identifier
21049 would incorrectly perform unqualified lookup again.
21051 Note that we can also have an IDENTIFIER_NODE if the earlier
21052 unqualified lookup found a dependent local extern declaration
21053 (as per finish_call_expr); in that case koenig_p will be false
21054 and we do want to do the lookup again to find the substituted
21055 declaration. */
21056 qualified_p = false;
21058 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
21059 /* Use tsubst_copy to substitute through the template arguments
21060 of the template-id without performing unqualified lookup of
21061 the template name. */
21062 function = tsubst_copy (function, args, complain, in_decl);
21064 else
21066 if (TREE_CODE (function) == COMPONENT_REF)
21068 tree op = TREE_OPERAND (function, 1);
21070 qualified_p = (TREE_CODE (op) == SCOPE_REF
21071 || (BASELINK_P (op)
21072 && BASELINK_QUALIFIED_P (op)));
21074 else
21075 qualified_p = false;
21077 if (TREE_CODE (function) == ADDR_EXPR
21078 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
21079 /* Avoid error about taking the address of a constructor. */
21080 function = TREE_OPERAND (function, 0);
21082 tsubst_flags_t subcomplain = complain;
21083 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
21084 /* When KOENIG_P, we don't want to mark_used the callee before
21085 augmenting the overload set via ADL, so during this initial
21086 substitution we disable mark_used by setting tf_conv (68942). */
21087 subcomplain |= tf_conv;
21088 function = tsubst_copy_and_build (function, args, subcomplain, in_decl);
21090 if (BASELINK_P (function))
21091 qualified_p = true;
21094 nargs = call_expr_nargs (t);
21095 releasing_vec call_args;
21096 tsubst_copy_and_build_call_args (t, args, complain, in_decl,
21097 call_args);
21099 /* Stripped-down processing for a call in a thunk. Specifically, in
21100 the thunk template for a generic lambda. */
21101 if (call_from_lambda_thunk_p (t))
21103 /* Now that we've expanded any packs, the number of call args
21104 might be different. */
21105 unsigned int cargs = call_args->length ();
21106 tree thisarg = NULL_TREE;
21107 if (TREE_CODE (function) == COMPONENT_REF)
21109 thisarg = TREE_OPERAND (function, 0);
21110 if (TREE_CODE (thisarg) == INDIRECT_REF)
21111 thisarg = TREE_OPERAND (thisarg, 0);
21112 function = TREE_OPERAND (function, 1);
21113 if (TREE_CODE (function) == BASELINK)
21114 function = BASELINK_FUNCTIONS (function);
21116 /* We aren't going to do normal overload resolution, so force the
21117 template-id to resolve. */
21118 function = resolve_nondeduced_context (function, complain);
21119 for (unsigned i = 0; i < cargs; ++i)
21121 /* In a thunk, pass through args directly, without any
21122 conversions. */
21123 tree arg = (*call_args)[i];
21124 while (TREE_CODE (arg) != PARM_DECL)
21125 arg = TREE_OPERAND (arg, 0);
21126 (*call_args)[i] = arg;
21128 if (thisarg)
21130 /* If there are no other args, just push 'this'. */
21131 if (cargs == 0)
21132 vec_safe_push (call_args, thisarg);
21133 else
21135 /* Otherwise, shift the other args over to make room. */
21136 tree last = (*call_args)[cargs - 1];
21137 vec_safe_push (call_args, last);
21138 for (int i = cargs - 1; i > 0; --i)
21139 (*call_args)[i] = (*call_args)[i - 1];
21140 (*call_args)[0] = thisarg;
21143 ret = build_call_a (function, call_args->length (),
21144 call_args->address ());
21145 /* The thunk location is not interesting. */
21146 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
21147 CALL_FROM_THUNK_P (ret) = true;
21148 if (CLASS_TYPE_P (TREE_TYPE (ret)))
21149 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
21151 RETURN (ret);
21154 /* We do not perform argument-dependent lookup if normal
21155 lookup finds a non-function, in accordance with the
21156 resolution of DR 218. */
21157 if (koenig_p
21158 && ((is_overloaded_fn (function)
21159 /* If lookup found a member function, the Koenig lookup is
21160 not appropriate, even if an unqualified-name was used
21161 to denote the function. */
21162 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
21163 || identifier_p (function)
21164 /* C++20 P0846: Lookup found nothing. */
21165 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21166 && identifier_p (TREE_OPERAND (function, 0))))
21167 /* Only do this when substitution turns a dependent call
21168 into a non-dependent call. */
21169 && type_dependent_expression_p_push (t)
21170 && !any_type_dependent_arguments_p (call_args))
21171 function = perform_koenig_lookup (function, call_args, tf_none);
21173 if (function != NULL_TREE
21174 && (identifier_p (function)
21175 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21176 && identifier_p (TREE_OPERAND (function, 0))
21177 && !any_dependent_template_arguments_p (TREE_OPERAND
21178 (function, 1))))
21179 && !any_type_dependent_arguments_p (call_args))
21181 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
21182 if (template_id_p)
21183 function = TREE_OPERAND (function, 0);
21184 if (koenig_p && (complain & tf_warning_or_error))
21186 /* For backwards compatibility and good diagnostics, try
21187 the unqualified lookup again if we aren't in SFINAE
21188 context. */
21189 tree unq = tsubst_copy_and_build (function, args,
21190 complain, in_decl);
21191 if (unq == error_mark_node)
21192 RETURN (error_mark_node);
21194 if (unq != function)
21196 char const *const msg
21197 = G_("%qD was not declared in this scope, "
21198 "and no declarations were found by "
21199 "argument-dependent lookup at the point "
21200 "of instantiation");
21202 bool in_lambda = (current_class_type
21203 && LAMBDA_TYPE_P (current_class_type));
21204 /* In a lambda fn, we have to be careful to not
21205 introduce new this captures. Legacy code can't
21206 be using lambdas anyway, so it's ok to be
21207 stricter. Be strict with C++20 template-id ADL too.
21208 And be strict if we're already failing anyway. */
21209 bool strict = in_lambda || template_id_p || seen_error();
21210 bool diag = true;
21211 if (strict)
21212 error_at (cp_expr_loc_or_input_loc (t),
21213 msg, function);
21214 else
21215 diag = permerror (cp_expr_loc_or_input_loc (t),
21216 msg, function);
21217 if (diag)
21219 tree fn = unq;
21221 if (INDIRECT_REF_P (fn))
21222 fn = TREE_OPERAND (fn, 0);
21223 if (is_overloaded_fn (fn))
21224 fn = get_first_fn (fn);
21226 if (!DECL_P (fn))
21227 /* Can't say anything more. */;
21228 else if (DECL_CLASS_SCOPE_P (fn))
21230 location_t loc = cp_expr_loc_or_input_loc (t);
21231 inform (loc,
21232 "declarations in dependent base %qT are "
21233 "not found by unqualified lookup",
21234 DECL_CLASS_CONTEXT (fn));
21235 if (current_class_ptr)
21236 inform (loc,
21237 "use %<this->%D%> instead", function);
21238 else
21239 inform (loc,
21240 "use %<%T::%D%> instead",
21241 current_class_name, function);
21243 else
21244 inform (DECL_SOURCE_LOCATION (fn),
21245 "%qD declared here, later in the "
21246 "translation unit", fn);
21247 if (strict)
21248 RETURN (error_mark_node);
21251 function = unq;
21254 if (identifier_p (function))
21256 if (complain & tf_error)
21257 unqualified_name_lookup_error (function);
21258 RETURN (error_mark_node);
21262 /* Remember that there was a reference to this entity. */
21263 if (function != NULL_TREE
21264 && DECL_P (function)
21265 && !mark_used (function, complain) && !(complain & tf_error))
21266 RETURN (error_mark_node);
21268 if (!maybe_fold_fn_template_args (function, complain))
21269 return error_mark_node;
21271 /* Put back tf_decltype for the actual call. */
21272 complain |= decltype_flag;
21274 if (function == NULL_TREE)
21275 switch (CALL_EXPR_IFN (t))
21277 case IFN_LAUNDER:
21278 gcc_assert (nargs == 1);
21279 if (vec_safe_length (call_args) != 1)
21281 error_at (cp_expr_loc_or_input_loc (t),
21282 "wrong number of arguments to "
21283 "%<__builtin_launder%>");
21284 ret = error_mark_node;
21286 else
21287 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21288 (*call_args)[0], complain);
21289 break;
21291 case IFN_VEC_CONVERT:
21292 gcc_assert (nargs == 1);
21293 if (vec_safe_length (call_args) != 1)
21295 error_at (cp_expr_loc_or_input_loc (t),
21296 "wrong number of arguments to "
21297 "%<__builtin_convertvector%>");
21298 ret = error_mark_node;
21299 break;
21301 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21302 tsubst (TREE_TYPE (t), args,
21303 complain, in_decl),
21304 complain);
21305 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21306 RETURN (ret);
21307 break;
21309 case IFN_SHUFFLEVECTOR:
21311 ret = build_x_shufflevector (input_location, call_args,
21312 complain);
21313 if (ret != error_mark_node)
21314 RETURN (ret);
21315 break;
21318 case IFN_ASSUME:
21319 gcc_assert (nargs == 1);
21320 if (vec_safe_length (call_args) != 1)
21322 error_at (cp_expr_loc_or_input_loc (t),
21323 "wrong number of arguments to "
21324 "%<assume%> attribute");
21325 ret = error_mark_node;
21327 else
21329 tree &arg = (*call_args)[0];
21330 if (!type_dependent_expression_p (arg))
21331 arg = contextual_conv_bool (arg, tf_warning_or_error);
21332 if (error_operand_p (arg))
21334 ret = error_mark_node;
21335 break;
21337 ret = build_assume_call (EXPR_LOCATION (t), arg);
21338 RETURN (ret);
21340 break;
21342 default:
21343 /* Unsupported internal function with arguments. */
21344 gcc_unreachable ();
21346 else if (TREE_CODE (function) == OFFSET_REF
21347 || TREE_CODE (function) == DOTSTAR_EXPR
21348 || TREE_CODE (function) == MEMBER_REF)
21349 ret = build_offset_ref_call_from_tree (function, &call_args,
21350 complain);
21351 else if (TREE_CODE (function) == COMPONENT_REF)
21353 tree instance = TREE_OPERAND (function, 0);
21354 tree fn = TREE_OPERAND (function, 1);
21356 if (processing_template_decl
21357 && (type_dependent_expression_p (instance)
21358 || (!BASELINK_P (fn)
21359 && TREE_CODE (fn) != FIELD_DECL)
21360 || type_dependent_expression_p (fn)
21361 || any_type_dependent_arguments_p (call_args)))
21362 ret = build_min_nt_call_vec (function, call_args);
21363 else if (!BASELINK_P (fn))
21364 ret = finish_call_expr (function, &call_args,
21365 /*disallow_virtual=*/false,
21366 /*koenig_p=*/false,
21367 complain);
21368 else
21369 ret = (build_new_method_call
21370 (instance, fn,
21371 &call_args, NULL_TREE,
21372 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21373 /*fn_p=*/NULL,
21374 complain));
21376 else if (concept_check_p (function))
21378 /* FUNCTION is a template-id referring to a concept definition. */
21379 tree id = unpack_concept_check (function);
21380 tree tmpl = TREE_OPERAND (id, 0);
21381 tree args = TREE_OPERAND (id, 1);
21383 /* Calls to standard and variable concepts should have been
21384 previously diagnosed. */
21385 gcc_assert (function_concept_p (tmpl));
21387 /* Ensure the result is wrapped as a call expression. */
21388 ret = build_concept_check (tmpl, args, tf_warning_or_error);
21390 else
21391 ret = finish_call_expr (function, &call_args,
21392 /*disallow_virtual=*/qualified_p,
21393 koenig_p,
21394 complain);
21396 if (ret != error_mark_node)
21398 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21399 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21400 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21401 if (op || ord || rev)
21402 if (tree call = extract_call_expr (ret))
21404 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21405 CALL_EXPR_ORDERED_ARGS (call) = ord;
21406 CALL_EXPR_REVERSE_ARGS (call) = rev;
21408 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21409 /* This also suppresses -Wredundant-move. */
21410 suppress_warning (ret, OPT_Wpessimizing_move);
21413 RETURN (ret);
21416 case COND_EXPR:
21418 tree cond = RECUR (TREE_OPERAND (t, 0));
21419 cond = mark_rvalue_use (cond);
21420 tree folded_cond = fold_non_dependent_expr (cond, complain);
21421 tree exp1, exp2;
21423 if (TREE_CODE (folded_cond) == INTEGER_CST)
21425 if (integer_zerop (folded_cond))
21427 ++c_inhibit_evaluation_warnings;
21428 exp1 = RECUR (TREE_OPERAND (t, 1));
21429 --c_inhibit_evaluation_warnings;
21430 exp2 = RECUR (TREE_OPERAND (t, 2));
21432 else
21434 exp1 = RECUR (TREE_OPERAND (t, 1));
21435 ++c_inhibit_evaluation_warnings;
21436 exp2 = RECUR (TREE_OPERAND (t, 2));
21437 --c_inhibit_evaluation_warnings;
21439 cond = folded_cond;
21441 else
21443 exp1 = RECUR (TREE_OPERAND (t, 1));
21444 exp2 = RECUR (TREE_OPERAND (t, 2));
21447 warning_sentinel s(warn_duplicated_branches);
21448 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21449 cond, exp1, exp2, complain));
21452 case PSEUDO_DTOR_EXPR:
21454 tree op0 = RECUR (TREE_OPERAND (t, 0));
21455 tree op1 = RECUR (TREE_OPERAND (t, 1));
21456 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21457 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21458 input_location));
21461 case TREE_LIST:
21462 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21464 case COMPONENT_REF:
21466 tree object;
21467 tree object_type;
21468 tree member;
21469 tree r;
21471 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21472 args, complain, in_decl);
21473 /* Remember that there was a reference to this entity. */
21474 if (DECL_P (object)
21475 && !mark_used (object, complain) && !(complain & tf_error))
21476 RETURN (error_mark_node);
21477 object_type = TREE_TYPE (object);
21479 member = TREE_OPERAND (t, 1);
21480 if (BASELINK_P (member))
21481 member = tsubst_baselink (member,
21482 non_reference (TREE_TYPE (object)),
21483 args, complain, in_decl);
21484 else
21485 member = tsubst_copy (member, args, complain, in_decl);
21486 if (member == error_mark_node)
21487 RETURN (error_mark_node);
21489 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21490 && TREE_CODE (member) == FIELD_DECL)
21492 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21493 RETURN (r);
21495 else if (TREE_CODE (member) == FIELD_DECL)
21497 r = finish_non_static_data_member (member, object, NULL_TREE,
21498 complain);
21499 if (TREE_CODE (r) == COMPONENT_REF)
21500 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21501 RETURN (r);
21503 else if (type_dependent_expression_p (object))
21504 /* We can't do much here. */;
21505 else if (!CLASS_TYPE_P (object_type))
21507 if (scalarish_type_p (object_type))
21509 tree s = NULL_TREE;
21510 tree dtor = member;
21512 if (TREE_CODE (dtor) == SCOPE_REF)
21514 s = TREE_OPERAND (dtor, 0);
21515 dtor = TREE_OPERAND (dtor, 1);
21517 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21519 dtor = TREE_OPERAND (dtor, 0);
21520 if (TYPE_P (dtor))
21521 RETURN (finish_pseudo_destructor_expr
21522 (object, s, dtor, input_location));
21526 else if (TREE_CODE (member) == SCOPE_REF
21527 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21529 /* Lookup the template functions now that we know what the
21530 scope is. */
21531 tree scope = TREE_OPERAND (member, 0);
21532 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21533 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21534 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21535 /*complain=*/false);
21536 if (BASELINK_P (member))
21538 BASELINK_FUNCTIONS (member)
21539 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21540 args);
21541 member = (adjust_result_of_qualified_name_lookup
21542 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21543 object_type));
21545 else
21547 qualified_name_lookup_error (scope, tmpl, member,
21548 input_location);
21549 RETURN (error_mark_node);
21552 else if (TREE_CODE (member) == SCOPE_REF
21553 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21554 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21556 if (complain & tf_error)
21558 if (TYPE_P (TREE_OPERAND (member, 0)))
21559 error ("%qT is not a class or namespace",
21560 TREE_OPERAND (member, 0));
21561 else
21562 error ("%qD is not a class or namespace",
21563 TREE_OPERAND (member, 0));
21565 RETURN (error_mark_node);
21568 r = finish_class_member_access_expr (object, member,
21569 /*template_p=*/false,
21570 complain);
21571 if (REF_PARENTHESIZED_P (t))
21572 r = force_paren_expr (r);
21573 RETURN (r);
21576 case THROW_EXPR:
21577 RETURN (build_throw
21578 (input_location, RECUR (TREE_OPERAND (t, 0))));
21580 case CONSTRUCTOR:
21582 vec<constructor_elt, va_gc> *n;
21583 constructor_elt *ce;
21584 unsigned HOST_WIDE_INT idx;
21585 bool process_index_p;
21586 int newlen;
21587 bool need_copy_p = false;
21588 tree r;
21590 tsubst_flags_t tcomplain = complain;
21591 if (COMPOUND_LITERAL_P (t))
21592 tcomplain |= tf_tst_ok;
21593 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21594 if (type == error_mark_node)
21595 RETURN (error_mark_node);
21597 /* We do not want to process the index of aggregate
21598 initializers as they are identifier nodes which will be
21599 looked up by digest_init. */
21600 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21602 if (null_member_pointer_value_p (t))
21604 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21605 RETURN (t);
21608 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21609 newlen = vec_safe_length (n);
21610 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21612 if (ce->index && process_index_p
21613 /* An identifier index is looked up in the type
21614 being initialized, not the current scope. */
21615 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21616 ce->index = RECUR (ce->index);
21618 if (PACK_EXPANSION_P (ce->value))
21620 /* Substitute into the pack expansion. */
21621 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21622 in_decl);
21624 if (ce->value == error_mark_node
21625 || PACK_EXPANSION_P (ce->value))
21627 else if (TREE_VEC_LENGTH (ce->value) == 1)
21628 /* Just move the argument into place. */
21629 ce->value = TREE_VEC_ELT (ce->value, 0);
21630 else
21632 /* Update the length of the final CONSTRUCTOR
21633 arguments vector, and note that we will need to
21634 copy.*/
21635 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21636 need_copy_p = true;
21639 else
21640 ce->value = RECUR (ce->value);
21643 if (need_copy_p)
21645 vec<constructor_elt, va_gc> *old_n = n;
21647 vec_alloc (n, newlen);
21648 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21650 if (TREE_CODE (ce->value) == TREE_VEC)
21652 int i, len = TREE_VEC_LENGTH (ce->value);
21653 for (i = 0; i < len; ++i)
21654 CONSTRUCTOR_APPEND_ELT (n, 0,
21655 TREE_VEC_ELT (ce->value, i));
21657 else
21658 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21662 r = build_constructor (init_list_type_node, n);
21663 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21664 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21665 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21667 if (TREE_HAS_CONSTRUCTOR (t))
21669 fcl_t cl = fcl_functional;
21670 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21671 cl = fcl_c99;
21672 RETURN (finish_compound_literal (type, r, complain, cl));
21675 TREE_TYPE (r) = type;
21676 RETURN (r);
21679 case TYPEID_EXPR:
21681 tree operand_0 = TREE_OPERAND (t, 0);
21682 if (TYPE_P (operand_0))
21684 operand_0 = tsubst (operand_0, args, complain, in_decl);
21685 RETURN (get_typeid (operand_0, complain));
21687 else
21689 operand_0 = RECUR (operand_0);
21690 RETURN (build_typeid (operand_0, complain));
21694 case VAR_DECL:
21695 if (!args)
21696 RETURN (t);
21697 /* Fall through */
21699 case PARM_DECL:
21701 tree r = tsubst_copy (t, args, complain, in_decl);
21702 /* ??? We're doing a subset of finish_id_expression here. */
21703 if (tree wrap = maybe_get_tls_wrapper_call (r))
21704 /* Replace an evaluated use of the thread_local variable with
21705 a call to its wrapper. */
21706 r = wrap;
21707 else if (outer_automatic_var_p (r))
21708 r = process_outer_var_ref (r, complain);
21710 if (!TYPE_REF_P (TREE_TYPE (t)))
21711 /* If the original type was a reference, we'll be wrapped in
21712 the appropriate INDIRECT_REF. */
21713 r = convert_from_reference (r);
21714 RETURN (r);
21717 case VA_ARG_EXPR:
21719 tree op0 = RECUR (TREE_OPERAND (t, 0));
21720 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21721 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21724 case OFFSETOF_EXPR:
21726 tree object_ptr
21727 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args,
21728 complain, in_decl);
21729 RETURN (finish_offsetof (object_ptr,
21730 RECUR (TREE_OPERAND (t, 0)),
21731 EXPR_LOCATION (t)));
21734 case ADDRESSOF_EXPR:
21735 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21736 RECUR (TREE_OPERAND (t, 0)), complain));
21738 case TRAIT_EXPR:
21740 tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
21741 complain, in_decl);
21742 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21743 complain, in_decl);
21744 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21745 TRAIT_EXPR_KIND (t), type1, type2));
21748 case STMT_EXPR:
21750 tree old_stmt_expr = cur_stmt_expr;
21751 tree stmt_expr = begin_stmt_expr ();
21753 cur_stmt_expr = stmt_expr;
21754 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
21755 stmt_expr = finish_stmt_expr (stmt_expr, false);
21756 cur_stmt_expr = old_stmt_expr;
21758 /* If the resulting list of expression statement is empty,
21759 fold it further into void_node. */
21760 if (empty_expr_stmt_p (stmt_expr))
21761 stmt_expr = void_node;
21763 RETURN (stmt_expr);
21766 case LAMBDA_EXPR:
21768 if (complain & tf_partial)
21770 /* We don't have a full set of template arguments yet; don't touch
21771 the lambda at all. */
21772 gcc_assert (processing_template_decl);
21773 return t;
21775 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21777 RETURN (build_lambda_object (r));
21780 case TRANSACTION_EXPR:
21781 RETURN (tsubst_expr (t, args, complain, in_decl));
21783 case PAREN_EXPR:
21784 if (REF_PARENTHESIZED_P (t))
21785 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21786 else
21787 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21789 tree op0 = RECUR (TREE_OPERAND (t, 0));
21790 RETURN (build1_loc (input_location, PAREN_EXPR,
21791 TREE_TYPE (op0), op0));
21794 case VEC_PERM_EXPR:
21796 tree op0 = RECUR (TREE_OPERAND (t, 0));
21797 tree op1 = RECUR (TREE_OPERAND (t, 1));
21798 tree op2 = RECUR (TREE_OPERAND (t, 2));
21799 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21800 complain));
21803 case REQUIRES_EXPR:
21805 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21806 RETURN (r);
21809 case RANGE_EXPR:
21810 /* No need to substitute further, a RANGE_EXPR will always be built
21811 with constant operands. */
21812 RETURN (t);
21814 case NON_LVALUE_EXPR:
21815 case VIEW_CONVERT_EXPR:
21817 tree op = RECUR (TREE_OPERAND (t, 0));
21819 if (location_wrapper_p (t))
21820 /* We need to do this here as well as in tsubst_copy so we get the
21821 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21822 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21824 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21825 if (REF_PARENTHESIZED_P (t))
21826 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21827 RETURN (finish_parenthesized_expr (op));
21829 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21830 parameter object const. */
21831 if (TREE_TYPE (op) == NULL_TREE
21832 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21834 /* The template argument is not const, presumably because
21835 it is still dependent, and so not the const template parm
21836 object. */
21837 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21838 if (TREE_CODE (op) == CONSTRUCTOR
21839 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21841 /* Don't add a wrapper to these. */
21842 op = copy_node (op);
21843 TREE_TYPE (op) = type;
21845 else
21846 /* Do add a wrapper otherwise (in particular, if op is
21847 another TEMPLATE_PARM_INDEX). */
21848 op = build1 (VIEW_CONVERT_EXPR, type, op);
21850 RETURN (op);
21853 default:
21854 /* Handle Objective-C++ constructs, if appropriate. */
21856 tree subst
21857 = objcp_tsubst_copy_and_build (t, args, complain, in_decl);
21858 if (subst)
21859 RETURN (subst);
21861 RETURN (tsubst_copy (t, args, complain, in_decl));
21864 #undef RECUR
21865 #undef RETURN
21866 out:
21867 input_location = save_loc;
21868 return retval;
21871 /* Verify that the instantiated ARGS are valid. For type arguments,
21872 make sure that the type's linkage is ok. For non-type arguments,
21873 make sure they are constants if they are integral or enumerations.
21874 Emit an error under control of COMPLAIN, and return TRUE on error. */
21876 static bool
21877 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21879 if (dependent_template_arg_p (t))
21880 return false;
21881 if (ARGUMENT_PACK_P (t))
21883 tree vec = ARGUMENT_PACK_ARGS (t);
21884 int len = TREE_VEC_LENGTH (vec);
21885 bool result = false;
21886 int i;
21888 for (i = 0; i < len; ++i)
21889 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21890 result = true;
21891 return result;
21893 else if (TYPE_P (t))
21895 /* [basic.link]: A name with no linkage (notably, the name
21896 of a class or enumeration declared in a local scope)
21897 shall not be used to declare an entity with linkage.
21898 This implies that names with no linkage cannot be used as
21899 template arguments
21901 DR 757 relaxes this restriction for C++0x. */
21902 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21903 : no_linkage_check (t, /*relaxed_p=*/false));
21905 if (nt)
21907 /* DR 488 makes use of a type with no linkage cause
21908 type deduction to fail. */
21909 if (complain & tf_error)
21911 if (TYPE_UNNAMED_P (nt))
21912 error ("%qT is/uses unnamed type", t);
21913 else
21914 error ("template argument for %qD uses local type %qT",
21915 tmpl, t);
21917 return true;
21919 /* In order to avoid all sorts of complications, we do not
21920 allow variably-modified types as template arguments. */
21921 else if (variably_modified_type_p (t, NULL_TREE))
21923 if (complain & tf_error)
21924 error ("%qT is a variably modified type", t);
21925 return true;
21928 /* Class template and alias template arguments should be OK. */
21929 else if (DECL_TYPE_TEMPLATE_P (t))
21931 /* A non-type argument of integral or enumerated type must be a
21932 constant. */
21933 else if (TREE_TYPE (t)
21934 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21935 && !REFERENCE_REF_P (t)
21936 && !TREE_CONSTANT (t))
21938 if (complain & tf_error)
21939 error ("integral expression %qE is not constant", t);
21940 return true;
21942 return false;
21945 static bool
21946 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21948 int ix, len = DECL_NTPARMS (tmpl);
21949 bool result = false;
21951 for (ix = 0; ix != len; ix++)
21953 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21954 result = true;
21956 if (result && (complain & tf_error))
21957 error (" trying to instantiate %qD", tmpl);
21958 return result;
21961 /* Call mark_used on each entity within the non-type template arguments in
21962 ARGS for an instantiation of TMPL, to ensure that each such entity is
21963 considered odr-used (and therefore marked for instantiation) regardless of
21964 whether the specialization was first formed in a template context (which
21965 inhibits mark_used).
21967 This function assumes push_to_top_level has been called beforehand. */
21969 static void
21970 mark_template_arguments_used (tree tmpl, tree args)
21972 /* It suffices to do this only when instantiating a primary template. */
21973 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21974 return;
21976 /* We already marked outer arguments when specializing the context. */
21977 args = INNERMOST_TEMPLATE_ARGS (args);
21979 for (tree arg : tree_vec_range (args))
21981 /* A (pointer/reference to) function or variable NTTP argument. */
21982 if (TREE_CODE (arg) == ADDR_EXPR
21983 || TREE_CODE (arg) == INDIRECT_REF)
21985 while (TREE_CODE (arg) == ADDR_EXPR
21986 || REFERENCE_REF_P (arg)
21987 || CONVERT_EXPR_P (arg))
21988 arg = TREE_OPERAND (arg, 0);
21989 if (VAR_OR_FUNCTION_DECL_P (arg))
21991 /* Pass tf_none to avoid duplicate diagnostics: if this call
21992 fails then an earlier call to mark_used for this argument
21993 must have also failed and emitted a diagnostic. */
21994 bool ok = mark_used (arg, tf_none);
21995 gcc_checking_assert (ok || seen_error ());
21998 /* A class NTTP argument. */
21999 else if (VAR_P (arg)
22000 && DECL_NTTP_OBJECT_P (arg))
22002 auto mark_used_r = [](tree *tp, int *, void *) {
22003 if (VAR_OR_FUNCTION_DECL_P (*tp))
22005 bool ok = mark_used (*tp, tf_none);
22006 gcc_checking_assert (ok || seen_error ());
22008 return NULL_TREE;
22010 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
22011 mark_used_r, nullptr);
22016 /* We're out of SFINAE context now, so generate diagnostics for the access
22017 errors we saw earlier when instantiating D from TMPL and ARGS. */
22019 static void
22020 recheck_decl_substitution (tree d, tree tmpl, tree args)
22022 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
22023 tree type = TREE_TYPE (pattern);
22024 location_t loc = input_location;
22026 push_access_scope (d);
22027 push_deferring_access_checks (dk_no_deferred);
22028 input_location = DECL_SOURCE_LOCATION (pattern);
22029 tsubst (type, args, tf_warning_or_error, d);
22030 input_location = loc;
22031 pop_deferring_access_checks ();
22032 pop_access_scope (d);
22035 /* Instantiate the indicated variable, function, or alias template TMPL with
22036 the template arguments in TARG_PTR. */
22038 tree
22039 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
22041 auto_timevar tv (TV_TEMPLATE_INST);
22043 tree targ_ptr = orig_args;
22044 tree fndecl;
22045 tree gen_tmpl;
22046 bool access_ok = true;
22048 if (tmpl == error_mark_node)
22049 return error_mark_node;
22051 /* The other flags are not relevant anymore here, especially tf_partial
22052 shouldn't be set. For instance, we may be called while doing a partial
22053 substitution of a template variable, but the type of the variable
22054 template may be auto, in which case we will call do_auto_deduction
22055 in mark_used (which clears tf_partial) and the auto must be properly
22056 reduced at that time for the deduction to work. */
22057 complain &= tf_warning_or_error;
22059 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
22061 if (modules_p ())
22062 lazy_load_pendings (tmpl);
22064 /* If this function is a clone, handle it specially. */
22065 if (DECL_CLONED_FUNCTION_P (tmpl))
22067 tree spec;
22068 tree clone;
22070 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
22071 DECL_CLONED_FUNCTION. */
22072 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
22073 targ_ptr, complain);
22074 if (spec == error_mark_node)
22075 return error_mark_node;
22077 /* Look for the clone. */
22078 FOR_EACH_CLONE (clone, spec)
22079 if (DECL_NAME (clone) == DECL_NAME (tmpl))
22080 return clone;
22081 /* We should always have found the clone by now. */
22082 gcc_unreachable ();
22083 return NULL_TREE;
22086 if (targ_ptr == error_mark_node)
22087 return error_mark_node;
22089 /* Check to see if we already have this specialization. */
22090 gen_tmpl = most_general_template (tmpl);
22091 if (TMPL_ARGS_DEPTH (targ_ptr)
22092 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22093 /* targ_ptr only has the innermost template args, so add the outer ones
22094 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22095 the case of a non-dependent call within a template definition). */
22096 targ_ptr = (add_outermost_template_args
22097 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22098 targ_ptr));
22100 hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
22101 tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
22103 gcc_checking_assert (tmpl == gen_tmpl
22104 || ((fndecl
22105 = retrieve_specialization (tmpl, orig_args, 0))
22106 == spec)
22107 || fndecl == NULL_TREE);
22109 if (spec != NULL_TREE)
22111 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22113 if (complain & tf_error)
22114 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22115 return error_mark_node;
22117 return spec;
22120 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22121 complain))
22122 return error_mark_node;
22124 /* We are building a FUNCTION_DECL, during which the access of its
22125 parameters and return types have to be checked. However this
22126 FUNCTION_DECL which is the desired context for access checking
22127 is not built yet. We solve this chicken-and-egg problem by
22128 deferring all checks until we have the FUNCTION_DECL. */
22129 push_deferring_access_checks (dk_deferred);
22131 /* Instantiation of the function happens in the context of the function
22132 template, not the context of the overload resolution we're doing. */
22133 push_to_top_level ();
22134 /* If there are dependent arguments, e.g. because we're doing partial
22135 ordering, make sure processing_template_decl stays set. */
22136 if (uses_template_parms (targ_ptr))
22137 ++processing_template_decl;
22138 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22140 tree ctx;
22141 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22142 /* If the context of the partially instantiated template is
22143 already non-dependent, then we might as well use it. */
22144 ctx = DECL_CONTEXT (tmpl);
22145 else
22146 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22147 complain, gen_tmpl, true);
22148 push_nested_class (ctx);
22151 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22153 tree partial_ti = NULL_TREE;
22154 fndecl = NULL_TREE;
22155 if (VAR_P (pattern))
22157 /* We need to determine if we're using a partial or explicit
22158 specialization now, because the type of the variable could be
22159 different. */
22160 tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
22161 partial_ti = most_specialized_partial_spec (tid, complain);
22162 if (partial_ti == error_mark_node)
22163 pattern = error_mark_node;
22164 else if (partial_ti)
22166 tree partial_tmpl = TI_TEMPLATE (partial_ti);
22167 tree partial_args = TI_ARGS (partial_ti);
22168 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22169 fndecl = tsubst_decl (partial_pat, partial_args, complain,
22170 /*use_spec_table=*/false);
22174 /* Substitute template parameters to obtain the specialization. */
22175 if (fndecl == NULL_TREE)
22176 fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
22177 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22178 pop_nested_class ();
22179 pop_from_top_level ();
22181 if (fndecl == error_mark_node)
22183 pop_deferring_access_checks ();
22184 return error_mark_node;
22187 /* The DECL_TI_TEMPLATE should always be the immediate parent
22188 template, not the most general template. */
22189 DECL_TI_TEMPLATE (fndecl) = tmpl;
22190 DECL_TI_ARGS (fndecl) = targ_ptr;
22191 if (VAR_P (pattern))
22192 /* Now that we we've formed this variable template specialization,
22193 remember the result of most_specialized_partial_spec for it. */
22194 TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
22196 fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
22197 if (fndecl == error_mark_node)
22198 return error_mark_node;
22200 set_instantiating_module (fndecl);
22202 /* Now we know the specialization, compute access previously
22203 deferred. Do no access control for inheriting constructors,
22204 as we already checked access for the inherited constructor. */
22205 if (!(flag_new_inheriting_ctors
22206 && DECL_INHERITED_CTOR (fndecl)))
22208 push_access_scope (fndecl);
22209 if (!perform_deferred_access_checks (complain))
22210 access_ok = false;
22211 pop_access_scope (fndecl);
22213 pop_deferring_access_checks ();
22215 /* If we've just instantiated the main entry point for a function,
22216 instantiate all the alternate entry points as well. We do this
22217 by cloning the instantiation of the main entry point, not by
22218 instantiating the template clones. */
22219 if (tree chain = DECL_CHAIN (gen_tmpl))
22220 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22221 clone_cdtor (fndecl, /*update_methods=*/false);
22223 if (!access_ok)
22225 if (!(complain & tf_error))
22227 /* Remember to reinstantiate when we're out of SFINAE so the user
22228 can see the errors. */
22229 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22231 return error_mark_node;
22234 return fndecl;
22237 /* Instantiate the alias template TMPL with ARGS. Also push a template
22238 instantiation level, which instantiate_template doesn't do because
22239 functions and variables have sufficient context established by the
22240 callers. */
22242 static tree
22243 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22245 if (tmpl == error_mark_node || args == error_mark_node)
22246 return error_mark_node;
22248 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22249 args, tmpl, complain);
22250 if (args == error_mark_node)
22251 return error_mark_node;
22253 /* FIXME check for satisfaction in check_instantiated_args. */
22254 if (!constraints_satisfied_p (tmpl, args))
22256 if (complain & tf_error)
22258 auto_diagnostic_group d;
22259 error ("template constraint failure for %qD", tmpl);
22260 diagnose_constraints (input_location, tmpl, args);
22262 return error_mark_node;
22265 if (!push_tinst_level (tmpl, args))
22266 return error_mark_node;
22267 tree r = instantiate_template (tmpl, args, complain);
22268 pop_tinst_level ();
22270 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22272 /* An alias template specialization can be dependent
22273 even if its underlying type is not. */
22274 TYPE_DEPENDENT_P (d) = true;
22275 TYPE_DEPENDENT_P_VALID (d) = true;
22276 /* Sometimes a dependent alias spec is equivalent to its expansion,
22277 sometimes not. So always use structural_comptypes. */
22278 SET_TYPE_STRUCTURAL_EQUALITY (d);
22281 return r;
22284 /* PARM is a template parameter pack for FN. Returns true iff
22285 PARM is used in a deducible way in the argument list of FN. */
22287 static bool
22288 pack_deducible_p (tree parm, tree fn)
22290 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22291 for (; t; t = TREE_CHAIN (t))
22293 tree type = TREE_VALUE (t);
22294 tree packs;
22295 if (!PACK_EXPANSION_P (type))
22296 continue;
22297 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22298 packs; packs = TREE_CHAIN (packs))
22299 if (template_args_equal (TREE_VALUE (packs), parm))
22301 /* The template parameter pack is used in a function parameter
22302 pack. If this is the end of the parameter list, the
22303 template parameter pack is deducible. */
22304 if (TREE_CHAIN (t) == void_list_node)
22305 return true;
22306 else
22307 /* Otherwise, not. Well, it could be deduced from
22308 a non-pack parameter, but doing so would end up with
22309 a deduction mismatch, so don't bother. */
22310 return false;
22313 /* The template parameter pack isn't used in any function parameter
22314 packs, but it might be used deeper, e.g. tuple<Args...>. */
22315 return true;
22318 /* Subroutine of fn_type_unification: check non-dependent parms for
22319 convertibility. */
22321 static int
22322 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22323 tree fn, unification_kind_t strict, int flags,
22324 struct conversion **convs, bool explain_p)
22326 /* Non-constructor methods need to leave a conversion for 'this', which
22327 isn't included in nargs here. */
22328 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22329 && !DECL_CONSTRUCTOR_P (fn));
22331 for (unsigned ia = 0;
22332 parms && parms != void_list_node && ia < nargs; )
22334 tree parm = TREE_VALUE (parms);
22336 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22337 && (!TREE_CHAIN (parms)
22338 || TREE_CHAIN (parms) == void_list_node))
22339 /* For a function parameter pack that occurs at the end of the
22340 parameter-declaration-list, the type A of each remaining
22341 argument of the call is compared with the type P of the
22342 declarator-id of the function parameter pack. */
22343 break;
22345 parms = TREE_CHAIN (parms);
22347 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22348 /* For a function parameter pack that does not occur at the
22349 end of the parameter-declaration-list, the type of the
22350 parameter pack is a non-deduced context. */
22351 continue;
22353 if (!uses_template_parms (parm))
22355 tree arg = args[ia];
22356 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22357 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22359 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22360 conv_p, explain_p))
22361 return 1;
22364 ++ia;
22367 return 0;
22370 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22371 NARGS elements of the arguments that are being used when calling
22372 it. TARGS is a vector into which the deduced template arguments
22373 are placed.
22375 Returns either a FUNCTION_DECL for the matching specialization of FN or
22376 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22377 true, diagnostics will be printed to explain why it failed.
22379 If FN is a conversion operator, or we are trying to produce a specific
22380 specialization, RETURN_TYPE is the return type desired.
22382 The EXPLICIT_TARGS are explicit template arguments provided via a
22383 template-id.
22385 The parameter STRICT is one of:
22387 DEDUCE_CALL:
22388 We are deducing arguments for a function call, as in
22389 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22390 deducing arguments for a call to the result of a conversion
22391 function template, as in [over.call.object].
22393 DEDUCE_CONV:
22394 We are deducing arguments for a conversion function, as in
22395 [temp.deduct.conv].
22397 DEDUCE_EXACT:
22398 We are deducing arguments when doing an explicit instantiation
22399 as in [temp.explicit], when determining an explicit specialization
22400 as in [temp.expl.spec], or when taking the address of a function
22401 template, as in [temp.deduct.funcaddr]. */
22403 tree
22404 fn_type_unification (tree fn,
22405 tree explicit_targs,
22406 tree targs,
22407 const tree *args,
22408 unsigned int nargs,
22409 tree return_type,
22410 unification_kind_t strict,
22411 int flags,
22412 struct conversion **convs,
22413 bool explain_p,
22414 bool decltype_p)
22416 tree parms;
22417 tree fntype;
22418 tree decl = NULL_TREE;
22419 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22420 bool ok;
22421 static int deduction_depth;
22422 /* type_unification_real will pass back any access checks from default
22423 template argument substitution. */
22424 vec<deferred_access_check, va_gc> *checks = NULL;
22425 /* We don't have all the template args yet. */
22426 bool incomplete = true;
22428 tree orig_fn = fn;
22429 if (flag_new_inheriting_ctors)
22430 fn = strip_inheriting_ctors (fn);
22432 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22433 tree r = error_mark_node;
22435 tree full_targs = targs;
22436 if (TMPL_ARGS_DEPTH (targs)
22437 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22438 full_targs = (add_outermost_template_args
22439 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22440 targs));
22442 if (decltype_p)
22443 complain |= tf_decltype;
22445 /* In C++0x, it's possible to have a function template whose type depends
22446 on itself recursively. This is most obvious with decltype, but can also
22447 occur with enumeration scope (c++/48969). So we need to catch infinite
22448 recursion and reject the substitution at deduction time; this function
22449 will return error_mark_node for any repeated substitution.
22451 This also catches excessive recursion such as when f<N> depends on
22452 f<N-1> across all integers, and returns error_mark_node for all the
22453 substitutions back up to the initial one.
22455 This is, of course, not reentrant. */
22456 if (excessive_deduction_depth)
22457 return error_mark_node;
22458 ++deduction_depth;
22460 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22462 fntype = TREE_TYPE (fn);
22463 if (explicit_targs)
22465 /* [temp.deduct]
22467 The specified template arguments must match the template
22468 parameters in kind (i.e., type, nontype, template), and there
22469 must not be more arguments than there are parameters;
22470 otherwise type deduction fails.
22472 Nontype arguments must match the types of the corresponding
22473 nontype template parameters, or must be convertible to the
22474 types of the corresponding nontype parameters as specified in
22475 _temp.arg.nontype_, otherwise type deduction fails.
22477 All references in the function type of the function template
22478 to the corresponding template parameters are replaced by the
22479 specified template argument values. If a substitution in a
22480 template parameter or in the function type of the function
22481 template results in an invalid type, type deduction fails. */
22482 int i, len = TREE_VEC_LENGTH (tparms);
22483 location_t loc = input_location;
22484 incomplete = false;
22486 if (explicit_targs == error_mark_node)
22487 goto fail;
22489 if (TMPL_ARGS_DEPTH (explicit_targs)
22490 < TMPL_ARGS_DEPTH (full_targs))
22491 explicit_targs = add_outermost_template_args (full_targs,
22492 explicit_targs);
22494 /* Adjust any explicit template arguments before entering the
22495 substitution context. */
22496 explicit_targs
22497 = (coerce_template_parms (tparms, explicit_targs, fn,
22498 complain|tf_partial,
22499 /*require_all_args=*/false));
22500 if (explicit_targs == error_mark_node)
22501 goto fail;
22503 /* Substitute the explicit args into the function type. This is
22504 necessary so that, for instance, explicitly declared function
22505 arguments can match null pointed constants. If we were given
22506 an incomplete set of explicit args, we must not do semantic
22507 processing during substitution as we could create partial
22508 instantiations. */
22509 for (i = 0; i < len; i++)
22511 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22512 bool parameter_pack = false;
22513 tree targ = TREE_VEC_ELT (explicit_targs, i);
22515 /* Dig out the actual parm. */
22516 if (TREE_CODE (parm) == TYPE_DECL
22517 || TREE_CODE (parm) == TEMPLATE_DECL)
22519 parm = TREE_TYPE (parm);
22520 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22522 else if (TREE_CODE (parm) == PARM_DECL)
22524 parm = DECL_INITIAL (parm);
22525 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22528 if (targ == NULL_TREE)
22529 /* No explicit argument for this template parameter. */
22530 incomplete = true;
22531 else if (parameter_pack && pack_deducible_p (parm, fn))
22533 /* Mark the argument pack as "incomplete". We could
22534 still deduce more arguments during unification.
22535 We remove this mark in type_unification_real. */
22536 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22537 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22538 = ARGUMENT_PACK_ARGS (targ);
22540 /* We have some incomplete argument packs. */
22541 incomplete = true;
22545 if (incomplete)
22547 if (!push_tinst_level (fn, explicit_targs))
22549 excessive_deduction_depth = true;
22550 goto fail;
22552 ++processing_template_decl;
22553 input_location = DECL_SOURCE_LOCATION (fn);
22554 /* Ignore any access checks; we'll see them again in
22555 instantiate_template and they might have the wrong
22556 access path at this point. */
22557 push_deferring_access_checks (dk_deferred);
22558 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22559 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22560 pop_deferring_access_checks ();
22561 input_location = loc;
22562 --processing_template_decl;
22563 pop_tinst_level ();
22565 if (fntype == error_mark_node)
22566 goto fail;
22569 /* Place the explicitly specified arguments in TARGS. */
22570 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22571 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22572 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22573 if (!incomplete && CHECKING_P
22574 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22575 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22576 (targs, NUM_TMPL_ARGS (explicit_targs));
22579 if (return_type && strict != DEDUCE_CALL)
22581 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22582 new_args[0] = return_type;
22583 memcpy (new_args + 1, args, nargs * sizeof (tree));
22584 args = new_args;
22585 ++nargs;
22588 if (!incomplete)
22589 goto deduced;
22591 /* Never do unification on the 'this' parameter. */
22592 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22594 if (return_type && strict == DEDUCE_CALL)
22596 /* We're deducing for a call to the result of a template conversion
22597 function. The parms we really want are in return_type. */
22598 if (INDIRECT_TYPE_P (return_type))
22599 return_type = TREE_TYPE (return_type);
22600 parms = TYPE_ARG_TYPES (return_type);
22602 else if (return_type)
22604 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22607 /* We allow incomplete unification without an error message here
22608 because the standard doesn't seem to explicitly prohibit it. Our
22609 callers must be ready to deal with unification failures in any
22610 event. */
22612 /* If we aren't explaining yet, push tinst context so we can see where
22613 any errors (e.g. from class instantiations triggered by instantiation
22614 of default template arguments) come from. If we are explaining, this
22615 context is redundant. */
22616 if (!explain_p && !push_tinst_level (fn, targs))
22618 excessive_deduction_depth = true;
22619 goto fail;
22622 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22623 full_targs, parms, args, nargs, /*subr=*/0,
22624 strict, &checks, explain_p);
22625 if (!explain_p)
22626 pop_tinst_level ();
22627 if (!ok)
22628 goto fail;
22630 /* Now that we have bindings for all of the template arguments,
22631 ensure that the arguments deduced for the template template
22632 parameters have compatible template parameter lists. We cannot
22633 check this property before we have deduced all template
22634 arguments, because the template parameter types of a template
22635 template parameter might depend on prior template parameters
22636 deduced after the template template parameter. The following
22637 ill-formed example illustrates this issue:
22639 template<typename T, template<T> class C> void f(C<5>, T);
22641 template<int N> struct X {};
22643 void g() {
22644 f(X<5>(), 5l); // error: template argument deduction fails
22647 The template parameter list of 'C' depends on the template type
22648 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22649 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22650 time that we deduce 'C'. */
22651 if (!template_template_parm_bindings_ok_p
22652 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22654 unify_inconsistent_template_template_parameters (explain_p);
22655 goto fail;
22658 deduced:
22660 /* CWG2369: Check satisfaction before non-deducible conversions. */
22661 if (!constraints_satisfied_p (fn, targs))
22663 if (explain_p)
22664 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22665 goto fail;
22668 /* DR 1391: All parameters have args, now check non-dependent parms for
22669 convertibility. We don't do this if all args were explicitly specified,
22670 as the standard says that we substitute explicit args immediately. */
22671 if (incomplete
22672 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22673 convs, explain_p))
22674 goto fail;
22676 /* All is well so far. Now, check:
22678 [temp.deduct]
22680 When all template arguments have been deduced, all uses of
22681 template parameters in nondeduced contexts are replaced with
22682 the corresponding deduced argument values. If the
22683 substitution results in an invalid type, as described above,
22684 type deduction fails. */
22685 if (!push_tinst_level (fn, targs))
22687 excessive_deduction_depth = true;
22688 goto fail;
22691 /* Also collect access checks from the instantiation. */
22692 reopen_deferring_access_checks (checks);
22694 decl = instantiate_template (fn, targs, complain);
22696 checks = get_deferred_access_checks ();
22697 pop_deferring_access_checks ();
22699 pop_tinst_level ();
22701 if (decl == error_mark_node)
22702 goto fail;
22704 /* Now perform any access checks encountered during substitution. */
22705 push_access_scope (decl);
22706 ok = perform_access_checks (checks, complain);
22707 pop_access_scope (decl);
22708 if (!ok)
22709 goto fail;
22711 /* If we're looking for an exact match, check that what we got
22712 is indeed an exact match. It might not be if some template
22713 parameters are used in non-deduced contexts. But don't check
22714 for an exact match if we have dependent template arguments;
22715 in that case we're doing partial ordering, and we already know
22716 that we have two candidates that will provide the actual type. */
22717 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22719 tree substed = TREE_TYPE (decl);
22720 unsigned int i;
22722 tree sarg
22723 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22724 if (return_type)
22725 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22726 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22727 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22729 unify_type_mismatch (explain_p, args[i],
22730 TREE_VALUE (sarg));
22731 goto fail;
22733 if ((i < nargs || sarg)
22734 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22735 doesn't contain the trailing void, and conv fns are always (). */
22736 && !DECL_CONV_FN_P (decl))
22738 unsigned nsargs = i + list_length (sarg);
22739 unify_arity (explain_p, nargs, nsargs);
22740 goto fail;
22744 /* After doing deduction with the inherited constructor, actually return an
22745 instantiation of the inheriting constructor. */
22746 if (orig_fn != fn)
22747 decl = instantiate_template (orig_fn, targs, complain);
22749 r = decl;
22751 fail:
22752 --deduction_depth;
22753 if (excessive_deduction_depth)
22755 if (deduction_depth == 0)
22756 /* Reset once we're all the way out. */
22757 excessive_deduction_depth = false;
22760 return r;
22763 /* Returns true iff PARM is a forwarding reference in the context of
22764 template argument deduction for TMPL. */
22766 static bool
22767 forwarding_reference_p (tree parm, tree tmpl)
22769 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22770 cv-unqualified template parameter ..." */
22771 if (TYPE_REF_P (parm)
22772 && TYPE_REF_IS_RVALUE (parm)
22773 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22774 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22776 parm = TREE_TYPE (parm);
22777 /* [temp.deduct.call], "... that does not represent a template parameter
22778 of a class template (during class template argument deduction)." */
22779 if (tmpl
22780 && deduction_guide_p (tmpl)
22781 && DECL_ARTIFICIAL (tmpl))
22783 /* Since the template parameters of a synthesized guide consist of
22784 the template parameters of the class template followed by those of
22785 the constructor (if any), we can tell if PARM represents a template
22786 parameter of the class template by comparing its index with the
22787 arity of the class template. */
22788 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22789 if (TEMPLATE_TYPE_IDX (parm)
22790 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22791 return false;
22793 return true;
22795 return false;
22798 /* Adjust types before performing type deduction, as described in
22799 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22800 sections are symmetric. PARM is the type of a function parameter
22801 or the return type of the conversion function. ARG is the type of
22802 the argument passed to the call, or the type of the value
22803 initialized with the result of the conversion function.
22804 ARG_EXPR is the original argument expression, which may be null. */
22806 static int
22807 maybe_adjust_types_for_deduction (tree tparms,
22808 unification_kind_t strict,
22809 tree* parm,
22810 tree* arg,
22811 tree arg_expr)
22813 int result = 0;
22815 switch (strict)
22817 case DEDUCE_CALL:
22818 break;
22820 case DEDUCE_CONV:
22821 /* [temp.deduct.conv] First remove a reference type on parm.
22822 DRs 322 & 976 affected this. */
22823 if (TYPE_REF_P (*parm))
22824 *parm = TREE_TYPE (*parm);
22826 /* Swap PARM and ARG throughout the remainder of this
22827 function; the handling is precisely symmetric since PARM
22828 will initialize ARG rather than vice versa. */
22829 std::swap (parm, arg);
22831 break;
22833 case DEDUCE_EXACT:
22834 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22835 too, but here handle it by stripping the reference from PARM
22836 rather than by adding it to ARG. */
22837 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22838 && TYPE_REF_P (*arg)
22839 && !TYPE_REF_IS_RVALUE (*arg))
22840 *parm = TREE_TYPE (*parm);
22841 /* Nothing else to do in this case. */
22842 return 0;
22844 default:
22845 gcc_unreachable ();
22848 if (!TYPE_REF_P (*parm))
22850 /* [temp.deduct.call]
22852 If P is not a reference type:
22854 --If A is an array type, the pointer type produced by the
22855 array-to-pointer standard conversion (_conv.array_) is
22856 used in place of A for type deduction; otherwise,
22858 --If A is a function type, the pointer type produced by
22859 the function-to-pointer standard conversion
22860 (_conv.func_) is used in place of A for type deduction;
22861 otherwise,
22863 --If A is a cv-qualified type, the top level
22864 cv-qualifiers of A's type are ignored for type
22865 deduction. */
22866 if (TREE_CODE (*arg) == ARRAY_TYPE)
22867 *arg = build_pointer_type (TREE_TYPE (*arg));
22868 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22869 *arg = build_pointer_type (*arg);
22870 else
22871 *arg = TYPE_MAIN_VARIANT (*arg);
22874 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22875 an lvalue, the type 'lvalue reference to A' is used in place of A for
22876 type deduction." */
22877 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22878 && (arg_expr ? lvalue_p (arg_expr)
22879 /* try_one_overload doesn't provide an arg_expr, but
22880 functions are always lvalues. */
22881 : TREE_CODE (*arg) == FUNCTION_TYPE))
22882 *arg = build_reference_type (*arg);
22884 /* [temp.deduct.call]
22886 If P is a cv-qualified type, the top level cv-qualifiers
22887 of P's type are ignored for type deduction. If P is a
22888 reference type, the type referred to by P is used for
22889 type deduction. */
22890 *parm = TYPE_MAIN_VARIANT (*parm);
22891 if (TYPE_REF_P (*parm))
22893 *parm = TREE_TYPE (*parm);
22894 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22897 return result;
22900 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22901 template which doesn't contain any deducible template parameters; check if
22902 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22903 unify_one_argument. */
22905 static int
22906 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22907 int flags, struct conversion **conv_p,
22908 bool explain_p)
22910 tree type;
22912 if (!TYPE_P (arg))
22913 type = TREE_TYPE (arg);
22914 else
22915 type = arg;
22917 if (same_type_p (parm, type))
22918 return unify_success (explain_p);
22920 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22921 if (strict == DEDUCE_CONV)
22923 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22924 return unify_success (explain_p);
22926 else if (strict == DEDUCE_CALL)
22928 bool ok = false;
22929 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22930 if (conv_p)
22931 /* Avoid recalculating this in add_function_candidate. */
22932 ok = (*conv_p
22933 = good_conversion (parm, type, conv_arg, flags, complain));
22934 else
22935 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22936 if (ok)
22937 return unify_success (explain_p);
22940 if (strict == DEDUCE_EXACT)
22941 return unify_type_mismatch (explain_p, parm, arg);
22942 else
22943 return unify_arg_conversion (explain_p, parm, type, arg);
22946 static bool uses_deducible_template_parms (tree type);
22948 /* Returns true iff the expression EXPR is one from which a template
22949 argument can be deduced. In other words, if it's an undecorated
22950 use of a template non-type parameter. */
22952 static bool
22953 deducible_expression (tree expr)
22955 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22956 while (CONVERT_EXPR_P (expr)
22957 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22958 || REFERENCE_REF_P (expr))
22959 expr = TREE_OPERAND (expr, 0);
22960 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22963 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22964 deducible way; that is, if it has a max value of <PARM> - 1. */
22966 static bool
22967 deducible_array_bound (tree domain)
22969 if (domain == NULL_TREE)
22970 return false;
22972 tree max = TYPE_MAX_VALUE (domain);
22973 if (TREE_CODE (max) != MINUS_EXPR)
22974 return false;
22976 return deducible_expression (TREE_OPERAND (max, 0));
22979 /* Returns true iff the template arguments ARGS use a template parameter
22980 in a deducible way. */
22982 static bool
22983 deducible_template_args (tree args)
22985 for (tree elt : tree_vec_range (args))
22987 bool deducible;
22988 if (ARGUMENT_PACK_P (elt))
22989 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22990 else
22992 if (PACK_EXPANSION_P (elt))
22993 elt = PACK_EXPANSION_PATTERN (elt);
22994 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22995 deducible = true;
22996 else if (TYPE_P (elt))
22997 deducible = uses_deducible_template_parms (elt);
22998 else
22999 deducible = deducible_expression (elt);
23001 if (deducible)
23002 return true;
23004 return false;
23007 /* Returns true iff TYPE contains any deducible references to template
23008 parameters, as per 14.8.2.5. */
23010 static bool
23011 uses_deducible_template_parms (tree type)
23013 if (PACK_EXPANSION_P (type))
23014 type = PACK_EXPANSION_PATTERN (type);
23016 /* T
23017 cv-list T
23018 TT<T>
23019 TT<i>
23020 TT<> */
23021 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
23022 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
23023 return true;
23025 /* T*
23027 T&& */
23028 if (INDIRECT_TYPE_P (type))
23029 return uses_deducible_template_parms (TREE_TYPE (type));
23031 /* T[integer-constant ]
23032 type [i] */
23033 if (TREE_CODE (type) == ARRAY_TYPE)
23034 return (uses_deducible_template_parms (TREE_TYPE (type))
23035 || deducible_array_bound (TYPE_DOMAIN (type)));
23037 /* T type ::*
23038 type T::*
23039 T T::*
23040 T (type ::*)()
23041 type (T::*)()
23042 type (type ::*)(T)
23043 type (T::*)(T)
23044 T (type ::*)(T)
23045 T (T::*)()
23046 T (T::*)(T) */
23047 if (TYPE_PTRMEM_P (type))
23048 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
23049 || (uses_deducible_template_parms
23050 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
23052 /* template-name <T> (where template-name refers to a class template)
23053 template-name <i> (where template-name refers to a class template) */
23054 if (CLASS_TYPE_P (type)
23055 && CLASSTYPE_TEMPLATE_INFO (type)
23056 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
23057 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
23058 (CLASSTYPE_TI_ARGS (type)));
23060 /* type (T)
23062 T(T) */
23063 if (FUNC_OR_METHOD_TYPE_P (type))
23065 if (uses_deducible_template_parms (TREE_TYPE (type)))
23066 return true;
23067 tree parm = TYPE_ARG_TYPES (type);
23068 if (TREE_CODE (type) == METHOD_TYPE)
23069 parm = TREE_CHAIN (parm);
23070 for (; parm; parm = TREE_CHAIN (parm))
23071 if (uses_deducible_template_parms (TREE_VALUE (parm)))
23072 return true;
23073 if (flag_noexcept_type
23074 && TYPE_RAISES_EXCEPTIONS (type)
23075 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
23076 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
23077 return true;
23080 return false;
23083 /* Subroutine of type_unification_real and unify_pack_expansion to
23084 handle unification of a single P/A pair. Parameters are as
23085 for those functions. */
23087 static int
23088 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23089 int subr, unification_kind_t strict,
23090 bool explain_p)
23092 tree arg_expr = NULL_TREE;
23093 int arg_strict;
23095 if (arg == error_mark_node || parm == error_mark_node)
23096 return unify_invalid (explain_p);
23097 if (arg == unknown_type_node)
23098 /* We can't deduce anything from this, but we might get all the
23099 template args from other function args. */
23100 return unify_success (explain_p);
23102 /* Implicit conversions (Clause 4) will be performed on a function
23103 argument to convert it to the type of the corresponding function
23104 parameter if the parameter type contains no template-parameters that
23105 participate in template argument deduction. */
23106 if (strict != DEDUCE_EXACT
23107 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23108 /* For function parameters with no deducible template parameters,
23109 just return. We'll check non-dependent conversions later. */
23110 return unify_success (explain_p);
23112 switch (strict)
23114 case DEDUCE_CALL:
23115 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23116 | UNIFY_ALLOW_MORE_CV_QUAL
23117 | UNIFY_ALLOW_DERIVED);
23118 break;
23120 case DEDUCE_CONV:
23121 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23122 break;
23124 case DEDUCE_EXACT:
23125 arg_strict = UNIFY_ALLOW_NONE;
23126 break;
23128 default:
23129 gcc_unreachable ();
23132 /* We only do these transformations if this is the top-level
23133 parameter_type_list in a call or declaration matching; in other
23134 situations (nested function declarators, template argument lists) we
23135 won't be comparing a type to an expression, and we don't do any type
23136 adjustments. */
23137 if (!subr)
23139 if (!TYPE_P (arg))
23141 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23142 if (type_unknown_p (arg))
23144 /* [temp.deduct.type] A template-argument can be
23145 deduced from a pointer to function or pointer
23146 to member function argument if the set of
23147 overloaded functions does not contain function
23148 templates and at most one of a set of
23149 overloaded functions provides a unique
23150 match. */
23151 resolve_overloaded_unification (tparms, targs, parm,
23152 arg, strict,
23153 arg_strict, explain_p);
23154 /* If a unique match was not found, this is a
23155 non-deduced context, so we still succeed. */
23156 return unify_success (explain_p);
23159 arg_expr = arg;
23160 arg = unlowered_expr_type (arg);
23161 if (arg == error_mark_node)
23162 return unify_invalid (explain_p);
23165 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23166 &parm, &arg, arg_expr);
23168 else
23169 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23170 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23171 return unify_template_argument_mismatch (explain_p, parm, arg);
23173 /* For deduction from an init-list we need the actual list. */
23174 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23175 arg = arg_expr;
23176 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23179 /* for_each_template_parm callback that always returns 0. */
23181 static int
23182 zero_r (tree, void *)
23184 return 0;
23187 /* for_each_template_parm any_fn callback to handle deduction of a template
23188 type argument from the type of an array bound. */
23190 static int
23191 array_deduction_r (tree t, void *data)
23193 tree_pair_p d = (tree_pair_p)data;
23194 tree &tparms = d->purpose;
23195 tree &targs = d->value;
23197 if (TREE_CODE (t) == ARRAY_TYPE)
23198 if (tree dom = TYPE_DOMAIN (t))
23199 if (tree max = TYPE_MAX_VALUE (dom))
23201 if (TREE_CODE (max) == MINUS_EXPR)
23202 max = TREE_OPERAND (max, 0);
23203 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23204 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23205 UNIFY_ALLOW_NONE, /*explain*/false);
23208 /* Keep walking. */
23209 return 0;
23212 /* Try to deduce any not-yet-deduced template type arguments from the type of
23213 an array bound. This is handled separately from unify because 14.8.2.5 says
23214 "The type of a type parameter is only deduced from an array bound if it is
23215 not otherwise deduced." */
23217 static void
23218 try_array_deduction (tree tparms, tree targs, tree parm)
23220 tree_pair_s data = { tparms, targs };
23221 hash_set<tree> visited;
23222 for_each_template_parm (parm, zero_r, &data, &visited,
23223 /*nondeduced*/false, array_deduction_r);
23226 /* Most parms like fn_type_unification.
23228 If SUBR is 1, we're being called recursively (to unify the
23229 arguments of a function or method parameter of a function
23230 template).
23232 CHECKS is a pointer to a vector of access checks encountered while
23233 substituting default template arguments. */
23235 static int
23236 type_unification_real (tree tparms,
23237 tree full_targs,
23238 tree xparms,
23239 const tree *xargs,
23240 unsigned int xnargs,
23241 int subr,
23242 unification_kind_t strict,
23243 vec<deferred_access_check, va_gc> **checks,
23244 bool explain_p)
23246 tree parm, arg;
23247 int i;
23248 int ntparms = TREE_VEC_LENGTH (tparms);
23249 int saw_undeduced = 0;
23250 tree parms;
23251 const tree *args;
23252 unsigned int nargs;
23253 unsigned int ia;
23255 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23256 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23257 gcc_assert (ntparms > 0);
23259 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23261 /* Reset the number of non-defaulted template arguments contained
23262 in TARGS. */
23263 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23265 again:
23266 parms = xparms;
23267 args = xargs;
23268 nargs = xnargs;
23270 /* Only fn_type_unification cares about terminal void. */
23271 if (nargs && args[nargs-1] == void_type_node)
23272 --nargs;
23274 ia = 0;
23275 while (parms && parms != void_list_node
23276 && ia < nargs)
23278 parm = TREE_VALUE (parms);
23280 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23281 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23282 /* For a function parameter pack that occurs at the end of the
23283 parameter-declaration-list, the type A of each remaining
23284 argument of the call is compared with the type P of the
23285 declarator-id of the function parameter pack. */
23286 break;
23288 parms = TREE_CHAIN (parms);
23290 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23291 /* For a function parameter pack that does not occur at the
23292 end of the parameter-declaration-list, the type of the
23293 parameter pack is a non-deduced context. */
23294 continue;
23296 arg = args[ia];
23297 ++ia;
23299 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23300 explain_p))
23301 return 1;
23304 if (parms
23305 && parms != void_list_node
23306 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23308 /* Unify the remaining arguments with the pack expansion type. */
23309 tree argvec;
23310 tree parmvec = make_tree_vec (1);
23312 /* Allocate a TREE_VEC and copy in all of the arguments */
23313 argvec = make_tree_vec (nargs - ia);
23314 for (i = 0; ia < nargs; ++ia, ++i)
23315 TREE_VEC_ELT (argvec, i) = args[ia];
23317 /* Copy the parameter into parmvec. */
23318 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23319 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23320 /*subr=*/subr, explain_p))
23321 return 1;
23323 /* Advance to the end of the list of parameters. */
23324 parms = TREE_CHAIN (parms);
23327 /* Fail if we've reached the end of the parm list, and more args
23328 are present, and the parm list isn't variadic. */
23329 if (ia < nargs && parms == void_list_node)
23330 return unify_too_many_arguments (explain_p, nargs, ia);
23331 /* Fail if parms are left and they don't have default values and
23332 they aren't all deduced as empty packs (c++/57397). This is
23333 consistent with sufficient_parms_p. */
23334 if (parms && parms != void_list_node
23335 && TREE_PURPOSE (parms) == NULL_TREE)
23337 unsigned int count = nargs;
23338 tree p = parms;
23339 bool type_pack_p;
23342 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23343 if (!type_pack_p)
23344 count++;
23345 p = TREE_CHAIN (p);
23347 while (p && p != void_list_node);
23348 if (count != nargs)
23349 return unify_too_few_arguments (explain_p, ia, count,
23350 type_pack_p);
23353 if (!subr)
23355 tsubst_flags_t complain = (explain_p
23356 ? tf_warning_or_error
23357 : tf_none);
23358 bool tried_array_deduction = (cxx_dialect < cxx17);
23360 for (i = 0; i < ntparms; i++)
23362 tree targ = TREE_VEC_ELT (targs, i);
23363 tree tparm = TREE_VEC_ELT (tparms, i);
23365 /* Clear the "incomplete" flags on all argument packs now so that
23366 substituting them into later default arguments works. */
23367 if (targ && ARGUMENT_PACK_P (targ))
23369 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23370 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23373 if (targ || tparm == error_mark_node)
23374 continue;
23375 tparm = TREE_VALUE (tparm);
23377 if (TREE_CODE (tparm) == TYPE_DECL
23378 && !tried_array_deduction)
23380 try_array_deduction (tparms, targs, xparms);
23381 tried_array_deduction = true;
23382 if (TREE_VEC_ELT (targs, i))
23383 continue;
23386 /* If this is an undeduced nontype parameter that depends on
23387 a type parameter, try another pass; its type may have been
23388 deduced from a later argument than the one from which
23389 this parameter can be deduced. */
23390 if (TREE_CODE (tparm) == PARM_DECL
23391 && !is_auto (TREE_TYPE (tparm))
23392 && uses_template_parms (TREE_TYPE (tparm))
23393 && saw_undeduced < 2)
23395 saw_undeduced = 1;
23396 continue;
23399 /* Core issue #226 (C++0x) [temp.deduct]:
23401 If a template argument has not been deduced, its
23402 default template argument, if any, is used.
23404 When we are in C++98 mode, TREE_PURPOSE will either
23405 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23406 to explicitly check cxx_dialect here. */
23407 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23408 /* OK, there is a default argument. Wait until after the
23409 conversion check to do substitution. */
23410 continue;
23412 /* If the type parameter is a parameter pack, then it will
23413 be deduced to an empty parameter pack. */
23414 if (template_parameter_pack_p (tparm))
23416 tree arg;
23418 if (TREE_CODE (tparm) == PARM_DECL)
23420 arg = make_node (NONTYPE_ARGUMENT_PACK);
23421 TREE_CONSTANT (arg) = 1;
23423 else
23424 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23426 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23428 TREE_VEC_ELT (targs, i) = arg;
23429 continue;
23432 return unify_parameter_deduction_failure (explain_p, tparm);
23435 /* During partial ordering, we deduce dependent template args. */
23436 bool any_dependent_targs = false;
23438 /* Now substitute into the default template arguments. */
23439 for (i = 0; i < ntparms; i++)
23441 tree targ = TREE_VEC_ELT (targs, i);
23442 tree tparm = TREE_VEC_ELT (tparms, i);
23444 if (targ)
23446 if (!any_dependent_targs && dependent_template_arg_p (targ))
23447 any_dependent_targs = true;
23448 continue;
23450 if (tparm == error_mark_node)
23451 continue;
23453 tree parm = TREE_VALUE (tparm);
23454 tree arg = TREE_PURPOSE (tparm);
23455 reopen_deferring_access_checks (*checks);
23456 location_t save_loc = input_location;
23457 if (DECL_P (parm))
23458 input_location = DECL_SOURCE_LOCATION (parm);
23460 if (saw_undeduced == 1
23461 && TREE_CODE (parm) == PARM_DECL
23462 && !is_auto (TREE_TYPE (parm))
23463 && uses_template_parms (TREE_TYPE (parm)))
23465 /* The type of this non-type parameter depends on undeduced
23466 parameters. Don't try to use its default argument yet,
23467 since we might deduce an argument for it on the next pass,
23468 but do check whether the arguments we already have cause
23469 substitution failure, so that that happens before we try
23470 later default arguments (78489). */
23471 ++processing_template_decl;
23472 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23473 NULL_TREE);
23474 --processing_template_decl;
23475 if (type == error_mark_node)
23476 arg = error_mark_node;
23477 else
23478 arg = NULL_TREE;
23480 else
23482 /* Even if the call is happening in template context, getting
23483 here means it's non-dependent, and a default argument is
23484 considered a separate definition under [temp.decls], so we can
23485 do this substitution without processing_template_decl. This
23486 is important if the default argument contains something that
23487 might be instantiation-dependent like access (87480). */
23488 processing_template_decl_sentinel s (!any_dependent_targs);
23489 tree substed = NULL_TREE;
23490 if (saw_undeduced == 1 && !any_dependent_targs)
23492 /* First instatiate in template context, in case we still
23493 depend on undeduced template parameters. */
23494 ++processing_template_decl;
23495 substed = tsubst_template_arg (arg, full_targs, complain,
23496 NULL_TREE);
23497 --processing_template_decl;
23498 if (substed != error_mark_node
23499 && !uses_template_parms (substed))
23500 /* We replaced all the tparms, substitute again out of
23501 template context. */
23502 substed = NULL_TREE;
23504 if (!substed)
23505 substed = tsubst_template_arg (arg, full_targs, complain,
23506 NULL_TREE);
23508 if (!uses_template_parms (substed))
23509 arg = convert_template_argument (parm, substed, full_targs,
23510 complain, i, NULL_TREE);
23511 else if (saw_undeduced == 1)
23512 arg = NULL_TREE;
23513 else if (!any_dependent_targs)
23514 arg = error_mark_node;
23517 input_location = save_loc;
23518 *checks = get_deferred_access_checks ();
23519 pop_deferring_access_checks ();
23521 if (arg == error_mark_node)
23522 return 1;
23523 else if (arg)
23525 TREE_VEC_ELT (targs, i) = arg;
23526 /* The position of the first default template argument,
23527 is also the number of non-defaulted arguments in TARGS.
23528 Record that. */
23529 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23530 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23534 if (saw_undeduced++ == 1)
23535 goto again;
23538 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23539 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23541 return unify_success (explain_p);
23544 /* Subroutine of type_unification_real. Args are like the variables
23545 at the call site. ARG is an overloaded function (or template-id);
23546 we try deducing template args from each of the overloads, and if
23547 only one succeeds, we go with that. Modifies TARGS and returns
23548 true on success. */
23550 static bool
23551 resolve_overloaded_unification (tree tparms,
23552 tree targs,
23553 tree parm,
23554 tree arg,
23555 unification_kind_t strict,
23556 int sub_strict,
23557 bool explain_p)
23559 tree tempargs = copy_node (targs);
23560 int good = 0;
23561 tree goodfn = NULL_TREE;
23562 bool addr_p;
23564 if (TREE_CODE (arg) == ADDR_EXPR)
23566 arg = TREE_OPERAND (arg, 0);
23567 addr_p = true;
23569 else
23570 addr_p = false;
23572 if (TREE_CODE (arg) == COMPONENT_REF)
23573 /* Handle `&x' where `x' is some static or non-static member
23574 function name. */
23575 arg = TREE_OPERAND (arg, 1);
23577 if (TREE_CODE (arg) == OFFSET_REF)
23578 arg = TREE_OPERAND (arg, 1);
23580 /* Strip baselink information. */
23581 if (BASELINK_P (arg))
23582 arg = BASELINK_FUNCTIONS (arg);
23584 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23586 /* If we got some explicit template args, we need to plug them into
23587 the affected templates before we try to unify, in case the
23588 explicit args will completely resolve the templates in question. */
23590 int ok = 0;
23591 tree expl_subargs = TREE_OPERAND (arg, 1);
23592 arg = TREE_OPERAND (arg, 0);
23594 for (lkp_iterator iter (arg); iter; ++iter)
23596 tree fn = *iter;
23597 tree subargs, elem;
23599 if (TREE_CODE (fn) != TEMPLATE_DECL)
23600 continue;
23602 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23603 expl_subargs, NULL_TREE, tf_none);
23604 if (subargs != error_mark_node
23605 && !any_dependent_template_arguments_p (subargs))
23607 fn = instantiate_template (fn, subargs, tf_none);
23608 if (!constraints_satisfied_p (fn))
23609 continue;
23610 if (undeduced_auto_decl (fn))
23612 /* Instantiate the function to deduce its return type. */
23613 ++function_depth;
23614 instantiate_decl (fn, /*defer*/false, /*class*/false);
23615 --function_depth;
23618 if (flag_noexcept_type)
23619 maybe_instantiate_noexcept (fn, tf_none);
23621 elem = TREE_TYPE (fn);
23622 if (try_one_overload (tparms, targs, tempargs, parm,
23623 elem, strict, sub_strict, addr_p, explain_p)
23624 && (!goodfn || !same_type_p (goodfn, elem)))
23626 goodfn = elem;
23627 ++good;
23630 else if (subargs)
23631 ++ok;
23633 /* If no templates (or more than one) are fully resolved by the
23634 explicit arguments, this template-id is a non-deduced context; it
23635 could still be OK if we deduce all template arguments for the
23636 enclosing call through other arguments. */
23637 if (good != 1)
23638 good = ok;
23640 else if (!OVL_P (arg))
23641 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23642 -- but the deduction does not succeed because the expression is
23643 not just the function on its own. */
23644 return false;
23645 else
23646 for (lkp_iterator iter (arg); iter; ++iter)
23648 tree fn = *iter;
23649 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23650 strict, sub_strict, addr_p, explain_p)
23651 && (!goodfn || !decls_match (goodfn, fn)))
23653 goodfn = fn;
23654 ++good;
23658 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23659 to function or pointer to member function argument if the set of
23660 overloaded functions does not contain function templates and at most
23661 one of a set of overloaded functions provides a unique match.
23663 So if we found multiple possibilities, we return success but don't
23664 deduce anything. */
23666 if (good == 1)
23668 int i = TREE_VEC_LENGTH (targs);
23669 for (; i--; )
23670 if (TREE_VEC_ELT (tempargs, i))
23672 tree old = TREE_VEC_ELT (targs, i);
23673 tree new_ = TREE_VEC_ELT (tempargs, i);
23674 if (new_ && old && ARGUMENT_PACK_P (old)
23675 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23676 /* Don't forget explicit template arguments in a pack. */
23677 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23678 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23679 TREE_VEC_ELT (targs, i) = new_;
23682 if (good)
23683 return true;
23685 return false;
23688 /* Core DR 115: In contexts where deduction is done and fails, or in
23689 contexts where deduction is not done, if a template argument list is
23690 specified and it, along with any default template arguments, identifies
23691 a single function template specialization, then the template-id is an
23692 lvalue for the function template specialization. */
23694 tree
23695 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23697 tree expr, offset, baselink;
23698 bool addr;
23700 if (!type_unknown_p (orig_expr))
23701 return orig_expr;
23703 expr = orig_expr;
23704 addr = false;
23705 offset = NULL_TREE;
23706 baselink = NULL_TREE;
23708 if (TREE_CODE (expr) == ADDR_EXPR)
23710 expr = TREE_OPERAND (expr, 0);
23711 addr = true;
23713 if (TREE_CODE (expr) == OFFSET_REF)
23715 offset = expr;
23716 expr = TREE_OPERAND (expr, 1);
23718 if (BASELINK_P (expr))
23720 baselink = expr;
23721 expr = BASELINK_FUNCTIONS (expr);
23724 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23726 int good = 0;
23727 tree goodfn = NULL_TREE;
23729 /* If we got some explicit template args, we need to plug them into
23730 the affected templates before we try to unify, in case the
23731 explicit args will completely resolve the templates in question. */
23733 tree expl_subargs = TREE_OPERAND (expr, 1);
23734 tree arg = TREE_OPERAND (expr, 0);
23735 tree badfn = NULL_TREE;
23736 tree badargs = NULL_TREE;
23738 for (lkp_iterator iter (arg); iter; ++iter)
23740 tree fn = *iter;
23741 tree subargs, elem;
23743 if (TREE_CODE (fn) != TEMPLATE_DECL)
23744 continue;
23746 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23747 expl_subargs, NULL_TREE, tf_none);
23748 if (subargs != error_mark_node
23749 && !any_dependent_template_arguments_p (subargs))
23751 elem = instantiate_template (fn, subargs, tf_none);
23752 if (elem == error_mark_node)
23754 badfn = fn;
23755 badargs = subargs;
23757 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23758 && constraints_satisfied_p (elem))
23760 goodfn = elem;
23761 ++good;
23765 if (good == 1)
23767 mark_used (goodfn);
23768 expr = goodfn;
23769 if (baselink)
23770 expr = build_baselink (BASELINK_BINFO (baselink),
23771 BASELINK_ACCESS_BINFO (baselink),
23772 expr, BASELINK_OPTYPE (baselink));
23773 if (offset)
23775 tree base
23776 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23777 expr = build_offset_ref (base, expr, addr, complain);
23779 if (addr)
23780 expr = cp_build_addr_expr (expr, complain);
23781 return expr;
23783 else if (good == 0 && badargs && (complain & tf_error))
23784 /* There were no good options and at least one bad one, so let the
23785 user know what the problem is. */
23786 instantiate_template (badfn, badargs, complain);
23788 return orig_expr;
23791 /* As above, but error out if the expression remains overloaded. */
23793 tree
23794 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23796 exp = resolve_nondeduced_context (exp, complain);
23797 if (type_unknown_p (exp))
23799 if (complain & tf_error)
23800 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23801 return error_mark_node;
23803 return exp;
23806 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23807 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23808 different overloads deduce different arguments for a given parm.
23809 ADDR_P is true if the expression for which deduction is being
23810 performed was of the form "& fn" rather than simply "fn".
23812 Returns 1 on success. */
23814 static int
23815 try_one_overload (tree tparms,
23816 tree orig_targs,
23817 tree targs,
23818 tree parm,
23819 tree arg,
23820 unification_kind_t strict,
23821 int sub_strict,
23822 bool addr_p,
23823 bool explain_p)
23825 int nargs;
23826 tree tempargs;
23827 int i;
23829 if (arg == error_mark_node)
23830 return 0;
23832 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23833 to function or pointer to member function argument if the set of
23834 overloaded functions does not contain function templates and at most
23835 one of a set of overloaded functions provides a unique match.
23837 So if this is a template, just return success. */
23839 if (uses_template_parms (arg))
23840 return 1;
23842 if (TREE_CODE (arg) == METHOD_TYPE)
23843 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23844 else if (addr_p)
23845 arg = build_pointer_type (arg);
23847 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23848 &parm, &arg, NULL_TREE);
23850 /* We don't copy orig_targs for this because if we have already deduced
23851 some template args from previous args, unify would complain when we
23852 try to deduce a template parameter for the same argument, even though
23853 there isn't really a conflict. */
23854 nargs = TREE_VEC_LENGTH (targs);
23855 tempargs = make_tree_vec (nargs);
23857 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23858 return 0;
23860 /* First make sure we didn't deduce anything that conflicts with
23861 explicitly specified args. */
23862 for (i = nargs; i--; )
23864 tree elt = TREE_VEC_ELT (tempargs, i);
23865 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23867 if (!elt)
23868 /*NOP*/;
23869 else if (uses_template_parms (elt))
23870 /* Since we're unifying against ourselves, we will fill in
23871 template args used in the function parm list with our own
23872 template parms. Discard them. */
23873 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23874 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23876 /* Check that the argument at each index of the deduced argument pack
23877 is equivalent to the corresponding explicitly specified argument.
23878 We may have deduced more arguments than were explicitly specified,
23879 and that's OK. */
23881 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23882 that's wrong if we deduce the same argument pack from multiple
23883 function arguments: it's only incomplete the first time. */
23885 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23886 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23888 if (TREE_VEC_LENGTH (deduced_pack)
23889 < TREE_VEC_LENGTH (explicit_pack))
23890 return 0;
23892 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23893 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23894 TREE_VEC_ELT (deduced_pack, j)))
23895 return 0;
23897 else if (oldelt && !template_args_equal (oldelt, elt))
23898 return 0;
23901 for (i = nargs; i--; )
23903 tree elt = TREE_VEC_ELT (tempargs, i);
23905 if (elt)
23906 TREE_VEC_ELT (targs, i) = elt;
23909 return 1;
23912 /* PARM is a template class (perhaps with unbound template
23913 parameters). ARG is a fully instantiated type. If ARG can be
23914 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23915 TARGS are as for unify. */
23917 static tree
23918 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23919 bool explain_p)
23921 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23922 return NULL_TREE;
23923 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23924 /* Matches anything. */;
23925 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23926 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23927 return NULL_TREE;
23929 /* We need to make a new template argument vector for the call to
23930 unify. If we used TARGS, we'd clutter it up with the result of
23931 the attempted unification, even if this class didn't work out.
23932 We also don't want to commit ourselves to all the unifications
23933 we've already done, since unification is supposed to be done on
23934 an argument-by-argument basis. In other words, consider the
23935 following pathological case:
23937 template <int I, int J, int K>
23938 struct S {};
23940 template <int I, int J>
23941 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23943 template <int I, int J, int K>
23944 void f(S<I, J, K>, S<I, I, I>);
23946 void g() {
23947 S<0, 0, 0> s0;
23948 S<0, 1, 2> s2;
23950 f(s0, s2);
23953 Now, by the time we consider the unification involving `s2', we
23954 already know that we must have `f<0, 0, 0>'. But, even though
23955 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23956 because there are two ways to unify base classes of S<0, 1, 2>
23957 with S<I, I, I>. If we kept the already deduced knowledge, we
23958 would reject the possibility I=1. */
23959 targs = copy_template_args (targs);
23960 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23961 targ = NULL_TREE;
23963 int err;
23964 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23965 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23966 else
23967 err = unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23968 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p);
23970 return err ? NULL_TREE : arg;
23973 /* Given a template type PARM and a class type ARG, find the unique
23974 base type in ARG that is an instance of PARM. We do not examine
23975 ARG itself; only its base-classes. If there is not exactly one
23976 appropriate base class, return NULL_TREE. PARM may be the type of
23977 a partial specialization, as well as a plain template type. Used
23978 by unify. */
23980 static enum template_base_result
23981 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23982 bool explain_p, tree *result)
23984 tree rval = NULL_TREE;
23985 tree binfo;
23987 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23989 binfo = TYPE_BINFO (complete_type (arg));
23990 if (!binfo)
23992 /* The type could not be completed. */
23993 *result = NULL_TREE;
23994 return tbr_incomplete_type;
23997 /* Walk in inheritance graph order. The search order is not
23998 important, and this avoids multiple walks of virtual bases. */
23999 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
24001 tree r = try_class_unification (tparms, targs, parm,
24002 BINFO_TYPE (binfo), explain_p);
24004 if (r)
24006 /* If there is more than one satisfactory baseclass, then:
24008 [temp.deduct.call]
24010 If they yield more than one possible deduced A, the type
24011 deduction fails.
24013 applies. */
24014 if (rval && !same_type_p (r, rval))
24016 /* [temp.deduct.call]/4.3: If there is a class C that is a
24017 (direct or indirect) base class of D and derived (directly or
24018 indirectly) from a class B and that would be a valid deduced
24019 A, the deduced A cannot be B or pointer to B, respectively. */
24020 if (DERIVED_FROM_P (r, rval))
24021 /* Ignore r. */
24022 continue;
24023 else if (DERIVED_FROM_P (rval, r))
24024 /* Ignore rval. */;
24025 else
24027 *result = NULL_TREE;
24028 return tbr_ambiguous_baseclass;
24032 rval = r;
24036 *result = rval;
24037 return tbr_success;
24040 /* Returns the level of DECL, which declares a template parameter. */
24042 static int
24043 template_decl_level (tree decl)
24045 switch (TREE_CODE (decl))
24047 case TYPE_DECL:
24048 case TEMPLATE_DECL:
24049 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
24051 case PARM_DECL:
24052 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
24054 default:
24055 gcc_unreachable ();
24057 return 0;
24060 /* Decide whether ARG can be unified with PARM, considering only the
24061 cv-qualifiers of each type, given STRICT as documented for unify.
24062 Returns nonzero iff the unification is OK on that basis. */
24064 static int
24065 check_cv_quals_for_unify (int strict, tree arg, tree parm)
24067 int arg_quals = cp_type_quals (arg);
24068 int parm_quals = cp_type_quals (parm);
24070 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24071 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24073 /* Although a CVR qualifier is ignored when being applied to a
24074 substituted template parameter ([8.3.2]/1 for example), that
24075 does not allow us to unify "const T" with "int&" because both
24076 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
24077 It is ok when we're allowing additional CV qualifiers
24078 at the outer level [14.8.2.1]/3,1st bullet. */
24079 if ((TYPE_REF_P (arg)
24080 || FUNC_OR_METHOD_TYPE_P (arg))
24081 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24082 return 0;
24084 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24085 && (parm_quals & TYPE_QUAL_RESTRICT))
24086 return 0;
24089 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24090 && (arg_quals & parm_quals) != parm_quals)
24091 return 0;
24093 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24094 && (parm_quals & arg_quals) != arg_quals)
24095 return 0;
24097 return 1;
24100 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24101 void
24102 template_parm_level_and_index (tree parm, int* level, int* index)
24104 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24105 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24106 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24108 *index = TEMPLATE_TYPE_IDX (parm);
24109 *level = TEMPLATE_TYPE_LEVEL (parm);
24111 else
24113 *index = TEMPLATE_PARM_IDX (parm);
24114 *level = TEMPLATE_PARM_LEVEL (parm);
24118 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24119 do { \
24120 if (unify (TP, TA, P, A, S, EP)) \
24121 return 1; \
24122 } while (0)
24124 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24125 expansion at the end of PACKED_PARMS. Returns 0 if the type
24126 deduction succeeds, 1 otherwise. STRICT is the same as in
24127 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24128 function call argument list. We'll need to adjust the arguments to make them
24129 types. SUBR tells us if this is from a recursive call to
24130 type_unification_real, or for comparing two template argument
24131 lists. */
24133 static int
24134 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24135 tree packed_args, unification_kind_t strict,
24136 bool subr, bool explain_p)
24138 tree parm
24139 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24140 tree pattern = PACK_EXPANSION_PATTERN (parm);
24141 tree pack, packs = NULL_TREE;
24142 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24144 /* Add in any args remembered from an earlier partial instantiation. */
24145 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24146 int levels = TMPL_ARGS_DEPTH (targs);
24148 packed_args = expand_template_argument_pack (packed_args);
24150 int len = TREE_VEC_LENGTH (packed_args);
24152 /* Determine the parameter packs we will be deducing from the
24153 pattern, and record their current deductions. */
24154 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24155 pack; pack = TREE_CHAIN (pack))
24157 tree parm_pack = TREE_VALUE (pack);
24158 int idx, level;
24160 /* Only template parameter packs can be deduced, not e.g. function
24161 parameter packs or __bases or __integer_pack. */
24162 if (!TEMPLATE_PARM_P (parm_pack))
24163 continue;
24165 /* Determine the index and level of this parameter pack. */
24166 template_parm_level_and_index (parm_pack, &level, &idx);
24167 if (level > levels)
24168 continue;
24170 /* Keep track of the parameter packs and their corresponding
24171 argument packs. */
24172 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24173 TREE_TYPE (packs) = make_tree_vec (len - start);
24176 /* Loop through all of the arguments that have not yet been
24177 unified and unify each with the pattern. */
24178 for (i = start; i < len; i++)
24180 tree parm;
24181 bool any_explicit = false;
24182 tree arg = TREE_VEC_ELT (packed_args, i);
24184 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24185 or the element of its argument pack at the current index if
24186 this argument was explicitly specified. */
24187 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24189 int idx, level;
24190 tree arg, pargs;
24191 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24193 arg = NULL_TREE;
24194 if (TREE_VALUE (pack)
24195 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24196 && (i - start < TREE_VEC_LENGTH (pargs)))
24198 any_explicit = true;
24199 arg = TREE_VEC_ELT (pargs, i - start);
24201 TMPL_ARG (targs, level, idx) = arg;
24204 /* If we had explicit template arguments, substitute them into the
24205 pattern before deduction. */
24206 if (any_explicit)
24208 /* Some arguments might still be unspecified or dependent. */
24209 bool dependent;
24210 ++processing_template_decl;
24211 dependent = any_dependent_template_arguments_p (targs);
24212 if (!dependent)
24213 --processing_template_decl;
24214 parm = tsubst (pattern, targs,
24215 explain_p ? tf_warning_or_error : tf_none,
24216 NULL_TREE);
24217 if (dependent)
24218 --processing_template_decl;
24219 if (parm == error_mark_node)
24220 return 1;
24222 else
24223 parm = pattern;
24225 /* Unify the pattern with the current argument. */
24226 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24227 explain_p))
24228 return 1;
24230 /* For each parameter pack, collect the deduced value. */
24231 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24233 int idx, level;
24234 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24236 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24237 TMPL_ARG (targs, level, idx);
24241 /* Verify that the results of unification with the parameter packs
24242 produce results consistent with what we've seen before, and make
24243 the deduced argument packs available. */
24244 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24246 tree old_pack = TREE_VALUE (pack);
24247 tree new_args = TREE_TYPE (pack);
24248 int i, len = TREE_VEC_LENGTH (new_args);
24249 int idx, level;
24250 bool nondeduced_p = false;
24252 /* By default keep the original deduced argument pack.
24253 If necessary, more specific code is going to update the
24254 resulting deduced argument later down in this function. */
24255 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24256 TMPL_ARG (targs, level, idx) = old_pack;
24258 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24259 actually deduce anything. */
24260 for (i = 0; i < len && !nondeduced_p; ++i)
24261 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24262 nondeduced_p = true;
24263 if (nondeduced_p)
24264 continue;
24266 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24268 /* If we had fewer function args than explicit template args,
24269 just use the explicits. */
24270 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24271 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24272 if (len < explicit_len)
24273 new_args = explicit_args;
24276 if (!old_pack)
24278 tree result;
24279 /* Build the deduced *_ARGUMENT_PACK. */
24280 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24282 result = make_node (NONTYPE_ARGUMENT_PACK);
24283 TREE_CONSTANT (result) = 1;
24285 else
24286 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24288 ARGUMENT_PACK_ARGS (result) = new_args;
24290 /* Note the deduced argument packs for this parameter
24291 pack. */
24292 TMPL_ARG (targs, level, idx) = result;
24294 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24295 && (ARGUMENT_PACK_ARGS (old_pack)
24296 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24298 /* We only had the explicitly-provided arguments before, but
24299 now we have a complete set of arguments. */
24300 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24302 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24303 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24304 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24306 else
24308 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24309 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24310 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24311 /* During template argument deduction for the aggregate deduction
24312 candidate, the number of elements in a trailing parameter pack
24313 is only deduced from the number of remaining function
24314 arguments if it is not otherwise deduced. */
24315 if (cxx_dialect >= cxx20
24316 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24317 /* FIXME This isn't set properly for partial instantiations. */
24318 && TPARMS_PRIMARY_TEMPLATE (tparms)
24319 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24320 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24321 if (!comp_template_args (old_args, new_args,
24322 &bad_old_arg, &bad_new_arg))
24323 /* Inconsistent unification of this parameter pack. */
24324 return unify_parameter_pack_inconsistent (explain_p,
24325 bad_old_arg,
24326 bad_new_arg);
24330 return unify_success (explain_p);
24333 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24334 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24335 parameters and return value are as for unify. */
24337 static int
24338 unify_array_domain (tree tparms, tree targs,
24339 tree parm_dom, tree arg_dom,
24340 bool explain_p)
24342 tree parm_max;
24343 tree arg_max;
24344 bool parm_cst;
24345 bool arg_cst;
24347 /* Our representation of array types uses "N - 1" as the
24348 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24349 not an integer constant. We cannot unify arbitrarily
24350 complex expressions, so we eliminate the MINUS_EXPRs
24351 here. */
24352 parm_max = TYPE_MAX_VALUE (parm_dom);
24353 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24354 if (!parm_cst)
24356 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24357 parm_max = TREE_OPERAND (parm_max, 0);
24359 arg_max = TYPE_MAX_VALUE (arg_dom);
24360 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24361 if (!arg_cst)
24363 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24364 trying to unify the type of a variable with the type
24365 of a template parameter. For example:
24367 template <unsigned int N>
24368 void f (char (&) [N]);
24369 int g();
24370 void h(int i) {
24371 char a[g(i)];
24372 f(a);
24375 Here, the type of the ARG will be "int [g(i)]", and
24376 may be a SAVE_EXPR, etc. */
24377 if (TREE_CODE (arg_max) != MINUS_EXPR)
24378 return unify_vla_arg (explain_p, arg_dom);
24379 arg_max = TREE_OPERAND (arg_max, 0);
24382 /* If only one of the bounds used a MINUS_EXPR, compensate
24383 by adding one to the other bound. */
24384 if (parm_cst && !arg_cst)
24385 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24386 integer_type_node,
24387 parm_max,
24388 integer_one_node);
24389 else if (arg_cst && !parm_cst)
24390 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24391 integer_type_node,
24392 arg_max,
24393 integer_one_node);
24395 return unify (tparms, targs, parm_max, arg_max,
24396 UNIFY_ALLOW_INTEGER, explain_p);
24399 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24401 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24403 static pa_kind_t
24404 pa_kind (tree t)
24406 if (PACK_EXPANSION_P (t))
24407 t = PACK_EXPANSION_PATTERN (t);
24408 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24409 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24410 || DECL_TYPE_TEMPLATE_P (t))
24411 return pa_tmpl;
24412 else if (TYPE_P (t))
24413 return pa_type;
24414 else
24415 return pa_expr;
24418 /* Deduce the value of template parameters. TPARMS is the (innermost)
24419 set of template parameters to a template. TARGS is the bindings
24420 for those template parameters, as determined thus far; TARGS may
24421 include template arguments for outer levels of template parameters
24422 as well. PARM is a parameter to a template function, or a
24423 subcomponent of that parameter; ARG is the corresponding argument.
24424 This function attempts to match PARM with ARG in a manner
24425 consistent with the existing assignments in TARGS. If more values
24426 are deduced, then TARGS is updated.
24428 Returns 0 if the type deduction succeeds, 1 otherwise. The
24429 parameter STRICT is a bitwise or of the following flags:
24431 UNIFY_ALLOW_NONE:
24432 Require an exact match between PARM and ARG.
24433 UNIFY_ALLOW_MORE_CV_QUAL:
24434 Allow the deduced ARG to be more cv-qualified (by qualification
24435 conversion) than ARG.
24436 UNIFY_ALLOW_LESS_CV_QUAL:
24437 Allow the deduced ARG to be less cv-qualified than ARG.
24438 UNIFY_ALLOW_DERIVED:
24439 Allow the deduced ARG to be a template base class of ARG,
24440 or a pointer to a template base class of the type pointed to by
24441 ARG.
24442 UNIFY_ALLOW_INTEGER:
24443 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24444 case for more information.
24445 UNIFY_ALLOW_OUTER_LEVEL:
24446 This is the outermost level of a deduction. Used to determine validity
24447 of qualification conversions. A valid qualification conversion must
24448 have const qualified pointers leading up to the inner type which
24449 requires additional CV quals, except at the outer level, where const
24450 is not required [conv.qual]. It would be normal to set this flag in
24451 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24452 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24453 This is the outermost level of a deduction, and PARM can be more CV
24454 qualified at this point.
24455 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24456 This is the outermost level of a deduction, and PARM can be less CV
24457 qualified at this point. */
24459 static int
24460 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24461 bool explain_p)
24463 int idx;
24464 tree targ;
24465 tree tparm;
24466 int strict_in = strict;
24467 tsubst_flags_t complain = (explain_p
24468 ? tf_warning_or_error
24469 : tf_none);
24471 /* I don't think this will do the right thing with respect to types.
24472 But the only case I've seen it in so far has been array bounds, where
24473 signedness is the only information lost, and I think that will be
24474 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24475 finish_id_expression_1, and are also OK. */
24476 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24477 parm = TREE_OPERAND (parm, 0);
24479 if (arg == error_mark_node)
24480 return unify_invalid (explain_p);
24481 if (arg == unknown_type_node
24482 || arg == init_list_type_node)
24483 /* We can't deduce anything from this, but we might get all the
24484 template args from other function args. */
24485 return unify_success (explain_p);
24487 if (parm == any_targ_node || arg == any_targ_node)
24488 return unify_success (explain_p);
24490 /* If PARM uses template parameters, then we can't bail out here,
24491 even if ARG == PARM, since we won't record unifications for the
24492 template parameters. We might need them if we're trying to
24493 figure out which of two things is more specialized. */
24494 if (arg == parm && !uses_template_parms (parm))
24495 return unify_success (explain_p);
24497 /* Handle init lists early, so the rest of the function can assume
24498 we're dealing with a type. */
24499 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24501 tree elttype;
24502 tree orig_parm = parm;
24504 if (!is_std_init_list (parm)
24505 && TREE_CODE (parm) != ARRAY_TYPE)
24506 /* We can only deduce from an initializer list argument if the
24507 parameter is std::initializer_list or an array; otherwise this
24508 is a non-deduced context. */
24509 return unify_success (explain_p);
24511 if (TREE_CODE (parm) == ARRAY_TYPE)
24512 elttype = TREE_TYPE (parm);
24513 else
24515 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24516 /* Deduction is defined in terms of a single type, so just punt
24517 on the (bizarre) std::initializer_list<T...>. */
24518 if (PACK_EXPANSION_P (elttype))
24519 return unify_success (explain_p);
24522 if (strict != DEDUCE_EXACT
24523 && TYPE_P (elttype)
24524 && !uses_deducible_template_parms (elttype))
24525 /* If ELTTYPE has no deducible template parms, skip deduction from
24526 the list elements. */;
24527 else
24528 for (auto &e: CONSTRUCTOR_ELTS (arg))
24530 tree elt = e.value;
24531 int elt_strict = strict;
24533 if (elt == error_mark_node)
24534 return unify_invalid (explain_p);
24536 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24538 tree type = TREE_TYPE (elt);
24539 if (type == error_mark_node)
24540 return unify_invalid (explain_p);
24541 /* It should only be possible to get here for a call. */
24542 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24543 elt_strict |= maybe_adjust_types_for_deduction
24544 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24545 elt = type;
24548 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24549 explain_p);
24552 if (TREE_CODE (parm) == ARRAY_TYPE
24553 && deducible_array_bound (TYPE_DOMAIN (parm)))
24555 /* Also deduce from the length of the initializer list. */
24556 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24557 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24558 if (idx == error_mark_node)
24559 return unify_invalid (explain_p);
24560 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24561 idx, explain_p);
24564 /* If the std::initializer_list<T> deduction worked, replace the
24565 deduced A with std::initializer_list<A>. */
24566 if (orig_parm != parm)
24568 idx = TEMPLATE_TYPE_IDX (orig_parm);
24569 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24570 targ = listify (targ);
24571 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24573 return unify_success (explain_p);
24576 /* If parm and arg aren't the same kind of thing (template, type, or
24577 expression), fail early. */
24578 if (pa_kind (parm) != pa_kind (arg))
24579 return unify_invalid (explain_p);
24581 /* Immediately reject some pairs that won't unify because of
24582 cv-qualification mismatches. */
24583 if (TREE_CODE (arg) == TREE_CODE (parm)
24584 && TYPE_P (arg)
24585 /* It is the elements of the array which hold the cv quals of an array
24586 type, and the elements might be template type parms. We'll check
24587 when we recurse. */
24588 && TREE_CODE (arg) != ARRAY_TYPE
24589 /* We check the cv-qualifiers when unifying with template type
24590 parameters below. We want to allow ARG `const T' to unify with
24591 PARM `T' for example, when computing which of two templates
24592 is more specialized, for example. */
24593 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24594 && !check_cv_quals_for_unify (strict_in, arg, parm))
24595 return unify_cv_qual_mismatch (explain_p, parm, arg);
24597 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24598 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24599 && !FUNC_OR_METHOD_TYPE_P (parm))
24600 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24601 /* PMFs recurse at the same level, so don't strip this yet. */
24602 if (!TYPE_PTRMEMFUNC_P (parm))
24603 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24604 strict &= ~UNIFY_ALLOW_DERIVED;
24605 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24606 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24608 switch (TREE_CODE (parm))
24610 case TYPENAME_TYPE:
24611 case SCOPE_REF:
24612 case UNBOUND_CLASS_TEMPLATE:
24613 /* In a type which contains a nested-name-specifier, template
24614 argument values cannot be deduced for template parameters used
24615 within the nested-name-specifier. */
24616 return unify_success (explain_p);
24618 case TEMPLATE_TYPE_PARM:
24619 case TEMPLATE_TEMPLATE_PARM:
24620 case BOUND_TEMPLATE_TEMPLATE_PARM:
24621 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24622 if (error_operand_p (tparm))
24623 return unify_invalid (explain_p);
24625 if (TEMPLATE_TYPE_LEVEL (parm)
24626 != template_decl_level (tparm))
24627 /* The PARM is not one we're trying to unify. Just check
24628 to see if it matches ARG. */
24630 if (TREE_CODE (arg) == TREE_CODE (parm)
24631 && (is_auto (parm) ? is_auto (arg)
24632 : same_type_p (parm, arg)))
24633 return unify_success (explain_p);
24634 else
24635 return unify_type_mismatch (explain_p, parm, arg);
24637 idx = TEMPLATE_TYPE_IDX (parm);
24638 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24639 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24640 if (error_operand_p (tparm))
24641 return unify_invalid (explain_p);
24643 /* Check for mixed types and values. */
24644 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24645 && TREE_CODE (tparm) != TYPE_DECL)
24646 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24647 && TREE_CODE (tparm) != TEMPLATE_DECL))
24648 gcc_unreachable ();
24650 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24652 if ((strict_in & UNIFY_ALLOW_DERIVED)
24653 && CLASS_TYPE_P (arg))
24655 /* First try to match ARG directly. */
24656 tree t = try_class_unification (tparms, targs, parm, arg,
24657 explain_p);
24658 if (!t)
24660 /* Otherwise, look for a suitable base of ARG, as below. */
24661 enum template_base_result r;
24662 r = get_template_base (tparms, targs, parm, arg,
24663 explain_p, &t);
24664 if (!t)
24665 return unify_no_common_base (explain_p, r, parm, arg);
24666 arg = t;
24669 /* ARG must be constructed from a template class or a template
24670 template parameter. */
24671 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24672 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24673 return unify_template_deduction_failure (explain_p, parm, arg);
24675 /* Deduce arguments T, i from TT<T> or TT<i>. */
24676 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24677 return 1;
24679 arg = TYPE_TI_TEMPLATE (arg);
24680 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24681 /* If the template is a template template parameter, use the
24682 TEMPLATE_TEMPLATE_PARM for matching. */
24683 arg = TREE_TYPE (arg);
24685 /* Fall through to deduce template name. */
24688 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24689 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24691 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24693 /* Simple cases: Value already set, does match or doesn't. */
24694 if (targ != NULL_TREE && template_args_equal (targ, arg))
24695 return unify_success (explain_p);
24696 else if (targ)
24697 return unify_inconsistency (explain_p, parm, targ, arg);
24699 else
24701 /* If PARM is `const T' and ARG is only `int', we don't have
24702 a match unless we are allowing additional qualification.
24703 If ARG is `const int' and PARM is just `T' that's OK;
24704 that binds `const int' to `T'. */
24705 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24706 arg, parm))
24707 return unify_cv_qual_mismatch (explain_p, parm, arg);
24709 /* Consider the case where ARG is `const volatile int' and
24710 PARM is `const T'. Then, T should be `volatile int'. */
24711 arg = cp_build_qualified_type
24712 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24713 if (arg == error_mark_node)
24714 return unify_invalid (explain_p);
24716 /* Simple cases: Value already set, does match or doesn't. */
24717 if (targ != NULL_TREE && same_type_p (targ, arg))
24718 return unify_success (explain_p);
24719 else if (targ)
24720 return unify_inconsistency (explain_p, parm, targ, arg);
24722 /* Make sure that ARG is not a variable-sized array. (Note
24723 that were talking about variable-sized arrays (like
24724 `int[n]'), rather than arrays of unknown size (like
24725 `int[]').) We'll get very confused by such a type since
24726 the bound of the array is not constant, and therefore
24727 not mangleable. Besides, such types are not allowed in
24728 ISO C++, so we can do as we please here. We do allow
24729 them for 'auto' deduction, since that isn't ABI-exposed. */
24730 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24731 return unify_vla_arg (explain_p, arg);
24733 /* Strip typedefs as in convert_template_argument. */
24734 arg = canonicalize_type_argument (arg, tf_none);
24737 /* If ARG is a parameter pack or an expansion, we cannot unify
24738 against it unless PARM is also a parameter pack. */
24739 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24740 && !template_parameter_pack_p (parm))
24741 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24743 /* If the argument deduction results is a METHOD_TYPE,
24744 then there is a problem.
24745 METHOD_TYPE doesn't map to any real C++ type the result of
24746 the deduction cannot be of that type. */
24747 if (TREE_CODE (arg) == METHOD_TYPE)
24748 return unify_method_type_error (explain_p, arg);
24750 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24751 return unify_success (explain_p);
24753 case TEMPLATE_PARM_INDEX:
24754 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24755 if (error_operand_p (tparm))
24756 return unify_invalid (explain_p);
24758 if (TEMPLATE_PARM_LEVEL (parm)
24759 != template_decl_level (tparm))
24761 /* The PARM is not one we're trying to unify. Just check
24762 to see if it matches ARG. */
24763 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24764 && cp_tree_equal (parm, arg));
24765 if (result)
24766 unify_expression_unequal (explain_p, parm, arg);
24767 return result;
24770 idx = TEMPLATE_PARM_IDX (parm);
24771 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24773 if (targ)
24775 if ((strict & UNIFY_ALLOW_INTEGER)
24776 && TREE_TYPE (targ) && TREE_TYPE (arg)
24777 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24778 /* We're deducing from an array bound, the type doesn't matter.
24779 This conversion should match the one below. */
24780 arg = fold (build_nop (TREE_TYPE (targ), arg));
24781 int x = !cp_tree_equal (targ, arg);
24782 if (x)
24783 unify_inconsistency (explain_p, parm, targ, arg);
24784 return x;
24787 /* [temp.deduct.type] If, in the declaration of a function template
24788 with a non-type template-parameter, the non-type
24789 template-parameter is used in an expression in the function
24790 parameter-list and, if the corresponding template-argument is
24791 deduced, the template-argument type shall match the type of the
24792 template-parameter exactly, except that a template-argument
24793 deduced from an array bound may be of any integral type.
24794 The non-type parameter might use already deduced type parameters. */
24795 tparm = TREE_TYPE (parm);
24796 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24797 /* We don't have enough levels of args to do any substitution. This
24798 can happen in the context of -fnew-ttp-matching. */;
24799 else
24801 ++processing_template_decl;
24802 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24803 --processing_template_decl;
24805 if (tree a = type_uses_auto (tparm))
24807 tparm = do_auto_deduction (tparm, arg, a,
24808 complain, adc_unify, targs,
24809 LOOKUP_NORMAL,
24810 TPARMS_PRIMARY_TEMPLATE (tparms));
24811 if (tparm == error_mark_node)
24812 return 1;
24816 if (!TREE_TYPE (arg)
24817 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24818 /* Template-parameter dependent expression. Just accept it for now.
24819 It will later be processed in convert_template_argument. */
24821 else if (same_type_ignoring_top_level_qualifiers_p
24822 (non_reference (TREE_TYPE (arg)),
24823 non_reference (tparm)))
24824 /* OK. Ignore top-level quals here because a class-type template
24825 parameter object is const. */;
24826 else if ((strict & UNIFY_ALLOW_INTEGER)
24827 && CP_INTEGRAL_TYPE_P (tparm))
24828 /* Convert the ARG to the type of PARM; the deduced non-type
24829 template argument must exactly match the types of the
24830 corresponding parameter. This conversion should match the
24831 one above. */
24832 arg = fold (build_nop (tparm, arg));
24833 else if (uses_template_parms (tparm))
24835 /* We haven't deduced the type of this parameter yet. */
24836 if (cxx_dialect >= cxx17
24837 /* We deduce from array bounds in try_array_deduction. */
24838 && !(strict & UNIFY_ALLOW_INTEGER)
24839 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24841 /* Deduce it from the non-type argument. As above, ignore
24842 top-level quals here too. */
24843 tree atype = cv_unqualified (TREE_TYPE (arg));
24844 RECUR_AND_CHECK_FAILURE (tparms, targs,
24845 tparm, atype,
24846 UNIFY_ALLOW_NONE, explain_p);
24847 /* Now check whether the type of this parameter is still
24848 dependent, and give up if so. */
24849 ++processing_template_decl;
24850 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24851 --processing_template_decl;
24852 if (uses_template_parms (tparm))
24853 return unify_success (explain_p);
24855 else
24856 /* Try again later. */
24857 return unify_success (explain_p);
24859 else
24860 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24862 /* If ARG is a parameter pack or an expansion, we cannot unify
24863 against it unless PARM is also a parameter pack. */
24864 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24865 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24866 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24869 bool removed_attr = false;
24870 arg = strip_typedefs_expr (arg, &removed_attr);
24872 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24873 return unify_success (explain_p);
24875 case PTRMEM_CST:
24877 /* A pointer-to-member constant can be unified only with
24878 another constant. */
24879 if (TREE_CODE (arg) != PTRMEM_CST)
24880 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24882 /* Just unify the class member. It would be useless (and possibly
24883 wrong, depending on the strict flags) to unify also
24884 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24885 arg refer to the same variable, even if through different
24886 classes. For instance:
24888 struct A { int x; };
24889 struct B : A { };
24891 Unification of &A::x and &B::x must succeed. */
24892 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24893 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24896 case POINTER_TYPE:
24898 if (!TYPE_PTR_P (arg))
24899 return unify_type_mismatch (explain_p, parm, arg);
24901 /* [temp.deduct.call]
24903 A can be another pointer or pointer to member type that can
24904 be converted to the deduced A via a qualification
24905 conversion (_conv.qual_).
24907 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24908 This will allow for additional cv-qualification of the
24909 pointed-to types if appropriate. */
24911 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24912 /* The derived-to-base conversion only persists through one
24913 level of pointers. */
24914 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24916 return unify (tparms, targs, TREE_TYPE (parm),
24917 TREE_TYPE (arg), strict, explain_p);
24920 case REFERENCE_TYPE:
24921 if (!TYPE_REF_P (arg))
24922 return unify_type_mismatch (explain_p, parm, arg);
24923 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24924 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24926 case ARRAY_TYPE:
24927 if (TREE_CODE (arg) != ARRAY_TYPE)
24928 return unify_type_mismatch (explain_p, parm, arg);
24929 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24930 != (TYPE_DOMAIN (arg) == NULL_TREE))
24931 return unify_type_mismatch (explain_p, parm, arg);
24932 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24933 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24934 if (TYPE_DOMAIN (parm) != NULL_TREE)
24935 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24936 TYPE_DOMAIN (arg), explain_p);
24937 return unify_success (explain_p);
24939 case REAL_TYPE:
24940 case COMPLEX_TYPE:
24941 case VECTOR_TYPE:
24942 case INTEGER_TYPE:
24943 case BOOLEAN_TYPE:
24944 case ENUMERAL_TYPE:
24945 case VOID_TYPE:
24946 case OPAQUE_TYPE:
24947 case NULLPTR_TYPE:
24948 if (TREE_CODE (arg) != TREE_CODE (parm))
24949 return unify_type_mismatch (explain_p, parm, arg);
24951 /* We have already checked cv-qualification at the top of the
24952 function. */
24953 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24954 return unify_type_mismatch (explain_p, parm, arg);
24956 /* As far as unification is concerned, this wins. Later checks
24957 will invalidate it if necessary. */
24958 return unify_success (explain_p);
24960 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24961 /* Type INTEGER_CST can come from ordinary constant template args. */
24962 case INTEGER_CST:
24963 case REAL_CST:
24964 while (CONVERT_EXPR_P (arg))
24965 arg = TREE_OPERAND (arg, 0);
24967 if (TREE_CODE (arg) != TREE_CODE (parm))
24968 return unify_template_argument_mismatch (explain_p, parm, arg);
24969 return (simple_cst_equal (parm, arg)
24970 ? unify_success (explain_p)
24971 : unify_template_argument_mismatch (explain_p, parm, arg));
24973 case TREE_VEC:
24975 int i, len, argslen;
24976 int parm_variadic_p = 0;
24978 if (TREE_CODE (arg) != TREE_VEC)
24979 return unify_template_argument_mismatch (explain_p, parm, arg);
24981 len = TREE_VEC_LENGTH (parm);
24982 argslen = TREE_VEC_LENGTH (arg);
24984 /* Check for pack expansions in the parameters. */
24985 for (i = 0; i < len; ++i)
24987 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24989 if (i == len - 1)
24990 /* We can unify against something with a trailing
24991 parameter pack. */
24992 parm_variadic_p = 1;
24993 else
24994 /* [temp.deduct.type]/9: If the template argument list of
24995 P contains a pack expansion that is not the last
24996 template argument, the entire template argument list
24997 is a non-deduced context. */
24998 return unify_success (explain_p);
25002 /* If we don't have enough arguments to satisfy the parameters
25003 (not counting the pack expression at the end), or we have
25004 too many arguments for a parameter list that doesn't end in
25005 a pack expression, we can't unify. */
25006 if (parm_variadic_p
25007 ? argslen < len - parm_variadic_p
25008 : argslen != len)
25009 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
25011 /* Unify all of the parameters that precede the (optional)
25012 pack expression. */
25013 for (i = 0; i < len - parm_variadic_p; ++i)
25015 RECUR_AND_CHECK_FAILURE (tparms, targs,
25016 TREE_VEC_ELT (parm, i),
25017 TREE_VEC_ELT (arg, i),
25018 UNIFY_ALLOW_NONE, explain_p);
25020 if (parm_variadic_p)
25021 return unify_pack_expansion (tparms, targs, parm, arg,
25022 DEDUCE_EXACT,
25023 /*subr=*/true, explain_p);
25024 return unify_success (explain_p);
25027 case RECORD_TYPE:
25028 case UNION_TYPE:
25029 if (TREE_CODE (arg) != TREE_CODE (parm))
25030 return unify_type_mismatch (explain_p, parm, arg);
25032 if (TYPE_PTRMEMFUNC_P (parm))
25034 if (!TYPE_PTRMEMFUNC_P (arg))
25035 return unify_type_mismatch (explain_p, parm, arg);
25037 return unify (tparms, targs,
25038 TYPE_PTRMEMFUNC_FN_TYPE (parm),
25039 TYPE_PTRMEMFUNC_FN_TYPE (arg),
25040 strict, explain_p);
25042 else if (TYPE_PTRMEMFUNC_P (arg))
25043 return unify_type_mismatch (explain_p, parm, arg);
25045 if (CLASSTYPE_TEMPLATE_INFO (parm))
25047 tree t = NULL_TREE;
25049 if (strict_in & UNIFY_ALLOW_DERIVED)
25051 /* First, we try to unify the PARM and ARG directly. */
25052 t = try_class_unification (tparms, targs,
25053 parm, arg, explain_p);
25055 if (!t)
25057 /* Fallback to the special case allowed in
25058 [temp.deduct.call]:
25060 If P is a class, and P has the form
25061 template-id, then A can be a derived class of
25062 the deduced A. Likewise, if P is a pointer to
25063 a class of the form template-id, A can be a
25064 pointer to a derived class pointed to by the
25065 deduced A. */
25066 enum template_base_result r;
25067 r = get_template_base (tparms, targs, parm, arg,
25068 explain_p, &t);
25070 if (!t)
25072 /* Don't give the derived diagnostic if we're
25073 already dealing with the same template. */
25074 bool same_template
25075 = (CLASSTYPE_TEMPLATE_INFO (arg)
25076 && (CLASSTYPE_TI_TEMPLATE (parm)
25077 == CLASSTYPE_TI_TEMPLATE (arg)));
25078 return unify_no_common_base (explain_p && !same_template,
25079 r, parm, arg);
25083 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25084 && (CLASSTYPE_TI_TEMPLATE (parm)
25085 == CLASSTYPE_TI_TEMPLATE (arg)))
25086 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25087 Then, we should unify `int' and `U'. */
25088 t = arg;
25089 else
25090 /* There's no chance of unification succeeding. */
25091 return unify_type_mismatch (explain_p, parm, arg);
25093 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
25094 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
25096 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25097 return unify_type_mismatch (explain_p, parm, arg);
25098 return unify_success (explain_p);
25100 case METHOD_TYPE:
25101 case FUNCTION_TYPE:
25103 unsigned int nargs;
25104 tree *args;
25105 tree a;
25106 unsigned int i;
25108 if (TREE_CODE (arg) != TREE_CODE (parm))
25109 return unify_type_mismatch (explain_p, parm, arg);
25111 /* CV qualifications for methods can never be deduced, they must
25112 match exactly. We need to check them explicitly here,
25113 because type_unification_real treats them as any other
25114 cv-qualified parameter. */
25115 if (TREE_CODE (parm) == METHOD_TYPE
25116 && (!check_cv_quals_for_unify
25117 (UNIFY_ALLOW_NONE,
25118 class_of_this_parm (arg),
25119 class_of_this_parm (parm))))
25120 return unify_cv_qual_mismatch (explain_p, parm, arg);
25121 if (TREE_CODE (arg) == FUNCTION_TYPE
25122 && type_memfn_quals (parm) != type_memfn_quals (arg))
25123 return unify_cv_qual_mismatch (explain_p, parm, arg);
25124 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25125 return unify_type_mismatch (explain_p, parm, arg);
25127 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25128 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25130 nargs = list_length (TYPE_ARG_TYPES (arg));
25131 args = XALLOCAVEC (tree, nargs);
25132 for (a = TYPE_ARG_TYPES (arg), i = 0;
25133 a != NULL_TREE && a != void_list_node;
25134 a = TREE_CHAIN (a), ++i)
25135 args[i] = TREE_VALUE (a);
25136 nargs = i;
25138 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25139 args, nargs, 1, DEDUCE_EXACT,
25140 NULL, explain_p))
25141 return 1;
25143 if (flag_noexcept_type)
25145 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25146 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25147 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25148 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25149 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25150 && uses_template_parms (TREE_PURPOSE (pspec)))
25151 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25152 TREE_PURPOSE (aspec),
25153 UNIFY_ALLOW_NONE, explain_p);
25154 else
25156 bool pn = nothrow_spec_p (pspec);
25157 bool an = nothrow_spec_p (aspec);
25158 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25159 /more/ noexcept, since function pointer conversions are the
25160 reverse of qualification conversions. */
25161 if (an == pn
25162 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25163 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25164 /* OK. */;
25165 else
25166 return unify_type_mismatch (explain_p, parm, arg);
25169 if (flag_tm)
25171 /* As for noexcept. */
25172 bool pn = tx_safe_fn_type_p (parm);
25173 bool an = tx_safe_fn_type_p (arg);
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 return 0;
25185 case OFFSET_TYPE:
25186 /* Unify a pointer to member with a pointer to member function, which
25187 deduces the type of the member as a function type. */
25188 if (TYPE_PTRMEMFUNC_P (arg))
25190 /* Check top-level cv qualifiers */
25191 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25192 return unify_cv_qual_mismatch (explain_p, parm, arg);
25194 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25195 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25196 UNIFY_ALLOW_NONE, explain_p);
25198 /* Determine the type of the function we are unifying against. */
25199 tree fntype = static_fn_type (arg);
25201 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25204 if (TREE_CODE (arg) != OFFSET_TYPE)
25205 return unify_type_mismatch (explain_p, parm, arg);
25206 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25207 TYPE_OFFSET_BASETYPE (arg),
25208 UNIFY_ALLOW_NONE, explain_p);
25209 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25210 strict, explain_p);
25212 case CONST_DECL:
25213 if (DECL_TEMPLATE_PARM_P (parm))
25214 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
25215 if (arg != scalar_constant_value (parm))
25216 return unify_template_argument_mismatch (explain_p, parm, arg);
25217 return unify_success (explain_p);
25219 case FIELD_DECL:
25220 case TEMPLATE_DECL:
25221 /* Matched cases are handled by the ARG == PARM test above. */
25222 return unify_template_argument_mismatch (explain_p, parm, arg);
25224 case VAR_DECL:
25225 /* We might get a variable as a non-type template argument in parm if the
25226 corresponding parameter is type-dependent. Make any necessary
25227 adjustments based on whether arg is a reference. */
25228 if (CONSTANT_CLASS_P (arg))
25229 parm = fold_non_dependent_expr (parm, complain);
25230 else if (REFERENCE_REF_P (arg))
25232 tree sub = TREE_OPERAND (arg, 0);
25233 STRIP_NOPS (sub);
25234 if (TREE_CODE (sub) == ADDR_EXPR)
25235 arg = TREE_OPERAND (sub, 0);
25237 /* Now use the normal expression code to check whether they match. */
25238 goto expr;
25240 case TYPE_ARGUMENT_PACK:
25241 case NONTYPE_ARGUMENT_PACK:
25242 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25243 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25245 case TYPEOF_TYPE:
25246 case DECLTYPE_TYPE:
25247 case TRAIT_TYPE:
25248 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25249 or TRAIT_TYPE nodes. */
25250 return unify_success (explain_p);
25252 case ERROR_MARK:
25253 /* Unification fails if we hit an error node. */
25254 return unify_invalid (explain_p);
25256 case INDIRECT_REF:
25257 if (REFERENCE_REF_P (parm))
25259 bool pexp = PACK_EXPANSION_P (arg);
25260 if (pexp)
25261 arg = PACK_EXPANSION_PATTERN (arg);
25262 if (REFERENCE_REF_P (arg))
25263 arg = TREE_OPERAND (arg, 0);
25264 if (pexp)
25265 arg = make_pack_expansion (arg, complain);
25266 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25267 strict, explain_p);
25269 /* FALLTHRU */
25271 default:
25272 /* An unresolved overload is a nondeduced context. */
25273 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25274 return unify_success (explain_p);
25275 gcc_assert (EXPR_P (parm)
25276 || TREE_CODE (parm) == CONSTRUCTOR
25277 || TREE_CODE (parm) == TRAIT_EXPR);
25278 expr:
25279 /* We must be looking at an expression. This can happen with
25280 something like:
25282 template <int I>
25283 void foo(S<I>, S<I + 2>);
25287 template<typename T>
25288 void foo(A<T, T{}>);
25290 This is a "non-deduced context":
25292 [deduct.type]
25294 The non-deduced contexts are:
25296 --A non-type template argument or an array bound in which
25297 a subexpression references a template parameter.
25299 In these cases, we assume deduction succeeded, but don't
25300 actually infer any unifications. */
25302 if (!uses_template_parms (parm)
25303 && !template_args_equal (parm, arg))
25304 return unify_expression_unequal (explain_p, parm, arg);
25305 else
25306 return unify_success (explain_p);
25309 #undef RECUR_AND_CHECK_FAILURE
25311 /* Note that DECL can be defined in this translation unit, if
25312 required. */
25314 static void
25315 mark_definable (tree decl)
25317 tree clone;
25318 DECL_NOT_REALLY_EXTERN (decl) = 1;
25319 FOR_EACH_CLONE (clone, decl)
25320 DECL_NOT_REALLY_EXTERN (clone) = 1;
25323 /* Called if RESULT is explicitly instantiated, or is a member of an
25324 explicitly instantiated class. */
25326 void
25327 mark_decl_instantiated (tree result, int extern_p)
25329 SET_DECL_EXPLICIT_INSTANTIATION (result);
25331 /* If this entity has already been written out, it's too late to
25332 make any modifications. */
25333 if (TREE_ASM_WRITTEN (result))
25334 return;
25336 /* consteval functions are never emitted. */
25337 if (TREE_CODE (result) == FUNCTION_DECL
25338 && DECL_IMMEDIATE_FUNCTION_P (result))
25339 return;
25341 /* For anonymous namespace we don't need to do anything. */
25342 if (decl_internal_context_p (result))
25344 gcc_assert (!TREE_PUBLIC (result));
25345 return;
25348 if (TREE_CODE (result) != FUNCTION_DECL)
25349 /* The TREE_PUBLIC flag for function declarations will have been
25350 set correctly by tsubst. */
25351 TREE_PUBLIC (result) = 1;
25353 if (extern_p)
25355 DECL_EXTERNAL (result) = 1;
25356 DECL_NOT_REALLY_EXTERN (result) = 0;
25358 else
25360 mark_definable (result);
25361 mark_needed (result);
25362 /* Always make artificials weak. */
25363 if (DECL_ARTIFICIAL (result) && flag_weak)
25364 comdat_linkage (result);
25365 /* For WIN32 we also want to put explicit instantiations in
25366 linkonce sections. */
25367 else if (TREE_PUBLIC (result))
25368 maybe_make_one_only (result);
25369 if (TREE_CODE (result) == FUNCTION_DECL
25370 && DECL_TEMPLATE_INSTANTIATED (result))
25371 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25372 since start_preparsed_function wouldn't have if we had an earlier
25373 extern explicit instantiation. */
25374 DECL_EXTERNAL (result) = 0;
25377 /* If EXTERN_P, then this function will not be emitted -- unless
25378 followed by an explicit instantiation, at which point its linkage
25379 will be adjusted. If !EXTERN_P, then this function will be
25380 emitted here. In neither circumstance do we want
25381 import_export_decl to adjust the linkage. */
25382 DECL_INTERFACE_KNOWN (result) = 1;
25385 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25386 important template arguments. If any are missing, we check whether
25387 they're important by using error_mark_node for substituting into any
25388 args that were used for partial ordering (the ones between ARGS and END)
25389 and seeing if it bubbles up. */
25391 static bool
25392 check_undeduced_parms (tree targs, tree args, tree end)
25394 bool found = false;
25395 for (tree& targ : tree_vec_range (targs))
25396 if (targ == NULL_TREE)
25398 found = true;
25399 targ = error_mark_node;
25401 if (found)
25403 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25404 if (substed == error_mark_node)
25405 return true;
25407 return false;
25410 /* Given two function templates PAT1 and PAT2, return:
25412 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25413 -1 if PAT2 is more specialized than PAT1.
25414 0 if neither is more specialized.
25416 LEN indicates the number of parameters we should consider
25417 (defaulted parameters should not be considered).
25419 The 1998 std underspecified function template partial ordering, and
25420 DR214 addresses the issue. We take pairs of arguments, one from
25421 each of the templates, and deduce them against each other. One of
25422 the templates will be more specialized if all the *other*
25423 template's arguments deduce against its arguments and at least one
25424 of its arguments *does* *not* deduce against the other template's
25425 corresponding argument. Deduction is done as for class templates.
25426 The arguments used in deduction have reference and top level cv
25427 qualifiers removed. Iff both arguments were originally reference
25428 types *and* deduction succeeds in both directions, an lvalue reference
25429 wins against an rvalue reference and otherwise the template
25430 with the more cv-qualified argument wins for that pairing (if
25431 neither is more cv-qualified, they both are equal). Unlike regular
25432 deduction, after all the arguments have been deduced in this way,
25433 we do *not* verify the deduced template argument values can be
25434 substituted into non-deduced contexts.
25436 The logic can be a bit confusing here, because we look at deduce1 and
25437 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25438 can find template arguments for pat1 to make arg1 look like arg2, that
25439 means that arg2 is at least as specialized as arg1. */
25442 more_specialized_fn (tree pat1, tree pat2, int len)
25444 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25445 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25446 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25447 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25448 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25449 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25450 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25451 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25452 tree origs1, origs2;
25453 bool lose1 = false;
25454 bool lose2 = false;
25456 /* Remove the this parameter from non-static member functions. If
25457 one is a non-static member function and the other is not a static
25458 member function, remove the first parameter from that function
25459 also. This situation occurs for operator functions where we
25460 locate both a member function (with this pointer) and non-member
25461 operator (with explicit first operand). */
25462 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25464 len--; /* LEN is the number of significant arguments for DECL1 */
25465 args1 = TREE_CHAIN (args1);
25466 if (!DECL_STATIC_FUNCTION_P (decl2))
25467 args2 = TREE_CHAIN (args2);
25469 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25471 args2 = TREE_CHAIN (args2);
25472 if (!DECL_STATIC_FUNCTION_P (decl1))
25474 len--;
25475 args1 = TREE_CHAIN (args1);
25479 /* If only one is a conversion operator, they are unordered. */
25480 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25481 return 0;
25483 /* Consider the return type for a conversion function */
25484 if (DECL_CONV_FN_P (decl1))
25486 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25487 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25488 len++;
25491 processing_template_decl++;
25493 origs1 = args1;
25494 origs2 = args2;
25496 while (len--
25497 /* Stop when an ellipsis is seen. */
25498 && args1 != NULL_TREE && args2 != NULL_TREE)
25500 tree arg1 = TREE_VALUE (args1);
25501 tree arg2 = TREE_VALUE (args2);
25502 int deduce1, deduce2;
25503 int quals1 = -1;
25504 int quals2 = -1;
25505 int ref1 = 0;
25506 int ref2 = 0;
25508 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25509 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25511 /* When both arguments are pack expansions, we need only
25512 unify the patterns themselves. */
25513 arg1 = PACK_EXPANSION_PATTERN (arg1);
25514 arg2 = PACK_EXPANSION_PATTERN (arg2);
25516 /* This is the last comparison we need to do. */
25517 len = 0;
25520 if (TYPE_REF_P (arg1))
25522 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25523 arg1 = TREE_TYPE (arg1);
25524 quals1 = cp_type_quals (arg1);
25527 if (TYPE_REF_P (arg2))
25529 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25530 arg2 = TREE_TYPE (arg2);
25531 quals2 = cp_type_quals (arg2);
25534 arg1 = TYPE_MAIN_VARIANT (arg1);
25535 arg2 = TYPE_MAIN_VARIANT (arg2);
25537 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25539 int i, len2 = remaining_arguments (args2);
25540 tree parmvec = make_tree_vec (1);
25541 tree argvec = make_tree_vec (len2);
25542 tree ta = args2;
25544 /* Setup the parameter vector, which contains only ARG1. */
25545 TREE_VEC_ELT (parmvec, 0) = arg1;
25547 /* Setup the argument vector, which contains the remaining
25548 arguments. */
25549 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25550 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25552 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25553 argvec, DEDUCE_EXACT,
25554 /*subr=*/true, /*explain_p=*/false)
25555 == 0);
25557 /* We cannot deduce in the other direction, because ARG1 is
25558 a pack expansion but ARG2 is not. */
25559 deduce2 = 0;
25561 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25563 int i, len1 = remaining_arguments (args1);
25564 tree parmvec = make_tree_vec (1);
25565 tree argvec = make_tree_vec (len1);
25566 tree ta = args1;
25568 /* Setup the parameter vector, which contains only ARG1. */
25569 TREE_VEC_ELT (parmvec, 0) = arg2;
25571 /* Setup the argument vector, which contains the remaining
25572 arguments. */
25573 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25574 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25576 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25577 argvec, DEDUCE_EXACT,
25578 /*subr=*/true, /*explain_p=*/false)
25579 == 0);
25581 /* We cannot deduce in the other direction, because ARG2 is
25582 a pack expansion but ARG1 is not.*/
25583 deduce1 = 0;
25586 else
25588 /* The normal case, where neither argument is a pack
25589 expansion. */
25590 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25591 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25592 == 0);
25593 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25594 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25595 == 0);
25598 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25599 arg2, then arg2 is not as specialized as arg1. */
25600 if (!deduce1)
25601 lose2 = true;
25602 if (!deduce2)
25603 lose1 = true;
25605 /* "If, for a given type, deduction succeeds in both directions
25606 (i.e., the types are identical after the transformations above)
25607 and both P and A were reference types (before being replaced with
25608 the type referred to above):
25609 - if the type from the argument template was an lvalue reference and
25610 the type from the parameter template was not, the argument type is
25611 considered to be more specialized than the other; otherwise,
25612 - if the type from the argument template is more cv-qualified
25613 than the type from the parameter template (as described above),
25614 the argument type is considered to be more specialized than the other;
25615 otherwise,
25616 - neither type is more specialized than the other." */
25618 if (deduce1 && deduce2)
25620 if (ref1 && ref2 && ref1 != ref2)
25622 if (ref1 > ref2)
25623 lose1 = true;
25624 else
25625 lose2 = true;
25627 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25629 if ((quals1 & quals2) == quals2)
25630 lose2 = true;
25631 if ((quals1 & quals2) == quals1)
25632 lose1 = true;
25636 if (lose1 && lose2)
25637 /* We've failed to deduce something in either direction.
25638 These must be unordered. */
25639 break;
25641 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25642 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25643 /* We have already processed all of the arguments in our
25644 handing of the pack expansion type. */
25645 len = 0;
25647 args1 = TREE_CHAIN (args1);
25648 args2 = TREE_CHAIN (args2);
25651 /* "In most cases, all template parameters must have values in order for
25652 deduction to succeed, but for partial ordering purposes a template
25653 parameter may remain without a value provided it is not used in the
25654 types being used for partial ordering."
25656 Thus, if we are missing any of the targs1 we need to substitute into
25657 origs1, then pat2 is not as specialized as pat1. This can happen when
25658 there is a nondeduced context. */
25659 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25660 lose2 = true;
25661 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25662 lose1 = true;
25664 processing_template_decl--;
25666 /* If both deductions succeed, the partial ordering selects the more
25667 constrained template. */
25668 /* P2113: If the corresponding template-parameters of the
25669 template-parameter-lists are not equivalent ([temp.over.link]) or if
25670 the function parameters that positionally correspond between the two
25671 templates are not of the same type, neither template is more
25672 specialized than the other. */
25673 if (!lose1 && !lose2
25674 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25675 DECL_TEMPLATE_PARMS (pat2))
25676 && compparms (origs1, origs2))
25678 int winner = more_constrained (decl1, decl2);
25679 if (winner > 0)
25680 lose2 = true;
25681 else if (winner < 0)
25682 lose1 = true;
25685 /* All things being equal, if the next argument is a pack expansion
25686 for one function but not for the other, prefer the
25687 non-variadic function. FIXME this is bogus; see c++/41958. */
25688 if (lose1 == lose2
25689 && args1 && TREE_VALUE (args1)
25690 && args2 && TREE_VALUE (args2))
25692 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25693 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25696 if (lose1 == lose2)
25697 return 0;
25698 else if (!lose1)
25699 return 1;
25700 else
25701 return -1;
25704 /* Determine which of two partial specializations of TMPL is more
25705 specialized.
25707 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25708 to the first partial specialization. The TREE_PURPOSE is the
25709 innermost set of template parameters for the partial
25710 specialization. PAT2 is similar, but for the second template.
25712 Return 1 if the first partial specialization is more specialized;
25713 -1 if the second is more specialized; 0 if neither is more
25714 specialized.
25716 See [temp.class.order] for information about determining which of
25717 two templates is more specialized. */
25719 static int
25720 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25722 tree targs;
25723 int winner = 0;
25724 bool any_deductions = false;
25726 tree tmpl1 = TREE_VALUE (pat1);
25727 tree tmpl2 = TREE_VALUE (pat2);
25728 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25729 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25731 /* Just like what happens for functions, if we are ordering between
25732 different template specializations, we may encounter dependent
25733 types in the arguments, and we need our dependency check functions
25734 to behave correctly. */
25735 ++processing_template_decl;
25736 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25737 if (targs)
25739 --winner;
25740 any_deductions = true;
25743 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25744 if (targs)
25746 ++winner;
25747 any_deductions = true;
25749 --processing_template_decl;
25751 /* If both deductions succeed, the partial ordering selects the more
25752 constrained template. */
25753 if (!winner && any_deductions)
25754 winner = more_constrained (tmpl1, tmpl2);
25756 /* In the case of a tie where at least one of the templates
25757 has a parameter pack at the end, the template with the most
25758 non-packed parameters wins. */
25759 if (winner == 0
25760 && any_deductions
25761 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25762 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25764 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25765 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25766 int len1 = TREE_VEC_LENGTH (args1);
25767 int len2 = TREE_VEC_LENGTH (args2);
25769 /* We don't count the pack expansion at the end. */
25770 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25771 --len1;
25772 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25773 --len2;
25775 if (len1 > len2)
25776 return 1;
25777 else if (len1 < len2)
25778 return -1;
25781 return winner;
25784 /* Return the template arguments that will produce the function signature
25785 DECL from the function template FN, with the explicit template
25786 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25787 also match. Return NULL_TREE if no satisfactory arguments could be
25788 found. */
25790 static tree
25791 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25793 int ntparms = DECL_NTPARMS (fn);
25794 tree targs = make_tree_vec (ntparms);
25795 tree decl_type = TREE_TYPE (decl);
25796 tree decl_arg_types;
25797 tree *args;
25798 unsigned int nargs, ix;
25799 tree arg;
25801 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25803 /* Never do unification on the 'this' parameter. */
25804 decl_arg_types = skip_artificial_parms_for (decl,
25805 TYPE_ARG_TYPES (decl_type));
25807 nargs = list_length (decl_arg_types);
25808 args = XALLOCAVEC (tree, nargs);
25809 for (arg = decl_arg_types, ix = 0;
25810 arg != NULL_TREE;
25811 arg = TREE_CHAIN (arg), ++ix)
25812 args[ix] = TREE_VALUE (arg);
25814 if (fn_type_unification (fn, explicit_args, targs,
25815 args, ix,
25816 (check_rettype || DECL_CONV_FN_P (fn)
25817 ? TREE_TYPE (decl_type) : NULL_TREE),
25818 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25819 /*explain_p=*/false,
25820 /*decltype*/false)
25821 == error_mark_node)
25822 return NULL_TREE;
25824 return targs;
25827 /* Return the innermost template arguments that, when applied to a partial
25828 specialization SPEC_TMPL of TMPL, yield the ARGS.
25830 For example, suppose we have:
25832 template <class T, class U> struct S {};
25833 template <class T> struct S<T*, int> {};
25835 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25836 partial specialization and the ARGS will be {double*, int}. The resulting
25837 vector will be {double}, indicating that `T' is bound to `double'. */
25839 static tree
25840 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25842 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25843 tree spec_args
25844 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25845 int i, ntparms = TREE_VEC_LENGTH (tparms);
25846 tree deduced_args;
25847 tree innermost_deduced_args;
25849 innermost_deduced_args = make_tree_vec (ntparms);
25850 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25852 deduced_args = copy_node (args);
25853 SET_TMPL_ARGS_LEVEL (deduced_args,
25854 TMPL_ARGS_DEPTH (deduced_args),
25855 innermost_deduced_args);
25857 else
25858 deduced_args = innermost_deduced_args;
25860 bool tried_array_deduction = (cxx_dialect < cxx17);
25861 again:
25862 if (unify (tparms, deduced_args,
25863 INNERMOST_TEMPLATE_ARGS (spec_args),
25864 INNERMOST_TEMPLATE_ARGS (args),
25865 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25866 return NULL_TREE;
25868 for (i = 0; i < ntparms; ++i)
25869 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25871 if (!tried_array_deduction)
25873 try_array_deduction (tparms, innermost_deduced_args,
25874 INNERMOST_TEMPLATE_ARGS (spec_args));
25875 tried_array_deduction = true;
25876 if (TREE_VEC_ELT (innermost_deduced_args, i))
25877 goto again;
25879 return NULL_TREE;
25882 if (!push_tinst_level (spec_tmpl, deduced_args))
25884 excessive_deduction_depth = true;
25885 return NULL_TREE;
25888 /* Verify that nondeduced template arguments agree with the type
25889 obtained from argument deduction.
25891 For example:
25893 struct A { typedef int X; };
25894 template <class T, class U> struct C {};
25895 template <class T> struct C<T, typename T::X> {};
25897 Then with the instantiation `C<A, int>', we can deduce that
25898 `T' is `A' but unify () does not check whether `typename T::X'
25899 is `int'. */
25900 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25902 if (spec_args != error_mark_node)
25903 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25904 INNERMOST_TEMPLATE_ARGS (spec_args),
25905 tmpl, tf_none, false);
25907 pop_tinst_level ();
25909 if (spec_args == error_mark_node
25910 /* We only need to check the innermost arguments; the other
25911 arguments will always agree. */
25912 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25913 INNERMOST_TEMPLATE_ARGS (args)))
25914 return NULL_TREE;
25916 /* Now that we have bindings for all of the template arguments,
25917 ensure that the arguments deduced for the template template
25918 parameters have compatible template parameter lists. See the use
25919 of template_template_parm_bindings_ok_p in fn_type_unification
25920 for more information. */
25921 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25922 return NULL_TREE;
25924 return deduced_args;
25927 // Compare two function templates T1 and T2 by deducing bindings
25928 // from one against the other. If both deductions succeed, compare
25929 // constraints to see which is more constrained.
25930 static int
25931 more_specialized_inst (tree t1, tree t2)
25933 int fate = 0;
25934 int count = 0;
25936 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25938 --fate;
25939 ++count;
25942 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25944 ++fate;
25945 ++count;
25948 // If both deductions succeed, then one may be more constrained.
25949 if (count == 2 && fate == 0)
25950 fate = more_constrained (t1, t2);
25952 return fate;
25955 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25956 Return the TREE_LIST node with the most specialized template, if
25957 any. If there is no most specialized template, the error_mark_node
25958 is returned.
25960 Note that this function does not look at, or modify, the
25961 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25962 returned is one of the elements of INSTANTIATIONS, callers may
25963 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25964 and retrieve it from the value returned. */
25966 tree
25967 most_specialized_instantiation (tree templates)
25969 tree fn, champ;
25971 ++processing_template_decl;
25973 champ = templates;
25974 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25976 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25977 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25978 if (fate == -1)
25979 champ = fn;
25980 else if (!fate)
25982 /* Equally specialized, move to next function. If there
25983 is no next function, nothing's most specialized. */
25984 fn = TREE_CHAIN (fn);
25985 champ = fn;
25986 if (!fn)
25987 break;
25991 if (champ)
25992 /* Now verify that champ is better than everything earlier in the
25993 instantiation list. */
25994 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25995 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25997 champ = NULL_TREE;
25998 break;
26002 processing_template_decl--;
26004 if (!champ)
26005 return error_mark_node;
26007 return champ;
26010 /* If DECL is a specialization of some template, return the most
26011 general such template. Otherwise, returns NULL_TREE.
26013 For example, given:
26015 template <class T> struct S { template <class U> void f(U); };
26017 if TMPL is `template <class U> void S<int>::f(U)' this will return
26018 the full template. This function will not trace past partial
26019 specializations, however. For example, given in addition:
26021 template <class T> struct S<T*> { template <class U> void f(U); };
26023 if TMPL is `template <class U> void S<int*>::f(U)' this will return
26024 `template <class T> template <class U> S<T*>::f(U)'. */
26026 tree
26027 most_general_template (tree decl)
26029 if (TREE_CODE (decl) != TEMPLATE_DECL)
26031 if (tree tinfo = get_template_info (decl))
26032 decl = TI_TEMPLATE (tinfo);
26033 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
26034 template friend, or a FIELD_DECL for a capture pack. */
26035 if (TREE_CODE (decl) != TEMPLATE_DECL)
26036 return NULL_TREE;
26039 if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
26040 return DECL_TI_TEMPLATE (DECL_TEMPLATE_RESULT (decl));
26042 /* Look for more and more general templates. */
26043 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
26045 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
26046 (See cp-tree.h for details.) */
26047 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
26048 break;
26050 if (CLASS_TYPE_P (TREE_TYPE (decl))
26051 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
26052 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
26053 break;
26055 /* Stop if we run into an explicitly specialized class template. */
26056 if (!DECL_NAMESPACE_SCOPE_P (decl)
26057 && DECL_CONTEXT (decl)
26058 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
26059 break;
26061 decl = DECL_TI_TEMPLATE (decl);
26064 return decl;
26067 /* Return the most specialized of the template partial specializations
26068 which can produce TARGET, a specialization of some class or variable
26069 template. The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
26070 TEMPLATE_DECL node corresponding to the partial specialization, while
26071 the TI_ARGS is the set of template arguments that must be substituted
26072 into the template pattern in order to generate TARGET. The result is
26073 cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
26074 RECHECKING is true.
26076 If the choice of partial specialization is ambiguous, a diagnostic
26077 is issued, and the error_mark_node is returned. If there are no
26078 partial specializations matching TARGET, then NULL_TREE is
26079 returned, indicating that the primary template should be used. */
26081 tree
26082 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
26083 bool rechecking /* = false */)
26085 tree tinfo = NULL_TREE;
26086 tree tmpl, args, decl;
26087 if (TYPE_P (target))
26089 tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26090 tmpl = TI_TEMPLATE (tinfo);
26091 args = TI_ARGS (tinfo);
26092 decl = TYPE_NAME (target);
26094 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26096 tmpl = TREE_OPERAND (target, 0);
26097 args = TREE_OPERAND (target, 1);
26098 decl = DECL_TEMPLATE_RESULT (tmpl);
26100 else if (VAR_P (target))
26102 tinfo = DECL_TEMPLATE_INFO (target);
26103 tmpl = TI_TEMPLATE (tinfo);
26104 args = TI_ARGS (tinfo);
26105 decl = target;
26107 else
26108 gcc_unreachable ();
26110 if (!PRIMARY_TEMPLATE_P (tmpl))
26111 return NULL_TREE;
26113 if (!rechecking
26114 && tinfo
26115 && (VAR_P (target) || COMPLETE_TYPE_P (target)))
26116 return TI_PARTIAL_INFO (tinfo);
26118 tree main_tmpl = most_general_template (tmpl);
26119 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26120 if (!specs)
26121 /* There are no partial specializations of this template. */
26122 return NULL_TREE;
26124 push_access_scope_guard pas (decl);
26125 deferring_access_check_sentinel acs (dk_no_deferred);
26127 /* For determining which partial specialization to use, only the
26128 innermost args are interesting. */
26129 tree outer_args = NULL_TREE;
26130 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26132 outer_args = strip_innermost_template_args (args, 1);
26133 args = INNERMOST_TEMPLATE_ARGS (args);
26136 /* The caller hasn't called push_to_top_level yet, but we need
26137 get_partial_spec_bindings to be done in non-template context so that we'll
26138 fully resolve everything. */
26139 processing_template_decl_sentinel ptds;
26141 tree list = NULL_TREE;
26142 for (tree t = specs; t; t = TREE_CHAIN (t))
26144 const tree ospec_tmpl = TREE_VALUE (t);
26146 tree spec_tmpl;
26147 if (outer_args)
26149 /* Substitute in the template args from the enclosing class. */
26150 ++processing_template_decl;
26151 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26152 --processing_template_decl;
26153 if (spec_tmpl == error_mark_node)
26154 return error_mark_node;
26156 else
26157 spec_tmpl = ospec_tmpl;
26159 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26160 if (spec_args)
26162 if (outer_args)
26163 spec_args = add_to_template_args (outer_args, spec_args);
26165 /* Keep the candidate only if its constraints are satisfied. */
26166 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26167 list = tree_cons (spec_args, ospec_tmpl, list);
26171 if (! list)
26172 return NULL_TREE;
26174 tree champ = list;
26175 bool ambiguous_p = false;
26176 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26178 int fate = more_specialized_partial_spec (tmpl, champ, t);
26179 if (fate == 1)
26181 else
26183 if (fate == 0)
26185 t = TREE_CHAIN (t);
26186 if (! t)
26188 ambiguous_p = true;
26189 break;
26192 champ = t;
26196 if (!ambiguous_p)
26197 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26199 int fate = more_specialized_partial_spec (tmpl, champ, t);
26200 if (fate != 1)
26202 ambiguous_p = true;
26203 break;
26207 if (ambiguous_p)
26209 const char *str;
26210 char *spaces = NULL;
26211 if (!(complain & tf_error))
26212 return error_mark_node;
26213 if (TYPE_P (target))
26214 error ("ambiguous template instantiation for %q#T", target);
26215 else
26216 error ("ambiguous template instantiation for %q#D", target);
26217 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26218 for (tree t = list; t; t = TREE_CHAIN (t))
26220 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26221 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26222 "%s %#qS", spaces ? spaces : str, subst);
26223 spaces = spaces ? spaces : get_spaces (str);
26225 free (spaces);
26226 return error_mark_node;
26229 tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
26230 if (!rechecking && tinfo)
26231 TI_PARTIAL_INFO (tinfo) = result;
26232 return result;
26235 /* Explicitly instantiate DECL. */
26237 void
26238 do_decl_instantiation (tree decl, tree storage)
26240 tree result = NULL_TREE;
26241 int extern_p = 0;
26243 if (!decl || decl == error_mark_node)
26244 /* An error occurred, for which grokdeclarator has already issued
26245 an appropriate message. */
26246 return;
26247 else if (! DECL_LANG_SPECIFIC (decl))
26249 error ("explicit instantiation of non-template %q#D", decl);
26250 return;
26252 else if (DECL_DECLARED_CONCEPT_P (decl))
26254 if (VAR_P (decl))
26255 error ("explicit instantiation of variable concept %q#D", decl);
26256 else
26257 error ("explicit instantiation of function concept %q#D", decl);
26258 return;
26261 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26262 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26264 if (VAR_P (decl) && !var_templ)
26266 /* There is an asymmetry here in the way VAR_DECLs and
26267 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26268 the latter, the DECL we get back will be marked as a
26269 template instantiation, and the appropriate
26270 DECL_TEMPLATE_INFO will be set up. This does not happen for
26271 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26272 should handle VAR_DECLs as it currently handles
26273 FUNCTION_DECLs. */
26274 if (!DECL_CLASS_SCOPE_P (decl))
26276 error ("%qD is not a static data member of a class template", decl);
26277 return;
26279 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26280 if (!result || !VAR_P (result))
26282 error ("no matching template for %qD found", decl);
26283 return;
26285 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26287 error ("type %qT for explicit instantiation %qD does not match "
26288 "declared type %qT", TREE_TYPE (result), decl,
26289 TREE_TYPE (decl));
26290 return;
26293 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26295 error ("explicit instantiation of %q#D", decl);
26296 return;
26298 else
26299 result = decl;
26301 /* Check for various error cases. Note that if the explicit
26302 instantiation is valid the RESULT will currently be marked as an
26303 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26304 until we get here. */
26306 if (DECL_TEMPLATE_SPECIALIZATION (result))
26308 /* DR 259 [temp.spec].
26310 Both an explicit instantiation and a declaration of an explicit
26311 specialization shall not appear in a program unless the explicit
26312 instantiation follows a declaration of the explicit specialization.
26314 For a given set of template parameters, if an explicit
26315 instantiation of a template appears after a declaration of an
26316 explicit specialization for that template, the explicit
26317 instantiation has no effect. */
26318 return;
26320 else if (DECL_EXPLICIT_INSTANTIATION (result))
26322 /* [temp.spec]
26324 No program shall explicitly instantiate any template more
26325 than once.
26327 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26328 the first instantiation was `extern' and the second is not,
26329 and EXTERN_P for the opposite case. */
26330 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26331 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26332 /* If an "extern" explicit instantiation follows an ordinary
26333 explicit instantiation, the template is instantiated. */
26334 if (extern_p)
26335 return;
26337 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26339 error ("no matching template for %qD found", result);
26340 return;
26342 else if (!DECL_TEMPLATE_INFO (result))
26344 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26345 return;
26348 if (storage == NULL_TREE)
26350 else if (storage == ridpointers[(int) RID_EXTERN])
26352 if (cxx_dialect == cxx98)
26353 pedwarn (input_location, OPT_Wpedantic,
26354 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26355 "instantiations");
26356 extern_p = 1;
26358 else
26359 error ("storage class %qD applied to template instantiation", storage);
26361 check_explicit_instantiation_namespace (result);
26362 mark_decl_instantiated (result, extern_p);
26363 if (! extern_p)
26364 instantiate_decl (result, /*defer_ok=*/true,
26365 /*expl_inst_class_mem_p=*/false);
26368 static void
26369 mark_class_instantiated (tree t, int extern_p)
26371 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26372 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26373 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26374 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26375 if (! extern_p)
26377 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26378 rest_of_type_compilation (t, 1);
26382 /* Perform an explicit instantiation of template class T. STORAGE, if
26383 non-null, is the RID for extern, inline or static. COMPLAIN is
26384 nonzero if this is called from the parser, zero if called recursively,
26385 since the standard is unclear (as detailed below). */
26387 void
26388 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26390 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26392 if (tree ti = TYPE_TEMPLATE_INFO (t))
26393 error ("explicit instantiation of non-class template %qD",
26394 TI_TEMPLATE (ti));
26395 else
26396 error ("explicit instantiation of non-template type %qT", t);
26397 return;
26400 complete_type (t);
26402 if (!COMPLETE_TYPE_P (t))
26404 if (complain & tf_error)
26405 error ("explicit instantiation of %q#T before definition of template",
26407 return;
26410 /* At most one of these will be true. */
26411 bool extern_p = false;
26412 bool nomem_p = false;
26413 bool static_p = false;
26415 if (storage != NULL_TREE)
26417 if (storage == ridpointers[(int) RID_EXTERN])
26419 if (cxx_dialect == cxx98)
26420 pedwarn (input_location, OPT_Wpedantic,
26421 "ISO C++ 1998 forbids the use of %<extern%> on "
26422 "explicit instantiations");
26424 else
26425 pedwarn (input_location, OPT_Wpedantic,
26426 "ISO C++ forbids the use of %qE"
26427 " on explicit instantiations", storage);
26429 if (storage == ridpointers[(int) RID_INLINE])
26430 nomem_p = true;
26431 else if (storage == ridpointers[(int) RID_EXTERN])
26432 extern_p = true;
26433 else if (storage == ridpointers[(int) RID_STATIC])
26434 static_p = true;
26435 else
26436 error ("storage class %qD applied to template instantiation",
26437 storage);
26440 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26441 /* DR 259 [temp.spec].
26443 Both an explicit instantiation and a declaration of an explicit
26444 specialization shall not appear in a program unless the
26445 explicit instantiation follows a declaration of the explicit
26446 specialization.
26448 For a given set of template parameters, if an explicit
26449 instantiation of a template appears after a declaration of an
26450 explicit specialization for that template, the explicit
26451 instantiation has no effect. */
26452 return;
26454 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26456 /* We've already instantiated the template. */
26458 /* [temp.spec]
26460 No program shall explicitly instantiate any template more
26461 than once.
26463 If EXTERN_P then this is ok. */
26464 if (!extern_p && (complain & tf_error))
26465 permerror (input_location,
26466 "duplicate explicit instantiation of %q#T", t);
26468 return;
26471 check_explicit_instantiation_namespace (TYPE_NAME (t));
26472 mark_class_instantiated (t, extern_p);
26474 if (nomem_p)
26475 return;
26477 /* In contrast to implicit instantiation, where only the
26478 declarations, and not the definitions, of members are
26479 instantiated, we have here:
26481 [temp.explicit]
26483 An explicit instantiation that names a class template
26484 specialization is also an explicit instantiation of the same
26485 kind (declaration or definition) of each of its members (not
26486 including members inherited from base classes and members
26487 that are templates) that has not been previously explicitly
26488 specialized in the translation unit containing the explicit
26489 instantiation, provided that the associated constraints, if
26490 any, of that member are satisfied by the template arguments
26491 of the explicit instantiation. */
26492 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26493 if ((VAR_P (fld)
26494 || (TREE_CODE (fld) == FUNCTION_DECL
26495 && !static_p
26496 && user_provided_p (fld)))
26497 && DECL_TEMPLATE_INSTANTIATION (fld)
26498 && constraints_satisfied_p (fld))
26500 mark_decl_instantiated (fld, extern_p);
26501 if (! extern_p)
26502 instantiate_decl (fld, /*defer_ok=*/true,
26503 /*expl_inst_class_mem_p=*/true);
26505 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26507 tree type = TREE_TYPE (fld);
26509 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26510 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26511 do_type_instantiation (type, storage, 0);
26515 /* Given a function DECL, which is a specialization of TMPL, modify
26516 DECL to be a re-instantiation of TMPL with the same template
26517 arguments. TMPL should be the template into which tsubst'ing
26518 should occur for DECL, not the most general template.
26520 One reason for doing this is a scenario like this:
26522 template <class T>
26523 void f(const T&, int i);
26525 void g() { f(3, 7); }
26527 template <class T>
26528 void f(const T& t, const int i) { }
26530 Note that when the template is first instantiated, with
26531 instantiate_template, the resulting DECL will have no name for the
26532 first parameter, and the wrong type for the second. So, when we go
26533 to instantiate the DECL, we regenerate it. */
26535 static void
26536 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26538 /* The arguments used to instantiate DECL, from the most general
26539 template. */
26540 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26542 /* Make sure that we can see identifiers, and compute access correctly. */
26543 push_access_scope (decl);
26545 if (TREE_CODE (decl) == FUNCTION_DECL)
26547 tree specs;
26548 int args_depth;
26549 int parms_depth;
26551 /* Don't bother with this for unique friends that can't be redeclared and
26552 might change type if regenerated (PR69836). */
26553 if (DECL_UNIQUE_FRIEND_P (decl))
26554 goto done;
26556 /* Use the source location of the definition. */
26557 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26559 args_depth = TMPL_ARGS_DEPTH (args);
26560 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26561 if (args_depth > parms_depth)
26562 args = get_innermost_template_args (args, parms_depth);
26564 /* Instantiate a dynamic exception-specification. noexcept will be
26565 handled below. */
26566 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26567 if (TREE_VALUE (raises))
26569 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26570 args, tf_error, NULL_TREE,
26571 /*defer_ok*/false);
26572 if (specs && specs != error_mark_node)
26573 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26574 specs);
26577 /* Merge parameter declarations. */
26578 if (tree pattern_parm
26579 = skip_artificial_parms_for (code_pattern,
26580 DECL_ARGUMENTS (code_pattern)))
26582 tree *p = &DECL_ARGUMENTS (decl);
26583 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26584 p = &DECL_CHAIN (*p);
26585 *p = tsubst_decl (pattern_parm, args, tf_error);
26586 for (tree t = *p; t; t = DECL_CHAIN (t))
26587 DECL_CONTEXT (t) = decl;
26590 if (DECL_CONTRACTS (decl))
26592 /* If we're regenerating a specialization, the contracts will have
26593 been copied from the most general template. Replace those with
26594 the ones from the actual specialization. */
26595 tree tmpl = DECL_TI_TEMPLATE (decl);
26596 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26598 remove_contract_attributes (decl);
26599 copy_contract_attributes (decl, code_pattern);
26602 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26605 /* Merge additional specifiers from the CODE_PATTERN. */
26606 if (DECL_DECLARED_INLINE_P (code_pattern)
26607 && !DECL_DECLARED_INLINE_P (decl))
26608 DECL_DECLARED_INLINE_P (decl) = 1;
26610 maybe_instantiate_noexcept (decl, tf_error);
26612 else if (VAR_P (decl))
26614 start_lambda_scope (decl);
26615 DECL_INITIAL (decl) =
26616 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26617 tf_error, DECL_TI_TEMPLATE (decl));
26618 finish_lambda_scope ();
26619 if (VAR_HAD_UNKNOWN_BOUND (decl))
26620 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26621 tf_error, DECL_TI_TEMPLATE (decl));
26623 else
26624 gcc_unreachable ();
26626 done:
26627 pop_access_scope (decl);
26630 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26631 substituted to get DECL. */
26633 tree
26634 template_for_substitution (tree decl)
26636 tree tmpl = DECL_TI_TEMPLATE (decl);
26638 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26639 for the instantiation. This is not always the most general
26640 template. Consider, for example:
26642 template <class T>
26643 struct S { template <class U> void f();
26644 template <> void f<int>(); };
26646 and an instantiation of S<double>::f<int>. We want TD to be the
26647 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26648 while (/* An instantiation cannot have a definition, so we need a
26649 more general template. */
26650 DECL_TEMPLATE_INSTANTIATION (tmpl)
26651 /* We must also deal with friend templates. Given:
26653 template <class T> struct S {
26654 template <class U> friend void f() {};
26657 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26658 so far as the language is concerned, but that's still
26659 where we get the pattern for the instantiation from. On
26660 other hand, if the definition comes outside the class, say:
26662 template <class T> struct S {
26663 template <class U> friend void f();
26665 template <class U> friend void f() {}
26667 we don't need to look any further. That's what the check for
26668 DECL_INITIAL is for. */
26669 || (TREE_CODE (decl) == FUNCTION_DECL
26670 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26671 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26673 /* The present template, TD, should not be a definition. If it
26674 were a definition, we should be using it! Note that we
26675 cannot restructure the loop to just keep going until we find
26676 a template with a definition, since that might go too far if
26677 a specialization was declared, but not defined. */
26679 /* Fetch the more general template. */
26680 tmpl = DECL_TI_TEMPLATE (tmpl);
26683 return tmpl;
26686 /* Returns true if we need to instantiate this template instance even if we
26687 know we aren't going to emit it. */
26689 bool
26690 always_instantiate_p (tree decl)
26692 /* We always instantiate inline functions so that we can inline them. An
26693 explicit instantiation declaration prohibits implicit instantiation of
26694 non-inline functions. With high levels of optimization, we would
26695 normally inline non-inline functions -- but we're not allowed to do
26696 that for "extern template" functions. Therefore, we check
26697 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26698 return ((TREE_CODE (decl) == FUNCTION_DECL
26699 && (DECL_DECLARED_INLINE_P (decl)
26700 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26701 /* And we need to instantiate static data members so that
26702 their initializers are available in integral constant
26703 expressions. */
26704 || (VAR_P (decl)
26705 && decl_maybe_constant_var_p (decl)));
26708 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26709 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26710 error, true otherwise. */
26712 bool
26713 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26715 if (fn == error_mark_node)
26716 return false;
26718 /* Don't instantiate a noexcept-specification from template context. */
26719 if (processing_template_decl
26720 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26721 return true;
26723 tree fntype = TREE_TYPE (fn);
26724 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26726 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26727 && DECL_MAYBE_DELETED (fn))
26729 if (fn == current_function_decl)
26730 /* We're in start_preparsed_function, keep going. */
26731 return true;
26733 ++function_depth;
26734 maybe_synthesize_method (fn);
26735 --function_depth;
26736 return !DECL_DELETED_FN (fn);
26739 if (!spec || !TREE_PURPOSE (spec))
26740 return true;
26742 tree noex = TREE_PURPOSE (spec);
26743 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26744 && TREE_CODE (noex) != DEFERRED_PARSE)
26745 return true;
26747 tree orig_fn = NULL_TREE;
26748 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26749 its FUNCTION_DECL for the rest of this function -- push_access_scope
26750 doesn't accept TEMPLATE_DECLs. */
26751 if (DECL_FUNCTION_TEMPLATE_P (fn))
26753 orig_fn = fn;
26754 fn = DECL_TEMPLATE_RESULT (fn);
26757 if (DECL_CLONED_FUNCTION_P (fn))
26759 tree prime = DECL_CLONED_FUNCTION (fn);
26760 if (!maybe_instantiate_noexcept (prime, complain))
26761 return false;
26762 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26764 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26766 static hash_set<tree>* fns = new hash_set<tree>;
26767 bool added = false;
26768 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26770 spec = get_defaulted_eh_spec (fn, complain);
26771 if (spec == error_mark_node)
26772 /* This might have failed because of an unparsed DMI, so
26773 let's try again later. */
26774 return false;
26776 else if (!(added = !fns->add (fn)))
26778 /* If hash_set::add returns true, the element was already there. */
26779 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26780 DECL_SOURCE_LOCATION (fn));
26781 error_at (loc,
26782 "exception specification of %qD depends on itself",
26783 fn);
26784 spec = noexcept_false_spec;
26786 else if (push_tinst_level (fn))
26788 push_to_top_level ();
26789 push_access_scope (fn);
26790 push_deferring_access_checks (dk_no_deferred);
26791 input_location = DECL_SOURCE_LOCATION (fn);
26793 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26794 && !DECL_LOCAL_DECL_P (fn))
26796 /* If needed, set current_class_ptr for the benefit of
26797 tsubst_copy/PARM_DECL. */
26798 tree this_parm = DECL_ARGUMENTS (fn);
26799 current_class_ptr = NULL_TREE;
26800 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26801 current_class_ptr = this_parm;
26804 /* If this function is represented by a TEMPLATE_DECL, then
26805 the deferred noexcept-specification might still contain
26806 dependent types, even after substitution. And we need the
26807 dependency check functions to work in build_noexcept_spec. */
26808 if (orig_fn)
26809 ++processing_template_decl;
26811 /* Do deferred instantiation of the noexcept-specifier. */
26812 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26813 DEFERRED_NOEXCEPT_ARGS (noex),
26814 tf_warning_or_error, fn);
26816 /* Build up the noexcept-specification. */
26817 spec = build_noexcept_spec (noex, tf_warning_or_error);
26819 if (orig_fn)
26820 --processing_template_decl;
26822 pop_deferring_access_checks ();
26823 pop_access_scope (fn);
26824 pop_tinst_level ();
26825 pop_from_top_level ();
26827 else
26828 spec = noexcept_false_spec;
26830 if (added)
26831 fns->remove (fn);
26834 if (spec == error_mark_node)
26836 /* This failed with a hard error, so let's go with false. */
26837 gcc_assert (seen_error ());
26838 spec = noexcept_false_spec;
26841 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26842 if (orig_fn)
26843 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26845 return true;
26848 /* We're starting to process the function INST, an instantiation of PATTERN;
26849 add their parameters to local_specializations. */
26851 void
26852 register_parameter_specializations (tree pattern, tree inst)
26854 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26855 tree spec_parm = DECL_ARGUMENTS (inst);
26856 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26858 register_local_specialization (spec_parm, tmpl_parm);
26859 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26860 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26862 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26864 if (!DECL_PACK_P (tmpl_parm))
26866 register_local_specialization (spec_parm, tmpl_parm);
26867 spec_parm = DECL_CHAIN (spec_parm);
26869 else
26871 /* Register the (value) argument pack as a specialization of
26872 TMPL_PARM, then move on. */
26873 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26874 register_local_specialization (argpack, tmpl_parm);
26877 gcc_assert (!spec_parm);
26880 /* Instantiate the body of D using PATTERN with ARGS. We have
26881 already determined PATTERN is the correct template to use.
26882 NESTED_P is true if this is a nested function, in which case
26883 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26885 static void
26886 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26888 tree td = NULL_TREE;
26889 tree code_pattern = pattern;
26891 if (!nested_p)
26893 td = pattern;
26894 code_pattern = DECL_TEMPLATE_RESULT (td);
26896 else
26897 /* Only OMP reductions are nested. */
26898 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26900 vec<tree> omp_privatization_save;
26901 if (current_function_decl)
26902 save_omp_privatization_clauses (omp_privatization_save);
26904 bool push_to_top = maybe_push_to_top_level (d);
26906 mark_template_arguments_used (pattern, args);
26908 if (VAR_P (d))
26910 /* The variable might be a lambda's extra scope, and that
26911 lambda's visibility depends on D's. */
26912 maybe_commonize_var (d);
26913 determine_visibility (d);
26916 /* Mark D as instantiated so that recursive calls to
26917 instantiate_decl do not try to instantiate it again. */
26918 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26920 if (td)
26921 /* Regenerate the declaration in case the template has been modified
26922 by a subsequent redeclaration. */
26923 regenerate_decl_from_template (d, td, args);
26925 /* We already set the file and line above. Reset them now in case
26926 they changed as a result of calling regenerate_decl_from_template. */
26927 input_location = DECL_SOURCE_LOCATION (d);
26929 if (VAR_P (d))
26931 /* Clear out DECL_RTL; whatever was there before may not be right
26932 since we've reset the type of the declaration. */
26933 SET_DECL_RTL (d, NULL);
26934 DECL_IN_AGGR_P (d) = 0;
26936 /* The initializer is placed in DECL_INITIAL by
26937 regenerate_decl_from_template so we don't need to
26938 push/pop_access_scope again here. Pull it out so that
26939 cp_finish_decl can process it. */
26940 bool const_init = false;
26941 tree init = DECL_INITIAL (d);
26942 DECL_INITIAL (d) = NULL_TREE;
26943 DECL_INITIALIZED_P (d) = 0;
26945 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26946 initializer. That function will defer actual emission until
26947 we have a chance to determine linkage. */
26948 DECL_EXTERNAL (d) = 0;
26950 /* Enter the scope of D so that access-checking works correctly. */
26951 bool enter_context = DECL_CLASS_SCOPE_P (d);
26952 if (enter_context)
26953 push_nested_class (DECL_CONTEXT (d));
26955 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26956 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26958 if (enter_context)
26959 pop_nested_class ();
26961 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26962 synthesize_method (d);
26963 else if (TREE_CODE (d) == FUNCTION_DECL)
26965 /* Set up the list of local specializations. */
26966 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26967 tree block = NULL_TREE;
26969 /* Set up context. */
26970 if (nested_p)
26971 block = push_stmt_list ();
26972 else
26974 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26976 perform_instantiation_time_access_checks (code_pattern, args);
26979 /* Create substitution entries for the parameters. */
26980 register_parameter_specializations (code_pattern, d);
26982 /* Substitute into the body of the function. */
26983 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26984 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26985 tf_warning_or_error, d);
26986 else
26988 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26989 tf_warning_or_error, DECL_TI_TEMPLATE (d));
26991 /* Set the current input_location to the end of the function
26992 so that finish_function knows where we are. */
26993 input_location
26994 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26996 /* Remember if we saw an infinite loop in the template. */
26997 current_function_infinite_loop
26998 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
27001 /* Finish the function. */
27002 if (nested_p)
27003 DECL_SAVED_TREE (d) = pop_stmt_list (block);
27004 else
27006 d = finish_function (/*inline_p=*/false);
27007 expand_or_defer_fn (d);
27010 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
27011 cp_check_omp_declare_reduction (d);
27014 /* We're not deferring instantiation any more. */
27015 if (!nested_p)
27016 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
27018 maybe_pop_from_top_level (push_to_top);
27020 if (current_function_decl)
27021 restore_omp_privatization_clauses (omp_privatization_save);
27024 /* Produce the definition of D, a _DECL generated from a template. If
27025 DEFER_OK is true, then we don't have to actually do the
27026 instantiation now; we just have to do it sometime. Normally it is
27027 an error if this is an explicit instantiation but D is undefined.
27028 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
27029 instantiated class template. */
27031 tree
27032 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
27034 tree tmpl = DECL_TI_TEMPLATE (d);
27035 tree gen_args;
27036 tree args;
27037 tree td;
27038 tree code_pattern;
27039 tree spec;
27040 tree gen_tmpl;
27041 bool pattern_defined;
27042 location_t saved_loc = input_location;
27043 int saved_unevaluated_operand = cp_unevaluated_operand;
27044 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
27045 bool external_p;
27046 bool deleted_p;
27048 /* This function should only be used to instantiate templates for
27049 functions and static member variables. */
27050 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
27052 /* A concept is never instantiated. */
27053 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
27055 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
27057 if (modules_p ())
27058 /* We may have a pending instantiation of D itself. */
27059 lazy_load_pendings (d);
27061 /* Variables are never deferred; if instantiation is required, they
27062 are instantiated right away. That allows for better code in the
27063 case that an expression refers to the value of the variable --
27064 if the variable has a constant value the referring expression can
27065 take advantage of that fact. */
27066 if (VAR_P (d))
27067 defer_ok = false;
27069 /* Don't instantiate cloned functions. Instead, instantiate the
27070 functions they cloned. */
27071 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
27072 d = DECL_CLONED_FUNCTION (d);
27074 if (DECL_TEMPLATE_INSTANTIATED (d)
27075 || TREE_TYPE (d) == error_mark_node
27076 || (TREE_CODE (d) == FUNCTION_DECL
27077 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
27078 || DECL_TEMPLATE_SPECIALIZATION (d))
27079 /* D has already been instantiated or explicitly specialized, so
27080 there's nothing for us to do here.
27082 It might seem reasonable to check whether or not D is an explicit
27083 instantiation, and, if so, stop here. But when an explicit
27084 instantiation is deferred until the end of the compilation,
27085 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
27086 the instantiation. */
27087 return d;
27089 /* Check to see whether we know that this template will be
27090 instantiated in some other file, as with "extern template"
27091 extension. */
27092 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
27094 /* In general, we do not instantiate such templates. */
27095 if (external_p && !always_instantiate_p (d))
27096 return d;
27098 gen_tmpl = most_general_template (tmpl);
27099 gen_args = DECL_TI_ARGS (d);
27101 /* We should already have the extra args. */
27102 gcc_checking_assert (tmpl == gen_tmpl
27103 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27104 == TMPL_ARGS_DEPTH (gen_args)));
27105 /* And what's in the hash table should match D. */
27106 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27107 == d
27108 || spec == NULL_TREE);
27110 /* This needs to happen before any tsubsting. */
27111 if (! push_tinst_level (d))
27112 return d;
27114 auto_timevar tv (TV_TEMPLATE_INST);
27116 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27117 for the instantiation. */
27118 td = template_for_substitution (d);
27119 args = gen_args;
27121 if (variable_template_specialization_p (d))
27123 /* Look up an explicit specialization, if any. */
27124 tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
27125 if (partial_ti && partial_ti != error_mark_node)
27127 td = TI_TEMPLATE (partial_ti);
27128 args = TI_ARGS (partial_ti);
27132 code_pattern = DECL_TEMPLATE_RESULT (td);
27134 /* We should never be trying to instantiate a member of a class
27135 template or partial specialization. */
27136 gcc_assert (d != code_pattern);
27138 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27139 || DECL_TEMPLATE_SPECIALIZATION (td))
27140 /* In the case of a friend template whose definition is provided
27141 outside the class, we may have too many arguments. Drop the
27142 ones we don't need. The same is true for specializations. */
27143 args = get_innermost_template_args
27144 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27146 if (TREE_CODE (d) == FUNCTION_DECL)
27148 deleted_p = DECL_DELETED_FN (code_pattern);
27149 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27150 && DECL_INITIAL (code_pattern) != error_mark_node)
27151 || DECL_DEFAULTED_FN (code_pattern)
27152 || deleted_p);
27154 else
27156 deleted_p = false;
27157 if (DECL_CLASS_SCOPE_P (code_pattern))
27158 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27159 else
27160 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27163 /* We may be in the middle of deferred access check. Disable it now. */
27164 push_deferring_access_checks (dk_no_deferred);
27166 /* Unless an explicit instantiation directive has already determined
27167 the linkage of D, remember that a definition is available for
27168 this entity. */
27169 if (pattern_defined
27170 && !DECL_INTERFACE_KNOWN (d)
27171 && !DECL_NOT_REALLY_EXTERN (d))
27172 mark_definable (d);
27174 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27175 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27176 input_location = DECL_SOURCE_LOCATION (d);
27178 /* If D is a member of an explicitly instantiated class template,
27179 and no definition is available, treat it like an implicit
27180 instantiation. */
27181 if (!pattern_defined && expl_inst_class_mem_p
27182 && DECL_EXPLICIT_INSTANTIATION (d))
27184 /* Leave linkage flags alone on instantiations with anonymous
27185 visibility. */
27186 if (TREE_PUBLIC (d))
27188 DECL_NOT_REALLY_EXTERN (d) = 0;
27189 DECL_INTERFACE_KNOWN (d) = 0;
27191 SET_DECL_IMPLICIT_INSTANTIATION (d);
27194 /* Defer all other templates, unless we have been explicitly
27195 forbidden from doing so. */
27196 if (/* If there is no definition, we cannot instantiate the
27197 template. */
27198 ! pattern_defined
27199 /* If it's OK to postpone instantiation, do so. */
27200 || defer_ok
27201 /* If this is a static data member that will be defined
27202 elsewhere, we don't want to instantiate the entire data
27203 member, but we do want to instantiate the initializer so that
27204 we can substitute that elsewhere. */
27205 || (external_p && VAR_P (d))
27206 /* Handle here a deleted function too, avoid generating
27207 its body (c++/61080). */
27208 || deleted_p)
27210 /* The definition of the static data member is now required so
27211 we must substitute the initializer. */
27212 if (VAR_P (d)
27213 && !DECL_INITIAL (d)
27214 && DECL_INITIAL (code_pattern))
27216 tree ns;
27217 tree init;
27218 bool const_init = false;
27219 bool enter_context = DECL_CLASS_SCOPE_P (d);
27221 ns = decl_namespace_context (d);
27222 push_nested_namespace (ns);
27223 if (enter_context)
27224 push_nested_class (DECL_CONTEXT (d));
27225 init = tsubst_expr (DECL_INITIAL (code_pattern),
27226 args,
27227 tf_warning_or_error, NULL_TREE);
27228 /* If instantiating the initializer involved instantiating this
27229 again, don't call cp_finish_decl twice. */
27230 if (!DECL_INITIAL (d))
27232 /* Make sure the initializer is still constant, in case of
27233 circular dependency (template/instantiate6.C). */
27234 const_init
27235 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27236 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27237 /*asmspec_tree=*/NULL_TREE, 0);
27239 if (enter_context)
27240 pop_nested_class ();
27241 pop_nested_namespace (ns);
27244 /* We restore the source position here because it's used by
27245 add_pending_template. */
27246 input_location = saved_loc;
27248 if (at_eof && !pattern_defined
27249 && DECL_EXPLICIT_INSTANTIATION (d)
27250 && DECL_NOT_REALLY_EXTERN (d))
27251 /* [temp.explicit]
27253 The definition of a non-exported function template, a
27254 non-exported member function template, or a non-exported
27255 member function or static data member of a class template
27256 shall be present in every translation unit in which it is
27257 explicitly instantiated. */
27258 permerror (input_location, "explicit instantiation of %qD "
27259 "but no definition available", d);
27261 /* If we're in unevaluated context, we just wanted to get the
27262 constant value; this isn't an odr use, so don't queue
27263 a full instantiation. */
27264 if (!cp_unevaluated_operand
27265 /* ??? Historically, we have instantiated inline functions, even
27266 when marked as "extern template". */
27267 && !(external_p && VAR_P (d)))
27268 add_pending_template (d);
27270 else
27272 set_instantiating_module (d);
27273 if (variable_template_p (gen_tmpl))
27274 note_variable_template_instantiation (d);
27275 instantiate_body (td, args, d, false);
27278 pop_deferring_access_checks ();
27279 pop_tinst_level ();
27280 input_location = saved_loc;
27281 cp_unevaluated_operand = saved_unevaluated_operand;
27282 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
27284 return d;
27287 /* Run through the list of templates that we wish we could
27288 instantiate, and instantiate any we can. RETRIES is the
27289 number of times we retry pending template instantiation. */
27291 void
27292 instantiate_pending_templates (int retries)
27294 int reconsider;
27295 location_t saved_loc = input_location;
27297 /* Instantiating templates may trigger vtable generation. This in turn
27298 may require further template instantiations. We place a limit here
27299 to avoid infinite loop. */
27300 if (pending_templates && retries >= max_tinst_depth)
27302 tree decl = pending_templates->tinst->maybe_get_node ();
27304 fatal_error (input_location,
27305 "template instantiation depth exceeds maximum of %d"
27306 " instantiating %q+D, possibly from virtual table generation"
27307 " (use %<-ftemplate-depth=%> to increase the maximum)",
27308 max_tinst_depth, decl);
27309 if (TREE_CODE (decl) == FUNCTION_DECL)
27310 /* Pretend that we defined it. */
27311 DECL_INITIAL (decl) = error_mark_node;
27312 return;
27317 struct pending_template **t = &pending_templates;
27318 struct pending_template *last = NULL;
27319 reconsider = 0;
27320 while (*t)
27322 tree instantiation = reopen_tinst_level ((*t)->tinst);
27323 bool complete = false;
27325 if (TYPE_P (instantiation))
27327 if (!COMPLETE_TYPE_P (instantiation))
27329 instantiate_class_template (instantiation);
27330 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27331 for (tree fld = TYPE_FIELDS (instantiation);
27332 fld; fld = TREE_CHAIN (fld))
27333 if ((VAR_P (fld)
27334 || (TREE_CODE (fld) == FUNCTION_DECL
27335 && !DECL_ARTIFICIAL (fld)))
27336 && DECL_TEMPLATE_INSTANTIATION (fld))
27337 instantiate_decl (fld,
27338 /*defer_ok=*/false,
27339 /*expl_inst_class_mem_p=*/false);
27341 if (COMPLETE_TYPE_P (instantiation))
27342 reconsider = 1;
27345 complete = COMPLETE_TYPE_P (instantiation);
27347 else
27349 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27350 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27352 instantiation
27353 = instantiate_decl (instantiation,
27354 /*defer_ok=*/false,
27355 /*expl_inst_class_mem_p=*/false);
27356 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27357 reconsider = 1;
27360 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27361 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27364 if (complete)
27366 /* If INSTANTIATION has been instantiated, then we don't
27367 need to consider it again in the future. */
27368 struct pending_template *drop = *t;
27369 *t = (*t)->next;
27370 set_refcount_ptr (drop->tinst);
27371 pending_template_freelist ().free (drop);
27373 else
27375 last = *t;
27376 t = &(*t)->next;
27378 tinst_depth = 0;
27379 set_refcount_ptr (current_tinst_level);
27381 last_pending_template = last;
27383 while (reconsider);
27385 input_location = saved_loc;
27388 /* Substitute ARGVEC into T, which is a list of initializers for
27389 either base class or a non-static data member. The TREE_PURPOSEs
27390 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27391 instantiate_decl. */
27393 static tree
27394 tsubst_initializer_list (tree t, tree argvec)
27396 tree inits = NULL_TREE;
27397 tree target_ctor = error_mark_node;
27399 for (; t; t = TREE_CHAIN (t))
27401 tree decl;
27402 tree init;
27403 tree expanded_bases = NULL_TREE;
27404 tree expanded_arguments = NULL_TREE;
27405 int i, len = 1;
27407 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27409 tree expr;
27410 tree arg;
27412 /* Expand the base class expansion type into separate base
27413 classes. */
27414 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27415 tf_warning_or_error,
27416 NULL_TREE);
27417 if (expanded_bases == error_mark_node)
27418 continue;
27420 /* We'll be building separate TREE_LISTs of arguments for
27421 each base. */
27422 len = TREE_VEC_LENGTH (expanded_bases);
27423 expanded_arguments = make_tree_vec (len);
27424 for (i = 0; i < len; i++)
27425 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27427 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27428 expand each argument in the TREE_VALUE of t. */
27429 expr = make_node (EXPR_PACK_EXPANSION);
27430 PACK_EXPANSION_LOCAL_P (expr) = true;
27431 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27432 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27434 if (TREE_VALUE (t) == void_type_node)
27435 /* VOID_TYPE_NODE is used to indicate
27436 value-initialization. */
27438 for (i = 0; i < len; i++)
27439 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27441 else
27443 /* Substitute parameter packs into each argument in the
27444 TREE_LIST. */
27445 in_base_initializer = 1;
27446 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27448 tree expanded_exprs;
27450 /* Expand the argument. */
27451 tree value;
27452 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27453 value = TREE_VALUE (arg);
27454 else
27456 value = expr;
27457 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27459 expanded_exprs
27460 = tsubst_pack_expansion (value, argvec,
27461 tf_warning_or_error,
27462 NULL_TREE);
27463 if (expanded_exprs == error_mark_node)
27464 continue;
27466 /* Prepend each of the expanded expressions to the
27467 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27468 for (i = 0; i < len; i++)
27469 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27470 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27471 TREE_VEC_ELT (expanded_arguments, i)
27472 = tree_cons (NULL_TREE,
27473 TREE_VEC_ELT (expanded_exprs, j),
27474 TREE_VEC_ELT (expanded_arguments, i));
27475 else
27476 TREE_VEC_ELT (expanded_arguments, i)
27477 = tree_cons (NULL_TREE,
27478 TREE_VEC_ELT (expanded_exprs, i),
27479 TREE_VEC_ELT (expanded_arguments, i));
27481 in_base_initializer = 0;
27483 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27484 since we built them backwards. */
27485 for (i = 0; i < len; i++)
27487 TREE_VEC_ELT (expanded_arguments, i) =
27488 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27493 for (i = 0; i < len; ++i)
27495 if (expanded_bases)
27497 decl = TREE_VEC_ELT (expanded_bases, i);
27498 decl = expand_member_init (decl);
27499 init = TREE_VEC_ELT (expanded_arguments, i);
27501 else
27503 tree tmp;
27504 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27505 tf_warning_or_error, NULL_TREE);
27507 decl = expand_member_init (decl);
27508 if (decl && !DECL_P (decl))
27509 in_base_initializer = 1;
27511 init = TREE_VALUE (t);
27512 tmp = init;
27513 if (init != void_type_node)
27514 init = tsubst_expr (init, argvec,
27515 tf_warning_or_error, NULL_TREE);
27516 if (init == NULL_TREE && tmp != NULL_TREE)
27517 /* If we had an initializer but it instantiated to nothing,
27518 value-initialize the object. This will only occur when
27519 the initializer was a pack expansion where the parameter
27520 packs used in that expansion were of length zero. */
27521 init = void_type_node;
27522 in_base_initializer = 0;
27525 if (target_ctor != error_mark_node
27526 && init != error_mark_node)
27528 error ("mem-initializer for %qD follows constructor delegation",
27529 decl);
27530 return inits;
27532 /* Look for a target constructor. */
27533 if (init != error_mark_node
27534 && decl && CLASS_TYPE_P (decl)
27535 && same_type_p (decl, current_class_type))
27537 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27538 if (inits)
27540 error ("constructor delegation follows mem-initializer for %qD",
27541 TREE_PURPOSE (inits));
27542 continue;
27544 target_ctor = init;
27547 if (decl)
27549 init = build_tree_list (decl, init);
27550 /* Carry over the dummy TREE_TYPE node containing the source
27551 location. */
27552 TREE_TYPE (init) = TREE_TYPE (t);
27553 TREE_CHAIN (init) = inits;
27554 inits = init;
27558 return inits;
27561 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27562 is the instantiation (which should have been created with
27563 start_enum) and ARGS are the template arguments to use. */
27565 static void
27566 tsubst_enum (tree tag, tree newtag, tree args)
27568 tree e;
27570 if (SCOPED_ENUM_P (newtag))
27571 begin_scope (sk_scoped_enum, newtag);
27573 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27575 tree value;
27576 tree decl = TREE_VALUE (e);
27578 /* Note that in a template enum, the TREE_VALUE is the
27579 CONST_DECL, not the corresponding INTEGER_CST. */
27580 value = tsubst_expr (DECL_INITIAL (decl),
27581 args, tf_warning_or_error, NULL_TREE);
27583 /* Give this enumeration constant the correct access. */
27584 set_current_access_from_decl (decl);
27586 /* Actually build the enumerator itself. Here we're assuming that
27587 enumerators can't have dependent attributes. */
27588 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27589 DECL_ATTRIBUTES (decl),
27590 DECL_SOURCE_LOCATION (decl));
27591 /* Attribute deprecated without an argument isn't sticky: it'll
27592 melt into a tree flag, so we need to propagate the flag here,
27593 since we just created a new enumerator. */
27594 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27595 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27598 if (SCOPED_ENUM_P (newtag))
27599 finish_scope ();
27601 finish_enum_value_list (newtag);
27602 finish_enum (newtag);
27604 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27605 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27606 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27607 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27610 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27611 its type -- but without substituting the innermost set of template
27612 arguments. So, innermost set of template parameters will appear in
27613 the type. */
27615 tree
27616 get_mostly_instantiated_function_type (tree decl)
27618 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27619 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27622 /* Return truthvalue if we're processing a template different from
27623 the last one involved in diagnostics. */
27624 bool
27625 problematic_instantiation_changed (void)
27627 return current_tinst_level != last_error_tinst_level;
27630 /* Remember current template involved in diagnostics. */
27631 void
27632 record_last_problematic_instantiation (void)
27634 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27637 struct tinst_level *
27638 current_instantiation (void)
27640 return current_tinst_level;
27643 /* Return TRUE if current_function_decl is being instantiated, false
27644 otherwise. */
27646 bool
27647 instantiating_current_function_p (void)
27649 return (current_instantiation ()
27650 && (current_instantiation ()->maybe_get_node ()
27651 == current_function_decl));
27654 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27655 type. Return false for ok, true for disallowed. Issue error and
27656 inform messages under control of COMPLAIN. */
27658 static bool
27659 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27661 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27662 return false;
27663 else if (TYPE_PTR_P (type))
27664 return false;
27665 else if (TYPE_REF_P (type)
27666 && !TYPE_REF_IS_RVALUE (type))
27667 return false;
27668 else if (TYPE_PTRMEM_P (type))
27669 return false;
27670 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27672 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27674 if (complain & tf_error)
27675 error ("non-type template parameters of deduced class type only "
27676 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27677 return true;
27679 return false;
27681 else if (TREE_CODE (type) == NULLPTR_TYPE)
27682 return false;
27683 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27684 && cxx_dialect < cxx11)
27685 /* Fall through; before C++11 alias templates, a bound ttp
27686 always instantiates into a class type. */;
27687 else if (WILDCARD_TYPE_P (type))
27688 /* Any other wildcard type not already handled above is allowed. */
27689 return false;
27690 else if (TREE_CODE (type) == COMPLEX_TYPE)
27691 /* Fall through. */;
27692 else if (VOID_TYPE_P (type))
27693 /* Fall through. */;
27694 else if (cxx_dialect >= cxx20)
27696 if (dependent_type_p (type))
27697 return false;
27698 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27699 return true;
27700 if (structural_type_p (type))
27701 return false;
27702 if (complain & tf_error)
27704 auto_diagnostic_group d;
27705 error ("%qT is not a valid type for a template non-type "
27706 "parameter because it is not structural", type);
27707 structural_type_p (type, true);
27709 return true;
27711 else if (CLASS_TYPE_P (type))
27713 if (complain & tf_error)
27714 error ("non-type template parameters of class type only available "
27715 "with %<-std=c++20%> or %<-std=gnu++20%>");
27716 return true;
27719 if (complain & tf_error)
27721 if (type == error_mark_node)
27722 inform (input_location, "invalid template non-type parameter");
27723 else
27724 error ("%q#T is not a valid type for a template non-type parameter",
27725 type);
27727 return true;
27730 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27732 static bool
27733 value_dependent_noexcept_spec_p (tree type)
27735 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27736 if (tree noex = TREE_PURPOSE (spec))
27737 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27738 affect overload resolution and treating it as dependent breaks
27739 things. Same for an unparsed noexcept expression. */
27740 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27741 && TREE_CODE (noex) != DEFERRED_PARSE
27742 && value_dependent_expression_p (noex))
27743 return true;
27745 return false;
27748 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27749 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27751 static bool
27752 dependent_type_p_r (tree type)
27754 tree scope;
27756 /* [temp.dep.type]
27758 A type is dependent if it is:
27760 -- a template parameter. Template template parameters are types
27761 for us (since TYPE_P holds true for them) so we handle
27762 them here. */
27763 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27764 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27765 return true;
27766 /* -- a qualified-id with a nested-name-specifier which contains a
27767 class-name that names a dependent type or whose unqualified-id
27768 names a dependent type. */
27769 if (TREE_CODE (type) == TYPENAME_TYPE)
27770 return true;
27772 /* An alias template specialization can be dependent even if the
27773 resulting type is not. */
27774 if (dependent_alias_template_spec_p (type, nt_transparent))
27775 return true;
27777 /* -- a cv-qualified type where the cv-unqualified type is
27778 dependent.
27779 No code is necessary for this bullet; the code below handles
27780 cv-qualified types, and we don't want to strip aliases with
27781 TYPE_MAIN_VARIANT because of DR 1558. */
27782 /* -- a compound type constructed from any dependent type. */
27783 if (TYPE_PTRMEM_P (type))
27784 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27785 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27786 (type)));
27787 else if (INDIRECT_TYPE_P (type))
27788 return dependent_type_p (TREE_TYPE (type));
27789 else if (FUNC_OR_METHOD_TYPE_P (type))
27791 tree arg_type;
27793 if (dependent_type_p (TREE_TYPE (type)))
27794 return true;
27795 for (arg_type = TYPE_ARG_TYPES (type);
27796 arg_type;
27797 arg_type = TREE_CHAIN (arg_type))
27798 if (dependent_type_p (TREE_VALUE (arg_type)))
27799 return true;
27800 if (cxx_dialect >= cxx17
27801 && value_dependent_noexcept_spec_p (type))
27802 /* A value-dependent noexcept-specifier makes the type dependent. */
27803 return true;
27804 return false;
27806 /* -- an array type constructed from any dependent type or whose
27807 size is specified by a constant expression that is
27808 value-dependent.
27810 We checked for type- and value-dependence of the bounds in
27811 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27812 if (TREE_CODE (type) == ARRAY_TYPE)
27814 if (TYPE_DOMAIN (type)
27815 && dependent_type_p (TYPE_DOMAIN (type)))
27816 return true;
27817 return dependent_type_p (TREE_TYPE (type));
27820 /* -- a template-id in which either the template name is a template
27821 parameter ... */
27822 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27823 return true;
27824 /* ... or any of the template arguments is a dependent type or
27825 an expression that is type-dependent or value-dependent. */
27826 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27827 && (any_dependent_template_arguments_p
27828 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27829 return true;
27831 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27832 dependent; if the argument of the `typeof' expression is not
27833 type-dependent, then it should already been have resolved. */
27834 if (TREE_CODE (type) == TYPEOF_TYPE
27835 || TREE_CODE (type) == DECLTYPE_TYPE
27836 || TREE_CODE (type) == TRAIT_TYPE)
27837 return true;
27839 /* A template argument pack is dependent if any of its packed
27840 arguments are. */
27841 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27843 tree args = ARGUMENT_PACK_ARGS (type);
27844 for (tree arg : tree_vec_range (args))
27845 if (dependent_template_arg_p (arg))
27846 return true;
27849 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27850 be template parameters. */
27851 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27852 return true;
27854 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27855 return true;
27857 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27858 return true;
27860 /* The standard does not specifically mention types that are local
27861 to template functions or local classes, but they should be
27862 considered dependent too. For example:
27864 template <int I> void f() {
27865 enum E { a = I };
27866 S<sizeof (E)> s;
27869 The size of `E' cannot be known until the value of `I' has been
27870 determined. Therefore, `E' must be considered dependent. */
27871 scope = TYPE_CONTEXT (type);
27872 if (scope && TYPE_P (scope))
27873 return dependent_type_p (scope);
27874 /* Don't use type_dependent_expression_p here, as it can lead
27875 to infinite recursion trying to determine whether a lambda
27876 nested in a lambda is dependent (c++/47687). */
27877 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27878 && DECL_LANG_SPECIFIC (scope)
27879 && DECL_TEMPLATE_INFO (scope)
27880 && (any_dependent_template_arguments_p
27881 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27882 return true;
27884 /* Other types are non-dependent. */
27885 return false;
27888 /* Returns TRUE if TYPE is dependent, in the sense of
27889 [temp.dep.type]. Note that a NULL type is considered dependent. */
27891 bool
27892 dependent_type_p (tree type)
27894 /* If there are no template parameters in scope, then there can't be
27895 any dependent types. */
27896 if (!processing_template_decl)
27898 /* If we are not processing a template, then nobody should be
27899 providing us with a dependent type. */
27900 gcc_assert (type);
27901 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27902 return false;
27905 /* If the type is NULL, we have not computed a type for the entity
27906 in question; in that case, the type is dependent. */
27907 if (!type)
27908 return true;
27910 /* Erroneous types can be considered non-dependent. */
27911 if (type == error_mark_node)
27912 return false;
27914 /* If we have not already computed the appropriate value for TYPE,
27915 do so now. */
27916 if (!TYPE_DEPENDENT_P_VALID (type))
27918 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27919 TYPE_DEPENDENT_P_VALID (type) = 1;
27922 return TYPE_DEPENDENT_P (type);
27925 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27926 lookup. In other words, a dependent type that is not the current
27927 instantiation. */
27929 bool
27930 dependent_scope_p (tree scope)
27932 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27933 && !currently_open_class (scope));
27936 /* True if we might find more declarations in SCOPE during instantiation than
27937 we can when parsing the template. */
27939 bool
27940 dependentish_scope_p (tree scope)
27942 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27945 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27946 an unknown base of 'this' (and is therefore instantiation-dependent). */
27948 static bool
27949 unknown_base_ref_p (tree t)
27951 if (!current_class_ptr)
27952 return false;
27954 tree mem = TREE_OPERAND (t, 1);
27955 if (shared_member_p (mem))
27956 return false;
27958 tree cur = current_nonlambda_class_type ();
27959 if (!any_dependent_bases_p (cur))
27960 return false;
27962 tree ctx = TREE_OPERAND (t, 0);
27963 if (DERIVED_FROM_P (ctx, cur))
27964 return false;
27966 return true;
27969 /* T is a SCOPE_REF; return whether we need to consider it
27970 instantiation-dependent so that we can check access at instantiation
27971 time even though we know which member it resolves to. */
27973 static bool
27974 instantiation_dependent_scope_ref_p (tree t)
27976 if (DECL_P (TREE_OPERAND (t, 1))
27977 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27978 && !dependent_scope_p (TREE_OPERAND (t, 0))
27979 && !unknown_base_ref_p (t)
27980 && accessible_in_template_p (TREE_OPERAND (t, 0),
27981 TREE_OPERAND (t, 1)))
27982 return false;
27983 else
27984 return true;
27987 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27988 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27989 expression. */
27991 /* Note that this predicate is not appropriate for general expressions;
27992 only constant expressions (that satisfy potential_constant_expression)
27993 can be tested for value dependence. */
27995 bool
27996 value_dependent_expression_p (tree expression)
27998 if (!processing_template_decl || expression == NULL_TREE)
27999 return false;
28001 /* A type-dependent expression is also value-dependent. */
28002 if (type_dependent_expression_p (expression))
28003 return true;
28005 switch (TREE_CODE (expression))
28007 case BASELINK:
28008 /* A dependent member function of the current instantiation. */
28009 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
28011 case FUNCTION_DECL:
28012 /* A dependent member function of the current instantiation. */
28013 if (DECL_CLASS_SCOPE_P (expression)
28014 && dependent_type_p (DECL_CONTEXT (expression)))
28015 return true;
28016 break;
28018 case IDENTIFIER_NODE:
28019 /* A name that has not been looked up -- must be dependent. */
28020 return true;
28022 case TEMPLATE_PARM_INDEX:
28023 /* A non-type template parm. */
28024 return true;
28026 case CONST_DECL:
28027 /* A non-type template parm. */
28028 if (DECL_TEMPLATE_PARM_P (expression))
28029 return true;
28030 return value_dependent_expression_p (DECL_INITIAL (expression));
28032 case VAR_DECL:
28033 /* A constant with literal type and is initialized
28034 with an expression that is value-dependent. */
28035 if (DECL_DEPENDENT_INIT_P (expression))
28036 return true;
28037 if (DECL_HAS_VALUE_EXPR_P (expression))
28039 tree value_expr = DECL_VALUE_EXPR (expression);
28040 if (value_dependent_expression_p (value_expr)
28041 /* __PRETTY_FUNCTION__ inside a template function is dependent
28042 on the name of the function. */
28043 || (DECL_PRETTY_FUNCTION_P (expression)
28044 /* It might be used in a template, but not a template
28045 function, in which case its DECL_VALUE_EXPR will be
28046 "top level". */
28047 && value_expr == error_mark_node))
28048 return true;
28050 else if (TYPE_REF_P (TREE_TYPE (expression)))
28051 /* FIXME cp_finish_decl doesn't fold reference initializers. */
28052 return true;
28053 /* We have a constexpr variable and we're processing a template. When
28054 there's lifetime extension involved (for which finish_compound_literal
28055 used to create a temporary), we'll not be able to evaluate the
28056 variable until instantiating, so pretend it's value-dependent. */
28057 else if (DECL_DECLARED_CONSTEXPR_P (expression)
28058 && !TREE_CONSTANT (expression))
28059 return true;
28060 return false;
28062 case DYNAMIC_CAST_EXPR:
28063 case STATIC_CAST_EXPR:
28064 case CONST_CAST_EXPR:
28065 case REINTERPRET_CAST_EXPR:
28066 case CAST_EXPR:
28067 case IMPLICIT_CONV_EXPR:
28068 /* These expressions are value-dependent if the type to which
28069 the cast occurs is dependent or the expression being casted
28070 is value-dependent. */
28072 tree type = TREE_TYPE (expression);
28074 if (dependent_type_p (type))
28075 return true;
28077 /* A functional cast has a list of operands. */
28078 expression = TREE_OPERAND (expression, 0);
28079 if (!expression)
28081 /* If there are no operands, it must be an expression such
28082 as "int()". This should not happen for aggregate types
28083 because it would form non-constant expressions. */
28084 gcc_assert (cxx_dialect >= cxx11
28085 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
28087 return false;
28090 if (TREE_CODE (expression) == TREE_LIST)
28091 return any_value_dependent_elements_p (expression);
28093 if (TREE_CODE (type) == REFERENCE_TYPE
28094 && has_value_dependent_address (expression))
28095 return true;
28097 return value_dependent_expression_p (expression);
28100 case SIZEOF_EXPR:
28101 if (SIZEOF_EXPR_TYPE_P (expression))
28102 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
28103 /* FALLTHRU */
28104 case ALIGNOF_EXPR:
28105 case TYPEID_EXPR:
28106 /* A `sizeof' expression is value-dependent if the operand is
28107 type-dependent or is a pack expansion. */
28108 expression = TREE_OPERAND (expression, 0);
28109 if (PACK_EXPANSION_P (expression))
28110 return true;
28111 else if (TYPE_P (expression))
28112 return dependent_type_p (expression);
28113 return instantiation_dependent_uneval_expression_p (expression);
28115 case AT_ENCODE_EXPR:
28116 /* An 'encode' expression is value-dependent if the operand is
28117 type-dependent. */
28118 expression = TREE_OPERAND (expression, 0);
28119 return dependent_type_p (expression);
28121 case NOEXCEPT_EXPR:
28122 expression = TREE_OPERAND (expression, 0);
28123 return instantiation_dependent_uneval_expression_p (expression);
28125 case SCOPE_REF:
28126 /* All instantiation-dependent expressions should also be considered
28127 value-dependent. */
28128 return instantiation_dependent_scope_ref_p (expression);
28130 case COMPONENT_REF:
28131 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28132 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28134 case NONTYPE_ARGUMENT_PACK:
28135 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28136 is value-dependent. */
28137 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28138 if (value_dependent_expression_p (arg))
28139 return true;
28140 return false;
28142 case TRAIT_EXPR:
28144 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28145 return true;
28147 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28148 if (!type2)
28149 return false;
28151 if (TREE_CODE (type2) != TREE_VEC)
28152 return dependent_type_p (type2);
28154 for (tree arg : tree_vec_range (type2))
28155 if (dependent_type_p (arg))
28156 return true;
28158 return false;
28161 case MODOP_EXPR:
28162 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28163 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28165 case ARRAY_REF:
28166 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28167 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28169 case ADDR_EXPR:
28171 tree op = TREE_OPERAND (expression, 0);
28172 return (value_dependent_expression_p (op)
28173 || has_value_dependent_address (op));
28176 case REQUIRES_EXPR:
28177 /* Treat all requires-expressions as value-dependent so
28178 we don't try to fold them. */
28179 return true;
28181 case TYPE_REQ:
28182 return dependent_type_p (TREE_OPERAND (expression, 0));
28184 case CALL_EXPR:
28186 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28187 return true;
28188 tree fn = get_callee_fndecl (expression);
28189 int i, nargs;
28190 nargs = call_expr_nargs (expression);
28191 for (i = 0; i < nargs; ++i)
28193 tree op = CALL_EXPR_ARG (expression, i);
28194 /* In a call to a constexpr member function, look through the
28195 implicit ADDR_EXPR on the object argument so that it doesn't
28196 cause the call to be considered value-dependent. We also
28197 look through it in potential_constant_expression. */
28198 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28199 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
28200 && TREE_CODE (op) == ADDR_EXPR)
28201 op = TREE_OPERAND (op, 0);
28202 if (value_dependent_expression_p (op))
28203 return true;
28205 return false;
28208 case TEMPLATE_ID_EXPR:
28209 return concept_definition_p (TREE_OPERAND (expression, 0))
28210 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28212 case CONSTRUCTOR:
28214 unsigned ix;
28215 tree val;
28216 if (dependent_type_p (TREE_TYPE (expression)))
28217 return true;
28218 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28219 if (value_dependent_expression_p (val))
28220 return true;
28221 return false;
28224 case STMT_EXPR:
28225 /* Treat a GNU statement expression as dependent to avoid crashing
28226 under instantiate_non_dependent_expr; it can't be constant. */
28227 return true;
28229 case NEW_EXPR:
28230 case VEC_NEW_EXPR:
28231 /* The second operand is a type, which type_dependent_expression_p
28232 (and therefore value_dependent_expression_p) doesn't want to see. */
28233 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28234 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28235 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28237 default:
28238 /* A constant expression is value-dependent if any subexpression is
28239 value-dependent. */
28240 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28242 case tcc_reference:
28243 case tcc_unary:
28244 case tcc_comparison:
28245 case tcc_binary:
28246 case tcc_expression:
28247 case tcc_vl_exp:
28249 int i, len = cp_tree_operand_length (expression);
28251 for (i = 0; i < len; i++)
28253 tree t = TREE_OPERAND (expression, i);
28255 /* In some cases, some of the operands may be missing.
28256 (For example, in the case of PREDECREMENT_EXPR, the
28257 amount to increment by may be missing.) That doesn't
28258 make the expression dependent. */
28259 if (t && value_dependent_expression_p (t))
28260 return true;
28263 break;
28264 default:
28265 break;
28267 break;
28270 /* The expression is not value-dependent. */
28271 return false;
28274 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28275 [temp.dep.expr]. Note that an expression with no type is
28276 considered dependent. Other parts of the compiler arrange for an
28277 expression with type-dependent subexpressions to have no type, so
28278 this function doesn't have to be fully recursive. */
28280 bool
28281 type_dependent_expression_p (tree expression)
28283 if (!processing_template_decl)
28284 return false;
28286 if (expression == NULL_TREE || expression == error_mark_node)
28287 return false;
28289 gcc_checking_assert (!TYPE_P (expression));
28291 STRIP_ANY_LOCATION_WRAPPER (expression);
28293 /* An unresolved name is always dependent. */
28294 if (identifier_p (expression)
28295 || TREE_CODE (expression) == USING_DECL
28296 || TREE_CODE (expression) == WILDCARD_DECL)
28297 return true;
28299 /* A lambda-expression in template context is dependent. dependent_type_p is
28300 true for a lambda in the scope of a class or function template, but that
28301 doesn't cover all template contexts, like a default template argument. */
28302 if (TREE_CODE (expression) == LAMBDA_EXPR)
28303 return true;
28305 /* A fold expression is type-dependent. */
28306 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28307 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28308 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28309 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28310 return true;
28312 /* Some expression forms are never type-dependent. */
28313 if (TREE_CODE (expression) == SIZEOF_EXPR
28314 || TREE_CODE (expression) == ALIGNOF_EXPR
28315 || TREE_CODE (expression) == AT_ENCODE_EXPR
28316 || TREE_CODE (expression) == NOEXCEPT_EXPR
28317 || TREE_CODE (expression) == TRAIT_EXPR
28318 || TREE_CODE (expression) == TYPEID_EXPR
28319 || TREE_CODE (expression) == DELETE_EXPR
28320 || TREE_CODE (expression) == VEC_DELETE_EXPR
28321 || TREE_CODE (expression) == THROW_EXPR
28322 || TREE_CODE (expression) == REQUIRES_EXPR)
28323 return false;
28325 /* The types of these expressions depends only on the type to which
28326 the cast occurs. */
28327 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28328 || TREE_CODE (expression) == STATIC_CAST_EXPR
28329 || TREE_CODE (expression) == CONST_CAST_EXPR
28330 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28331 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28332 || TREE_CODE (expression) == CAST_EXPR)
28333 return dependent_type_p (TREE_TYPE (expression));
28335 /* The types of these expressions depends only on the type created
28336 by the expression. */
28337 if (TREE_CODE (expression) == NEW_EXPR
28338 || TREE_CODE (expression) == VEC_NEW_EXPR)
28340 /* For NEW_EXPR tree nodes created inside a template, either
28341 the object type itself or a TREE_LIST may appear as the
28342 operand 1. */
28343 tree type = TREE_OPERAND (expression, 1);
28344 if (TREE_CODE (type) == TREE_LIST)
28345 /* This is an array type. We need to check array dimensions
28346 as well. */
28347 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28348 || value_dependent_expression_p
28349 (TREE_OPERAND (TREE_VALUE (type), 1));
28350 /* Array type whose dimension has to be deduced. */
28351 else if (TREE_CODE (type) == ARRAY_TYPE
28352 && TREE_OPERAND (expression, 2) == NULL_TREE)
28353 return true;
28354 else
28355 return dependent_type_p (type);
28358 if (TREE_CODE (expression) == SCOPE_REF)
28360 tree scope = TREE_OPERAND (expression, 0);
28361 tree name = TREE_OPERAND (expression, 1);
28363 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28364 contains an identifier associated by name lookup with one or more
28365 declarations declared with a dependent type, or...a
28366 nested-name-specifier or qualified-id that names a member of an
28367 unknown specialization. */
28368 return (type_dependent_expression_p (name)
28369 || dependent_scope_p (scope));
28372 if (TREE_CODE (expression) == TEMPLATE_DECL
28373 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28374 return uses_outer_template_parms (expression);
28376 if (TREE_CODE (expression) == STMT_EXPR)
28377 expression = stmt_expr_value_expr (expression);
28379 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28381 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28382 if (type_dependent_expression_p (elt.value))
28383 return true;
28384 return false;
28387 /* A static data member of the current instantiation with incomplete
28388 array type is type-dependent, as the definition and specializations
28389 can have different bounds. */
28390 if (VAR_P (expression)
28391 && DECL_CLASS_SCOPE_P (expression)
28392 && dependent_type_p (DECL_CONTEXT (expression))
28393 && VAR_HAD_UNKNOWN_BOUND (expression))
28394 return true;
28396 /* An array of unknown bound depending on a variadic parameter, eg:
28398 template<typename... Args>
28399 void foo (Args... args)
28401 int arr[] = { args... };
28404 template<int... vals>
28405 void bar ()
28407 int arr[] = { vals... };
28410 If the array has no length and has an initializer, it must be that
28411 we couldn't determine its length in cp_complete_array_type because
28412 it is dependent. */
28413 if (((VAR_P (expression) && DECL_INITIAL (expression))
28414 || COMPOUND_LITERAL_P (expression))
28415 && TREE_TYPE (expression) != NULL_TREE
28416 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28417 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28418 return true;
28420 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28421 if (BASELINK_P (expression))
28423 if (BASELINK_OPTYPE (expression)
28424 && dependent_type_p (BASELINK_OPTYPE (expression)))
28425 return true;
28426 expression = BASELINK_FUNCTIONS (expression);
28429 /* A function or variable template-id is type-dependent if it has any
28430 dependent template arguments. */
28431 if (VAR_OR_FUNCTION_DECL_P (expression)
28432 && DECL_LANG_SPECIFIC (expression)
28433 && DECL_TEMPLATE_INFO (expression))
28435 /* Consider the innermost template arguments, since those are the ones
28436 that come from the template-id; the template arguments for the
28437 enclosing class do not make it type-dependent unless they are used in
28438 the type of the decl. */
28439 if (instantiates_primary_template_p (expression)
28440 && (any_dependent_template_arguments_p
28441 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28442 return true;
28445 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28446 type-dependent. Checking this is important for functions with auto return
28447 type, which looks like a dependent type. */
28448 if (TREE_CODE (expression) == FUNCTION_DECL
28449 && !(DECL_CLASS_SCOPE_P (expression)
28450 && dependent_type_p (DECL_CONTEXT (expression)))
28451 && !(DECL_LANG_SPECIFIC (expression)
28452 && DECL_UNIQUE_FRIEND_P (expression)
28453 && (!DECL_FRIEND_CONTEXT (expression)
28454 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28455 && !DECL_LOCAL_DECL_P (expression))
28457 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28458 || undeduced_auto_decl (expression));
28459 return false;
28462 /* Otherwise, its constraints could still depend on outer template parameters
28463 from its (dependent) scope. */
28464 if (TREE_CODE (expression) == FUNCTION_DECL
28465 /* As an optimization, check this cheaper sufficient condition first.
28466 (At this point we've established that we're looking at a member of
28467 a dependent class, so it makes sense to start treating say undeduced
28468 auto as dependent.) */
28469 && !dependent_type_p (TREE_TYPE (expression))
28470 && uses_outer_template_parms_in_constraints (expression))
28471 return true;
28473 /* Always dependent, on the number of arguments if nothing else. */
28474 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28475 return true;
28477 if (TREE_TYPE (expression) == unknown_type_node)
28479 if (TREE_CODE (expression) == ADDR_EXPR)
28480 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28481 if (TREE_CODE (expression) == COMPONENT_REF
28482 || TREE_CODE (expression) == OFFSET_REF)
28484 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28485 return true;
28486 expression = TREE_OPERAND (expression, 1);
28487 if (identifier_p (expression))
28488 return false;
28490 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28491 if (TREE_CODE (expression) == SCOPE_REF)
28492 return false;
28494 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28495 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28496 || TREE_CODE (expression) == CO_YIELD_EXPR)
28497 return true;
28499 if (BASELINK_P (expression))
28501 if (BASELINK_OPTYPE (expression)
28502 && dependent_type_p (BASELINK_OPTYPE (expression)))
28503 return true;
28504 expression = BASELINK_FUNCTIONS (expression);
28507 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28509 if (any_dependent_template_arguments_p
28510 (TREE_OPERAND (expression, 1)))
28511 return true;
28512 expression = TREE_OPERAND (expression, 0);
28513 if (identifier_p (expression))
28514 return true;
28517 gcc_assert (OVL_P (expression));
28519 for (lkp_iterator iter (expression); iter; ++iter)
28520 if (type_dependent_expression_p (*iter))
28521 return true;
28523 return false;
28526 /* The type of a non-type template parm declared with a placeholder type
28527 depends on the corresponding template argument, even though
28528 placeholders are not normally considered dependent. */
28529 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28530 && is_auto (TREE_TYPE (expression)))
28531 return true;
28533 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28535 /* Dependent type attributes might not have made it from the decl to
28536 the type yet. */
28537 if (DECL_P (expression)
28538 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28539 return true;
28541 return (dependent_type_p (TREE_TYPE (expression)));
28544 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28545 type-dependent if the expression refers to a member of the current
28546 instantiation and the type of the referenced member is dependent, or the
28547 class member access expression refers to a member of an unknown
28548 specialization.
28550 This function returns true if the OBJECT in such a class member access
28551 expression is of an unknown specialization. */
28553 bool
28554 type_dependent_object_expression_p (tree object)
28556 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28557 dependent. */
28558 if (TREE_CODE (object) == IDENTIFIER_NODE)
28559 return true;
28560 tree scope = TREE_TYPE (object);
28561 return (!scope || dependent_scope_p (scope));
28564 /* walk_tree callback function for instantiation_dependent_expression_p,
28565 below. Returns non-zero if a dependent subexpression is found. */
28567 static tree
28568 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28569 void * /*data*/)
28571 if (TYPE_P (*tp))
28573 /* We don't have to worry about decltype currently because decltype
28574 of an instantiation-dependent expr is a dependent type. This
28575 might change depending on the resolution of DR 1172. */
28576 *walk_subtrees = false;
28577 return NULL_TREE;
28579 enum tree_code code = TREE_CODE (*tp);
28580 switch (code)
28582 /* Don't treat an argument list as dependent just because it has no
28583 TREE_TYPE. */
28584 case TREE_LIST:
28585 case TREE_VEC:
28586 case NONTYPE_ARGUMENT_PACK:
28587 return NULL_TREE;
28589 case TEMPLATE_PARM_INDEX:
28590 if (dependent_type_p (TREE_TYPE (*tp)))
28591 return *tp;
28592 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28593 return *tp;
28594 /* We'll check value-dependence separately. */
28595 return NULL_TREE;
28597 /* Handle expressions with type operands. */
28598 case SIZEOF_EXPR:
28599 case ALIGNOF_EXPR:
28600 case TYPEID_EXPR:
28601 case AT_ENCODE_EXPR:
28603 tree op = TREE_OPERAND (*tp, 0);
28604 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28605 op = TREE_TYPE (op);
28606 if (TYPE_P (op))
28608 if (dependent_type_p (op))
28609 return *tp;
28610 else
28612 *walk_subtrees = false;
28613 return NULL_TREE;
28616 break;
28619 case COMPONENT_REF:
28620 if (identifier_p (TREE_OPERAND (*tp, 1)))
28621 /* In a template, finish_class_member_access_expr creates a
28622 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28623 type-dependent, so that we can check access control at
28624 instantiation time (PR 42277). See also Core issue 1273. */
28625 return *tp;
28626 break;
28628 case SCOPE_REF:
28629 if (instantiation_dependent_scope_ref_p (*tp))
28630 return *tp;
28631 else
28632 break;
28634 /* Treat statement-expressions as dependent. */
28635 case BIND_EXPR:
28636 return *tp;
28638 /* Treat requires-expressions as dependent. */
28639 case REQUIRES_EXPR:
28640 return *tp;
28642 case CONSTRUCTOR:
28643 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28644 return *tp;
28645 break;
28647 case TEMPLATE_DECL:
28648 case FUNCTION_DECL:
28649 /* Before C++17, a noexcept-specifier isn't part of the function type
28650 so it doesn't affect type dependence, but we still want to consider it
28651 for instantiation dependence. */
28652 if (cxx_dialect < cxx17
28653 && DECL_DECLARES_FUNCTION_P (*tp)
28654 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28655 return *tp;
28656 break;
28658 default:
28659 break;
28662 if (type_dependent_expression_p (*tp))
28663 return *tp;
28664 else
28665 return NULL_TREE;
28668 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28669 sense defined by the ABI:
28671 "An expression is instantiation-dependent if it is type-dependent
28672 or value-dependent, or it has a subexpression that is type-dependent
28673 or value-dependent."
28675 Except don't actually check value-dependence for unevaluated expressions,
28676 because in sizeof(i) we don't care about the value of i. Checking
28677 type-dependence will in turn check value-dependence of array bounds/template
28678 arguments as needed. */
28680 bool
28681 instantiation_dependent_uneval_expression_p (tree expression)
28683 tree result;
28685 if (!processing_template_decl)
28686 return false;
28688 if (expression == error_mark_node)
28689 return false;
28691 result = cp_walk_tree_without_duplicates (&expression,
28692 instantiation_dependent_r, NULL);
28693 return result != NULL_TREE;
28696 /* As above, but also check value-dependence of the expression as a whole. */
28698 bool
28699 instantiation_dependent_expression_p (tree expression)
28701 return (instantiation_dependent_uneval_expression_p (expression)
28702 || (processing_template_decl
28703 && potential_constant_expression (expression)
28704 && value_dependent_expression_p (expression)));
28707 /* Like type_dependent_expression_p, but it also works while not processing
28708 a template definition, i.e. during substitution or mangling. */
28710 bool
28711 type_dependent_expression_p_push (tree expr)
28713 bool b;
28714 ++processing_template_decl;
28715 b = type_dependent_expression_p (expr);
28716 --processing_template_decl;
28717 return b;
28720 /* Returns TRUE if ARGS contains a type-dependent expression. */
28722 bool
28723 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28725 if (!processing_template_decl || !args)
28726 return false;
28728 for (tree arg : *args)
28729 if (type_dependent_expression_p (arg))
28730 return true;
28732 return false;
28735 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28736 expressions) contains any type-dependent expressions. */
28738 bool
28739 any_type_dependent_elements_p (const_tree list)
28741 for (; list; list = TREE_CHAIN (list))
28742 if (type_dependent_expression_p (TREE_VALUE (list)))
28743 return true;
28745 return false;
28748 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28749 expressions) contains any value-dependent expressions. */
28751 bool
28752 any_value_dependent_elements_p (const_tree list)
28754 for (; list; list = TREE_CHAIN (list))
28755 if (value_dependent_expression_p (TREE_VALUE (list)))
28756 return true;
28758 return false;
28761 /* Returns TRUE if the ARG (a template argument) is dependent. */
28763 bool
28764 dependent_template_arg_p (tree arg)
28766 if (!processing_template_decl)
28767 return false;
28769 /* Assume a template argument that was wrongly written by the user
28770 is dependent. This is consistent with what
28771 any_dependent_template_arguments_p [that calls this function]
28772 does. */
28773 if (!arg || arg == error_mark_node)
28774 return true;
28776 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28777 arg = argument_pack_select_arg (arg);
28779 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28780 return true;
28781 if (TREE_CODE (arg) == TEMPLATE_DECL)
28783 if (DECL_TEMPLATE_PARM_P (arg))
28784 return true;
28785 /* A member template of a dependent class is not necessarily
28786 type-dependent, but it is a dependent template argument because it
28787 will be a member of an unknown specialization to that template. */
28788 tree scope = CP_DECL_CONTEXT (arg);
28789 return TYPE_P (scope) && dependent_type_p (scope);
28791 else if (ARGUMENT_PACK_P (arg))
28793 tree args = ARGUMENT_PACK_ARGS (arg);
28794 for (tree arg : tree_vec_range (args))
28795 if (dependent_template_arg_p (arg))
28796 return true;
28797 return false;
28799 else if (TYPE_P (arg))
28800 return dependent_type_p (arg);
28801 else
28802 return value_dependent_expression_p (arg);
28805 /* Identify any expressions that use function parms. */
28807 static tree
28808 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28810 tree t = *tp;
28811 if (TREE_CODE (t) == PARM_DECL)
28813 *walk_subtrees = 0;
28814 return t;
28816 return NULL_TREE;
28819 /* Returns true if a type specialization formed using the template
28820 arguments ARGS needs to use structural equality. */
28822 bool
28823 any_template_arguments_need_structural_equality_p (tree args)
28825 int i;
28826 int j;
28828 if (!args)
28829 return false;
28830 if (args == error_mark_node)
28831 return true;
28833 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28835 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28836 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28838 tree arg = TREE_VEC_ELT (level, j);
28839 tree packed_args = NULL_TREE;
28840 int k, len = 1;
28842 if (ARGUMENT_PACK_P (arg))
28844 /* Look inside the argument pack. */
28845 packed_args = ARGUMENT_PACK_ARGS (arg);
28846 len = TREE_VEC_LENGTH (packed_args);
28849 for (k = 0; k < len; ++k)
28851 if (packed_args)
28852 arg = TREE_VEC_ELT (packed_args, k);
28854 if (error_operand_p (arg))
28855 return true;
28856 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28857 continue;
28858 else if (arg == any_targ_node)
28859 /* An any_targ_node argument (added by add_defaults_to_ttp)
28860 makes the corresponding specialization not canonicalizable,
28861 since template_args_equal always return true for it. We
28862 may see this when called from bind_template_template_parm. */
28863 return true;
28864 /* Checking current_function_decl because this structural
28865 comparison is only necessary for redeclaration. */
28866 else if (!current_function_decl
28867 && dependent_template_arg_p (arg)
28868 && (cp_walk_tree_without_duplicates
28869 (&arg, find_parm_usage_r, NULL)))
28870 /* The identity of a class template specialization that uses
28871 a function parameter depends on the identity of the function.
28872 And if this specialization appeared in the trailing return
28873 type thereof, we don't know the identity of the function
28874 (e.g. if it's a redeclaration or a new function) until we
28875 form its signature and go through duplicate_decls. Thus
28876 it's unsafe to decide on a canonical type now (which depends
28877 on the DECL_CONTEXT of the function parameter, which can get
28878 mutated after the fact by duplicate_decls), so just require
28879 structural equality in this case (PR52830). */
28880 return true;
28885 return false;
28888 /* Returns true if ARGS (a collection of template arguments) contains
28889 any dependent arguments. */
28891 bool
28892 any_dependent_template_arguments_p (const_tree args)
28894 if (args == error_mark_node)
28895 return true;
28896 if (!processing_template_decl || !args)
28897 return false;
28899 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28901 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28902 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28903 if (dependent_template_arg_p (arg))
28904 return true;
28907 return false;
28910 /* Returns true if ARGS contains any errors. */
28912 bool
28913 any_erroneous_template_args_p (const_tree args)
28915 int i;
28916 int j;
28918 if (args == error_mark_node)
28919 return true;
28921 if (args && TREE_CODE (args) != TREE_VEC)
28923 if (tree ti = get_template_info (args))
28924 args = TI_ARGS (ti);
28925 else
28926 args = NULL_TREE;
28929 if (!args)
28930 return false;
28932 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28934 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28935 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28936 if (error_operand_p (TREE_VEC_ELT (level, j)))
28937 return true;
28940 return false;
28943 /* Returns TRUE if the template TMPL is type-dependent. */
28945 bool
28946 dependent_template_p (tree tmpl)
28948 if (TREE_CODE (tmpl) == OVERLOAD)
28950 for (lkp_iterator iter (tmpl); iter; ++iter)
28951 if (dependent_template_p (*iter))
28952 return true;
28953 return false;
28956 /* Template template parameters are dependent. */
28957 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28958 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28959 return true;
28960 /* So are names that have not been looked up. */
28961 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28962 return true;
28963 return false;
28966 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28968 bool
28969 dependent_template_id_p (tree tmpl, tree args)
28971 return (dependent_template_p (tmpl)
28972 || any_dependent_template_arguments_p (args));
28975 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28976 are dependent. */
28978 bool
28979 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28981 int i;
28983 if (!processing_template_decl)
28984 return false;
28986 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28988 tree decl = TREE_VEC_ELT (declv, i);
28989 tree init = TREE_VEC_ELT (initv, i);
28990 tree cond = TREE_VEC_ELT (condv, i);
28991 tree incr = TREE_VEC_ELT (incrv, i);
28993 if (type_dependent_expression_p (decl)
28994 || TREE_CODE (decl) == SCOPE_REF)
28995 return true;
28997 if (init && type_dependent_expression_p (init))
28998 return true;
29000 if (cond == global_namespace)
29001 return true;
29003 if (type_dependent_expression_p (cond))
29004 return true;
29006 if (COMPARISON_CLASS_P (cond)
29007 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
29008 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
29009 return true;
29011 if (TREE_CODE (incr) == MODOP_EXPR)
29013 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
29014 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
29015 return true;
29017 else if (type_dependent_expression_p (incr))
29018 return true;
29019 else if (TREE_CODE (incr) == MODIFY_EXPR)
29021 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
29022 return true;
29023 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
29025 tree t = TREE_OPERAND (incr, 1);
29026 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
29027 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
29028 return true;
29030 /* If this loop has a class iterator with != comparison
29031 with increment other than i++/++i/i--/--i, make sure the
29032 increment is constant. */
29033 if (CLASS_TYPE_P (TREE_TYPE (decl))
29034 && TREE_CODE (cond) == NE_EXPR)
29036 if (TREE_OPERAND (t, 0) == decl)
29037 t = TREE_OPERAND (t, 1);
29038 else
29039 t = TREE_OPERAND (t, 0);
29040 if (TREE_CODE (t) != INTEGER_CST)
29041 return true;
29047 return false;
29050 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
29051 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
29052 no such TYPE can be found. Note that this function peers inside
29053 uninstantiated templates and therefore should be used only in
29054 extremely limited situations. ONLY_CURRENT_P restricts this
29055 peering to the currently open classes hierarchy (which is required
29056 when comparing types). */
29058 tree
29059 resolve_typename_type (tree type, bool only_current_p)
29061 tree scope;
29062 tree name;
29063 tree decl;
29064 int quals;
29065 tree pushed_scope;
29066 tree result;
29068 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
29070 scope = TYPE_CONTEXT (type);
29071 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
29072 gcc_checking_assert (uses_template_parms (scope));
29074 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
29075 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
29076 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
29077 representing the typedef. In that case TYPE_IDENTIFIER (type) is
29078 not the non-qualified identifier of the TYPENAME_TYPE anymore.
29079 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
29080 the TYPENAME_TYPE instead, we avoid messing up with a possible
29081 typedef variant case. */
29082 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
29084 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
29085 it first before we can figure out what NAME refers to. */
29086 if (TREE_CODE (scope) == TYPENAME_TYPE)
29088 if (TYPENAME_IS_RESOLVING_P (scope))
29089 /* Given a class template A with a dependent base with nested type C,
29090 typedef typename A::C::C C will land us here, as trying to resolve
29091 the initial A::C leads to the local C typedef, which leads back to
29092 A::C::C. So we break the recursion now. */
29093 return type;
29094 else
29095 scope = resolve_typename_type (scope, only_current_p);
29097 /* If we don't know what SCOPE refers to, then we cannot resolve the
29098 TYPENAME_TYPE. */
29099 if (!CLASS_TYPE_P (scope))
29100 return type;
29101 /* If this is a typedef, we don't want to look inside (c++/11987). */
29102 if (typedef_variant_p (type))
29103 return type;
29104 /* If SCOPE isn't the template itself, it will not have a valid
29105 TYPE_FIELDS list. */
29106 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29107 /* scope is either the template itself or a compatible instantiation
29108 like X<T>, so look up the name in the original template. */
29109 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29110 /* If scope has no fields, it can't be a current instantiation. Check this
29111 before currently_open_class to avoid infinite recursion (71515). */
29112 if (!TYPE_FIELDS (scope))
29113 return type;
29114 /* If the SCOPE is not the current instantiation, there's no reason
29115 to look inside it. */
29116 if (only_current_p && !currently_open_class (scope))
29117 return type;
29118 /* Enter the SCOPE so that name lookup will be resolved as if we
29119 were in the class definition. In particular, SCOPE will no
29120 longer be considered a dependent type. */
29121 pushed_scope = push_scope (scope);
29122 /* Look up the declaration. */
29123 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29124 tf_warning_or_error);
29126 result = NULL_TREE;
29128 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29129 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29130 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29131 if (!decl)
29132 /*nop*/;
29133 else if (identifier_p (fullname)
29134 && TREE_CODE (decl) == TYPE_DECL)
29136 result = TREE_TYPE (decl);
29137 if (result == error_mark_node)
29138 result = NULL_TREE;
29140 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29141 && DECL_CLASS_TEMPLATE_P (decl))
29143 /* Obtain the template and the arguments. */
29144 tree tmpl = TREE_OPERAND (fullname, 0);
29145 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29147 /* We get here with a plain identifier because a previous tentative
29148 parse of the nested-name-specifier as part of a ptr-operator saw
29149 ::template X<A>. The use of ::template is necessary in a
29150 ptr-operator, but wrong in a declarator-id.
29152 [temp.names]: In a qualified-id of a declarator-id, the keyword
29153 template shall not appear at the top level. */
29154 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29155 "keyword %<template%> not allowed in declarator-id");
29156 tmpl = decl;
29158 tree args = TREE_OPERAND (fullname, 1);
29159 /* Instantiate the template. */
29160 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29161 /*entering_scope=*/true,
29162 tf_error | tf_user);
29163 if (result == error_mark_node)
29164 result = NULL_TREE;
29167 /* Leave the SCOPE. */
29168 if (pushed_scope)
29169 pop_scope (pushed_scope);
29171 /* If we failed to resolve it, return the original typename. */
29172 if (!result)
29173 return type;
29175 /* If lookup found a typename type, resolve that too. */
29176 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29178 /* Ill-formed programs can cause infinite recursion here, so we
29179 must catch that. */
29180 TYPENAME_IS_RESOLVING_P (result) = 1;
29181 result = resolve_typename_type (result, only_current_p);
29182 TYPENAME_IS_RESOLVING_P (result) = 0;
29185 /* Qualify the resulting type. */
29186 quals = cp_type_quals (type);
29187 if (quals)
29188 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29190 return result;
29193 /* EXPR is an expression which is not type-dependent. Return a proxy
29194 for EXPR that can be used to compute the types of larger
29195 expressions containing EXPR. */
29197 tree
29198 build_non_dependent_expr (tree expr)
29200 tree orig_expr = expr;
29201 tree inner_expr;
29203 /* When checking, try to get a constant value for all non-dependent
29204 expressions in order to expose bugs in *_dependent_expression_p
29205 and constexpr. This can affect code generation, see PR70704, so
29206 only do this for -fchecking=2. */
29207 if (flag_checking > 1
29208 && cxx_dialect >= cxx11
29209 /* Don't do this during nsdmi parsing as it can lead to
29210 unexpected recursive instantiations. */
29211 && !parsing_nsdmi ()
29212 /* Don't do this during concept processing either and for
29213 the same reason. */
29214 && !processing_constraint_expression_p ())
29215 fold_non_dependent_expr (expr, tf_none);
29217 STRIP_ANY_LOCATION_WRAPPER (expr);
29219 /* Preserve OVERLOADs; the functions must be available to resolve
29220 types. */
29221 inner_expr = expr;
29222 if (TREE_CODE (inner_expr) == STMT_EXPR)
29223 inner_expr = stmt_expr_value_expr (inner_expr);
29224 if (TREE_CODE (inner_expr) == ADDR_EXPR)
29225 inner_expr = TREE_OPERAND (inner_expr, 0);
29226 if (TREE_CODE (inner_expr) == COMPONENT_REF)
29227 inner_expr = TREE_OPERAND (inner_expr, 1);
29228 if (is_overloaded_fn (inner_expr)
29229 || TREE_CODE (inner_expr) == OFFSET_REF)
29230 return orig_expr;
29231 /* There is no need to return a proxy for a variable, parameter
29232 or enumerator. */
29233 if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
29234 || TREE_CODE (expr) == CONST_DECL)
29235 return orig_expr;
29236 /* Preserve string constants; conversions from string constants to
29237 "char *" are allowed, even though normally a "const char *"
29238 cannot be used to initialize a "char *". */
29239 if (TREE_CODE (expr) == STRING_CST)
29240 return orig_expr;
29241 /* Preserve void and arithmetic constants, as an optimization -- there is no
29242 reason to create a new node. */
29243 if (TREE_CODE (expr) == VOID_CST
29244 || TREE_CODE (expr) == INTEGER_CST
29245 || TREE_CODE (expr) == REAL_CST)
29246 return orig_expr;
29247 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
29248 There is at least one place where we want to know that a
29249 particular expression is a throw-expression: when checking a ?:
29250 expression, there are special rules if the second or third
29251 argument is a throw-expression. */
29252 if (TREE_CODE (expr) == THROW_EXPR)
29253 return orig_expr;
29255 /* Don't wrap an initializer list, we need to be able to look inside. */
29256 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
29257 return orig_expr;
29259 /* Don't wrap a dummy object, we need to be able to test for it. */
29260 if (is_dummy_object (expr))
29261 return orig_expr;
29263 if (TREE_CODE (expr) == COND_EXPR)
29264 return build3 (COND_EXPR,
29265 TREE_TYPE (expr),
29266 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
29267 (TREE_OPERAND (expr, 1)
29268 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
29269 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
29270 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
29271 if (TREE_CODE (expr) == COMPOUND_EXPR)
29272 return build2 (COMPOUND_EXPR,
29273 TREE_TYPE (expr),
29274 TREE_OPERAND (expr, 0),
29275 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
29277 /* If the type is unknown, it can't really be non-dependent */
29278 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
29280 /* Otherwise, build a NON_DEPENDENT_EXPR. */
29281 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
29282 TREE_TYPE (expr), expr);
29285 /* ARGS is a vector of expressions as arguments to a function call.
29286 Replace the arguments with equivalent non-dependent expressions.
29287 This modifies ARGS in place. */
29289 void
29290 make_args_non_dependent (vec<tree, va_gc> *args)
29292 unsigned int ix;
29293 tree arg;
29295 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
29297 tree newarg = build_non_dependent_expr (arg);
29298 if (newarg != arg)
29299 (*args)[ix] = newarg;
29303 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29304 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29305 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29307 static tree
29308 make_auto_1 (tree name, bool set_canonical, int level = -1)
29310 if (level == -1)
29311 level = current_template_depth + 1;
29312 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29313 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29314 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29315 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29316 (0, level, level, TYPE_NAME (au), NULL_TREE);
29317 if (set_canonical)
29318 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29319 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29320 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29321 if (name == decltype_auto_identifier)
29322 AUTO_IS_DECLTYPE (au) = true;
29324 return au;
29327 tree
29328 make_decltype_auto (void)
29330 return make_auto_1 (decltype_auto_identifier, true);
29333 tree
29334 make_auto (void)
29336 return make_auto_1 (auto_identifier, true);
29339 /* Return a C++17 deduction placeholder for class template TMPL.
29340 There are represented as an 'auto' with the special level 0 and
29341 CLASS_PLACEHOLDER_TEMPLATE set. */
29343 tree
29344 make_template_placeholder (tree tmpl)
29346 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29347 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29348 /* Our canonical type depends on the placeholder. */
29349 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29350 return t;
29353 /* True iff T is a C++17 class template deduction placeholder. */
29355 bool
29356 template_placeholder_p (tree t)
29358 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29361 /* Make a "constrained auto" type-specifier. This is an auto or
29362 decltype(auto) type with constraints that must be associated after
29363 deduction. The constraint is formed from the given concept CON
29364 and its optional sequence of template arguments ARGS.
29366 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29368 static tree
29369 make_constrained_placeholder_type (tree type, tree con, tree args)
29371 /* Build the constraint. */
29372 tree tmpl = DECL_TI_TEMPLATE (con);
29373 tree expr = tmpl;
29374 if (TREE_CODE (con) == FUNCTION_DECL)
29375 expr = ovl_make (tmpl);
29376 ++processing_template_decl;
29377 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29378 --processing_template_decl;
29380 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29381 = build_tree_list (current_template_parms, expr);
29383 /* Our canonical type depends on the constraint. */
29384 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29386 /* Attach the constraint to the type declaration. */
29387 return TYPE_NAME (type);
29390 /* Make a "constrained auto" type-specifier. */
29392 tree
29393 make_constrained_auto (tree con, tree args)
29395 tree type = make_auto_1 (auto_identifier, false);
29396 return make_constrained_placeholder_type (type, con, args);
29399 /* Make a "constrained decltype(auto)" type-specifier. */
29401 tree
29402 make_constrained_decltype_auto (tree con, tree args)
29404 tree type = make_auto_1 (decltype_auto_identifier, false);
29405 return make_constrained_placeholder_type (type, con, args);
29408 /* Returns true if the placeholder type constraint T has any dependent
29409 (explicit) template arguments. */
29411 static bool
29412 placeholder_type_constraint_dependent_p (tree t)
29414 tree id = unpack_concept_check (t);
29415 tree args = TREE_OPERAND (id, 1);
29416 tree first = TREE_VEC_ELT (args, 0);
29417 if (ARGUMENT_PACK_P (first))
29419 args = expand_template_argument_pack (args);
29420 first = TREE_VEC_ELT (args, 0);
29422 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29423 || is_auto (first));
29424 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29425 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29426 return true;
29427 return false;
29430 /* Build and return a concept definition. Like other templates, the
29431 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29432 the TEMPLATE_DECL. */
29434 tree
29435 finish_concept_definition (cp_expr id, tree init, tree attrs)
29437 gcc_assert (identifier_p (id));
29438 gcc_assert (processing_template_decl);
29440 location_t loc = id.get_location();
29442 /* A concept-definition shall not have associated constraints. */
29443 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29445 error_at (loc, "a concept cannot be constrained");
29446 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29449 /* A concept-definition shall appear in namespace scope. Templates
29450 aren't allowed in block scope, so we only need to check for class
29451 scope. */
29452 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29454 error_at (loc, "concept %qE not in namespace scope", *id);
29455 return error_mark_node;
29458 if (current_template_depth > 1)
29460 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29461 return error_mark_node;
29464 /* Initially build the concept declaration; its type is bool. */
29465 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29466 DECL_CONTEXT (decl) = current_scope ();
29467 DECL_INITIAL (decl) = init;
29469 if (attrs)
29470 cplus_decl_attributes (&decl, attrs, 0);
29472 set_originating_module (decl, false);
29474 /* Push the enclosing template. */
29475 return push_template_decl (decl);
29478 /* Given type ARG, return std::initializer_list<ARG>. */
29480 static tree
29481 listify (tree arg)
29483 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29485 if (std_init_list == error_mark_node
29486 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29488 gcc_rich_location richloc (input_location);
29489 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29490 error_at (&richloc,
29491 "deducing from brace-enclosed initializer list"
29492 " requires %<#include <initializer_list>%>");
29494 return error_mark_node;
29496 tree argvec = make_tree_vec (1);
29497 TREE_VEC_ELT (argvec, 0) = arg;
29499 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29500 NULL_TREE, 0, tf_warning_or_error);
29503 /* Replace auto in TYPE with std::initializer_list<auto>. */
29505 static tree
29506 listify_autos (tree type, tree auto_node)
29508 tree init_auto = listify (strip_top_quals (auto_node));
29509 tree argvec = make_tree_vec (1);
29510 TREE_VEC_ELT (argvec, 0) = init_auto;
29511 if (processing_template_decl)
29512 argvec = add_to_template_args (current_template_args (), argvec);
29513 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29516 /* Hash traits for hashing possibly constrained 'auto'
29517 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29519 struct auto_hash : default_hash_traits<tree>
29521 static inline hashval_t hash (tree);
29522 static inline bool equal (tree, tree);
29525 /* Hash the 'auto' T. */
29527 inline hashval_t
29528 auto_hash::hash (tree t)
29530 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29531 /* Matching constrained-type-specifiers denote the same template
29532 parameter, so hash the constraint. */
29533 return hash_placeholder_constraint (c);
29534 else
29535 /* But unconstrained autos are all separate, so just hash the pointer. */
29536 return iterative_hash_object (t, 0);
29539 /* Compare two 'auto's. */
29541 inline bool
29542 auto_hash::equal (tree t1, tree t2)
29544 if (t1 == t2)
29545 return true;
29547 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29548 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29550 /* Two unconstrained autos are distinct. */
29551 if (!c1 || !c2)
29552 return false;
29554 return equivalent_placeholder_constraints (c1, c2);
29557 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29558 constrained) auto, add it to the vector. */
29560 static int
29561 extract_autos_r (tree t, void *data)
29563 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29564 if (is_auto (t) && !template_placeholder_p (t))
29566 /* All the autos were built with index 0; fix that up now. */
29567 tree *p = hash.find_slot (t, INSERT);
29568 int idx;
29569 if (*p)
29570 /* If this is a repeated constrained-type-specifier, use the index we
29571 chose before. */
29572 idx = TEMPLATE_TYPE_IDX (*p);
29573 else
29575 /* Otherwise this is new, so use the current count. */
29576 *p = t;
29577 idx = hash.elements () - 1;
29579 if (idx != TEMPLATE_TYPE_IDX (t))
29581 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29582 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29583 TEMPLATE_TYPE_IDX (t) = idx;
29584 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29588 /* Always keep walking. */
29589 return 0;
29592 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29593 says they can appear anywhere in the type. */
29595 static tree
29596 extract_autos (tree type)
29598 hash_set<tree> visited;
29599 hash_table<auto_hash> hash (2);
29601 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29603 tree tree_vec = make_tree_vec (hash.elements());
29604 for (tree elt : hash)
29606 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29607 TREE_VEC_ELT (tree_vec, i)
29608 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29611 return tree_vec;
29614 /* The stem for deduction guide names. */
29615 const char *const dguide_base = "__dguide_";
29617 /* Return the name for a deduction guide for class template TMPL. */
29619 tree
29620 dguide_name (tree tmpl)
29622 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29623 tree tname = TYPE_IDENTIFIER (type);
29624 char *buf = (char *) alloca (1 + strlen (dguide_base)
29625 + IDENTIFIER_LENGTH (tname));
29626 memcpy (buf, dguide_base, strlen (dguide_base));
29627 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29628 IDENTIFIER_LENGTH (tname) + 1);
29629 tree dname = get_identifier (buf);
29630 TREE_TYPE (dname) = type;
29631 return dname;
29634 /* True if NAME is the name of a deduction guide. */
29636 bool
29637 dguide_name_p (tree name)
29639 return (TREE_CODE (name) == IDENTIFIER_NODE
29640 && TREE_TYPE (name)
29641 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29644 /* True if FN is a deduction guide. */
29646 bool
29647 deduction_guide_p (const_tree fn)
29649 if (DECL_P (fn))
29650 if (tree name = DECL_NAME (fn))
29651 return dguide_name_p (name);
29652 return false;
29655 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29657 bool
29658 copy_guide_p (const_tree fn)
29660 gcc_assert (deduction_guide_p (fn));
29661 if (!DECL_ARTIFICIAL (fn))
29662 return false;
29663 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29664 return (TREE_CHAIN (parms) == void_list_node
29665 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29668 /* True if FN is a guide generated from a constructor template. */
29670 bool
29671 template_guide_p (const_tree fn)
29673 gcc_assert (deduction_guide_p (fn));
29674 if (!DECL_ARTIFICIAL (fn))
29675 return false;
29676 tree tmpl = DECL_TI_TEMPLATE (fn);
29677 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29678 return PRIMARY_TEMPLATE_P (org);
29679 return false;
29682 /* True if FN is an aggregate initialization guide or the copy deduction
29683 guide. */
29685 bool
29686 builtin_guide_p (const_tree fn)
29688 if (!deduction_guide_p (fn))
29689 return false;
29690 if (!DECL_ARTIFICIAL (fn))
29691 /* Explicitly declared. */
29692 return false;
29693 if (DECL_ABSTRACT_ORIGIN (fn))
29694 /* Derived from a constructor. */
29695 return false;
29696 return true;
29699 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29700 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29701 template parameter types. Note that the handling of template template
29702 parameters relies on current_template_parms being set appropriately for the
29703 new template. */
29705 static tree
29706 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29707 tree tsubst_args, tsubst_flags_t complain)
29709 if (olddecl == error_mark_node)
29710 return error_mark_node;
29712 tree oldidx = get_template_parm_index (olddecl);
29714 tree newtype;
29715 if (TREE_CODE (olddecl) == TYPE_DECL
29716 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29718 tree oldtype = TREE_TYPE (olddecl);
29719 newtype = cxx_make_type (TREE_CODE (oldtype));
29720 TYPE_MAIN_VARIANT (newtype) = newtype;
29722 else
29724 newtype = TREE_TYPE (olddecl);
29725 if (type_uses_auto (newtype))
29727 // Substitute once to fix references to other template parameters.
29728 newtype = tsubst (newtype, tsubst_args,
29729 complain|tf_partial, NULL_TREE);
29730 // Now substitute again to reduce the level of the auto.
29731 newtype = tsubst (newtype, current_template_args (),
29732 complain, NULL_TREE);
29734 else
29735 newtype = tsubst (newtype, tsubst_args,
29736 complain, NULL_TREE);
29739 tree newdecl
29740 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29741 DECL_NAME (olddecl), newtype);
29742 SET_DECL_TEMPLATE_PARM_P (newdecl);
29744 tree newidx;
29745 if (TREE_CODE (olddecl) == TYPE_DECL
29746 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29748 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29749 = build_template_parm_index (index, level, level,
29750 newdecl, newtype);
29751 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29752 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29753 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29755 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29757 tree newresult
29758 = build_lang_decl_loc (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29759 DECL_NAME (olddecl), newtype);
29760 DECL_ARTIFICIAL (newresult) = true;
29761 DECL_TEMPLATE_RESULT (newdecl) = newresult;
29762 // First create a copy (ttargs) of tsubst_args with an
29763 // additional level for the template template parameter's own
29764 // template parameters (ttparms).
29765 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29766 (DECL_TEMPLATE_PARMS (olddecl)));
29767 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29768 tree ttargs = make_tree_vec (depth + 1);
29769 for (int i = 0; i < depth; ++i)
29770 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29771 TREE_VEC_ELT (ttargs, depth)
29772 = template_parms_level_to_args (ttparms);
29773 // Substitute ttargs into ttparms to fix references to
29774 // other template parameters.
29775 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29776 complain|tf_partial);
29777 // Now substitute again with args based on tparms, to reduce
29778 // the level of the ttparms.
29779 ttargs = current_template_args ();
29780 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29781 complain);
29782 // Finally, tack the adjusted parms onto tparms.
29783 ttparms = tree_cons (size_int (level + 1), ttparms,
29784 copy_node (current_template_parms));
29785 // As with all template template parms, the parameter list captured
29786 // by this template template parm that corresponds to its own level
29787 // should be empty. This avoids infinite recursion when structurally
29788 // comparing two such rewritten template template parms (PR102479).
29789 gcc_assert (!TREE_VEC_LENGTH
29790 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29791 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29792 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29793 // All done.
29794 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29795 DECL_TEMPLATE_INFO (newresult)
29796 = build_template_info (newdecl, template_parms_to_args (ttparms));
29799 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29800 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29801 else
29802 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29804 else
29806 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29807 tree newconst
29808 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29809 TREE_CODE (oldconst),
29810 DECL_NAME (oldconst), newtype);
29811 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29812 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29813 SET_DECL_TEMPLATE_PARM_P (newconst);
29814 newidx = build_template_parm_index (index, level, level,
29815 newconst, newtype);
29816 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29817 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29818 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29821 return newdecl;
29824 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29825 template parameter. */
29827 static tree
29828 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29829 tree targs, unsigned targs_index, tsubst_flags_t complain)
29831 tree olddecl = TREE_VALUE (oldelt);
29832 tree newdecl = rewrite_template_parm (olddecl, index, level,
29833 targs, complain);
29834 if (newdecl == error_mark_node)
29835 return error_mark_node;
29836 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29837 targs, complain, NULL_TREE);
29838 tree list = build_tree_list (newdef, newdecl);
29839 TEMPLATE_PARM_CONSTRAINTS (list)
29840 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29841 targs, complain, NULL_TREE);
29842 int depth = TMPL_ARGS_DEPTH (targs);
29843 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29844 return list;
29847 /* Returns a C++17 class deduction guide template based on the constructor
29848 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29849 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29850 aggregate initialization guide. OUTER_ARGS are the template arguments
29851 for the enclosing scope of the class. */
29853 static tree
29854 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29856 tree tparms, targs, fparms, fargs, ci;
29857 bool memtmpl = false;
29858 bool explicit_p;
29859 location_t loc;
29860 tree fn_tmpl = NULL_TREE;
29862 if (outer_args)
29864 ++processing_template_decl;
29865 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29866 --processing_template_decl;
29869 if (!DECL_DECLARES_FUNCTION_P (ctor))
29871 if (TYPE_P (ctor))
29873 bool copy_p = TYPE_REF_P (ctor);
29874 if (copy_p)
29875 fparms = tree_cons (NULL_TREE, type, void_list_node);
29876 else
29877 fparms = void_list_node;
29879 else if (TREE_CODE (ctor) == TREE_LIST)
29880 fparms = ctor;
29881 else
29882 gcc_unreachable ();
29884 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29885 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29886 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29887 ci = NULL_TREE;
29888 fargs = NULL_TREE;
29889 loc = DECL_SOURCE_LOCATION (ctmpl);
29890 explicit_p = false;
29892 else
29894 ++processing_template_decl;
29895 bool ok = true;
29897 complain |= tf_dguide;
29899 fn_tmpl
29900 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29901 : DECL_TI_TEMPLATE (ctor));
29902 if (outer_args)
29903 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29904 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29906 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29907 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29908 fully specialized args for the enclosing class. Strip those off, as
29909 the deduction guide won't have those template parameters. */
29910 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29911 TMPL_PARMS_DEPTH (tparms));
29912 /* Discard the 'this' parameter. */
29913 fparms = FUNCTION_ARG_CHAIN (ctor);
29914 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29915 ci = get_constraints (ctor);
29916 loc = DECL_SOURCE_LOCATION (ctor);
29917 explicit_p = DECL_NONCONVERTING_P (ctor);
29919 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29921 memtmpl = true;
29923 /* For a member template constructor, we need to flatten the two
29924 template parameter lists into one, and then adjust the function
29925 signature accordingly. This gets...complicated. */
29926 tree save_parms = current_template_parms;
29928 /* For a member template we should have two levels of parms/args, one
29929 for the class and one for the constructor. We stripped
29930 specialized args for further enclosing classes above. */
29931 const int depth = 2;
29932 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29934 /* Template args for translating references to the two-level template
29935 parameters into references to the one-level template parameters we
29936 are creating. */
29937 tree tsubst_args = copy_node (targs);
29938 TMPL_ARGS_LEVEL (tsubst_args, depth)
29939 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29941 /* Template parms for the constructor template. */
29942 tree ftparms = TREE_VALUE (tparms);
29943 unsigned flen = TREE_VEC_LENGTH (ftparms);
29944 /* Template parms for the class template. */
29945 tparms = TREE_CHAIN (tparms);
29946 tree ctparms = TREE_VALUE (tparms);
29947 unsigned clen = TREE_VEC_LENGTH (ctparms);
29948 /* Template parms for the deduction guide start as a copy of the
29949 template parms for the class. We set current_template_parms for
29950 lookup_template_class_1. */
29951 current_template_parms = tparms = copy_node (tparms);
29952 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29953 for (unsigned i = 0; i < clen; ++i)
29954 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29956 /* Now we need to rewrite the constructor parms to append them to the
29957 class parms. */
29958 for (unsigned i = 0; i < flen; ++i)
29960 unsigned index = i + clen;
29961 unsigned level = 1;
29962 tree oldelt = TREE_VEC_ELT (ftparms, i);
29963 tree newelt
29964 = rewrite_tparm_list (oldelt, index, level,
29965 tsubst_args, i, complain);
29966 if (newelt == error_mark_node)
29967 ok = false;
29968 TREE_VEC_ELT (new_vec, index) = newelt;
29971 /* Now we have a final set of template parms to substitute into the
29972 function signature. */
29973 targs = template_parms_to_args (tparms);
29974 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29975 complain, ctor);
29976 if (fparms == error_mark_node)
29977 ok = false;
29978 if (ci)
29980 if (outer_args)
29981 /* FIXME: We'd like to avoid substituting outer template
29982 arguments into the constraint ahead of time, but the
29983 construction of tsubst_args assumes that outer arguments
29984 are already substituted in. */
29985 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29986 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29989 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29990 cp_unevaluated_operand. */
29991 cp_evaluated ev;
29992 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29993 current_template_parms = save_parms;
29995 else
29997 /* Substitute in the same arguments to rewrite class members into
29998 references to members of an unknown specialization. */
29999 cp_evaluated ev;
30000 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
30001 fargs = tsubst (fargs, targs, complain, ctor);
30002 if (ci)
30004 if (outer_args)
30005 /* FIXME: As above. */
30006 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
30007 ci = tsubst_constraint_info (ci, targs, complain, ctor);
30011 --processing_template_decl;
30012 if (!ok)
30013 return error_mark_node;
30016 if (!memtmpl)
30018 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
30019 tparms = copy_node (tparms);
30020 INNERMOST_TEMPLATE_PARMS (tparms)
30021 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
30024 tree fntype = build_function_type (type, fparms);
30025 tree ded_fn = build_lang_decl_loc (loc,
30026 FUNCTION_DECL,
30027 dguide_name (type), fntype);
30028 DECL_ARGUMENTS (ded_fn) = fargs;
30029 DECL_ARTIFICIAL (ded_fn) = true;
30030 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
30031 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
30032 DECL_ARTIFICIAL (ded_tmpl) = true;
30033 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
30034 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
30035 if (DECL_P (ctor))
30036 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
30037 if (ci)
30038 set_constraints (ded_tmpl, ci);
30040 return ded_tmpl;
30043 /* Add to LIST the member types for the reshaped initializer CTOR. */
30045 static tree
30046 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
30048 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
30049 tree idx, val; unsigned i;
30050 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
30052 tree ftype = elt ? elt : TREE_TYPE (idx);
30053 if (BRACE_ENCLOSED_INITIALIZER_P (val)
30054 && CONSTRUCTOR_BRACES_ELIDED_P (val))
30056 tree subelt = NULL_TREE;
30057 if (TREE_CODE (ftype) == ARRAY_TYPE)
30058 subelt = TREE_TYPE (ftype);
30059 list = collect_ctor_idx_types (val, list, subelt);
30060 continue;
30062 tree arg = NULL_TREE;
30063 if (i == v->length() - 1
30064 && PACK_EXPANSION_P (ftype))
30065 /* Give the trailing pack expansion parameter a default argument to
30066 match aggregate initialization behavior, even if we deduce the
30067 length of the pack separately to more than we have initializers. */
30068 arg = build_constructor (init_list_type_node, NULL);
30069 /* if ei is of array type and xi is a braced-init-list or string literal,
30070 Ti is an rvalue reference to the declared type of ei */
30071 STRIP_ANY_LOCATION_WRAPPER (val);
30072 if (TREE_CODE (ftype) == ARRAY_TYPE
30073 && (BRACE_ENCLOSED_INITIALIZER_P (val)
30074 || TREE_CODE (val) == STRING_CST))
30076 if (TREE_CODE (val) == STRING_CST)
30077 ftype = cp_build_qualified_type
30078 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
30079 ftype = (cp_build_reference_type
30080 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
30082 list = tree_cons (arg, ftype, list);
30085 return list;
30088 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
30090 static bool
30091 is_spec_or_derived (tree etype, tree tmpl)
30093 if (!etype || !CLASS_TYPE_P (etype))
30094 return false;
30096 etype = cv_unqualified (etype);
30097 tree type = TREE_TYPE (tmpl);
30098 tree tparms = (INNERMOST_TEMPLATE_PARMS
30099 (DECL_TEMPLATE_PARMS (tmpl)));
30100 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30101 int err = unify (tparms, targs, type, etype,
30102 UNIFY_ALLOW_DERIVED, /*explain*/false);
30103 ggc_free (targs);
30104 return !err;
30107 static tree alias_ctad_tweaks (tree, tree);
30109 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30110 INIT. */
30112 static tree
30113 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30115 if (cxx_dialect < cxx20)
30116 return NULL_TREE;
30118 if (init == NULL_TREE)
30119 return NULL_TREE;
30121 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30123 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30124 tree tinfo = get_template_info (under);
30125 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30126 return alias_ctad_tweaks (tmpl, guide);
30127 return NULL_TREE;
30130 /* We might be creating a guide for a class member template, e.g.,
30132 template<typename U> struct A {
30133 template<typename T> struct B { T t; };
30136 At this point, A will have been instantiated. Below, we need to
30137 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30138 const bool member_template_p
30139 = (DECL_TEMPLATE_INFO (tmpl)
30140 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30141 tree type = TREE_TYPE (tmpl);
30142 tree template_type = (member_template_p
30143 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30144 : type);
30145 if (!CP_AGGREGATE_TYPE_P (template_type))
30146 return NULL_TREE;
30148 /* No aggregate candidate for copy-initialization. */
30149 if (args->length() == 1)
30151 tree val = (*args)[0];
30152 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30153 return NULL_TREE;
30156 /* If we encounter a problem, we just won't add the candidate. */
30157 tsubst_flags_t complain = tf_none;
30159 tree parms = NULL_TREE;
30160 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30162 init = reshape_init (template_type, init, complain);
30163 if (init == error_mark_node)
30164 return NULL_TREE;
30165 parms = collect_ctor_idx_types (init, parms);
30166 /* If we're creating a deduction guide for a member class template,
30167 we've used the original template pattern type for the reshape_init
30168 above; this is done because we want PARMS to be a template parameter
30169 type, something that can be deduced when used as a function template
30170 parameter. At this point the outer class template has already been
30171 partially instantiated (we deferred the deduction until the enclosing
30172 scope is non-dependent). Therefore we have to partially instantiate
30173 PARMS, so that its template level is properly reduced and we don't get
30174 mismatches when deducing types using the guide with PARMS. */
30175 if (member_template_p)
30177 ++processing_template_decl;
30178 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30179 --processing_template_decl;
30182 else if (TREE_CODE (init) == TREE_LIST)
30184 int len = list_length (init);
30185 for (tree field = TYPE_FIELDS (type);
30186 len;
30187 --len, field = DECL_CHAIN (field))
30189 field = next_aggregate_field (field);
30190 if (!field)
30191 return NULL_TREE;
30192 tree ftype = finish_decltype_type (field, true, complain);
30193 parms = tree_cons (NULL_TREE, ftype, parms);
30196 else
30197 /* Aggregate initialization doesn't apply to an initializer expression. */
30198 return NULL_TREE;
30200 if (parms)
30202 tree last = parms;
30203 parms = nreverse (parms);
30204 TREE_CHAIN (last) = void_list_node;
30205 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30206 return guide;
30209 return NULL_TREE;
30212 /* UGUIDES are the deduction guides for the underlying template of alias
30213 template TMPL; adjust them to be deduction guides for TMPL. */
30215 static tree
30216 alias_ctad_tweaks (tree tmpl, tree uguides)
30218 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30219 class type (9.2.8.2) where the template-name names an alias template A,
30220 the defining-type-id of A must be of the form
30222 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30224 as specified in 9.2.8.2. The guides of A are the set of functions or
30225 function templates formed as follows. For each function or function
30226 template f in the guides of the template named by the simple-template-id
30227 of the defining-type-id, the template arguments of the return type of f
30228 are deduced from the defining-type-id of A according to the process in
30229 13.10.2.5 with the exception that deduction does not fail if not all
30230 template arguments are deduced. Let g denote the result of substituting
30231 these deductions into f. If substitution succeeds, form a function or
30232 function template f' with the following properties and add it to the set
30233 of guides of A:
30235 * The function type of f' is the function type of g.
30237 * If f is a function template, f' is a function template whose template
30238 parameter list consists of all the template parameters of A (including
30239 their default template arguments) that appear in the above deductions or
30240 (recursively) in their default template arguments, followed by the
30241 template parameters of f that were not deduced (including their default
30242 template arguments), otherwise f' is not a function template.
30244 * The associated constraints (13.5.2) are the conjunction of the
30245 associated constraints of g and a constraint that is satisfied if and only
30246 if the arguments of A are deducible (see below) from the return type.
30248 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30249 be so as well.
30251 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30252 considered to be so as well.
30254 * The explicit-specifier of f' is the explicit-specifier of g (if
30255 any). */
30257 tsubst_flags_t complain = tf_warning_or_error;
30258 tree atype = TREE_TYPE (tmpl);
30259 tree aguides = NULL_TREE;
30260 tree fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30261 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30262 unsigned natparms = TREE_VEC_LENGTH (atparms);
30263 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30264 for (ovl_iterator iter (uguides); iter; ++iter)
30266 tree f = *iter;
30267 tree in_decl = f;
30268 location_t loc = DECL_SOURCE_LOCATION (f);
30269 tree ret = TREE_TYPE (TREE_TYPE (f));
30270 tree fprime = f;
30271 if (TREE_CODE (f) == TEMPLATE_DECL)
30273 processing_template_decl_sentinel ptds (/*reset*/false);
30274 ++processing_template_decl;
30276 /* Deduce template arguments for f from the type-id of A. */
30277 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30278 unsigned len = TREE_VEC_LENGTH (ftparms);
30279 tree targs = make_tree_vec (len);
30280 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30281 if (err)
30282 /* CWG2664: Discard any deductions, still build the guide. */
30283 for (unsigned i = 0; i < len; ++i)
30284 TREE_VEC_ELT (targs, i) = NULL_TREE;
30286 /* The number of parms for f' is the number of parms of A used in
30287 the deduced arguments plus non-deduced parms of f. */
30288 unsigned ndlen = 0;
30289 unsigned j;
30290 for (unsigned i = 0; i < len; ++i)
30291 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30292 ++ndlen;
30293 find_template_parameter_info ftpi (fullatparms);
30294 ftpi.find_in_recursive (targs);
30295 unsigned nusedatparms = ftpi.num_found ();
30296 unsigned nfparms = nusedatparms + ndlen;
30297 tree gtparms = make_tree_vec (nfparms);
30299 /* Set current_template_parms as in build_deduction_guide. */
30300 auto ctp = make_temp_override (current_template_parms);
30301 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
30302 TREE_VALUE (current_template_parms) = gtparms;
30304 j = 0;
30305 unsigned level = 1;
30307 /* First copy over the used parms of A. */
30308 tree atargs = make_tree_vec (natparms);
30309 for (unsigned i = 0; i < natparms; ++i)
30311 tree elt = TREE_VEC_ELT (atparms, i);
30312 if (ftpi.found (elt))
30314 unsigned index = j++;
30315 tree nelt = rewrite_tparm_list (elt, index, level,
30316 atargs, i, complain);
30317 TREE_VEC_ELT (gtparms, index) = nelt;
30320 gcc_checking_assert (j == nusedatparms);
30322 /* Adjust the deduced template args for f to refer to the A parms
30323 with their new indexes. */
30324 if (nusedatparms && nusedatparms != natparms)
30325 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30327 /* Now rewrite the non-deduced parms of f. */
30328 for (unsigned i = 0; ndlen && i < len; ++i)
30329 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30331 --ndlen;
30332 unsigned index = j++;
30333 tree oldlist = TREE_VEC_ELT (ftparms, i);
30334 tree list = rewrite_tparm_list (oldlist, index, level,
30335 targs, i, complain);
30336 TREE_VEC_ELT (gtparms, index) = list;
30338 gtparms = build_tree_list (size_one_node, gtparms);
30340 /* Substitute the deduced arguments plus the rewritten template
30341 parameters into f to get g. This covers the type, copyness,
30342 guideness, and explicit-specifier. */
30343 tree g;
30345 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30346 if cp_unevaluated_operand. */
30347 cp_evaluated ev;
30348 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
30350 if (g == error_mark_node)
30351 continue;
30352 if (nfparms == 0)
30354 /* The targs are all non-dependent, so g isn't a template. */
30355 fprime = g;
30356 ret = TREE_TYPE (TREE_TYPE (fprime));
30357 goto non_template;
30359 DECL_USE_TEMPLATE (g) = 0;
30360 fprime = build_template_decl (g, gtparms, false);
30361 DECL_TEMPLATE_RESULT (fprime) = g;
30362 TREE_TYPE (fprime) = TREE_TYPE (g);
30363 tree gtargs = template_parms_to_args (gtparms);
30364 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30365 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30367 /* Substitute the associated constraints. */
30368 tree ci = get_constraints (f);
30369 if (ci)
30370 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30371 if (ci == error_mark_node)
30372 continue;
30374 /* Add a constraint that the return type matches the instantiation of
30375 A with the same template arguments. */
30376 ret = TREE_TYPE (TREE_TYPE (fprime));
30377 if (!same_type_p (atype, ret)
30378 /* FIXME this should mean they don't compare as equivalent. */
30379 || dependent_alias_template_spec_p (atype, nt_opaque))
30381 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30382 ci = append_constraint (ci, same);
30385 if (ci)
30387 remove_constraints (fprime);
30388 set_constraints (fprime, ci);
30391 else
30393 /* For a non-template deduction guide, if the arguments of A aren't
30394 deducible from the return type, don't add the candidate. */
30395 non_template:
30396 if (!type_targs_deducible_from (tmpl, ret))
30397 continue;
30400 aguides = lookup_add (fprime, aguides);
30403 return aguides;
30406 /* True iff template arguments for TMPL can be deduced from TYPE.
30407 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30408 [over.match.class.deduct].
30410 This check is specified in terms of partial specialization, so the behavior
30411 should be parallel to that of get_partial_spec_bindings. */
30413 bool
30414 type_targs_deducible_from (tree tmpl, tree type)
30416 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30417 int len = TREE_VEC_LENGTH (tparms);
30418 tree targs = make_tree_vec (len);
30419 bool tried_array_deduction = (cxx_dialect < cxx17);
30421 /* If tmpl is a class template, this is trivial: it's deducible if TYPE is a
30422 specialization of TMPL. */
30423 if (DECL_CLASS_TEMPLATE_P (tmpl))
30424 return (CLASS_TYPE_P (type)
30425 && CLASSTYPE_TEMPLATE_INFO (type)
30426 && CLASSTYPE_TI_TEMPLATE (type) == tmpl);
30428 /* Otherwise it's an alias template. */
30429 again:
30430 if (unify (tparms, targs, TREE_TYPE (tmpl), type,
30431 UNIFY_ALLOW_NONE, false))
30432 return false;
30434 /* We don't fail on an undeduced targ the second time through (like
30435 get_partial_spec_bindings) because we're going to try defaults. */
30436 for (int i = 0; i < len; ++i)
30437 if (! TREE_VEC_ELT (targs, i))
30439 tree tparm = TREE_VEC_ELT (tparms, i);
30440 tparm = TREE_VALUE (tparm);
30442 if (!tried_array_deduction
30443 && TREE_CODE (tparm) == TYPE_DECL)
30445 try_array_deduction (tparms, targs, TREE_TYPE (tmpl));
30446 tried_array_deduction = true;
30447 if (TREE_VEC_ELT (targs, i))
30448 goto again;
30450 /* If the type parameter is a parameter pack, then it will be deduced
30451 to an empty parameter pack. This is another case that doesn't model
30452 well as partial specialization. */
30453 if (template_parameter_pack_p (tparm))
30455 tree arg;
30456 if (TREE_CODE (tparm) == PARM_DECL)
30458 arg = make_node (NONTYPE_ARGUMENT_PACK);
30459 TREE_CONSTANT (arg) = 1;
30461 else
30462 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30463 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30464 TREE_VEC_ELT (targs, i) = arg;
30468 /* Maybe add in default template args. This seems like a flaw in the
30469 specification in terms of partial specialization, since it says the
30470 partial specialization has the the template parameter list of A, but a
30471 partial specialization can't have default targs. */
30472 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30473 if (targs == error_mark_node)
30474 return false;
30476 /* I believe we don't need the template_template_parm_bindings_ok_p call
30477 because coerce_template_parms did coerce_template_template_parms. */
30479 return constraints_satisfied_p (tmpl, targs);
30482 /* Return artificial deduction guides built from the constructors of class
30483 template TMPL. */
30485 static tree
30486 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30488 tree outer_args = outer_template_args (tmpl);
30489 tree type = TREE_TYPE (most_general_template (tmpl));
30491 tree cands = NULL_TREE;
30493 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30495 /* Skip inherited constructors. */
30496 if (iter.using_p ())
30497 continue;
30499 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30500 cands = lookup_add (guide, cands);
30503 /* Add implicit default constructor deduction guide. */
30504 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30506 tree guide = build_deduction_guide (type, type, outer_args,
30507 complain);
30508 cands = lookup_add (guide, cands);
30511 /* Add copy guide. */
30513 tree gtype = build_reference_type (type);
30514 tree guide = build_deduction_guide (type, gtype, outer_args,
30515 complain);
30516 cands = lookup_add (guide, cands);
30519 return cands;
30522 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30524 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30525 aggregate candidate is added separately because it depends on the
30526 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30527 guide. */
30529 static tree
30530 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30532 tree guides = NULL_TREE;
30533 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30535 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30536 tree tinfo = get_template_info (under);
30537 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30538 complain);
30540 else
30542 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30543 dguide_name (tmpl),
30544 LOOK_want::NORMAL, /*complain*/false);
30545 if (guides == error_mark_node)
30546 guides = NULL_TREE;
30547 else
30548 any_dguides_p = true;
30551 /* Cache the deduction guides for a template. We also remember the result of
30552 lookup, and rebuild everything if it changes; should be very rare. */
30553 tree_pair_p cache = NULL;
30554 if (tree_pair_p &r
30555 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30557 cache = r;
30558 if (cache->purpose == guides)
30559 return cache->value;
30561 else
30563 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30564 cache->purpose = guides;
30567 tree cands = NULL_TREE;
30568 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30569 cands = alias_ctad_tweaks (tmpl, guides);
30570 else
30572 cands = ctor_deduction_guides_for (tmpl, complain);
30573 for (ovl_iterator it (guides); it; ++it)
30574 cands = lookup_add (*it, cands);
30577 cache->value = cands;
30578 return cands;
30581 /* Return whether TMPL is a (class template argument-) deducible template. */
30583 bool
30584 ctad_template_p (tree tmpl)
30586 /* A deducible template is either a class template or is an alias template
30587 whose defining-type-id is of the form
30589 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30591 where the nested-name-specifier (if any) is non-dependent and the
30592 template-name of the simple-template-id names a deducible template. */
30594 if (DECL_CLASS_TEMPLATE_P (tmpl)
30595 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30596 return true;
30597 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30598 return false;
30599 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30600 if (tree tinfo = get_template_info (orig))
30601 return ctad_template_p (TI_TEMPLATE (tinfo));
30602 return false;
30605 /* Deduce template arguments for the class template placeholder PTYPE for
30606 template TMPL based on the initializer INIT, and return the resulting
30607 type. */
30609 static tree
30610 do_class_deduction (tree ptype, tree tmpl, tree init,
30611 int flags, tsubst_flags_t complain)
30613 /* We should have handled this in the caller. */
30614 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30615 return ptype;
30617 /* If the class was erroneous, don't try to deduce, because that
30618 can generate a lot of diagnostic. */
30619 if (TREE_TYPE (tmpl)
30620 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30621 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30622 return ptype;
30624 /* Wait until the enclosing scope is non-dependent. */
30625 if (DECL_CLASS_SCOPE_P (tmpl)
30626 && dependent_type_p (DECL_CONTEXT (tmpl)))
30627 return ptype;
30629 /* Initializing one placeholder from another. */
30630 if (init
30631 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30632 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30633 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30634 == TEMPLATE_PARM_INDEX)))
30635 && is_auto (TREE_TYPE (init))
30636 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30637 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30639 if (!ctad_template_p (tmpl))
30641 if (complain & tf_error)
30642 error ("non-deducible template %qT used without template arguments", tmpl);
30643 return error_mark_node;
30645 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30647 if (complain & tf_error)
30649 /* Be permissive with equivalent alias templates. */
30650 tree u = get_underlying_template (tmpl);
30651 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30652 bool complained
30653 = emit_diagnostic (dk, input_location, 0,
30654 "alias template deduction only available "
30655 "with %<-std=c++20%> or %<-std=gnu++20%>");
30656 if (u == tmpl)
30657 return error_mark_node;
30658 else if (complained)
30660 inform (input_location, "use %qD directly instead", u);
30661 tmpl = u;
30664 else
30665 return error_mark_node;
30668 /* Wait until the initializer is non-dependent. */
30669 if (type_dependent_expression_p (init))
30670 return ptype;
30672 /* Don't bother with the alias rules for an equivalent template. */
30673 tmpl = get_underlying_template (tmpl);
30675 tree type = TREE_TYPE (tmpl);
30677 bool try_list_cand = false;
30678 bool list_init_p = false;
30680 releasing_vec rv_args = NULL;
30681 vec<tree,va_gc> *&args = *&rv_args;
30682 if (init == NULL_TREE)
30683 args = make_tree_vector ();
30684 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30686 list_init_p = true;
30687 try_list_cand = true;
30688 if (CONSTRUCTOR_NELTS (init) == 1
30689 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30691 /* As an exception, the first phase in 16.3.1.7 (considering the
30692 initializer list as a single argument) is omitted if the
30693 initializer list consists of a single expression of type cv U,
30694 where U is a specialization of C or a class derived from a
30695 specialization of C. */
30696 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30697 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30698 try_list_cand = false;
30700 if (try_list_cand || is_std_init_list (type))
30701 args = make_tree_vector_single (init);
30702 else
30703 args = make_tree_vector_from_ctor (init);
30705 else if (TREE_CODE (init) == TREE_LIST)
30706 args = make_tree_vector_from_list (init);
30707 else
30708 args = make_tree_vector_single (init);
30710 /* Do this now to avoid problems with erroneous args later on. */
30711 args = resolve_args (args, complain);
30712 if (args == NULL)
30713 return error_mark_node;
30715 bool any_dguides_p = false;
30716 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30717 if (cands == error_mark_node)
30718 return error_mark_node;
30720 /* Prune explicit deduction guides in copy-initialization context (but
30721 not copy-list-initialization). */
30722 bool elided = false;
30723 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30725 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30726 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30727 elided = true;
30729 if (elided)
30731 /* Found a nonconverting guide, prune the candidates. */
30732 tree pruned = NULL_TREE;
30733 for (lkp_iterator iter (cands); iter; ++iter)
30734 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30735 pruned = lookup_add (*iter, pruned);
30737 cands = pruned;
30741 if (!any_dguides_p)
30742 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30743 cands = lookup_add (guide, cands);
30745 tree fndecl = error_mark_node;
30747 /* If this is list-initialization and the class has a list guide, first
30748 try deducing from the list as a single argument, as [over.match.list]. */
30749 if (try_list_cand)
30751 tree list_cands = NULL_TREE;
30752 for (tree dg : lkp_range (cands))
30753 if (is_list_ctor (dg))
30754 list_cands = lookup_add (dg, list_cands);
30755 if (list_cands)
30756 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30757 if (fndecl == error_mark_node)
30759 /* That didn't work, now try treating the list as a sequence of
30760 arguments. */
30761 release_tree_vector (args);
30762 args = make_tree_vector_from_ctor (init);
30763 args = resolve_args (args, complain);
30764 if (args == NULL)
30765 return error_mark_node;
30769 if (elided && !cands)
30771 error ("cannot deduce template arguments for copy-initialization"
30772 " of %qT, as it has no non-explicit deduction guides or "
30773 "user-declared constructors", type);
30774 return error_mark_node;
30776 else if (!cands && fndecl == error_mark_node)
30778 error ("cannot deduce template arguments of %qT, as it has no viable "
30779 "deduction guides", type);
30780 return error_mark_node;
30783 if (fndecl == error_mark_node)
30784 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30786 if (fndecl == error_mark_node)
30788 if (complain & tf_warning_or_error)
30790 error ("class template argument deduction failed:");
30791 perform_dguide_overload_resolution (cands, args, complain);
30792 if (elided)
30793 inform (input_location, "explicit deduction guides not considered "
30794 "for copy-initialization");
30796 return error_mark_node;
30798 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30799 constructor is chosen, the initialization is ill-formed. */
30800 else if (flags & LOOKUP_ONLYCONVERTING)
30802 if (DECL_NONCONVERTING_P (fndecl))
30804 if (complain & tf_warning_or_error)
30806 // TODO: Pass down location from cp_finish_decl.
30807 error ("class template argument deduction for %qT failed: "
30808 "explicit deduction guide selected in "
30809 "copy-list-initialization", type);
30810 inform (DECL_SOURCE_LOCATION (fndecl),
30811 "explicit deduction guide declared here");
30814 return error_mark_node;
30818 /* If CTAD succeeded but the type doesn't have any explicit deduction
30819 guides, this deduction might not be what the user intended. */
30820 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30822 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30823 || global_dc->dc_warn_system_headers)
30824 && warning (OPT_Wctad_maybe_unsupported,
30825 "%qT may not intend to support class template argument "
30826 "deduction", type))
30827 inform (input_location, "add a deduction guide to suppress this "
30828 "warning");
30831 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30832 cp_type_quals (ptype));
30835 /* Return true if INIT is an unparenthesized id-expression or an
30836 unparenthesized class member access. Used for the argument of
30837 decltype(auto). */
30839 bool
30840 unparenthesized_id_or_class_member_access_p (tree init)
30842 STRIP_ANY_LOCATION_WRAPPER (init);
30844 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30845 reference type). Only the latter is an id-expression. */
30846 if (REFERENCE_REF_P (init)
30847 && !REF_PARENTHESIZED_P (init))
30848 init = TREE_OPERAND (init, 0);
30849 return (DECL_P (init)
30850 || ((TREE_CODE (init) == COMPONENT_REF
30851 || TREE_CODE (init) == SCOPE_REF)
30852 && !REF_PARENTHESIZED_P (init)));
30855 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30856 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30857 The CONTEXT determines the context in which auto deduction is performed
30858 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30860 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30861 to properly substitute the result. It's also used in the adc_unify and
30862 adc_requirement contexts to communicate the necessary template arguments
30863 to satisfaction. OUTER_TARGS is ignored in other contexts.
30865 Additionally for adc_unify contexts TMPL is the template for which TYPE
30866 is a template parameter type.
30868 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30869 scope may be appended to the list of deduced template arguments prior to
30870 determining constraint satisfaction as appropriate. */
30872 tree
30873 do_auto_deduction (tree type, tree init, tree auto_node,
30874 tsubst_flags_t complain /* = tf_warning_or_error */,
30875 auto_deduction_context context /* = adc_unspecified */,
30876 tree outer_targs /* = NULL_TREE */,
30877 int flags /* = LOOKUP_NORMAL */,
30878 tree tmpl /* = NULL_TREE */)
30880 if (type == error_mark_node || init == error_mark_node)
30881 return error_mark_node;
30883 if (init && type_dependent_expression_p (init)
30884 && context != adc_unify)
30885 /* Defining a subset of type-dependent expressions that we can deduce
30886 from ahead of time isn't worth the trouble. */
30887 return type;
30889 /* Similarly, we can't deduce from another undeduced decl. */
30890 if (init && undeduced_auto_decl (init))
30891 return type;
30893 /* We may be doing a partial substitution, but we still want to replace
30894 auto_node. */
30895 complain &= ~tf_partial;
30897 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30899 /* We don't recurse here because we can't deduce from a nested
30900 initializer_list. */
30901 if (CONSTRUCTOR_ELTS (init))
30902 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30903 elt.value = resolve_nondeduced_context (elt.value, complain);
30905 else if (init)
30906 init = resolve_nondeduced_context (init, complain);
30908 /* In C++23, we must deduce the type to int&& for code like
30909 decltype(auto) f(int&& x) { return (x); }
30911 auto&& f(int x) { return x; }
30912 so we use treat_lvalue_as_rvalue_p. But don't do it for
30913 decltype(auto) f(int x) { return x; }
30914 where we should deduce 'int' rather than 'int&&'; transmogrifying
30915 INIT to an rvalue would break that. */
30916 tree r;
30917 if (cxx_dialect >= cxx23
30918 && context == adc_return_type
30919 && (!AUTO_IS_DECLTYPE (auto_node)
30920 || !unparenthesized_id_or_class_member_access_p (init))
30921 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30922 /*return*/true)))
30923 init = r;
30925 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30926 /* C++17 class template argument deduction. */
30927 return do_class_deduction (type, ctmpl, init, flags, complain);
30929 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30930 /* Nothing we can do with this, even in deduction context. */
30931 return type;
30933 location_t loc = cp_expr_loc_or_input_loc (init);
30935 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30936 with either a new invented type template parameter U or, if the
30937 initializer is a braced-init-list (8.5.4), with
30938 std::initializer_list<U>. */
30939 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30941 if (!DIRECT_LIST_INIT_P (init))
30942 type = listify_autos (type, auto_node);
30943 else if (CONSTRUCTOR_NELTS (init) == 1)
30944 init = CONSTRUCTOR_ELT (init, 0)->value;
30945 else
30947 if (complain & tf_warning_or_error)
30949 if (permerror (loc, "direct-list-initialization of "
30950 "%<auto%> requires exactly one element"))
30951 inform (loc,
30952 "for deduction to %<std::initializer_list%>, use copy-"
30953 "list-initialization (i.e. add %<=%> before the %<{%>)");
30955 type = listify_autos (type, auto_node);
30959 if (type == error_mark_node || init == error_mark_node)
30960 return error_mark_node;
30962 tree targs;
30963 if (context == adc_decomp_type
30964 && auto_node == type
30965 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30967 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30968 and initializer has array type, deduce cv-qualified array type. */
30969 targs = make_tree_vec (1);
30970 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30972 else if (AUTO_IS_DECLTYPE (auto_node))
30974 const bool id = unparenthesized_id_or_class_member_access_p (init);
30975 tree deduced = finish_decltype_type (init, id, complain);
30976 deduced = canonicalize_type_argument (deduced, complain);
30977 if (deduced == error_mark_node)
30978 return error_mark_node;
30979 targs = make_tree_vec (1);
30980 TREE_VEC_ELT (targs, 0) = deduced;
30982 else
30984 if (error_operand_p (init))
30985 return error_mark_node;
30987 tree parms = build_tree_list (NULL_TREE, type);
30988 tree tparms;
30990 if (flag_concepts_ts)
30991 tparms = extract_autos (type);
30992 else
30994 tparms = make_tree_vec (1);
30995 TREE_VEC_ELT (tparms, 0)
30996 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30999 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
31000 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
31001 DEDUCE_CALL,
31002 NULL, /*explain_p=*/false);
31003 if (val > 0)
31005 if (processing_template_decl)
31006 /* Try again at instantiation time. */
31007 return type;
31008 if (type && type != error_mark_node
31009 && (complain & tf_error))
31010 /* If type is error_mark_node a diagnostic must have been
31011 emitted by now. Also, having a mention to '<type error>'
31012 in the diagnostic is not really useful to the user. */
31014 if (cfun
31015 && FNDECL_USED_AUTO (current_function_decl)
31016 && (auto_node
31017 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
31018 && LAMBDA_FUNCTION_P (current_function_decl))
31019 error_at (loc, "unable to deduce lambda return type from %qE",
31020 init);
31021 else
31022 error_at (loc, "unable to deduce %qT from %qE", type, init);
31023 type_unification_real (tparms, targs, parms, &init, 1, 0,
31024 DEDUCE_CALL,
31025 NULL, /*explain_p=*/true);
31027 return error_mark_node;
31031 /* Check any placeholder constraints against the deduced type. */
31032 if (processing_template_decl && context == adc_unify)
31033 /* Constraints will be checked after deduction. */;
31034 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
31036 if (processing_template_decl)
31038 gcc_checking_assert (context == adc_variable_type
31039 || context == adc_return_type
31040 || context == adc_decomp_type);
31041 gcc_checking_assert (!type_dependent_expression_p (init));
31042 /* If the constraint is dependent, we need to wait until
31043 instantiation time to resolve the placeholder. */
31044 if (placeholder_type_constraint_dependent_p (constr))
31045 return type;
31048 if (context == adc_return_type
31049 || context == adc_variable_type
31050 || context == adc_decomp_type)
31051 if (tree fn = current_function_decl)
31052 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
31054 outer_targs = DECL_TEMPLATE_INFO (fn)
31055 ? DECL_TI_ARGS (fn) : NULL_TREE;
31056 if (LAMBDA_FUNCTION_P (fn))
31058 /* As in satisfy_declaration_constraints. */
31059 tree regen_args = lambda_regenerating_args (fn);
31060 if (outer_targs)
31061 outer_targs = add_to_template_args (regen_args, outer_targs);
31062 else
31063 outer_targs = regen_args;
31067 tree full_targs = outer_targs;
31068 if (context == adc_unify && tmpl)
31069 full_targs = add_outermost_template_args (tmpl, full_targs);
31070 full_targs = add_to_template_args (full_targs, targs);
31072 /* HACK: Compensate for callers not always communicating all levels of
31073 outer template arguments by filling in the outermost missing levels
31074 with dummy levels before checking satisfaction. We'll still crash
31075 if the constraint depends on a template argument belonging to one of
31076 these missing levels, but this hack otherwise allows us to handle a
31077 large subset of possible constraints (including all non-dependent
31078 constraints). */
31079 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
31080 - TMPL_ARGS_DEPTH (full_targs)))
31082 tree dummy_levels = make_tree_vec (missing_levels);
31083 for (int i = 0; i < missing_levels; ++i)
31084 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
31085 full_targs = add_to_template_args (dummy_levels, full_targs);
31088 if (!constraints_satisfied_p (auto_node, full_targs))
31090 if (complain & tf_warning_or_error)
31092 auto_diagnostic_group d;
31093 switch (context)
31095 case adc_unspecified:
31096 case adc_unify:
31097 error_at (loc, "placeholder constraints not satisfied");
31098 break;
31099 case adc_variable_type:
31100 case adc_decomp_type:
31101 error_at (loc, "deduced initializer does not satisfy "
31102 "placeholder constraints");
31103 break;
31104 case adc_return_type:
31105 error_at (loc, "deduced return type does not satisfy "
31106 "placeholder constraints");
31107 break;
31108 case adc_requirement:
31109 error_at (loc, "deduced expression type does not satisfy "
31110 "placeholder constraints");
31111 break;
31113 diagnose_constraints (loc, auto_node, full_targs);
31115 return error_mark_node;
31119 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31120 /* The outer template arguments are already substituted into type
31121 (but we still may have used them for constraint checking above). */;
31122 else if (context == adc_unify)
31123 targs = add_to_template_args (outer_targs, targs);
31124 else if (processing_template_decl)
31125 targs = add_to_template_args (current_template_args (), targs);
31126 return tsubst (type, targs, complain, NULL_TREE);
31129 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31130 result. */
31132 tree
31133 splice_late_return_type (tree type, tree late_return_type)
31135 if (late_return_type)
31137 gcc_assert (is_auto (type) || seen_error ());
31138 return late_return_type;
31141 if (tree auto_node = find_type_usage (type, is_auto))
31142 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31144 /* In an abbreviated function template we didn't know we were dealing
31145 with a function template when we saw the auto return type, so rebuild
31146 the return type using an auto with the correct level. */
31147 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31148 tree auto_vec = make_tree_vec (1);
31149 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31150 tree targs = add_outermost_template_args (current_template_args (),
31151 auto_vec);
31152 /* Also rebuild the constraint info in terms of the new auto. */
31153 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31154 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31155 = build_tree_list (current_template_parms,
31156 tsubst_constraint (TREE_VALUE (ci), targs,
31157 tf_none, NULL_TREE));
31158 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31159 return tsubst (type, targs, tf_none, NULL_TREE);
31161 return type;
31164 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31165 'decltype(auto)' or a deduced class template. */
31167 bool
31168 is_auto (const_tree type)
31170 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31171 && (TYPE_IDENTIFIER (type) == auto_identifier
31172 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31173 return true;
31174 else
31175 return false;
31178 /* for_each_template_parm callback for type_uses_auto. */
31181 is_auto_r (tree tp, void */*data*/)
31183 return is_auto (tp);
31186 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31187 a use of `auto'. Returns NULL_TREE otherwise. */
31189 tree
31190 type_uses_auto (tree type)
31192 if (type == NULL_TREE)
31193 return NULL_TREE;
31195 /* For parameter packs, check the contents of the pack. */
31196 if (PACK_EXPANSION_P (type))
31197 type = PACK_EXPANSION_PATTERN (type);
31199 if (flag_concepts_ts)
31201 /* The Concepts TS allows multiple autos in one type-specifier; just
31202 return the first one we find, do_auto_deduction will collect all of
31203 them. */
31204 if (uses_template_parms (type))
31205 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31206 /*visited*/NULL, /*nondeduced*/false);
31207 else
31208 return NULL_TREE;
31210 else
31211 return find_type_usage (type, is_auto);
31214 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31215 concepts are enabled, auto is acceptable in template arguments, but
31216 only when TEMPL identifies a template class. Return TRUE if any
31217 such errors were reported. */
31219 bool
31220 check_auto_in_tmpl_args (tree tmpl, tree args)
31222 if (!flag_concepts_ts)
31223 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31224 have already been rejected by the parser more generally. */
31225 return false;
31227 /* If there were previous errors, nevermind. */
31228 if (!args || TREE_CODE (args) != TREE_VEC)
31229 return false;
31231 /* If TMPL is an identifier, we're parsing and we can't tell yet
31232 whether TMPL is supposed to be a type, a function or a variable.
31233 We'll only be able to tell during template substitution, so we
31234 expect to be called again then. If concepts are enabled and we
31235 know we have a type, we're ok. */
31236 if (identifier_p (tmpl)
31237 || (DECL_P (tmpl)
31238 && (DECL_TYPE_TEMPLATE_P (tmpl)
31239 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31240 return false;
31242 /* Quickly search for any occurrences of auto; usually there won't
31243 be any, and then we'll avoid allocating the vector. */
31244 if (!type_uses_auto (args))
31245 return false;
31247 bool errors = false;
31249 tree vec = extract_autos (args);
31250 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31252 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31253 error_at (DECL_SOURCE_LOCATION (xauto),
31254 "invalid use of %qT in template argument", xauto);
31255 errors = true;
31258 return errors;
31261 /* Recursively walk over && expressions searching for EXPR. Return a reference
31262 to that expression. */
31264 static tree *find_template_requirement (tree *t, tree key)
31266 if (*t == key)
31267 return t;
31268 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31270 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31271 return p;
31272 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31273 return p;
31275 return 0;
31278 /* Convert the generic type parameters in PARM that match the types given in the
31279 range [START_IDX, END_IDX) from the current_template_parms into generic type
31280 packs. */
31282 tree
31283 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31285 tree current = current_template_parms;
31286 int depth = TMPL_PARMS_DEPTH (current);
31287 current = INNERMOST_TEMPLATE_PARMS (current);
31288 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31290 for (int i = 0; i < start_idx; ++i)
31291 TREE_VEC_ELT (replacement, i)
31292 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31294 for (int i = start_idx; i < end_idx; ++i)
31296 /* Create a distinct parameter pack type from the current parm and add it
31297 to the replacement args to tsubst below into the generic function
31298 parameter. */
31299 tree node = TREE_VEC_ELT (current, i);
31300 tree o = TREE_TYPE (TREE_VALUE (node));
31301 tree t = copy_type (o);
31302 TEMPLATE_TYPE_PARM_INDEX (t)
31303 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31304 t, 0, 0, tf_none);
31305 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31306 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31307 TYPE_MAIN_VARIANT (t) = t;
31308 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31309 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31310 TREE_VEC_ELT (replacement, i) = t;
31312 /* Replace the current template parameter with new pack. */
31313 TREE_VALUE (node) = TREE_CHAIN (t);
31315 /* Surgically adjust the associated constraint of adjusted parameter
31316 and it's corresponding contribution to the current template
31317 requirements. */
31318 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31320 tree id = unpack_concept_check (constr);
31321 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31322 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
31323 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31325 /* If there was a constraint, we also need to replace that in
31326 the template requirements, which we've already built. */
31327 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31328 reqs = find_template_requirement (reqs, constr);
31329 *reqs = fold;
31333 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31334 TREE_VEC_ELT (replacement, i)
31335 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31337 /* If there are more levels then build up the replacement with the outer
31338 template parms. */
31339 if (depth > 1)
31340 replacement = add_to_template_args (template_parms_to_args
31341 (TREE_CHAIN (current_template_parms)),
31342 replacement);
31344 return tsubst (parm, replacement, tf_none, NULL_TREE);
31347 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31348 0..N-1. */
31350 void
31351 declare_integer_pack (void)
31353 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31354 build_function_type_list (integer_type_node,
31355 integer_type_node,
31356 NULL_TREE),
31357 NULL_TREE, ECF_CONST);
31358 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31359 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31360 CP_BUILT_IN_INTEGER_PACK);
31363 /* Walk the decl or type specialization table calling FN on each
31364 entry. */
31366 void
31367 walk_specializations (bool decls_p,
31368 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31369 void *data)
31371 spec_hash_table *table = decls_p ? decl_specializations
31372 : type_specializations;
31373 spec_hash_table::iterator end (table->end ());
31374 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31375 fn (decls_p, *iter, data);
31378 /* Lookup the specialization of *ELT, in the decl or type
31379 specialization table. Return the SPEC that's already there, or
31380 NULL if nothing. */
31382 tree
31383 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31385 hash_table<spec_hasher> *specializations
31386 = decl_p ? decl_specializations : type_specializations;
31387 hashval_t hash = spec_hasher::hash (elt);
31388 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31390 if (slot)
31391 return (*slot)->spec;
31393 return NULL_TREE;
31396 /* Return flags encoding whether SPEC is on the instantiation and/or
31397 specialization lists of TMPL. */
31399 unsigned
31400 get_mergeable_specialization_flags (tree tmpl, tree decl)
31402 unsigned flags = 0;
31404 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31405 inst; inst = TREE_CHAIN (inst))
31406 if (TREE_VALUE (inst) == decl)
31408 flags |= 1;
31409 break;
31412 if (CLASS_TYPE_P (TREE_TYPE (decl))
31413 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31414 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31415 /* Only need to search if DECL is a partial specialization. */
31416 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31417 part; part = TREE_CHAIN (part))
31418 if (TREE_VALUE (part) == decl)
31420 flags |= 2;
31421 break;
31424 return flags;
31427 /* Add a new specialization described by SPEC. DECL is the
31428 maybe-template decl and FLAGS is as returned from
31429 get_mergeable_specialization_flags. */
31431 void
31432 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31433 tree decl, unsigned flags)
31435 hashval_t hash = spec_hasher::hash (elt);
31436 if (decl_p)
31438 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31440 gcc_checking_assert (!*slot);
31441 auto entry = ggc_alloc<spec_entry> ();
31442 *entry = *elt;
31443 *slot = entry;
31445 if (alias_p)
31447 elt->spec = TREE_TYPE (elt->spec);
31448 gcc_checking_assert (elt->spec);
31452 if (!decl_p || alias_p)
31454 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31456 /* We don't distinguish different constrained partial type
31457 specializations, so there could be duplicates. Everything else
31458 must be new. */
31459 if (!(flags & 2 && *slot))
31461 gcc_checking_assert (!*slot);
31463 auto entry = ggc_alloc<spec_entry> ();
31464 *entry = *elt;
31465 *slot = entry;
31469 if (flags & 1)
31470 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31471 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31473 if (flags & 2)
31475 /* A partial specialization. */
31476 tree cons = tree_cons (elt->args, decl,
31477 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31478 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31479 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31483 /* Set up the hash tables for template instantiations. */
31485 void
31486 init_template_processing (void)
31488 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31489 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31491 if (cxx_dialect >= cxx11)
31492 declare_integer_pack ();
31495 /* Print stats about the template hash tables for -fstats. */
31497 void
31498 print_template_statistics (void)
31500 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31501 "%f collisions\n", (long) decl_specializations->size (),
31502 (long) decl_specializations->elements (),
31503 decl_specializations->collisions ());
31504 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31505 "%f collisions\n", (long) type_specializations->size (),
31506 (long) type_specializations->elements (),
31507 type_specializations->collisions ());
31510 #if CHECKING_P
31512 namespace selftest {
31514 /* Verify that build_non_dependent_expr () works, for various expressions,
31515 and that location wrappers don't affect the results. */
31517 static void
31518 test_build_non_dependent_expr ()
31520 location_t loc = BUILTINS_LOCATION;
31522 /* Verify constants, without and with location wrappers. */
31523 tree int_cst = build_int_cst (integer_type_node, 42);
31524 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
31526 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
31527 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
31528 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
31530 tree string_lit = build_string (4, "foo");
31531 TREE_TYPE (string_lit) = char_array_type_node;
31532 string_lit = fix_string_type (string_lit);
31533 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
31535 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
31536 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
31537 ASSERT_EQ (wrapped_string_lit,
31538 build_non_dependent_expr (wrapped_string_lit));
31541 /* Verify that type_dependent_expression_p () works correctly, even
31542 in the presence of location wrapper nodes. */
31544 static void
31545 test_type_dependent_expression_p ()
31547 location_t loc = BUILTINS_LOCATION;
31549 tree name = get_identifier ("foo");
31551 /* If no templates are involved, nothing is type-dependent. */
31552 gcc_assert (!processing_template_decl);
31553 ASSERT_FALSE (type_dependent_expression_p (name));
31555 ++processing_template_decl;
31557 /* Within a template, an unresolved name is always type-dependent. */
31558 ASSERT_TRUE (type_dependent_expression_p (name));
31560 /* Ensure it copes with NULL_TREE and errors. */
31561 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31562 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31564 /* A USING_DECL in a template should be type-dependent, even if wrapped
31565 with a location wrapper (PR c++/83799). */
31566 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31567 TREE_TYPE (using_decl) = integer_type_node;
31568 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31569 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31570 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31571 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31573 --processing_template_decl;
31576 /* Run all of the selftests within this file. */
31578 void
31579 cp_pt_cc_tests ()
31581 test_build_non_dependent_expr ();
31582 test_type_dependent_expression_p ();
31585 } // namespace selftest
31587 #endif /* #if CHECKING_P */
31589 #include "gt-cp-pt.h"