typeck.c (cp_build_binary_op): Do not handle RROTATE_EXPR and LROTATE_EXPR.
[official-gcc.git] / gcc / cp / pt.c
blob7fecc03f6cc3aff1a7e582f06207693c73952006
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2019 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 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "cp-tree.h"
31 #include "timevar.h"
32 #include "stringpool.h"
33 #include "varasm.h"
34 #include "attribs.h"
35 #include "stor-layout.h"
36 #include "intl.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "toplev.h"
40 #include "tree-iterator.h"
41 #include "type-utils.h"
42 #include "gimplify.h"
43 #include "gcc-rich-location.h"
44 #include "selftest.h"
46 /* The type of functions taking a tree, and some additional data, and
47 returning an int. */
48 typedef int (*tree_fn_t) (tree, void*);
50 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
51 instantiations have been deferred, either because their definitions
52 were not yet available, or because we were putting off doing the work. */
53 struct GTY ((chain_next ("%h.next"))) pending_template
55 struct pending_template *next;
56 struct tinst_level *tinst;
59 static GTY(()) struct pending_template *pending_templates;
60 static GTY(()) struct pending_template *last_pending_template;
62 int processing_template_parmlist;
63 static int template_header_count;
65 static GTY(()) tree saved_trees;
66 static vec<int> inline_parm_levels;
68 static GTY(()) struct tinst_level *current_tinst_level;
70 static GTY(()) vec<tree, va_gc> *saved_access_scope;
72 /* Live only within one (recursive) call to tsubst_expr. We use
73 this to pass the statement expression node from the STMT_EXPR
74 to the EXPR_STMT that is its result. */
75 static tree cur_stmt_expr;
77 // -------------------------------------------------------------------------- //
78 // Local Specialization Stack
80 // Implementation of the RAII helper for creating new local
81 // specializations.
82 local_specialization_stack::local_specialization_stack (lss_policy policy)
83 : saved (local_specializations)
85 if (policy == lss_blank || !saved)
86 local_specializations = new hash_map<tree, tree>;
87 else
88 local_specializations = new hash_map<tree, tree>(*saved);
91 local_specialization_stack::~local_specialization_stack ()
93 delete local_specializations;
94 local_specializations = saved;
97 /* True if we've recursed into fn_type_unification too many times. */
98 static bool excessive_deduction_depth;
100 struct GTY((for_user)) spec_entry
102 tree tmpl;
103 tree args;
104 tree spec;
107 struct spec_hasher : ggc_ptr_hash<spec_entry>
109 static hashval_t hash (spec_entry *);
110 static bool equal (spec_entry *, spec_entry *);
113 static GTY (()) hash_table<spec_hasher> *decl_specializations;
115 static GTY (()) hash_table<spec_hasher> *type_specializations;
117 /* Contains canonical template parameter types. The vector is indexed by
118 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
119 TREE_LIST, whose TREE_VALUEs contain the canonical template
120 parameters of various types and levels. */
121 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
123 #define UNIFY_ALLOW_NONE 0
124 #define UNIFY_ALLOW_MORE_CV_QUAL 1
125 #define UNIFY_ALLOW_LESS_CV_QUAL 2
126 #define UNIFY_ALLOW_DERIVED 4
127 #define UNIFY_ALLOW_INTEGER 8
128 #define UNIFY_ALLOW_OUTER_LEVEL 16
129 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
130 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
132 enum template_base_result {
133 tbr_incomplete_type,
134 tbr_ambiguous_baseclass,
135 tbr_success
138 static bool resolve_overloaded_unification (tree, tree, tree, tree,
139 unification_kind_t, int,
140 bool);
141 static int try_one_overload (tree, tree, tree, tree, tree,
142 unification_kind_t, int, bool, bool);
143 static int unify (tree, tree, tree, tree, int, bool);
144 static void add_pending_template (tree);
145 static tree reopen_tinst_level (struct tinst_level *);
146 static tree tsubst_initializer_list (tree, tree);
147 static tree get_partial_spec_bindings (tree, tree, tree);
148 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
149 bool, bool);
150 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
151 bool, bool);
152 static void tsubst_enum (tree, tree, tree);
153 static tree add_to_template_args (tree, tree);
154 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
155 static int check_non_deducible_conversion (tree, tree, int, int,
156 struct conversion **, bool);
157 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
158 tree);
159 static int type_unification_real (tree, tree, tree, const tree *,
160 unsigned int, int, unification_kind_t,
161 vec<deferred_access_check, va_gc> **,
162 bool);
163 static void note_template_header (int);
164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166 static tree convert_template_argument (tree, tree, tree,
167 tsubst_flags_t, int, tree);
168 static tree for_each_template_parm (tree, tree_fn_t, void*,
169 hash_set<tree> *, bool, tree_fn_t = NULL);
170 static tree expand_template_argument_pack (tree);
171 static tree build_template_parm_index (int, int, int, tree, tree);
172 static bool inline_needs_template_parms (tree, bool);
173 static void push_inline_template_parms_recursive (tree, int);
174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175 static int mark_template_parm (tree, void *);
176 static int template_parm_this_level_p (tree, void *);
177 static tree tsubst_friend_function (tree, tree);
178 static tree tsubst_friend_class (tree, tree);
179 static int can_complete_type_without_circularity (tree);
180 static tree get_bindings (tree, tree, tree, bool);
181 static int template_decl_level (tree);
182 static int check_cv_quals_for_unify (int, tree, tree);
183 static int unify_pack_expansion (tree, tree, tree,
184 tree, unification_kind_t, bool, bool);
185 static tree copy_template_args (tree);
186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
191 static bool check_specialization_scope (void);
192 static tree process_partial_specialization (tree);
193 static void set_current_access_from_decl (tree);
194 static enum template_base_result get_template_base (tree, tree, tree, tree,
195 bool , tree *);
196 static tree try_class_unification (tree, tree, tree, tree, bool);
197 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
198 tree, tree);
199 static bool template_template_parm_bindings_ok_p (tree, tree);
200 static void tsubst_default_arguments (tree, tsubst_flags_t);
201 static tree for_each_template_parm_r (tree *, int *, void *);
202 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
203 static void copy_default_args_to_explicit_spec (tree);
204 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
205 static bool dependent_template_arg_p (tree);
206 static bool any_template_arguments_need_structural_equality_p (tree);
207 static bool dependent_type_p_r (tree);
208 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_decl (tree, tree, tsubst_flags_t);
210 static void perform_typedefs_access_check (tree tmpl, tree targs);
211 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
212 location_t);
213 static tree listify (tree);
214 static tree listify_autos (tree, tree);
215 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
216 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
217 static bool complex_alias_template_p (const_tree tmpl);
218 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
219 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
220 static tree make_argument_pack (tree);
221 static void register_parameter_specializations (tree, tree);
222 static tree enclosing_instantiation_of (tree tctx);
224 /* Make the current scope suitable for access checking when we are
225 processing T. T can be FUNCTION_DECL for instantiated function
226 template, VAR_DECL for static member variable, or TYPE_DECL for
227 alias template (needed by instantiate_decl). */
229 void
230 push_access_scope (tree t)
232 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
233 || TREE_CODE (t) == TYPE_DECL);
235 if (DECL_FRIEND_CONTEXT (t))
236 push_nested_class (DECL_FRIEND_CONTEXT (t));
237 else if (DECL_CLASS_SCOPE_P (t))
238 push_nested_class (DECL_CONTEXT (t));
239 else
240 push_to_top_level ();
242 if (TREE_CODE (t) == FUNCTION_DECL)
244 vec_safe_push (saved_access_scope, current_function_decl);
245 current_function_decl = t;
249 /* Restore the scope set up by push_access_scope. T is the node we
250 are processing. */
252 void
253 pop_access_scope (tree t)
255 if (TREE_CODE (t) == FUNCTION_DECL)
256 current_function_decl = saved_access_scope->pop();
258 if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
259 pop_nested_class ();
260 else
261 pop_from_top_level ();
264 /* Do any processing required when DECL (a member template
265 declaration) is finished. Returns the TEMPLATE_DECL corresponding
266 to DECL, unless it is a specialization, in which case the DECL
267 itself is returned. */
269 tree
270 finish_member_template_decl (tree decl)
272 if (decl == error_mark_node)
273 return error_mark_node;
275 gcc_assert (DECL_P (decl));
277 if (TREE_CODE (decl) == TYPE_DECL)
279 tree type;
281 type = TREE_TYPE (decl);
282 if (type == error_mark_node)
283 return error_mark_node;
284 if (MAYBE_CLASS_TYPE_P (type)
285 && CLASSTYPE_TEMPLATE_INFO (type)
286 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
288 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
289 check_member_template (tmpl);
290 return tmpl;
292 return NULL_TREE;
294 else if (TREE_CODE (decl) == FIELD_DECL)
295 error_at (DECL_SOURCE_LOCATION (decl),
296 "data member %qD cannot be a member template", decl);
297 else if (DECL_TEMPLATE_INFO (decl))
299 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
301 check_member_template (DECL_TI_TEMPLATE (decl));
302 return DECL_TI_TEMPLATE (decl);
304 else
305 return decl;
307 else
308 error_at (DECL_SOURCE_LOCATION (decl),
309 "invalid member template declaration %qD", decl);
311 return error_mark_node;
314 /* Create a template info node. */
316 tree
317 build_template_info (tree template_decl, tree template_args)
319 tree result = make_node (TEMPLATE_INFO);
320 TI_TEMPLATE (result) = template_decl;
321 TI_ARGS (result) = template_args;
322 return result;
325 /* Return the template info node corresponding to T, whatever T is. */
327 tree
328 get_template_info (const_tree t)
330 tree tinfo = NULL_TREE;
332 if (!t || t == error_mark_node)
333 return NULL;
335 if (TREE_CODE (t) == NAMESPACE_DECL
336 || TREE_CODE (t) == PARM_DECL)
337 return NULL;
339 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
340 tinfo = DECL_TEMPLATE_INFO (t);
342 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
343 t = TREE_TYPE (t);
345 if (OVERLOAD_TYPE_P (t))
346 tinfo = TYPE_TEMPLATE_INFO (t);
347 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
348 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
350 return tinfo;
353 /* Returns the template nesting level of the indicated class TYPE.
355 For example, in:
356 template <class T>
357 struct A
359 template <class U>
360 struct B {};
363 A<T>::B<U> has depth two, while A<T> has depth one.
364 Both A<T>::B<int> and A<int>::B<U> have depth one, if
365 they are instantiations, not specializations.
367 This function is guaranteed to return 0 if passed NULL_TREE so
368 that, for example, `template_class_depth (current_class_type)' is
369 always safe. */
372 template_class_depth (tree type)
374 int depth;
376 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
378 tree tinfo = get_template_info (type);
380 if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
381 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
382 ++depth;
384 if (DECL_P (type))
385 type = CP_DECL_CONTEXT (type);
386 else if (LAMBDA_TYPE_P (type))
387 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
388 else
389 type = CP_TYPE_CONTEXT (type);
392 return depth;
395 /* Return TRUE if NODE instantiates a template that has arguments of
396 its own, be it directly a primary template or indirectly through a
397 partial specializations. */
398 static bool
399 instantiates_primary_template_p (tree node)
401 tree tinfo = get_template_info (node);
402 if (!tinfo)
403 return false;
405 tree tmpl = TI_TEMPLATE (tinfo);
406 if (PRIMARY_TEMPLATE_P (tmpl))
407 return true;
409 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
410 return false;
412 /* So now we know we have a specialization, but it could be a full
413 or a partial specialization. To tell which, compare the depth of
414 its template arguments with those of its context. */
416 tree ctxt = DECL_CONTEXT (tmpl);
417 tree ctinfo = get_template_info (ctxt);
418 if (!ctinfo)
419 return true;
421 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
422 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
425 /* Subroutine of maybe_begin_member_template_processing.
426 Returns true if processing DECL needs us to push template parms. */
428 static bool
429 inline_needs_template_parms (tree decl, bool nsdmi)
431 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
432 return false;
434 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
435 > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
438 /* Subroutine of maybe_begin_member_template_processing.
439 Push the template parms in PARMS, starting from LEVELS steps into the
440 chain, and ending at the beginning, since template parms are listed
441 innermost first. */
443 static void
444 push_inline_template_parms_recursive (tree parmlist, int levels)
446 tree parms = TREE_VALUE (parmlist);
447 int i;
449 if (levels > 1)
450 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
452 ++processing_template_decl;
453 current_template_parms
454 = tree_cons (size_int (processing_template_decl),
455 parms, current_template_parms);
456 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
458 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
459 NULL);
460 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
462 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
464 if (error_operand_p (parm))
465 continue;
467 gcc_assert (DECL_P (parm));
469 switch (TREE_CODE (parm))
471 case TYPE_DECL:
472 case TEMPLATE_DECL:
473 pushdecl (parm);
474 break;
476 case PARM_DECL:
477 /* Push the CONST_DECL. */
478 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
479 break;
481 default:
482 gcc_unreachable ();
487 /* Restore the template parameter context for a member template, a
488 friend template defined in a class definition, or a non-template
489 member of template class. */
491 void
492 maybe_begin_member_template_processing (tree decl)
494 tree parms;
495 int levels = 0;
496 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
498 if (nsdmi)
500 tree ctx = DECL_CONTEXT (decl);
501 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
502 /* Disregard full specializations (c++/60999). */
503 && uses_template_parms (ctx)
504 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
507 if (inline_needs_template_parms (decl, nsdmi))
509 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
510 levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
512 if (DECL_TEMPLATE_SPECIALIZATION (decl))
514 --levels;
515 parms = TREE_CHAIN (parms);
518 push_inline_template_parms_recursive (parms, levels);
521 /* Remember how many levels of template parameters we pushed so that
522 we can pop them later. */
523 inline_parm_levels.safe_push (levels);
526 /* Undo the effects of maybe_begin_member_template_processing. */
528 void
529 maybe_end_member_template_processing (void)
531 int i;
532 int last;
534 if (inline_parm_levels.length () == 0)
535 return;
537 last = inline_parm_levels.pop ();
538 for (i = 0; i < last; ++i)
540 --processing_template_decl;
541 current_template_parms = TREE_CHAIN (current_template_parms);
542 poplevel (0, 0, 0);
546 /* Return a new template argument vector which contains all of ARGS,
547 but has as its innermost set of arguments the EXTRA_ARGS. */
549 static tree
550 add_to_template_args (tree args, tree extra_args)
552 tree new_args;
553 int extra_depth;
554 int i;
555 int j;
557 if (args == NULL_TREE || extra_args == error_mark_node)
558 return extra_args;
560 extra_depth = TMPL_ARGS_DEPTH (extra_args);
561 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
563 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
564 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
566 for (j = 1; j <= extra_depth; ++j, ++i)
567 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
569 return new_args;
572 /* Like add_to_template_args, but only the outermost ARGS are added to
573 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
574 (EXTRA_ARGS) levels are added. This function is used to combine
575 the template arguments from a partial instantiation with the
576 template arguments used to attain the full instantiation from the
577 partial instantiation. */
579 tree
580 add_outermost_template_args (tree args, tree extra_args)
582 tree new_args;
584 /* If there are more levels of EXTRA_ARGS than there are ARGS,
585 something very fishy is going on. */
586 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
588 /* If *all* the new arguments will be the EXTRA_ARGS, just return
589 them. */
590 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
591 return extra_args;
593 /* For the moment, we make ARGS look like it contains fewer levels. */
594 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
596 new_args = add_to_template_args (args, extra_args);
598 /* Now, we restore ARGS to its full dimensions. */
599 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
601 return new_args;
604 /* Return the N levels of innermost template arguments from the ARGS. */
606 tree
607 get_innermost_template_args (tree args, int n)
609 tree new_args;
610 int extra_levels;
611 int i;
613 gcc_assert (n >= 0);
615 /* If N is 1, just return the innermost set of template arguments. */
616 if (n == 1)
617 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
619 /* If we're not removing anything, just return the arguments we were
620 given. */
621 extra_levels = TMPL_ARGS_DEPTH (args) - n;
622 gcc_assert (extra_levels >= 0);
623 if (extra_levels == 0)
624 return args;
626 /* Make a new set of arguments, not containing the outer arguments. */
627 new_args = make_tree_vec (n);
628 for (i = 1; i <= n; ++i)
629 SET_TMPL_ARGS_LEVEL (new_args, i,
630 TMPL_ARGS_LEVEL (args, i + extra_levels));
632 return new_args;
635 /* The inverse of get_innermost_template_args: Return all but the innermost
636 EXTRA_LEVELS levels of template arguments from the ARGS. */
638 static tree
639 strip_innermost_template_args (tree args, int extra_levels)
641 tree new_args;
642 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
643 int i;
645 gcc_assert (n >= 0);
647 /* If N is 1, just return the outermost set of template arguments. */
648 if (n == 1)
649 return TMPL_ARGS_LEVEL (args, 1);
651 /* If we're not removing anything, just return the arguments we were
652 given. */
653 gcc_assert (extra_levels >= 0);
654 if (extra_levels == 0)
655 return args;
657 /* Make a new set of arguments, not containing the inner 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));
663 return new_args;
666 /* We've got a template header coming up; push to a new level for storing
667 the parms. */
669 void
670 begin_template_parm_list (void)
672 /* We use a non-tag-transparent scope here, which causes pushtag to
673 put tags in this scope, rather than in the enclosing class or
674 namespace scope. This is the right thing, since we want
675 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
676 global template class, push_template_decl handles putting the
677 TEMPLATE_DECL into top-level scope. For a nested template class,
678 e.g.:
680 template <class T> struct S1 {
681 template <class T> struct S2 {};
684 pushtag contains special code to insert the TEMPLATE_DECL for S2
685 at the right scope. */
686 begin_scope (sk_template_parms, NULL);
687 ++processing_template_decl;
688 ++processing_template_parmlist;
689 note_template_header (0);
691 /* Add a dummy parameter level while we process the parameter list. */
692 current_template_parms
693 = tree_cons (size_int (processing_template_decl),
694 make_tree_vec (0),
695 current_template_parms);
698 /* This routine is called when a specialization is declared. If it is
699 invalid to declare a specialization here, an error is reported and
700 false is returned, otherwise this routine will return true. */
702 static bool
703 check_specialization_scope (void)
705 tree scope = current_scope ();
707 /* [temp.expl.spec]
709 An explicit specialization shall be declared in the namespace of
710 which the template is a member, or, for member templates, in the
711 namespace of which the enclosing class or enclosing class
712 template is a member. An explicit specialization of a member
713 function, member class or static data member of a class template
714 shall be declared in the namespace of which the class template
715 is a member. */
716 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
718 error ("explicit specialization in non-namespace scope %qD", scope);
719 return false;
722 /* [temp.expl.spec]
724 In an explicit specialization declaration for a member of a class
725 template or a member template that appears in namespace scope,
726 the member template and some of its enclosing class templates may
727 remain unspecialized, except that the declaration shall not
728 explicitly specialize a class member template if its enclosing
729 class templates are not explicitly specialized as well. */
730 if (current_template_parms)
732 error ("enclosing class templates are not explicitly specialized");
733 return false;
736 return true;
739 /* We've just seen template <>. */
741 bool
742 begin_specialization (void)
744 begin_scope (sk_template_spec, NULL);
745 note_template_header (1);
746 return check_specialization_scope ();
749 /* Called at then end of processing a declaration preceded by
750 template<>. */
752 void
753 end_specialization (void)
755 finish_scope ();
756 reset_specialization ();
759 /* Any template <>'s that we have seen thus far are not referring to a
760 function specialization. */
762 void
763 reset_specialization (void)
765 processing_specialization = 0;
766 template_header_count = 0;
769 /* We've just seen a template header. If SPECIALIZATION is nonzero,
770 it was of the form template <>. */
772 static void
773 note_template_header (int specialization)
775 processing_specialization = specialization;
776 template_header_count++;
779 /* We're beginning an explicit instantiation. */
781 void
782 begin_explicit_instantiation (void)
784 gcc_assert (!processing_explicit_instantiation);
785 processing_explicit_instantiation = true;
789 void
790 end_explicit_instantiation (void)
792 gcc_assert (processing_explicit_instantiation);
793 processing_explicit_instantiation = false;
796 /* An explicit specialization or partial specialization of TMPL is being
797 declared. Check that the namespace in which the specialization is
798 occurring is permissible. Returns false iff it is invalid to
799 specialize TMPL in the current namespace. */
801 static bool
802 check_specialization_namespace (tree tmpl)
804 tree tpl_ns = decl_namespace_context (tmpl);
806 /* [tmpl.expl.spec]
808 An explicit specialization shall be declared in a namespace enclosing the
809 specialized template. An explicit specialization whose declarator-id is
810 not qualified shall be declared in the nearest enclosing namespace of the
811 template, or, if the namespace is inline (7.3.1), any namespace from its
812 enclosing namespace set. */
813 if (current_scope() != DECL_CONTEXT (tmpl)
814 && !at_namespace_scope_p ())
816 error ("specialization of %qD must appear at namespace scope", tmpl);
817 return false;
820 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
821 /* Same or enclosing namespace. */
822 return true;
823 else
825 auto_diagnostic_group d;
826 if (permerror (input_location,
827 "specialization of %qD in different namespace", tmpl))
828 inform (DECL_SOURCE_LOCATION (tmpl),
829 " from definition of %q#D", tmpl);
830 return false;
834 /* SPEC is an explicit instantiation. Check that it is valid to
835 perform this explicit instantiation in the current namespace. */
837 static void
838 check_explicit_instantiation_namespace (tree spec)
840 tree ns;
842 /* DR 275: An explicit instantiation shall appear in an enclosing
843 namespace of its template. */
844 ns = decl_namespace_context (spec);
845 if (!is_nested_namespace (current_namespace, ns))
846 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
847 "(which does not enclose namespace %qD)",
848 spec, current_namespace, ns);
851 // Returns the type of a template specialization only if that
852 // specialization needs to be defined. Otherwise (e.g., if the type has
853 // already been defined), the function returns NULL_TREE.
854 static tree
855 maybe_new_partial_specialization (tree type)
857 // An implicit instantiation of an incomplete type implies
858 // the definition of a new class template.
860 // template<typename T>
861 // struct S;
863 // template<typename T>
864 // struct S<T*>;
866 // Here, S<T*> is an implicit instantiation of S whose type
867 // is incomplete.
868 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
869 return type;
871 // It can also be the case that TYPE is a completed specialization.
872 // Continuing the previous example, suppose we also declare:
874 // template<typename T>
875 // requires Integral<T>
876 // struct S<T*>;
878 // Here, S<T*> refers to the specialization S<T*> defined
879 // above. However, we need to differentiate definitions because
880 // we intend to define a new partial specialization. In this case,
881 // we rely on the fact that the constraints are different for
882 // this declaration than that above.
884 // Note that we also get here for injected class names and
885 // late-parsed template definitions. We must ensure that we
886 // do not create new type declarations for those cases.
887 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
889 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
890 tree args = CLASSTYPE_TI_ARGS (type);
892 // If there are no template parameters, this cannot be a new
893 // partial template specializtion?
894 if (!current_template_parms)
895 return NULL_TREE;
897 // The injected-class-name is not a new partial specialization.
898 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
899 return NULL_TREE;
901 // If the constraints are not the same as those of the primary
902 // then, we can probably create a new specialization.
903 tree type_constr = current_template_constraints ();
905 if (type == TREE_TYPE (tmpl))
907 tree main_constr = get_constraints (tmpl);
908 if (equivalent_constraints (type_constr, main_constr))
909 return NULL_TREE;
912 // Also, if there's a pre-existing specialization with matching
913 // constraints, then this also isn't new.
914 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
915 while (specs)
917 tree spec_tmpl = TREE_VALUE (specs);
918 tree spec_args = TREE_PURPOSE (specs);
919 tree spec_constr = get_constraints (spec_tmpl);
920 if (comp_template_args (args, spec_args)
921 && equivalent_constraints (type_constr, spec_constr))
922 return NULL_TREE;
923 specs = TREE_CHAIN (specs);
926 // Create a new type node (and corresponding type decl)
927 // for the newly declared specialization.
928 tree t = make_class_type (TREE_CODE (type));
929 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
930 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
932 /* We only need a separate type node for storing the definition of this
933 partial specialization; uses of S<T*> are unconstrained, so all are
934 equivalent. So keep TYPE_CANONICAL the same. */
935 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
937 // Build the corresponding type decl.
938 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
939 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
940 DECL_SOURCE_LOCATION (d) = input_location;
942 return t;
945 return NULL_TREE;
948 /* The TYPE is being declared. If it is a template type, that means it
949 is a partial specialization. Do appropriate error-checking. */
951 tree
952 maybe_process_partial_specialization (tree type)
954 tree context;
956 if (type == error_mark_node)
957 return error_mark_node;
959 /* A lambda that appears in specialization context is not itself a
960 specialization. */
961 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
962 return type;
964 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
966 error ("name of class shadows template template parameter %qD",
967 TYPE_NAME (type));
968 return error_mark_node;
971 context = TYPE_CONTEXT (type);
973 if (TYPE_ALIAS_P (type))
975 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
977 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
978 error ("specialization of alias template %qD",
979 TI_TEMPLATE (tinfo));
980 else
981 error ("explicit specialization of non-template %qT", type);
982 return error_mark_node;
984 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
986 /* This is for ordinary explicit specialization and partial
987 specialization of a template class such as:
989 template <> class C<int>;
993 template <class T> class C<T*>;
995 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
997 if (tree t = maybe_new_partial_specialization (type))
999 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1000 && !at_namespace_scope_p ())
1001 return error_mark_node;
1002 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1003 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1004 if (processing_template_decl)
1006 tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1007 if (decl == error_mark_node)
1008 return error_mark_node;
1009 return TREE_TYPE (decl);
1012 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1013 error ("specialization of %qT after instantiation", type);
1014 else if (errorcount && !processing_specialization
1015 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1016 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1017 /* Trying to define a specialization either without a template<> header
1018 or in an inappropriate place. We've already given an error, so just
1019 bail now so we don't actually define the specialization. */
1020 return error_mark_node;
1022 else if (CLASS_TYPE_P (type)
1023 && !CLASSTYPE_USE_TEMPLATE (type)
1024 && CLASSTYPE_TEMPLATE_INFO (type)
1025 && context && CLASS_TYPE_P (context)
1026 && CLASSTYPE_TEMPLATE_INFO (context))
1028 /* This is for an explicit specialization of member class
1029 template according to [temp.expl.spec/18]:
1031 template <> template <class U> class C<int>::D;
1033 The context `C<int>' must be an implicit instantiation.
1034 Otherwise this is just a member class template declared
1035 earlier like:
1037 template <> class C<int> { template <class U> class D; };
1038 template <> template <class U> class C<int>::D;
1040 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1041 while in the second case, `C<int>::D' is a primary template
1042 and `C<T>::D' may not exist. */
1044 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1045 && !COMPLETE_TYPE_P (type))
1047 tree t;
1048 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1050 if (current_namespace
1051 != decl_namespace_context (tmpl))
1053 if (permerror (input_location,
1054 "specialization of %qD in different namespace",
1055 type))
1056 inform (DECL_SOURCE_LOCATION (tmpl),
1057 "from definition of %q#D", tmpl);
1060 /* Check for invalid specialization after instantiation:
1062 template <> template <> class C<int>::D<int>;
1063 template <> template <class U> class C<int>::D; */
1065 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1066 t; t = TREE_CHAIN (t))
1068 tree inst = TREE_VALUE (t);
1069 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1070 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1072 /* We already have a full specialization of this partial
1073 instantiation, or a full specialization has been
1074 looked up but not instantiated. Reassign it to the
1075 new member specialization template. */
1076 spec_entry elt;
1077 spec_entry *entry;
1079 elt.tmpl = most_general_template (tmpl);
1080 elt.args = CLASSTYPE_TI_ARGS (inst);
1081 elt.spec = inst;
1083 type_specializations->remove_elt (&elt);
1085 elt.tmpl = tmpl;
1086 CLASSTYPE_TI_ARGS (inst)
1087 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1089 spec_entry **slot
1090 = type_specializations->find_slot (&elt, INSERT);
1091 entry = ggc_alloc<spec_entry> ();
1092 *entry = elt;
1093 *slot = entry;
1095 else
1096 /* But if we've had an implicit instantiation, that's a
1097 problem ([temp.expl.spec]/6). */
1098 error ("specialization %qT after instantiation %qT",
1099 type, inst);
1102 /* Mark TYPE as a specialization. And as a result, we only
1103 have one level of template argument for the innermost
1104 class template. */
1105 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1106 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1107 CLASSTYPE_TI_ARGS (type)
1108 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1111 else if (processing_specialization)
1113 /* Someday C++0x may allow for enum template specialization. */
1114 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1115 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1116 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1117 "of %qD not allowed by ISO C++", type);
1118 else
1120 error ("explicit specialization of non-template %qT", type);
1121 return error_mark_node;
1125 return type;
1128 /* Returns nonzero if we can optimize the retrieval of specializations
1129 for TMPL, a TEMPLATE_DECL. In particular, for such a template, we
1130 do not use DECL_TEMPLATE_SPECIALIZATIONS at all. */
1132 static inline bool
1133 optimize_specialization_lookup_p (tree tmpl)
1135 return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1136 && DECL_CLASS_SCOPE_P (tmpl)
1137 /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1138 parameter. */
1139 && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1140 /* The optimized lookup depends on the fact that the
1141 template arguments for the member function template apply
1142 purely to the containing class, which is not true if the
1143 containing class is an explicit or partial
1144 specialization. */
1145 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1146 && !DECL_MEMBER_TEMPLATE_P (tmpl)
1147 && !DECL_CONV_FN_P (tmpl)
1148 /* It is possible to have a template that is not a member
1149 template and is not a member of a template class:
1151 template <typename T>
1152 struct S { friend A::f(); };
1154 Here, the friend function is a template, but the context does
1155 not have template information. The optimized lookup relies
1156 on having ARGS be the template arguments for both the class
1157 and the function template. */
1158 && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1161 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1162 gone through coerce_template_parms by now. */
1164 static void
1165 verify_unstripped_args_1 (tree inner)
1167 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1169 tree arg = TREE_VEC_ELT (inner, i);
1170 if (TREE_CODE (arg) == TEMPLATE_DECL)
1171 /* OK */;
1172 else if (TYPE_P (arg))
1173 gcc_assert (strip_typedefs (arg, NULL) == arg);
1174 else if (ARGUMENT_PACK_P (arg))
1175 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1176 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1177 /* Allow typedefs on the type of a non-type argument, since a
1178 parameter can have them. */;
1179 else
1180 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1184 static void
1185 verify_unstripped_args (tree args)
1187 ++processing_template_decl;
1188 if (!any_dependent_template_arguments_p (args))
1189 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1190 --processing_template_decl;
1193 /* Retrieve the specialization (in the sense of [temp.spec] - a
1194 specialization is either an instantiation or an explicit
1195 specialization) of TMPL for the given template ARGS. If there is
1196 no such specialization, return NULL_TREE. The ARGS are a vector of
1197 arguments, or a vector of vectors of arguments, in the case of
1198 templates with more than one level of parameters.
1200 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1201 then we search for a partial specialization matching ARGS. This
1202 parameter is ignored if TMPL is not a class template.
1204 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1205 result is a NONTYPE_ARGUMENT_PACK. */
1207 static tree
1208 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1210 if (tmpl == NULL_TREE)
1211 return NULL_TREE;
1213 if (args == error_mark_node)
1214 return NULL_TREE;
1216 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1217 || TREE_CODE (tmpl) == FIELD_DECL);
1219 /* There should be as many levels of arguments as there are
1220 levels of parameters. */
1221 gcc_assert (TMPL_ARGS_DEPTH (args)
1222 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1223 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1224 : template_class_depth (DECL_CONTEXT (tmpl))));
1226 if (flag_checking)
1227 verify_unstripped_args (args);
1229 /* Lambda functions in templates aren't instantiated normally, but through
1230 tsubst_lambda_expr. */
1231 if (lambda_fn_in_template_p (tmpl))
1232 return NULL_TREE;
1234 if (optimize_specialization_lookup_p (tmpl))
1236 /* The template arguments actually apply to the containing
1237 class. Find the class specialization with those
1238 arguments. */
1239 tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1240 tree class_specialization
1241 = retrieve_specialization (class_template, args, 0);
1242 if (!class_specialization)
1243 return NULL_TREE;
1245 /* Find the instance of TMPL. */
1246 tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1247 for (ovl_iterator iter (fns); iter; ++iter)
1249 tree fn = *iter;
1250 if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1251 /* using-declarations can add base methods to the method vec,
1252 and we don't want those here. */
1253 && DECL_CONTEXT (fn) == class_specialization)
1254 return fn;
1256 return NULL_TREE;
1258 else
1260 spec_entry *found;
1261 spec_entry elt;
1262 hash_table<spec_hasher> *specializations;
1264 elt.tmpl = tmpl;
1265 elt.args = args;
1266 elt.spec = NULL_TREE;
1268 if (DECL_CLASS_TEMPLATE_P (tmpl))
1269 specializations = type_specializations;
1270 else
1271 specializations = decl_specializations;
1273 if (hash == 0)
1274 hash = spec_hasher::hash (&elt);
1275 found = specializations->find_with_hash (&elt, hash);
1276 if (found)
1277 return found->spec;
1280 return NULL_TREE;
1283 /* Like retrieve_specialization, but for local declarations. */
1285 tree
1286 retrieve_local_specialization (tree tmpl)
1288 if (local_specializations == NULL)
1289 return NULL_TREE;
1291 tree *slot = local_specializations->get (tmpl);
1292 return slot ? *slot : NULL_TREE;
1295 /* Returns nonzero iff DECL is a specialization of TMPL. */
1298 is_specialization_of (tree decl, tree tmpl)
1300 tree t;
1302 if (TREE_CODE (decl) == FUNCTION_DECL)
1304 for (t = decl;
1305 t != NULL_TREE;
1306 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1307 if (t == tmpl)
1308 return 1;
1310 else
1312 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1314 for (t = TREE_TYPE (decl);
1315 t != NULL_TREE;
1316 t = CLASSTYPE_USE_TEMPLATE (t)
1317 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1318 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1319 return 1;
1322 return 0;
1325 /* Returns nonzero iff DECL is a specialization of friend declaration
1326 FRIEND_DECL according to [temp.friend]. */
1328 bool
1329 is_specialization_of_friend (tree decl, tree friend_decl)
1331 bool need_template = true;
1332 int template_depth;
1334 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1335 || TREE_CODE (decl) == TYPE_DECL);
1337 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1338 of a template class, we want to check if DECL is a specialization
1339 if this. */
1340 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1341 && DECL_TEMPLATE_INFO (friend_decl)
1342 && !DECL_USE_TEMPLATE (friend_decl))
1344 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1345 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1346 need_template = false;
1348 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1349 && !PRIMARY_TEMPLATE_P (friend_decl))
1350 need_template = false;
1352 /* There is nothing to do if this is not a template friend. */
1353 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1354 return false;
1356 if (is_specialization_of (decl, friend_decl))
1357 return true;
1359 /* [temp.friend/6]
1360 A member of a class template may be declared to be a friend of a
1361 non-template class. In this case, the corresponding member of
1362 every specialization of the class template is a friend of the
1363 class granting friendship.
1365 For example, given a template friend declaration
1367 template <class T> friend void A<T>::f();
1369 the member function below is considered a friend
1371 template <> struct A<int> {
1372 void f();
1375 For this type of template friend, TEMPLATE_DEPTH below will be
1376 nonzero. To determine if DECL is a friend of FRIEND, we first
1377 check if the enclosing class is a specialization of another. */
1379 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1380 if (template_depth
1381 && DECL_CLASS_SCOPE_P (decl)
1382 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1383 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1385 /* Next, we check the members themselves. In order to handle
1386 a few tricky cases, such as when FRIEND_DECL's are
1388 template <class T> friend void A<T>::g(T t);
1389 template <class T> template <T t> friend void A<T>::h();
1391 and DECL's are
1393 void A<int>::g(int);
1394 template <int> void A<int>::h();
1396 we need to figure out ARGS, the template arguments from
1397 the context of DECL. This is required for template substitution
1398 of `T' in the function parameter of `g' and template parameter
1399 of `h' in the above examples. Here ARGS corresponds to `int'. */
1401 tree context = DECL_CONTEXT (decl);
1402 tree args = NULL_TREE;
1403 int current_depth = 0;
1405 while (current_depth < template_depth)
1407 if (CLASSTYPE_TEMPLATE_INFO (context))
1409 if (current_depth == 0)
1410 args = TYPE_TI_ARGS (context);
1411 else
1412 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1413 current_depth++;
1415 context = TYPE_CONTEXT (context);
1418 if (TREE_CODE (decl) == FUNCTION_DECL)
1420 bool is_template;
1421 tree friend_type;
1422 tree decl_type;
1423 tree friend_args_type;
1424 tree decl_args_type;
1426 /* Make sure that both DECL and FRIEND_DECL are templates or
1427 non-templates. */
1428 is_template = DECL_TEMPLATE_INFO (decl)
1429 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1430 if (need_template ^ is_template)
1431 return false;
1432 else if (is_template)
1434 /* If both are templates, check template parameter list. */
1435 tree friend_parms
1436 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1437 args, tf_none);
1438 if (!comp_template_parms
1439 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1440 friend_parms))
1441 return false;
1443 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1445 else
1446 decl_type = TREE_TYPE (decl);
1448 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1449 tf_none, NULL_TREE);
1450 if (friend_type == error_mark_node)
1451 return false;
1453 /* Check if return types match. */
1454 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1455 return false;
1457 /* Check if function parameter types match, ignoring the
1458 `this' parameter. */
1459 friend_args_type = TYPE_ARG_TYPES (friend_type);
1460 decl_args_type = TYPE_ARG_TYPES (decl_type);
1461 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1462 friend_args_type = TREE_CHAIN (friend_args_type);
1463 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1464 decl_args_type = TREE_CHAIN (decl_args_type);
1466 return compparms (decl_args_type, friend_args_type);
1468 else
1470 /* DECL is a TYPE_DECL */
1471 bool is_template;
1472 tree decl_type = TREE_TYPE (decl);
1474 /* Make sure that both DECL and FRIEND_DECL are templates or
1475 non-templates. */
1476 is_template
1477 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1478 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1480 if (need_template ^ is_template)
1481 return false;
1482 else if (is_template)
1484 tree friend_parms;
1485 /* If both are templates, check the name of the two
1486 TEMPLATE_DECL's first because is_friend didn't. */
1487 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1488 != DECL_NAME (friend_decl))
1489 return false;
1491 /* Now check template parameter list. */
1492 friend_parms
1493 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1494 args, tf_none);
1495 return comp_template_parms
1496 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1497 friend_parms);
1499 else
1500 return (DECL_NAME (decl)
1501 == DECL_NAME (friend_decl));
1504 return false;
1507 /* Register the specialization SPEC as a specialization of TMPL with
1508 the indicated ARGS. IS_FRIEND indicates whether the specialization
1509 is actually just a friend declaration. ATTRLIST is the list of
1510 attributes that the specialization is declared with or NULL when
1511 it isn't. Returns SPEC, or an equivalent prior declaration, if
1512 available.
1514 We also store instantiations of field packs in the hash table, even
1515 though they are not themselves templates, to make lookup easier. */
1517 static tree
1518 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1519 hashval_t hash)
1521 tree fn;
1522 spec_entry **slot = NULL;
1523 spec_entry elt;
1525 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1526 || (TREE_CODE (tmpl) == FIELD_DECL
1527 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1529 if (TREE_CODE (spec) == FUNCTION_DECL
1530 && uses_template_parms (DECL_TI_ARGS (spec)))
1531 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1532 register it; we want the corresponding TEMPLATE_DECL instead.
1533 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1534 the more obvious `uses_template_parms (spec)' to avoid problems
1535 with default function arguments. In particular, given
1536 something like this:
1538 template <class T> void f(T t1, T t = T())
1540 the default argument expression is not substituted for in an
1541 instantiation unless and until it is actually needed. */
1542 return spec;
1544 if (optimize_specialization_lookup_p (tmpl))
1545 /* We don't put these specializations in the hash table, but we might
1546 want to give an error about a mismatch. */
1547 fn = retrieve_specialization (tmpl, args, 0);
1548 else
1550 elt.tmpl = tmpl;
1551 elt.args = args;
1552 elt.spec = spec;
1554 if (hash == 0)
1555 hash = spec_hasher::hash (&elt);
1557 slot =
1558 decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1559 if (*slot)
1560 fn = ((spec_entry *) *slot)->spec;
1561 else
1562 fn = NULL_TREE;
1565 /* We can sometimes try to re-register a specialization that we've
1566 already got. In particular, regenerate_decl_from_template calls
1567 duplicate_decls which will update the specialization list. But,
1568 we'll still get called again here anyhow. It's more convenient
1569 to simply allow this than to try to prevent it. */
1570 if (fn == spec)
1571 return spec;
1572 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1574 if (DECL_TEMPLATE_INSTANTIATION (fn))
1576 if (DECL_ODR_USED (fn)
1577 || DECL_EXPLICIT_INSTANTIATION (fn))
1579 error ("specialization of %qD after instantiation",
1580 fn);
1581 return error_mark_node;
1583 else
1585 tree clone;
1586 /* This situation should occur only if the first
1587 specialization is an implicit instantiation, the
1588 second is an explicit specialization, and the
1589 implicit instantiation has not yet been used. That
1590 situation can occur if we have implicitly
1591 instantiated a member function and then specialized
1592 it later.
1594 We can also wind up here if a friend declaration that
1595 looked like an instantiation turns out to be a
1596 specialization:
1598 template <class T> void foo(T);
1599 class S { friend void foo<>(int) };
1600 template <> void foo(int);
1602 We transform the existing DECL in place so that any
1603 pointers to it become pointers to the updated
1604 declaration.
1606 If there was a definition for the template, but not
1607 for the specialization, we want this to look as if
1608 there were no definition, and vice versa. */
1609 DECL_INITIAL (fn) = NULL_TREE;
1610 duplicate_decls (spec, fn, is_friend);
1611 /* The call to duplicate_decls will have applied
1612 [temp.expl.spec]:
1614 An explicit specialization of a function template
1615 is inline only if it is explicitly declared to be,
1616 and independently of whether its function template
1619 to the primary function; now copy the inline bits to
1620 the various clones. */
1621 FOR_EACH_CLONE (clone, fn)
1623 DECL_DECLARED_INLINE_P (clone)
1624 = DECL_DECLARED_INLINE_P (fn);
1625 DECL_SOURCE_LOCATION (clone)
1626 = DECL_SOURCE_LOCATION (fn);
1627 DECL_DELETED_FN (clone)
1628 = DECL_DELETED_FN (fn);
1630 check_specialization_namespace (tmpl);
1632 return fn;
1635 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1637 tree dd = duplicate_decls (spec, fn, is_friend);
1638 if (dd == error_mark_node)
1639 /* We've already complained in duplicate_decls. */
1640 return error_mark_node;
1642 if (dd == NULL_TREE && DECL_INITIAL (spec))
1643 /* Dup decl failed, but this is a new definition. Set the
1644 line number so any errors match this new
1645 definition. */
1646 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1648 return fn;
1651 else if (fn)
1652 return duplicate_decls (spec, fn, is_friend);
1654 /* A specialization must be declared in the same namespace as the
1655 template it is specializing. */
1656 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1657 && !check_specialization_namespace (tmpl))
1658 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1660 if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1662 spec_entry *entry = ggc_alloc<spec_entry> ();
1663 gcc_assert (tmpl && args && spec);
1664 *entry = elt;
1665 *slot = entry;
1666 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1667 && PRIMARY_TEMPLATE_P (tmpl)
1668 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1669 || variable_template_p (tmpl))
1670 /* If TMPL is a forward declaration of a template function, keep a list
1671 of all specializations in case we need to reassign them to a friend
1672 template later in tsubst_friend_function.
1674 Also keep a list of all variable template instantiations so that
1675 process_partial_specialization can check whether a later partial
1676 specialization would have used it. */
1677 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1678 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1681 return spec;
1684 /* Returns true iff two spec_entry nodes are equivalent. */
1686 int comparing_specializations;
1688 bool
1689 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1691 int equal;
1693 ++comparing_specializations;
1694 equal = (e1->tmpl == e2->tmpl
1695 && comp_template_args (e1->args, e2->args));
1696 if (equal && flag_concepts
1697 /* tmpl could be a FIELD_DECL for a capture pack. */
1698 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1699 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1700 && uses_template_parms (e1->args))
1702 /* Partial specializations of a variable template can be distinguished by
1703 constraints. */
1704 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1705 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1706 equal = equivalent_constraints (c1, c2);
1708 --comparing_specializations;
1710 return equal;
1713 /* Returns a hash for a template TMPL and template arguments ARGS. */
1715 static hashval_t
1716 hash_tmpl_and_args (tree tmpl, tree args)
1718 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1719 return iterative_hash_template_arg (args, val);
1722 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1723 ignoring SPEC. */
1725 hashval_t
1726 spec_hasher::hash (spec_entry *e)
1728 return hash_tmpl_and_args (e->tmpl, e->args);
1731 /* Recursively calculate a hash value for a template argument ARG, for use
1732 in the hash tables of template specializations. */
1734 hashval_t
1735 iterative_hash_template_arg (tree arg, hashval_t val)
1737 unsigned HOST_WIDE_INT i;
1738 enum tree_code code;
1739 char tclass;
1741 if (arg == NULL_TREE)
1742 return iterative_hash_object (arg, val);
1744 if (!TYPE_P (arg))
1745 STRIP_NOPS (arg);
1747 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1748 gcc_unreachable ();
1750 code = TREE_CODE (arg);
1751 tclass = TREE_CODE_CLASS (code);
1753 val = iterative_hash_object (code, val);
1755 switch (code)
1757 case ERROR_MARK:
1758 return val;
1760 case IDENTIFIER_NODE:
1761 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1763 case TREE_VEC:
1765 int i, len = TREE_VEC_LENGTH (arg);
1766 for (i = 0; i < len; ++i)
1767 val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1768 return val;
1771 case TYPE_PACK_EXPANSION:
1772 case EXPR_PACK_EXPANSION:
1773 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1774 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1776 case TYPE_ARGUMENT_PACK:
1777 case NONTYPE_ARGUMENT_PACK:
1778 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1780 case TREE_LIST:
1781 for (; arg; arg = TREE_CHAIN (arg))
1782 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1783 return val;
1785 case OVERLOAD:
1786 for (lkp_iterator iter (arg); iter; ++iter)
1787 val = iterative_hash_template_arg (*iter, val);
1788 return val;
1790 case CONSTRUCTOR:
1792 tree field, value;
1793 iterative_hash_template_arg (TREE_TYPE (arg), val);
1794 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1796 val = iterative_hash_template_arg (field, val);
1797 val = iterative_hash_template_arg (value, val);
1799 return val;
1802 case PARM_DECL:
1803 if (!DECL_ARTIFICIAL (arg))
1805 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1806 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1808 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1810 case TARGET_EXPR:
1811 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1813 case PTRMEM_CST:
1814 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1815 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1817 case TEMPLATE_PARM_INDEX:
1818 val = iterative_hash_template_arg
1819 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1820 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1821 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1823 case TRAIT_EXPR:
1824 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1825 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1826 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1828 case BASELINK:
1829 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1830 val);
1831 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1832 val);
1834 case MODOP_EXPR:
1835 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1836 code = TREE_CODE (TREE_OPERAND (arg, 1));
1837 val = iterative_hash_object (code, val);
1838 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1840 case LAMBDA_EXPR:
1841 /* [temp.over.link] Two lambda-expressions are never considered
1842 equivalent.
1844 So just hash the closure type. */
1845 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1847 case CAST_EXPR:
1848 case IMPLICIT_CONV_EXPR:
1849 case STATIC_CAST_EXPR:
1850 case REINTERPRET_CAST_EXPR:
1851 case CONST_CAST_EXPR:
1852 case DYNAMIC_CAST_EXPR:
1853 case NEW_EXPR:
1854 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1855 /* Now hash operands as usual. */
1856 break;
1858 case CALL_EXPR:
1860 tree fn = CALL_EXPR_FN (arg);
1861 if (tree name = dependent_name (fn))
1863 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1864 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1865 fn = name;
1867 val = iterative_hash_template_arg (fn, val);
1868 call_expr_arg_iterator ai;
1869 for (tree x = first_call_expr_arg (arg, &ai); x;
1870 x = next_call_expr_arg (&ai))
1871 val = iterative_hash_template_arg (x, val);
1872 return val;
1875 default:
1876 break;
1879 switch (tclass)
1881 case tcc_type:
1882 if (alias_template_specialization_p (arg))
1884 // We want an alias specialization that survived strip_typedefs
1885 // to hash differently from its TYPE_CANONICAL, to avoid hash
1886 // collisions that compare as different in template_args_equal.
1887 // These could be dependent specializations that strip_typedefs
1888 // left alone, or untouched specializations because
1889 // coerce_template_parms returns the unconverted template
1890 // arguments if it sees incomplete argument packs.
1891 tree ti = TYPE_ALIAS_TEMPLATE_INFO (arg);
1892 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1894 if (TYPE_CANONICAL (arg))
1895 return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1896 val);
1897 else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1898 return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1899 /* Otherwise just compare the types during lookup. */
1900 return val;
1902 case tcc_declaration:
1903 case tcc_constant:
1904 return iterative_hash_expr (arg, val);
1906 default:
1907 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1909 unsigned n = cp_tree_operand_length (arg);
1910 for (i = 0; i < n; ++i)
1911 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1912 return val;
1915 gcc_unreachable ();
1916 return 0;
1919 /* Unregister the specialization SPEC as a specialization of TMPL.
1920 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1921 if the SPEC was listed as a specialization of TMPL.
1923 Note that SPEC has been ggc_freed, so we can't look inside it. */
1925 bool
1926 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1928 spec_entry *entry;
1929 spec_entry elt;
1931 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1932 elt.args = TI_ARGS (tinfo);
1933 elt.spec = NULL_TREE;
1935 entry = decl_specializations->find (&elt);
1936 if (entry != NULL)
1938 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1939 gcc_assert (new_spec != NULL_TREE);
1940 entry->spec = new_spec;
1941 return 1;
1944 return 0;
1947 /* Like register_specialization, but for local declarations. We are
1948 registering SPEC, an instantiation of TMPL. */
1950 void
1951 register_local_specialization (tree spec, tree tmpl)
1953 gcc_assert (tmpl != spec);
1954 local_specializations->put (tmpl, spec);
1957 /* TYPE is a class type. Returns true if TYPE is an explicitly
1958 specialized class. */
1960 bool
1961 explicit_class_specialization_p (tree type)
1963 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1964 return false;
1965 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1968 /* Print the list of functions at FNS, going through all the overloads
1969 for each element of the list. Alternatively, FNS cannot be a
1970 TREE_LIST, in which case it will be printed together with all the
1971 overloads.
1973 MORE and *STR should respectively be FALSE and NULL when the function
1974 is called from the outside. They are used internally on recursive
1975 calls. print_candidates manages the two parameters and leaves NULL
1976 in *STR when it ends. */
1978 static void
1979 print_candidates_1 (tree fns, char **str, bool more = false)
1981 if (TREE_CODE (fns) == TREE_LIST)
1982 for (; fns; fns = TREE_CHAIN (fns))
1983 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1984 else
1985 for (lkp_iterator iter (fns); iter;)
1987 tree cand = *iter;
1988 ++iter;
1990 const char *pfx = *str;
1991 if (!pfx)
1993 if (more || iter)
1994 pfx = _("candidates are:");
1995 else
1996 pfx = _("candidate is:");
1997 *str = get_spaces (pfx);
1999 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2003 /* Print the list of candidate FNS in an error message. FNS can also
2004 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2006 void
2007 print_candidates (tree fns)
2009 char *str = NULL;
2010 print_candidates_1 (fns, &str);
2011 free (str);
2014 /* Get a (possibly) constrained template declaration for the
2015 purpose of ordering candidates. */
2016 static tree
2017 get_template_for_ordering (tree list)
2019 gcc_assert (TREE_CODE (list) == TREE_LIST);
2020 tree f = TREE_VALUE (list);
2021 if (tree ti = DECL_TEMPLATE_INFO (f))
2022 return TI_TEMPLATE (ti);
2023 return f;
2026 /* Among candidates having the same signature, return the
2027 most constrained or NULL_TREE if there is no best candidate.
2028 If the signatures of candidates vary (e.g., template
2029 specialization vs. member function), then there can be no
2030 most constrained.
2032 Note that we don't compare constraints on the functions
2033 themselves, but rather those of their templates. */
2034 static tree
2035 most_constrained_function (tree candidates)
2037 // Try to find the best candidate in a first pass.
2038 tree champ = candidates;
2039 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2041 int winner = more_constrained (get_template_for_ordering (champ),
2042 get_template_for_ordering (c));
2043 if (winner == -1)
2044 champ = c; // The candidate is more constrained
2045 else if (winner == 0)
2046 return NULL_TREE; // Neither is more constrained
2049 // Verify that the champ is better than previous candidates.
2050 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2051 if (!more_constrained (get_template_for_ordering (champ),
2052 get_template_for_ordering (c)))
2053 return NULL_TREE;
2056 return champ;
2060 /* Returns the template (one of the functions given by TEMPLATE_ID)
2061 which can be specialized to match the indicated DECL with the
2062 explicit template args given in TEMPLATE_ID. The DECL may be
2063 NULL_TREE if none is available. In that case, the functions in
2064 TEMPLATE_ID are non-members.
2066 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2067 specialization of a member template.
2069 The TEMPLATE_COUNT is the number of references to qualifying
2070 template classes that appeared in the name of the function. See
2071 check_explicit_specialization for a more accurate description.
2073 TSK indicates what kind of template declaration (if any) is being
2074 declared. TSK_TEMPLATE indicates that the declaration given by
2075 DECL, though a FUNCTION_DECL, has template parameters, and is
2076 therefore a template function.
2078 The template args (those explicitly specified and those deduced)
2079 are output in a newly created vector *TARGS_OUT.
2081 If it is impossible to determine the result, an error message is
2082 issued. The error_mark_node is returned to indicate failure. */
2084 static tree
2085 determine_specialization (tree template_id,
2086 tree decl,
2087 tree* targs_out,
2088 int need_member_template,
2089 int template_count,
2090 tmpl_spec_kind tsk)
2092 tree fns;
2093 tree targs;
2094 tree explicit_targs;
2095 tree candidates = NULL_TREE;
2097 /* A TREE_LIST of templates of which DECL may be a specialization.
2098 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2099 corresponding TREE_PURPOSE is the set of template arguments that,
2100 when used to instantiate the template, would produce a function
2101 with the signature of DECL. */
2102 tree templates = NULL_TREE;
2103 int header_count;
2104 cp_binding_level *b;
2106 *targs_out = NULL_TREE;
2108 if (template_id == error_mark_node || decl == error_mark_node)
2109 return error_mark_node;
2111 /* We shouldn't be specializing a member template of an
2112 unspecialized class template; we already gave an error in
2113 check_specialization_scope, now avoid crashing. */
2114 if (!VAR_P (decl)
2115 && template_count && DECL_CLASS_SCOPE_P (decl)
2116 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2118 gcc_assert (errorcount);
2119 return error_mark_node;
2122 fns = TREE_OPERAND (template_id, 0);
2123 explicit_targs = TREE_OPERAND (template_id, 1);
2125 if (fns == error_mark_node)
2126 return error_mark_node;
2128 /* Check for baselinks. */
2129 if (BASELINK_P (fns))
2130 fns = BASELINK_FUNCTIONS (fns);
2132 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2134 error_at (DECL_SOURCE_LOCATION (decl),
2135 "%qD is not a function template", fns);
2136 return error_mark_node;
2138 else if (VAR_P (decl) && !variable_template_p (fns))
2140 error ("%qD is not a variable template", fns);
2141 return error_mark_node;
2144 /* Count the number of template headers specified for this
2145 specialization. */
2146 header_count = 0;
2147 for (b = current_binding_level;
2148 b->kind == sk_template_parms;
2149 b = b->level_chain)
2150 ++header_count;
2152 tree orig_fns = fns;
2154 if (variable_template_p (fns))
2156 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2157 targs = coerce_template_parms (parms, explicit_targs, fns,
2158 tf_warning_or_error,
2159 /*req_all*/true, /*use_defarg*/true);
2160 if (targs != error_mark_node)
2161 templates = tree_cons (targs, fns, templates);
2163 else for (lkp_iterator iter (fns); iter; ++iter)
2165 tree fn = *iter;
2167 if (TREE_CODE (fn) == TEMPLATE_DECL)
2169 tree decl_arg_types;
2170 tree fn_arg_types;
2171 tree insttype;
2173 /* In case of explicit specialization, we need to check if
2174 the number of template headers appearing in the specialization
2175 is correct. This is usually done in check_explicit_specialization,
2176 but the check done there cannot be exhaustive when specializing
2177 member functions. Consider the following code:
2179 template <> void A<int>::f(int);
2180 template <> template <> void A<int>::f(int);
2182 Assuming that A<int> is not itself an explicit specialization
2183 already, the first line specializes "f" which is a non-template
2184 member function, whilst the second line specializes "f" which
2185 is a template member function. So both lines are syntactically
2186 correct, and check_explicit_specialization does not reject
2187 them.
2189 Here, we can do better, as we are matching the specialization
2190 against the declarations. We count the number of template
2191 headers, and we check if they match TEMPLATE_COUNT + 1
2192 (TEMPLATE_COUNT is the number of qualifying template classes,
2193 plus there must be another header for the member template
2194 itself).
2196 Notice that if header_count is zero, this is not a
2197 specialization but rather a template instantiation, so there
2198 is no check we can perform here. */
2199 if (header_count && header_count != template_count + 1)
2200 continue;
2202 /* Check that the number of template arguments at the
2203 innermost level for DECL is the same as for FN. */
2204 if (current_binding_level->kind == sk_template_parms
2205 && !current_binding_level->explicit_spec_p
2206 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2207 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2208 (current_template_parms))))
2209 continue;
2211 /* DECL might be a specialization of FN. */
2212 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2213 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2215 /* For a non-static member function, we need to make sure
2216 that the const qualification is the same. Since
2217 get_bindings does not try to merge the "this" parameter,
2218 we must do the comparison explicitly. */
2219 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2221 if (!same_type_p (TREE_VALUE (fn_arg_types),
2222 TREE_VALUE (decl_arg_types)))
2223 continue;
2225 /* And the ref-qualification. */
2226 if (type_memfn_rqual (TREE_TYPE (decl))
2227 != type_memfn_rqual (TREE_TYPE (fn)))
2228 continue;
2231 /* Skip the "this" parameter and, for constructors of
2232 classes with virtual bases, the VTT parameter. A
2233 full specialization of a constructor will have a VTT
2234 parameter, but a template never will. */
2235 decl_arg_types
2236 = skip_artificial_parms_for (decl, decl_arg_types);
2237 fn_arg_types
2238 = skip_artificial_parms_for (fn, fn_arg_types);
2240 /* Function templates cannot be specializations; there are
2241 no partial specializations of functions. Therefore, if
2242 the type of DECL does not match FN, there is no
2243 match.
2245 Note that it should never be the case that we have both
2246 candidates added here, and for regular member functions
2247 below. */
2248 if (tsk == tsk_template)
2250 if (compparms (fn_arg_types, decl_arg_types))
2251 candidates = tree_cons (NULL_TREE, fn, candidates);
2252 continue;
2255 /* See whether this function might be a specialization of this
2256 template. Suppress access control because we might be trying
2257 to make this specialization a friend, and we have already done
2258 access control for the declaration of the specialization. */
2259 push_deferring_access_checks (dk_no_check);
2260 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2261 pop_deferring_access_checks ();
2263 if (!targs)
2264 /* We cannot deduce template arguments that when used to
2265 specialize TMPL will produce DECL. */
2266 continue;
2268 if (uses_template_parms (targs))
2269 /* We deduced something involving 'auto', which isn't a valid
2270 template argument. */
2271 continue;
2273 /* Remove, from the set of candidates, all those functions
2274 whose constraints are not satisfied. */
2275 if (flag_concepts && !constraints_satisfied_p (fn, targs))
2276 continue;
2278 // Then, try to form the new function type.
2279 insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2280 if (insttype == error_mark_node)
2281 continue;
2282 fn_arg_types
2283 = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2284 if (!compparms (fn_arg_types, decl_arg_types))
2285 continue;
2287 /* Save this template, and the arguments deduced. */
2288 templates = tree_cons (targs, fn, templates);
2290 else if (need_member_template)
2291 /* FN is an ordinary member function, and we need a
2292 specialization of a member template. */
2294 else if (TREE_CODE (fn) != FUNCTION_DECL)
2295 /* We can get IDENTIFIER_NODEs here in certain erroneous
2296 cases. */
2298 else if (!DECL_FUNCTION_MEMBER_P (fn))
2299 /* This is just an ordinary non-member function. Nothing can
2300 be a specialization of that. */
2302 else if (DECL_ARTIFICIAL (fn))
2303 /* Cannot specialize functions that are created implicitly. */
2305 else
2307 tree decl_arg_types;
2309 /* This is an ordinary member function. However, since
2310 we're here, we can assume its enclosing class is a
2311 template class. For example,
2313 template <typename T> struct S { void f(); };
2314 template <> void S<int>::f() {}
2316 Here, S<int>::f is a non-template, but S<int> is a
2317 template class. If FN has the same type as DECL, we
2318 might be in business. */
2320 if (!DECL_TEMPLATE_INFO (fn))
2321 /* Its enclosing class is an explicit specialization
2322 of a template class. This is not a candidate. */
2323 continue;
2325 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2326 TREE_TYPE (TREE_TYPE (fn))))
2327 /* The return types differ. */
2328 continue;
2330 /* Adjust the type of DECL in case FN is a static member. */
2331 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2332 if (DECL_STATIC_FUNCTION_P (fn)
2333 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2334 decl_arg_types = TREE_CHAIN (decl_arg_types);
2336 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2337 decl_arg_types))
2338 continue;
2340 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2341 && (type_memfn_rqual (TREE_TYPE (decl))
2342 != type_memfn_rqual (TREE_TYPE (fn))))
2343 continue;
2345 // If the deduced arguments do not satisfy the constraints,
2346 // this is not a candidate.
2347 if (flag_concepts && !constraints_satisfied_p (fn))
2348 continue;
2350 // Add the candidate.
2351 candidates = tree_cons (NULL_TREE, fn, candidates);
2355 if (templates && TREE_CHAIN (templates))
2357 /* We have:
2359 [temp.expl.spec]
2361 It is possible for a specialization with a given function
2362 signature to be instantiated from more than one function
2363 template. In such cases, explicit specification of the
2364 template arguments must be used to uniquely identify the
2365 function template specialization being specialized.
2367 Note that here, there's no suggestion that we're supposed to
2368 determine which of the candidate templates is most
2369 specialized. However, we, also have:
2371 [temp.func.order]
2373 Partial ordering of overloaded function template
2374 declarations is used in the following contexts to select
2375 the function template to which a function template
2376 specialization refers:
2378 -- when an explicit specialization refers to a function
2379 template.
2381 So, we do use the partial ordering rules, at least for now.
2382 This extension can only serve to make invalid programs valid,
2383 so it's safe. And, there is strong anecdotal evidence that
2384 the committee intended the partial ordering rules to apply;
2385 the EDG front end has that behavior, and John Spicer claims
2386 that the committee simply forgot to delete the wording in
2387 [temp.expl.spec]. */
2388 tree tmpl = most_specialized_instantiation (templates);
2389 if (tmpl != error_mark_node)
2391 templates = tmpl;
2392 TREE_CHAIN (templates) = NULL_TREE;
2396 // Concepts allows multiple declarations of member functions
2397 // with the same signature. Like above, we need to rely on
2398 // on the partial ordering of those candidates to determine which
2399 // is the best.
2400 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2402 if (tree cand = most_constrained_function (candidates))
2404 candidates = cand;
2405 TREE_CHAIN (cand) = NULL_TREE;
2409 if (templates == NULL_TREE && candidates == NULL_TREE)
2411 error ("template-id %qD for %q+D does not match any template "
2412 "declaration", template_id, decl);
2413 if (header_count && header_count != template_count + 1)
2414 inform (DECL_SOURCE_LOCATION (decl),
2415 "saw %d %<template<>%>, need %d for "
2416 "specializing a member function template",
2417 header_count, template_count + 1);
2418 else
2419 print_candidates (orig_fns);
2420 return error_mark_node;
2422 else if ((templates && TREE_CHAIN (templates))
2423 || (candidates && TREE_CHAIN (candidates))
2424 || (templates && candidates))
2426 error ("ambiguous template specialization %qD for %q+D",
2427 template_id, decl);
2428 candidates = chainon (candidates, templates);
2429 print_candidates (candidates);
2430 return error_mark_node;
2433 /* We have one, and exactly one, match. */
2434 if (candidates)
2436 tree fn = TREE_VALUE (candidates);
2437 *targs_out = copy_node (DECL_TI_ARGS (fn));
2439 /* Propagate the candidate's constraints to the declaration. */
2440 set_constraints (decl, get_constraints (fn));
2442 /* DECL is a re-declaration or partial instantiation of a template
2443 function. */
2444 if (TREE_CODE (fn) == TEMPLATE_DECL)
2445 return fn;
2446 /* It was a specialization of an ordinary member function in a
2447 template class. */
2448 return DECL_TI_TEMPLATE (fn);
2451 /* It was a specialization of a template. */
2452 targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2453 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2455 *targs_out = copy_node (targs);
2456 SET_TMPL_ARGS_LEVEL (*targs_out,
2457 TMPL_ARGS_DEPTH (*targs_out),
2458 TREE_PURPOSE (templates));
2460 else
2461 *targs_out = TREE_PURPOSE (templates);
2462 return TREE_VALUE (templates);
2465 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2466 but with the default argument values filled in from those in the
2467 TMPL_TYPES. */
2469 static tree
2470 copy_default_args_to_explicit_spec_1 (tree spec_types,
2471 tree tmpl_types)
2473 tree new_spec_types;
2475 if (!spec_types)
2476 return NULL_TREE;
2478 if (spec_types == void_list_node)
2479 return void_list_node;
2481 /* Substitute into the rest of the list. */
2482 new_spec_types =
2483 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2484 TREE_CHAIN (tmpl_types));
2486 /* Add the default argument for this parameter. */
2487 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2488 TREE_VALUE (spec_types),
2489 new_spec_types);
2492 /* DECL is an explicit specialization. Replicate default arguments
2493 from the template it specializes. (That way, code like:
2495 template <class T> void f(T = 3);
2496 template <> void f(double);
2497 void g () { f (); }
2499 works, as required.) An alternative approach would be to look up
2500 the correct default arguments at the call-site, but this approach
2501 is consistent with how implicit instantiations are handled. */
2503 static void
2504 copy_default_args_to_explicit_spec (tree decl)
2506 tree tmpl;
2507 tree spec_types;
2508 tree tmpl_types;
2509 tree new_spec_types;
2510 tree old_type;
2511 tree new_type;
2512 tree t;
2513 tree object_type = NULL_TREE;
2514 tree in_charge = NULL_TREE;
2515 tree vtt = NULL_TREE;
2517 /* See if there's anything we need to do. */
2518 tmpl = DECL_TI_TEMPLATE (decl);
2519 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2520 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2521 if (TREE_PURPOSE (t))
2522 break;
2523 if (!t)
2524 return;
2526 old_type = TREE_TYPE (decl);
2527 spec_types = TYPE_ARG_TYPES (old_type);
2529 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2531 /* Remove the this pointer, but remember the object's type for
2532 CV quals. */
2533 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2534 spec_types = TREE_CHAIN (spec_types);
2535 tmpl_types = TREE_CHAIN (tmpl_types);
2537 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2539 /* DECL may contain more parameters than TMPL due to the extra
2540 in-charge parameter in constructors and destructors. */
2541 in_charge = spec_types;
2542 spec_types = TREE_CHAIN (spec_types);
2544 if (DECL_HAS_VTT_PARM_P (decl))
2546 vtt = spec_types;
2547 spec_types = TREE_CHAIN (spec_types);
2551 /* Compute the merged default arguments. */
2552 new_spec_types =
2553 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2555 /* Compute the new FUNCTION_TYPE. */
2556 if (object_type)
2558 if (vtt)
2559 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2560 TREE_VALUE (vtt),
2561 new_spec_types);
2563 if (in_charge)
2564 /* Put the in-charge parameter back. */
2565 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2566 TREE_VALUE (in_charge),
2567 new_spec_types);
2569 new_type = build_method_type_directly (object_type,
2570 TREE_TYPE (old_type),
2571 new_spec_types);
2573 else
2574 new_type = build_function_type (TREE_TYPE (old_type),
2575 new_spec_types);
2576 new_type = cp_build_type_attribute_variant (new_type,
2577 TYPE_ATTRIBUTES (old_type));
2578 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2580 TREE_TYPE (decl) = new_type;
2583 /* Return the number of template headers we expect to see for a definition
2584 or specialization of CTYPE or one of its non-template members. */
2587 num_template_headers_for_class (tree ctype)
2589 int num_templates = 0;
2591 while (ctype && CLASS_TYPE_P (ctype))
2593 /* You're supposed to have one `template <...>' for every
2594 template class, but you don't need one for a full
2595 specialization. For example:
2597 template <class T> struct S{};
2598 template <> struct S<int> { void f(); };
2599 void S<int>::f () {}
2601 is correct; there shouldn't be a `template <>' for the
2602 definition of `S<int>::f'. */
2603 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2604 /* If CTYPE does not have template information of any
2605 kind, then it is not a template, nor is it nested
2606 within a template. */
2607 break;
2608 if (explicit_class_specialization_p (ctype))
2609 break;
2610 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2611 ++num_templates;
2613 ctype = TYPE_CONTEXT (ctype);
2616 return num_templates;
2619 /* Do a simple sanity check on the template headers that precede the
2620 variable declaration DECL. */
2622 void
2623 check_template_variable (tree decl)
2625 tree ctx = CP_DECL_CONTEXT (decl);
2626 int wanted = num_template_headers_for_class (ctx);
2627 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2628 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2630 if (cxx_dialect < cxx14)
2631 pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2632 "variable templates only available with "
2633 "%<-std=c++14%> or %<-std=gnu++14%>");
2635 // Namespace-scope variable templates should have a template header.
2636 ++wanted;
2638 if (template_header_count > wanted)
2640 auto_diagnostic_group d;
2641 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2642 "too many template headers for %qD "
2643 "(should be %d)",
2644 decl, wanted);
2645 if (warned && CLASS_TYPE_P (ctx)
2646 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2647 inform (DECL_SOURCE_LOCATION (decl),
2648 "members of an explicitly specialized class are defined "
2649 "without a template header");
2653 /* An explicit specialization whose declarator-id or class-head-name is not
2654 qualified shall be declared in the nearest enclosing namespace of the
2655 template, or, if the namespace is inline (7.3.1), any namespace from its
2656 enclosing namespace set.
2658 If the name declared in the explicit instantiation is an unqualified name,
2659 the explicit instantiation shall appear in the namespace where its template
2660 is declared or, if that namespace is inline (7.3.1), any namespace from its
2661 enclosing namespace set. */
2663 void
2664 check_unqualified_spec_or_inst (tree t, location_t loc)
2666 tree tmpl = most_general_template (t);
2667 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2668 && !is_nested_namespace (current_namespace,
2669 CP_DECL_CONTEXT (tmpl), true))
2671 if (processing_specialization)
2672 permerror (loc, "explicit specialization of %qD outside its "
2673 "namespace must use a nested-name-specifier", tmpl);
2674 else if (processing_explicit_instantiation
2675 && cxx_dialect >= cxx11)
2676 /* This was allowed in C++98, so only pedwarn. */
2677 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2678 "outside its namespace must use a nested-name-"
2679 "specifier", tmpl);
2683 /* Warn for a template specialization SPEC that is missing some of a set
2684 of function or type attributes that the template TEMPL is declared with.
2685 ATTRLIST is a list of additional attributes that SPEC should be taken
2686 to ultimately be declared with. */
2688 static void
2689 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2691 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2692 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2694 /* Avoid warning if the difference between the primary and
2695 the specialization is not in one of the attributes below. */
2696 const char* const blacklist[] = {
2697 "alloc_align", "alloc_size", "assume_aligned", "format",
2698 "format_arg", "malloc", "nonnull", NULL
2701 /* Put together a list of the black listed attributes that the primary
2702 template is declared with that the specialization is not, in case
2703 it's not apparent from the most recent declaration of the primary. */
2704 pretty_printer str;
2705 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2706 blacklist, &str);
2708 if (!nattrs)
2709 return;
2711 auto_diagnostic_group d;
2712 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2713 "explicit specialization %q#D may be missing attributes",
2714 spec))
2715 inform (DECL_SOURCE_LOCATION (tmpl),
2716 nattrs > 1
2717 ? G_("missing primary template attributes %s")
2718 : G_("missing primary template attribute %s"),
2719 pp_formatted_text (&str));
2722 /* Check to see if the function just declared, as indicated in
2723 DECLARATOR, and in DECL, is a specialization of a function
2724 template. We may also discover that the declaration is an explicit
2725 instantiation at this point.
2727 Returns DECL, or an equivalent declaration that should be used
2728 instead if all goes well. Issues an error message if something is
2729 amiss. Returns error_mark_node if the error is not easily
2730 recoverable.
2732 FLAGS is a bitmask consisting of the following flags:
2734 2: The function has a definition.
2735 4: The function is a friend.
2737 The TEMPLATE_COUNT is the number of references to qualifying
2738 template classes that appeared in the name of the function. For
2739 example, in
2741 template <class T> struct S { void f(); };
2742 void S<int>::f();
2744 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2745 classes are not counted in the TEMPLATE_COUNT, so that in
2747 template <class T> struct S {};
2748 template <> struct S<int> { void f(); }
2749 template <> void S<int>::f();
2751 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2752 invalid; there should be no template <>.)
2754 If the function is a specialization, it is marked as such via
2755 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2756 is set up correctly, and it is added to the list of specializations
2757 for that template. */
2759 tree
2760 check_explicit_specialization (tree declarator,
2761 tree decl,
2762 int template_count,
2763 int flags,
2764 tree attrlist)
2766 int have_def = flags & 2;
2767 int is_friend = flags & 4;
2768 bool is_concept = flags & 8;
2769 int specialization = 0;
2770 int explicit_instantiation = 0;
2771 int member_specialization = 0;
2772 tree ctype = DECL_CLASS_CONTEXT (decl);
2773 tree dname = DECL_NAME (decl);
2774 tmpl_spec_kind tsk;
2776 if (is_friend)
2778 if (!processing_specialization)
2779 tsk = tsk_none;
2780 else
2781 tsk = tsk_excessive_parms;
2783 else
2784 tsk = current_tmpl_spec_kind (template_count);
2786 switch (tsk)
2788 case tsk_none:
2789 if (processing_specialization && !VAR_P (decl))
2791 specialization = 1;
2792 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2794 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2796 if (is_friend)
2797 /* This could be something like:
2799 template <class T> void f(T);
2800 class S { friend void f<>(int); } */
2801 specialization = 1;
2802 else
2804 /* This case handles bogus declarations like template <>
2805 template <class T> void f<int>(); */
2807 error_at (cp_expr_loc_or_input_loc (declarator),
2808 "template-id %qE in declaration of primary template",
2809 declarator);
2810 return decl;
2813 break;
2815 case tsk_invalid_member_spec:
2816 /* The error has already been reported in
2817 check_specialization_scope. */
2818 return error_mark_node;
2820 case tsk_invalid_expl_inst:
2821 error ("template parameter list used in explicit instantiation");
2823 /* Fall through. */
2825 case tsk_expl_inst:
2826 if (have_def)
2827 error ("definition provided for explicit instantiation");
2829 explicit_instantiation = 1;
2830 break;
2832 case tsk_excessive_parms:
2833 case tsk_insufficient_parms:
2834 if (tsk == tsk_excessive_parms)
2835 error ("too many template parameter lists in declaration of %qD",
2836 decl);
2837 else if (template_header_count)
2838 error("too few template parameter lists in declaration of %qD", decl);
2839 else
2840 error("explicit specialization of %qD must be introduced by "
2841 "%<template <>%>", decl);
2843 /* Fall through. */
2844 case tsk_expl_spec:
2845 if (is_concept)
2846 error ("explicit specialization declared %<concept%>");
2848 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2849 /* In cases like template<> constexpr bool v = true;
2850 We'll give an error in check_template_variable. */
2851 break;
2853 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2854 if (ctype)
2855 member_specialization = 1;
2856 else
2857 specialization = 1;
2858 break;
2860 case tsk_template:
2861 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2863 /* This case handles bogus declarations like template <>
2864 template <class T> void f<int>(); */
2866 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2867 error_at (cp_expr_loc_or_input_loc (declarator),
2868 "template-id %qE in declaration of primary template",
2869 declarator);
2870 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2872 /* Partial specialization of variable template. */
2873 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2874 specialization = 1;
2875 goto ok;
2877 else if (cxx_dialect < cxx14)
2878 error_at (cp_expr_loc_or_input_loc (declarator),
2879 "non-type partial specialization %qE "
2880 "is not allowed", declarator);
2881 else
2882 error_at (cp_expr_loc_or_input_loc (declarator),
2883 "non-class, non-variable partial specialization %qE "
2884 "is not allowed", declarator);
2885 return decl;
2886 ok:;
2889 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2890 /* This is a specialization of a member template, without
2891 specialization the containing class. Something like:
2893 template <class T> struct S {
2894 template <class U> void f (U);
2896 template <> template <class U> void S<int>::f(U) {}
2898 That's a specialization -- but of the entire template. */
2899 specialization = 1;
2900 break;
2902 default:
2903 gcc_unreachable ();
2906 if ((specialization || member_specialization)
2907 /* This doesn't apply to variable templates. */
2908 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2910 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2911 for (; t; t = TREE_CHAIN (t))
2912 if (TREE_PURPOSE (t))
2914 permerror (input_location,
2915 "default argument specified in explicit specialization");
2916 break;
2920 if (specialization || member_specialization || explicit_instantiation)
2922 tree tmpl = NULL_TREE;
2923 tree targs = NULL_TREE;
2924 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2926 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2927 if (!was_template_id)
2929 tree fns;
2931 gcc_assert (identifier_p (declarator));
2932 if (ctype)
2933 fns = dname;
2934 else
2936 /* If there is no class context, the explicit instantiation
2937 must be at namespace scope. */
2938 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2940 /* Find the namespace binding, using the declaration
2941 context. */
2942 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2943 false, true);
2944 if (fns == error_mark_node)
2945 /* If lookup fails, look for a friend declaration so we can
2946 give a better diagnostic. */
2947 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2948 /*type*/false, /*complain*/true,
2949 /*hidden*/true);
2951 if (fns == error_mark_node || !is_overloaded_fn (fns))
2953 error ("%qD is not a template function", dname);
2954 fns = error_mark_node;
2958 declarator = lookup_template_function (fns, NULL_TREE);
2961 if (declarator == error_mark_node)
2962 return error_mark_node;
2964 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2966 if (!explicit_instantiation)
2967 /* A specialization in class scope. This is invalid,
2968 but the error will already have been flagged by
2969 check_specialization_scope. */
2970 return error_mark_node;
2971 else
2973 /* It's not valid to write an explicit instantiation in
2974 class scope, e.g.:
2976 class C { template void f(); }
2978 This case is caught by the parser. However, on
2979 something like:
2981 template class C { void f(); };
2983 (which is invalid) we can get here. The error will be
2984 issued later. */
2988 return decl;
2990 else if (ctype != NULL_TREE
2991 && (identifier_p (TREE_OPERAND (declarator, 0))))
2993 // We'll match variable templates in start_decl.
2994 if (VAR_P (decl))
2995 return decl;
2997 /* Find the list of functions in ctype that have the same
2998 name as the declared function. */
2999 tree name = TREE_OPERAND (declarator, 0);
3001 if (constructor_name_p (name, ctype))
3003 if (DECL_CONSTRUCTOR_P (decl)
3004 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3005 : !CLASSTYPE_DESTRUCTOR (ctype))
3007 /* From [temp.expl.spec]:
3009 If such an explicit specialization for the member
3010 of a class template names an implicitly-declared
3011 special member function (clause _special_), the
3012 program is ill-formed.
3014 Similar language is found in [temp.explicit]. */
3015 error ("specialization of implicitly-declared special member function");
3016 return error_mark_node;
3019 name = DECL_NAME (decl);
3022 /* For a type-conversion operator, We might be looking for
3023 `operator int' which will be a specialization of
3024 `operator T'. Grab all the conversion operators, and
3025 then select from them. */
3026 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3027 ? conv_op_identifier : name);
3029 if (fns == NULL_TREE)
3031 error ("no member function %qD declared in %qT", name, ctype);
3032 return error_mark_node;
3034 else
3035 TREE_OPERAND (declarator, 0) = fns;
3038 /* Figure out what exactly is being specialized at this point.
3039 Note that for an explicit instantiation, even one for a
3040 member function, we cannot tell a priori whether the
3041 instantiation is for a member template, or just a member
3042 function of a template class. Even if a member template is
3043 being instantiated, the member template arguments may be
3044 elided if they can be deduced from the rest of the
3045 declaration. */
3046 tmpl = determine_specialization (declarator, decl,
3047 &targs,
3048 member_specialization,
3049 template_count,
3050 tsk);
3052 if (!tmpl || tmpl == error_mark_node)
3053 /* We couldn't figure out what this declaration was
3054 specializing. */
3055 return error_mark_node;
3056 else
3058 if (TREE_CODE (decl) == FUNCTION_DECL
3059 && DECL_HIDDEN_FRIEND_P (tmpl))
3061 auto_diagnostic_group d;
3062 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3063 "friend declaration %qD is not visible to "
3064 "explicit specialization", tmpl))
3065 inform (DECL_SOURCE_LOCATION (tmpl),
3066 "friend declaration here");
3068 else if (!ctype && !is_friend
3069 && CP_DECL_CONTEXT (decl) == current_namespace)
3070 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3072 tree gen_tmpl = most_general_template (tmpl);
3074 if (explicit_instantiation)
3076 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3077 is done by do_decl_instantiation later. */
3079 int arg_depth = TMPL_ARGS_DEPTH (targs);
3080 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3082 if (arg_depth > parm_depth)
3084 /* If TMPL is not the most general template (for
3085 example, if TMPL is a friend template that is
3086 injected into namespace scope), then there will
3087 be too many levels of TARGS. Remove some of them
3088 here. */
3089 int i;
3090 tree new_targs;
3092 new_targs = make_tree_vec (parm_depth);
3093 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3094 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3095 = TREE_VEC_ELT (targs, i);
3096 targs = new_targs;
3099 return instantiate_template (tmpl, targs, tf_error);
3102 /* If we thought that the DECL was a member function, but it
3103 turns out to be specializing a static member function,
3104 make DECL a static member function as well. */
3105 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3106 && DECL_STATIC_FUNCTION_P (tmpl)
3107 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3108 revert_static_member_fn (decl);
3110 /* If this is a specialization of a member template of a
3111 template class, we want to return the TEMPLATE_DECL, not
3112 the specialization of it. */
3113 if (tsk == tsk_template && !was_template_id)
3115 tree result = DECL_TEMPLATE_RESULT (tmpl);
3116 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3117 DECL_INITIAL (result) = NULL_TREE;
3118 if (have_def)
3120 tree parm;
3121 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3122 DECL_SOURCE_LOCATION (result)
3123 = DECL_SOURCE_LOCATION (decl);
3124 /* We want to use the argument list specified in the
3125 definition, not in the original declaration. */
3126 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3127 for (parm = DECL_ARGUMENTS (result); parm;
3128 parm = DECL_CHAIN (parm))
3129 DECL_CONTEXT (parm) = result;
3131 return register_specialization (tmpl, gen_tmpl, targs,
3132 is_friend, 0);
3135 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3136 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3138 if (was_template_id)
3139 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3141 /* Inherit default function arguments from the template
3142 DECL is specializing. */
3143 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3144 copy_default_args_to_explicit_spec (decl);
3146 /* This specialization has the same protection as the
3147 template it specializes. */
3148 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3149 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3151 /* 7.1.1-1 [dcl.stc]
3153 A storage-class-specifier shall not be specified in an
3154 explicit specialization...
3156 The parser rejects these, so unless action is taken here,
3157 explicit function specializations will always appear with
3158 global linkage.
3160 The action recommended by the C++ CWG in response to C++
3161 defect report 605 is to make the storage class and linkage
3162 of the explicit specialization match the templated function:
3164 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3166 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3168 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3169 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3171 /* A concept cannot be specialized. */
3172 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3174 error ("explicit specialization of function concept %qD",
3175 gen_tmpl);
3176 return error_mark_node;
3179 /* This specialization has the same linkage and visibility as
3180 the function template it specializes. */
3181 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3182 if (! TREE_PUBLIC (decl))
3184 DECL_INTERFACE_KNOWN (decl) = 1;
3185 DECL_NOT_REALLY_EXTERN (decl) = 1;
3187 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3188 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3190 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3191 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3195 /* If DECL is a friend declaration, declared using an
3196 unqualified name, the namespace associated with DECL may
3197 have been set incorrectly. For example, in:
3199 template <typename T> void f(T);
3200 namespace N {
3201 struct S { friend void f<int>(int); }
3204 we will have set the DECL_CONTEXT for the friend
3205 declaration to N, rather than to the global namespace. */
3206 if (DECL_NAMESPACE_SCOPE_P (decl))
3207 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3209 if (is_friend && !have_def)
3210 /* This is not really a declaration of a specialization.
3211 It's just the name of an instantiation. But, it's not
3212 a request for an instantiation, either. */
3213 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3214 else if (TREE_CODE (decl) == FUNCTION_DECL)
3215 /* A specialization is not necessarily COMDAT. */
3216 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3217 && DECL_DECLARED_INLINE_P (decl));
3218 else if (VAR_P (decl))
3219 DECL_COMDAT (decl) = false;
3221 /* If this is a full specialization, register it so that we can find
3222 it again. Partial specializations will be registered in
3223 process_partial_specialization. */
3224 if (!processing_template_decl)
3226 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3228 decl = register_specialization (decl, gen_tmpl, targs,
3229 is_friend, 0);
3233 /* A 'structor should already have clones. */
3234 gcc_assert (decl == error_mark_node
3235 || variable_template_p (tmpl)
3236 || !(DECL_CONSTRUCTOR_P (decl)
3237 || DECL_DESTRUCTOR_P (decl))
3238 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3242 return decl;
3245 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3246 parameters. These are represented in the same format used for
3247 DECL_TEMPLATE_PARMS. */
3250 comp_template_parms (const_tree parms1, const_tree parms2)
3252 const_tree p1;
3253 const_tree p2;
3255 if (parms1 == parms2)
3256 return 1;
3258 for (p1 = parms1, p2 = parms2;
3259 p1 != NULL_TREE && p2 != NULL_TREE;
3260 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3262 tree t1 = TREE_VALUE (p1);
3263 tree t2 = TREE_VALUE (p2);
3264 int i;
3266 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3267 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3269 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3270 return 0;
3272 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3274 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3275 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3277 /* If either of the template parameters are invalid, assume
3278 they match for the sake of error recovery. */
3279 if (error_operand_p (parm1) || error_operand_p (parm2))
3280 return 1;
3282 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3283 return 0;
3285 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3286 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3287 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3288 continue;
3289 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3290 return 0;
3294 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3295 /* One set of parameters has more parameters lists than the
3296 other. */
3297 return 0;
3299 return 1;
3302 /* Returns true if two template parameters are declared with
3303 equivalent constraints. */
3305 static bool
3306 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3308 tree req1 = TREE_TYPE (parm1);
3309 tree req2 = TREE_TYPE (parm2);
3310 if (!req1 != !req2)
3311 return false;
3312 if (req1)
3313 return cp_tree_equal (req1, req2);
3314 return true;
3317 /* Returns true when two template parameters are equivalent. */
3319 static bool
3320 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3322 tree decl1 = TREE_VALUE (parm1);
3323 tree decl2 = TREE_VALUE (parm2);
3325 /* If either of the template parameters are invalid, assume
3326 they match for the sake of error recovery. */
3327 if (error_operand_p (decl1) || error_operand_p (decl2))
3328 return true;
3330 /* ... they declare parameters of the same kind. */
3331 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3332 return false;
3334 /* ... one parameter was introduced by a parameter declaration, then
3335 both are. This case arises as a result of eagerly rewriting declarations
3336 during parsing. */
3337 if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3338 return false;
3340 /* ... if either declares a pack, they both do. */
3341 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3342 return false;
3344 if (TREE_CODE (decl1) == PARM_DECL)
3346 /* ... if they declare non-type parameters, the types are equivalent. */
3347 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3348 return false;
3350 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3352 /* ... if they declare template template parameters, their template
3353 parameter lists are equivalent. */
3354 if (!template_heads_equivalent_p (decl1, decl2))
3355 return false;
3358 /* ... if they are declared with a qualified-concept name, they both
3359 are, and those names are equivalent. */
3360 return template_parameter_constraints_equivalent_p (parm1, parm2);
3363 /* Returns true if two template parameters lists are equivalent.
3364 Two template parameter lists are equivalent if they have the
3365 same length and their corresponding parameters are equivalent.
3367 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3368 data structure returned by DECL_TEMPLATE_PARMS.
3370 This is generally the same implementation as comp_template_parms
3371 except that it also the concept names and arguments used to
3372 introduce parameters. */
3374 static bool
3375 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3377 if (parms1 == parms2)
3378 return true;
3380 const_tree p1 = parms1;
3381 const_tree p2 = parms2;
3382 while (p1 != NULL_TREE && p2 != NULL_TREE)
3384 tree list1 = TREE_VALUE (p1);
3385 tree list2 = TREE_VALUE (p2);
3387 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3388 return 0;
3390 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3392 tree parm1 = TREE_VEC_ELT (list1, i);
3393 tree parm2 = TREE_VEC_ELT (list2, i);
3394 if (!template_parameters_equivalent_p (parm1, parm2))
3395 return false;
3398 p1 = TREE_CHAIN (p1);
3399 p2 = TREE_CHAIN (p2);
3402 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3403 return false;
3405 return true;
3408 /* Return true if the requires-clause of the template parameter lists are
3409 equivalent and false otherwise. */
3410 static bool
3411 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3413 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3414 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3415 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3416 return false;
3417 if (!cp_tree_equal (req1, req2))
3418 return false;
3419 return true;
3422 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3423 Two template heads are equivalent if their template parameter
3424 lists are equivalent and their requires clauses are equivalent.
3426 In pre-C++20, this is equivalent to calling comp_template_parms
3427 for the template parameters of TMPL1 and TMPL2. */
3429 bool
3430 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3432 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3433 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3435 /* Don't change the matching rules for pre-C++20. */
3436 if (cxx_dialect < cxx2a)
3437 return comp_template_parms (parms1, parms2);
3439 /* ... have the same number of template parameters, and their
3440 corresponding parameters are equivalent. */
3441 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3442 return false;
3444 /* ... if either has a requires-clause, they both do and their
3445 corresponding constraint-expressions are equivalent. */
3446 return template_requirements_equivalent_p (parms1, parms2);
3449 /* Determine whether PARM is a parameter pack. */
3451 bool
3452 template_parameter_pack_p (const_tree parm)
3454 /* Determine if we have a non-type template parameter pack. */
3455 if (TREE_CODE (parm) == PARM_DECL)
3456 return (DECL_TEMPLATE_PARM_P (parm)
3457 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3458 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3459 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3461 /* If this is a list of template parameters, we could get a
3462 TYPE_DECL or a TEMPLATE_DECL. */
3463 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3464 parm = TREE_TYPE (parm);
3466 /* Otherwise it must be a type template parameter. */
3467 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3468 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3469 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3472 /* Determine if T is a function parameter pack. */
3474 bool
3475 function_parameter_pack_p (const_tree t)
3477 if (t && TREE_CODE (t) == PARM_DECL)
3478 return DECL_PACK_P (t);
3479 return false;
3482 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3483 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3485 tree
3486 get_function_template_decl (const_tree primary_func_tmpl_inst)
3488 if (! primary_func_tmpl_inst
3489 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3490 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3491 return NULL;
3493 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3496 /* Return true iff the function parameter PARAM_DECL was expanded
3497 from the function parameter pack PACK. */
3499 bool
3500 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3502 if (DECL_ARTIFICIAL (param_decl)
3503 || !function_parameter_pack_p (pack))
3504 return false;
3506 /* The parameter pack and its pack arguments have the same
3507 DECL_PARM_INDEX. */
3508 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3511 /* Determine whether ARGS describes a variadic template args list,
3512 i.e., one that is terminated by a template argument pack. */
3514 static bool
3515 template_args_variadic_p (tree args)
3517 int nargs;
3518 tree last_parm;
3520 if (args == NULL_TREE)
3521 return false;
3523 args = INNERMOST_TEMPLATE_ARGS (args);
3524 nargs = TREE_VEC_LENGTH (args);
3526 if (nargs == 0)
3527 return false;
3529 last_parm = TREE_VEC_ELT (args, nargs - 1);
3531 return ARGUMENT_PACK_P (last_parm);
3534 /* Generate a new name for the parameter pack name NAME (an
3535 IDENTIFIER_NODE) that incorporates its */
3537 static tree
3538 make_ith_pack_parameter_name (tree name, int i)
3540 /* Munge the name to include the parameter index. */
3541 #define NUMBUF_LEN 128
3542 char numbuf[NUMBUF_LEN];
3543 char* newname;
3544 int newname_len;
3546 if (name == NULL_TREE)
3547 return name;
3548 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3549 newname_len = IDENTIFIER_LENGTH (name)
3550 + strlen (numbuf) + 2;
3551 newname = (char*)alloca (newname_len);
3552 snprintf (newname, newname_len,
3553 "%s#%i", IDENTIFIER_POINTER (name), i);
3554 return get_identifier (newname);
3557 /* Return true if T is a primary function, class or alias template
3558 specialization, not including the template pattern. */
3560 bool
3561 primary_template_specialization_p (const_tree t)
3563 if (!t)
3564 return false;
3566 if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3567 return (DECL_LANG_SPECIFIC (t)
3568 && DECL_USE_TEMPLATE (t)
3569 && DECL_TEMPLATE_INFO (t)
3570 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3571 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3572 return (CLASSTYPE_TEMPLATE_INFO (t)
3573 && CLASSTYPE_USE_TEMPLATE (t)
3574 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3575 else if (alias_template_specialization_p (t))
3576 return true;
3577 return false;
3580 /* Return true if PARM is a template template parameter. */
3582 bool
3583 template_template_parameter_p (const_tree parm)
3585 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3588 /* Return true iff PARM is a DECL representing a type template
3589 parameter. */
3591 bool
3592 template_type_parameter_p (const_tree parm)
3594 return (parm
3595 && (TREE_CODE (parm) == TYPE_DECL
3596 || TREE_CODE (parm) == TEMPLATE_DECL)
3597 && DECL_TEMPLATE_PARM_P (parm));
3600 /* Return the template parameters of T if T is a
3601 primary template instantiation, NULL otherwise. */
3603 tree
3604 get_primary_template_innermost_parameters (const_tree t)
3606 tree parms = NULL, template_info = NULL;
3608 if ((template_info = get_template_info (t))
3609 && primary_template_specialization_p (t))
3610 parms = INNERMOST_TEMPLATE_PARMS
3611 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3613 return parms;
3616 /* Return the template parameters of the LEVELth level from the full list
3617 of template parameters PARMS. */
3619 tree
3620 get_template_parms_at_level (tree parms, int level)
3622 tree p;
3623 if (!parms
3624 || TREE_CODE (parms) != TREE_LIST
3625 || level > TMPL_PARMS_DEPTH (parms))
3626 return NULL_TREE;
3628 for (p = parms; p; p = TREE_CHAIN (p))
3629 if (TMPL_PARMS_DEPTH (p) == level)
3630 return p;
3632 return NULL_TREE;
3635 /* Returns the template arguments of T if T is a template instantiation,
3636 NULL otherwise. */
3638 tree
3639 get_template_innermost_arguments (const_tree t)
3641 tree args = NULL, template_info = NULL;
3643 if ((template_info = get_template_info (t))
3644 && TI_ARGS (template_info))
3645 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3647 return args;
3650 /* Return the argument pack elements of T if T is a template argument pack,
3651 NULL otherwise. */
3653 tree
3654 get_template_argument_pack_elems (const_tree t)
3656 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3657 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3658 return NULL;
3660 return ARGUMENT_PACK_ARGS (t);
3663 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3664 ARGUMENT_PACK_SELECT represents. */
3666 static tree
3667 argument_pack_select_arg (tree t)
3669 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3670 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3672 /* If the selected argument is an expansion E, that most likely means we were
3673 called from gen_elem_of_pack_expansion_instantiation during the
3674 substituting of an argument pack (of which the Ith element is a pack
3675 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3676 In this case, the Ith element resulting from this substituting is going to
3677 be a pack expansion, which pattern is the pattern of E. Let's return the
3678 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3679 resulting pack expansion from it. */
3680 if (PACK_EXPANSION_P (arg))
3682 /* Make sure we aren't throwing away arg info. */
3683 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3684 arg = PACK_EXPANSION_PATTERN (arg);
3687 return arg;
3691 /* True iff FN is a function representing a built-in variadic parameter
3692 pack. */
3694 bool
3695 builtin_pack_fn_p (tree fn)
3697 if (!fn
3698 || TREE_CODE (fn) != FUNCTION_DECL
3699 || !DECL_IS_BUILTIN (fn))
3700 return false;
3702 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3703 return true;
3705 return false;
3708 /* True iff CALL is a call to a function representing a built-in variadic
3709 parameter pack. */
3711 static bool
3712 builtin_pack_call_p (tree call)
3714 if (TREE_CODE (call) != CALL_EXPR)
3715 return false;
3716 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3719 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3721 static tree
3722 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3723 tree in_decl)
3725 tree ohi = CALL_EXPR_ARG (call, 0);
3726 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3727 false/*fn*/, true/*int_cst*/);
3729 if (value_dependent_expression_p (hi))
3731 if (hi != ohi)
3733 call = copy_node (call);
3734 CALL_EXPR_ARG (call, 0) = hi;
3736 tree ex = make_pack_expansion (call, complain);
3737 tree vec = make_tree_vec (1);
3738 TREE_VEC_ELT (vec, 0) = ex;
3739 return vec;
3741 else
3743 hi = cxx_constant_value (hi);
3744 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3746 /* Calculate the largest value of len that won't make the size of the vec
3747 overflow an int. The compiler will exceed resource limits long before
3748 this, but it seems a decent place to diagnose. */
3749 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3751 if (len < 0 || len > max)
3753 if ((complain & tf_error)
3754 && hi != error_mark_node)
3755 error ("argument to %<__integer_pack%> must be between 0 and %d",
3756 max);
3757 return error_mark_node;
3760 tree vec = make_tree_vec (len);
3762 for (int i = 0; i < len; ++i)
3763 TREE_VEC_ELT (vec, i) = size_int (i);
3765 return vec;
3769 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3770 CALL. */
3772 static tree
3773 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3774 tree in_decl)
3776 if (!builtin_pack_call_p (call))
3777 return NULL_TREE;
3779 tree fn = CALL_EXPR_FN (call);
3781 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3782 return expand_integer_pack (call, args, complain, in_decl);
3784 return NULL_TREE;
3787 /* Structure used to track the progress of find_parameter_packs_r. */
3788 struct find_parameter_pack_data
3790 /* TREE_LIST that will contain all of the parameter packs found by
3791 the traversal. */
3792 tree* parameter_packs;
3794 /* Set of AST nodes that have been visited by the traversal. */
3795 hash_set<tree> *visited;
3797 /* True iff we're making a type pack expansion. */
3798 bool type_pack_expansion_p;
3801 /* Identifies all of the argument packs that occur in a template
3802 argument and appends them to the TREE_LIST inside DATA, which is a
3803 find_parameter_pack_data structure. This is a subroutine of
3804 make_pack_expansion and uses_parameter_packs. */
3805 static tree
3806 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3808 tree t = *tp;
3809 struct find_parameter_pack_data* ppd =
3810 (struct find_parameter_pack_data*)data;
3811 bool parameter_pack_p = false;
3813 /* Handle type aliases/typedefs. */
3814 if (TYPE_ALIAS_P (t))
3816 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3817 cp_walk_tree (&TI_ARGS (tinfo),
3818 &find_parameter_packs_r,
3819 ppd, ppd->visited);
3820 *walk_subtrees = 0;
3821 return NULL_TREE;
3824 /* Identify whether this is a parameter pack or not. */
3825 switch (TREE_CODE (t))
3827 case TEMPLATE_PARM_INDEX:
3828 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3829 parameter_pack_p = true;
3830 break;
3832 case TEMPLATE_TYPE_PARM:
3833 t = TYPE_MAIN_VARIANT (t);
3834 /* FALLTHRU */
3835 case TEMPLATE_TEMPLATE_PARM:
3836 /* If the placeholder appears in the decl-specifier-seq of a function
3837 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3838 is a pack expansion, the invented template parameter is a template
3839 parameter pack. */
3840 if (ppd->type_pack_expansion_p && is_auto (t))
3841 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3842 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3843 parameter_pack_p = true;
3844 break;
3846 case FIELD_DECL:
3847 case PARM_DECL:
3848 if (DECL_PACK_P (t))
3850 /* We don't want to walk into the type of a PARM_DECL,
3851 because we don't want to see the type parameter pack. */
3852 *walk_subtrees = 0;
3853 parameter_pack_p = true;
3855 break;
3857 case VAR_DECL:
3858 if (DECL_PACK_P (t))
3860 /* We don't want to walk into the type of a variadic capture proxy,
3861 because we don't want to see the type parameter pack. */
3862 *walk_subtrees = 0;
3863 parameter_pack_p = true;
3865 else if (variable_template_specialization_p (t))
3867 cp_walk_tree (&DECL_TI_ARGS (t),
3868 find_parameter_packs_r,
3869 ppd, ppd->visited);
3870 *walk_subtrees = 0;
3872 break;
3874 case CALL_EXPR:
3875 if (builtin_pack_call_p (t))
3876 parameter_pack_p = true;
3877 break;
3879 case BASES:
3880 parameter_pack_p = true;
3881 break;
3882 default:
3883 /* Not a parameter pack. */
3884 break;
3887 if (parameter_pack_p)
3889 /* Add this parameter pack to the list. */
3890 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3893 if (TYPE_P (t))
3894 cp_walk_tree (&TYPE_CONTEXT (t),
3895 &find_parameter_packs_r, ppd, ppd->visited);
3897 /* This switch statement will return immediately if we don't find a
3898 parameter pack. */
3899 switch (TREE_CODE (t))
3901 case TEMPLATE_PARM_INDEX:
3902 return NULL_TREE;
3904 case BOUND_TEMPLATE_TEMPLATE_PARM:
3905 /* Check the template itself. */
3906 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3907 &find_parameter_packs_r, ppd, ppd->visited);
3908 /* Check the template arguments. */
3909 cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3910 ppd->visited);
3911 *walk_subtrees = 0;
3912 return NULL_TREE;
3914 case TEMPLATE_TYPE_PARM:
3915 case TEMPLATE_TEMPLATE_PARM:
3916 return NULL_TREE;
3918 case PARM_DECL:
3919 return NULL_TREE;
3921 case DECL_EXPR:
3922 /* Ignore the declaration of a capture proxy for a parameter pack. */
3923 if (is_capture_proxy (DECL_EXPR_DECL (t)))
3924 *walk_subtrees = 0;
3925 return NULL_TREE;
3927 case RECORD_TYPE:
3928 if (TYPE_PTRMEMFUNC_P (t))
3929 return NULL_TREE;
3930 /* Fall through. */
3932 case UNION_TYPE:
3933 case ENUMERAL_TYPE:
3934 if (TYPE_TEMPLATE_INFO (t))
3935 cp_walk_tree (&TYPE_TI_ARGS (t),
3936 &find_parameter_packs_r, ppd, ppd->visited);
3938 *walk_subtrees = 0;
3939 return NULL_TREE;
3941 case TEMPLATE_DECL:
3942 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3943 return NULL_TREE;
3944 gcc_fallthrough();
3946 case CONSTRUCTOR:
3947 cp_walk_tree (&TREE_TYPE (t),
3948 &find_parameter_packs_r, ppd, ppd->visited);
3949 return NULL_TREE;
3951 case TYPENAME_TYPE:
3952 cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3953 ppd, ppd->visited);
3954 *walk_subtrees = 0;
3955 return NULL_TREE;
3957 case TYPE_PACK_EXPANSION:
3958 case EXPR_PACK_EXPANSION:
3959 *walk_subtrees = 0;
3960 return NULL_TREE;
3962 case INTEGER_TYPE:
3963 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3964 ppd, ppd->visited);
3965 *walk_subtrees = 0;
3966 return NULL_TREE;
3968 case IDENTIFIER_NODE:
3969 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3970 ppd->visited);
3971 *walk_subtrees = 0;
3972 return NULL_TREE;
3974 case LAMBDA_EXPR:
3976 /* Look at explicit captures. */
3977 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3978 cap; cap = TREE_CHAIN (cap))
3979 cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3980 ppd->visited);
3981 /* Since we defer implicit capture, look in the parms and body. */
3982 tree fn = lambda_function (t);
3983 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
3984 ppd->visited);
3985 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3986 ppd->visited);
3987 *walk_subtrees = 0;
3988 return NULL_TREE;
3991 case DECLTYPE_TYPE:
3993 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3994 type_pack_expansion_p to false so that any placeholders
3995 within the expression don't get marked as parameter packs. */
3996 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3997 ppd->type_pack_expansion_p = false;
3998 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3999 ppd, ppd->visited);
4000 ppd->type_pack_expansion_p = type_pack_expansion_p;
4001 *walk_subtrees = 0;
4002 return NULL_TREE;
4005 case IF_STMT:
4006 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4007 ppd, ppd->visited);
4008 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4009 ppd, ppd->visited);
4010 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4011 ppd, ppd->visited);
4012 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4013 *walk_subtrees = 0;
4014 return NULL_TREE;
4016 default:
4017 return NULL_TREE;
4020 return NULL_TREE;
4023 /* Determines if the expression or type T uses any parameter packs. */
4024 tree
4025 uses_parameter_packs (tree t)
4027 tree parameter_packs = NULL_TREE;
4028 struct find_parameter_pack_data ppd;
4029 ppd.parameter_packs = &parameter_packs;
4030 ppd.visited = new hash_set<tree>;
4031 ppd.type_pack_expansion_p = false;
4032 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4033 delete ppd.visited;
4034 return parameter_packs;
4037 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4038 representation a base-class initializer into a parameter pack
4039 expansion. If all goes well, the resulting node will be an
4040 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4041 respectively. */
4042 tree
4043 make_pack_expansion (tree arg, tsubst_flags_t complain)
4045 tree result;
4046 tree parameter_packs = NULL_TREE;
4047 bool for_types = false;
4048 struct find_parameter_pack_data ppd;
4050 if (!arg || arg == error_mark_node)
4051 return arg;
4053 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4055 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4056 class initializer. In this case, the TREE_PURPOSE will be a
4057 _TYPE node (representing the base class expansion we're
4058 initializing) and the TREE_VALUE will be a TREE_LIST
4059 containing the initialization arguments.
4061 The resulting expansion looks somewhat different from most
4062 expansions. Rather than returning just one _EXPANSION, we
4063 return a TREE_LIST whose TREE_PURPOSE is a
4064 TYPE_PACK_EXPANSION containing the bases that will be
4065 initialized. The TREE_VALUE will be identical to the
4066 original TREE_VALUE, which is a list of arguments that will
4067 be passed to each base. We do not introduce any new pack
4068 expansion nodes into the TREE_VALUE (although it is possible
4069 that some already exist), because the TREE_PURPOSE and
4070 TREE_VALUE all need to be expanded together with the same
4071 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4072 resulting TREE_PURPOSE will mention the parameter packs in
4073 both the bases and the arguments to the bases. */
4074 tree purpose;
4075 tree value;
4076 tree parameter_packs = NULL_TREE;
4078 /* Determine which parameter packs will be used by the base
4079 class expansion. */
4080 ppd.visited = new hash_set<tree>;
4081 ppd.parameter_packs = &parameter_packs;
4082 ppd.type_pack_expansion_p = false;
4083 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4084 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4085 &ppd, ppd.visited);
4087 if (parameter_packs == NULL_TREE)
4089 if (complain & tf_error)
4090 error ("base initializer expansion %qT contains no parameter packs",
4091 arg);
4092 delete ppd.visited;
4093 return error_mark_node;
4096 if (TREE_VALUE (arg) != void_type_node)
4098 /* Collect the sets of parameter packs used in each of the
4099 initialization arguments. */
4100 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4102 /* Determine which parameter packs will be expanded in this
4103 argument. */
4104 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4105 &ppd, ppd.visited);
4109 delete ppd.visited;
4111 /* Create the pack expansion type for the base type. */
4112 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4113 SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4114 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4115 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4117 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4118 they will rarely be compared to anything. */
4119 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4121 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4124 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4125 for_types = true;
4127 /* Build the PACK_EXPANSION_* node. */
4128 result = for_types
4129 ? cxx_make_type (TYPE_PACK_EXPANSION)
4130 : make_node (EXPR_PACK_EXPANSION);
4131 SET_PACK_EXPANSION_PATTERN (result, arg);
4132 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4134 /* Propagate type and const-expression information. */
4135 TREE_TYPE (result) = TREE_TYPE (arg);
4136 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4137 /* Mark this read now, since the expansion might be length 0. */
4138 mark_exp_read (arg);
4140 else
4141 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4142 they will rarely be compared to anything. */
4143 SET_TYPE_STRUCTURAL_EQUALITY (result);
4145 /* Determine which parameter packs will be expanded. */
4146 ppd.parameter_packs = &parameter_packs;
4147 ppd.visited = new hash_set<tree>;
4148 ppd.type_pack_expansion_p = TYPE_P (arg);
4149 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4150 delete ppd.visited;
4152 /* Make sure we found some parameter packs. */
4153 if (parameter_packs == NULL_TREE)
4155 if (complain & tf_error)
4157 if (TYPE_P (arg))
4158 error ("expansion pattern %qT contains no parameter packs", arg);
4159 else
4160 error ("expansion pattern %qE contains no parameter packs", arg);
4162 return error_mark_node;
4164 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4166 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4168 return result;
4171 /* Checks T for any "bare" parameter packs, which have not yet been
4172 expanded, and issues an error if any are found. This operation can
4173 only be done on full expressions or types (e.g., an expression
4174 statement, "if" condition, etc.), because we could have expressions like:
4176 foo(f(g(h(args)))...)
4178 where "args" is a parameter pack. check_for_bare_parameter_packs
4179 should not be called for the subexpressions args, h(args),
4180 g(h(args)), or f(g(h(args))), because we would produce erroneous
4181 error messages.
4183 Returns TRUE and emits an error if there were bare parameter packs,
4184 returns FALSE otherwise. */
4185 bool
4186 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4188 tree parameter_packs = NULL_TREE;
4189 struct find_parameter_pack_data ppd;
4191 if (!processing_template_decl || !t || t == error_mark_node)
4192 return false;
4194 /* A lambda might use a parameter pack from the containing context. */
4195 if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4196 && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4197 return false;
4199 if (TREE_CODE (t) == TYPE_DECL)
4200 t = TREE_TYPE (t);
4202 ppd.parameter_packs = &parameter_packs;
4203 ppd.visited = new hash_set<tree>;
4204 ppd.type_pack_expansion_p = false;
4205 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4206 delete ppd.visited;
4208 if (parameter_packs)
4210 if (loc == UNKNOWN_LOCATION)
4211 loc = cp_expr_loc_or_input_loc (t);
4212 error_at (loc, "parameter packs not expanded with %<...%>:");
4213 while (parameter_packs)
4215 tree pack = TREE_VALUE (parameter_packs);
4216 tree name = NULL_TREE;
4218 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4219 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4220 name = TYPE_NAME (pack);
4221 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4222 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4223 else if (TREE_CODE (pack) == CALL_EXPR)
4224 name = DECL_NAME (CALL_EXPR_FN (pack));
4225 else
4226 name = DECL_NAME (pack);
4228 if (name)
4229 inform (loc, " %qD", name);
4230 else
4231 inform (loc, " %s", "<anonymous>");
4233 parameter_packs = TREE_CHAIN (parameter_packs);
4236 return true;
4239 return false;
4242 /* Expand any parameter packs that occur in the template arguments in
4243 ARGS. */
4244 tree
4245 expand_template_argument_pack (tree args)
4247 if (args == error_mark_node)
4248 return error_mark_node;
4250 tree result_args = NULL_TREE;
4251 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4252 int num_result_args = -1;
4253 int non_default_args_count = -1;
4255 /* First, determine if we need to expand anything, and the number of
4256 slots we'll need. */
4257 for (in_arg = 0; in_arg < nargs; ++in_arg)
4259 tree arg = TREE_VEC_ELT (args, in_arg);
4260 if (arg == NULL_TREE)
4261 return args;
4262 if (ARGUMENT_PACK_P (arg))
4264 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4265 if (num_result_args < 0)
4266 num_result_args = in_arg + num_packed;
4267 else
4268 num_result_args += num_packed;
4270 else
4272 if (num_result_args >= 0)
4273 num_result_args++;
4277 /* If no expansion is necessary, we're done. */
4278 if (num_result_args < 0)
4279 return args;
4281 /* Expand arguments. */
4282 result_args = make_tree_vec (num_result_args);
4283 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4284 non_default_args_count =
4285 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4286 for (in_arg = 0; in_arg < nargs; ++in_arg)
4288 tree arg = TREE_VEC_ELT (args, in_arg);
4289 if (ARGUMENT_PACK_P (arg))
4291 tree packed = ARGUMENT_PACK_ARGS (arg);
4292 int i, num_packed = TREE_VEC_LENGTH (packed);
4293 for (i = 0; i < num_packed; ++i, ++out_arg)
4294 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4295 if (non_default_args_count > 0)
4296 non_default_args_count += num_packed - 1;
4298 else
4300 TREE_VEC_ELT (result_args, out_arg) = arg;
4301 ++out_arg;
4304 if (non_default_args_count >= 0)
4305 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4306 return result_args;
4309 /* Checks if DECL shadows a template parameter.
4311 [temp.local]: A template-parameter shall not be redeclared within its
4312 scope (including nested scopes).
4314 Emits an error and returns TRUE if the DECL shadows a parameter,
4315 returns FALSE otherwise. */
4317 bool
4318 check_template_shadow (tree decl)
4320 tree olddecl;
4322 /* If we're not in a template, we can't possibly shadow a template
4323 parameter. */
4324 if (!current_template_parms)
4325 return true;
4327 /* Figure out what we're shadowing. */
4328 decl = OVL_FIRST (decl);
4329 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4331 /* If there's no previous binding for this name, we're not shadowing
4332 anything, let alone a template parameter. */
4333 if (!olddecl)
4334 return true;
4336 /* If we're not shadowing a template parameter, we're done. Note
4337 that OLDDECL might be an OVERLOAD (or perhaps even an
4338 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4339 node. */
4340 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4341 return true;
4343 /* We check for decl != olddecl to avoid bogus errors for using a
4344 name inside a class. We check TPFI to avoid duplicate errors for
4345 inline member templates. */
4346 if (decl == olddecl
4347 || (DECL_TEMPLATE_PARM_P (decl)
4348 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4349 return true;
4351 /* Don't complain about the injected class name, as we've already
4352 complained about the class itself. */
4353 if (DECL_SELF_REFERENCE_P (decl))
4354 return false;
4356 if (DECL_TEMPLATE_PARM_P (decl))
4357 error ("declaration of template parameter %q+D shadows "
4358 "template parameter", decl);
4359 else
4360 error ("declaration of %q+#D shadows template parameter", decl);
4361 inform (DECL_SOURCE_LOCATION (olddecl),
4362 "template parameter %qD declared here", olddecl);
4363 return false;
4366 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4367 ORIG_LEVEL, DECL, and TYPE. */
4369 static tree
4370 build_template_parm_index (int index,
4371 int level,
4372 int orig_level,
4373 tree decl,
4374 tree type)
4376 tree t = make_node (TEMPLATE_PARM_INDEX);
4377 TEMPLATE_PARM_IDX (t) = index;
4378 TEMPLATE_PARM_LEVEL (t) = level;
4379 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4380 TEMPLATE_PARM_DECL (t) = decl;
4381 TREE_TYPE (t) = type;
4382 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4383 TREE_READONLY (t) = TREE_READONLY (decl);
4385 return t;
4388 /* Find the canonical type parameter for the given template type
4389 parameter. Returns the canonical type parameter, which may be TYPE
4390 if no such parameter existed. */
4392 static tree
4393 canonical_type_parameter (tree type)
4395 tree list;
4396 int idx = TEMPLATE_TYPE_IDX (type);
4397 if (!canonical_template_parms)
4398 vec_alloc (canonical_template_parms, idx + 1);
4400 if (canonical_template_parms->length () <= (unsigned) idx)
4401 vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4403 list = (*canonical_template_parms)[idx];
4404 while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4405 list = TREE_CHAIN (list);
4407 if (list)
4408 return TREE_VALUE (list);
4409 else
4411 (*canonical_template_parms)[idx]
4412 = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4413 return type;
4417 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4418 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4419 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4420 new one is created. */
4422 static tree
4423 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4424 tsubst_flags_t complain)
4426 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4427 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4428 != TEMPLATE_PARM_LEVEL (index) - levels)
4429 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4431 tree orig_decl = TEMPLATE_PARM_DECL (index);
4432 tree decl, t;
4434 decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4435 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4436 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4437 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4438 DECL_ARTIFICIAL (decl) = 1;
4439 SET_DECL_TEMPLATE_PARM_P (decl);
4441 t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4442 TEMPLATE_PARM_LEVEL (index) - levels,
4443 TEMPLATE_PARM_ORIG_LEVEL (index),
4444 decl, type);
4445 TEMPLATE_PARM_DESCENDANTS (index) = t;
4446 TEMPLATE_PARM_PARAMETER_PACK (t)
4447 = TEMPLATE_PARM_PARAMETER_PACK (index);
4449 /* Template template parameters need this. */
4450 if (TREE_CODE (decl) == TEMPLATE_DECL)
4452 DECL_TEMPLATE_RESULT (decl)
4453 = build_decl (DECL_SOURCE_LOCATION (decl),
4454 TYPE_DECL, DECL_NAME (decl), type);
4455 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4456 DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4457 (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4461 return TEMPLATE_PARM_DESCENDANTS (index);
4464 /* Process information from new template parameter PARM and append it
4465 to the LIST being built. This new parameter is a non-type
4466 parameter iff IS_NON_TYPE is true. This new parameter is a
4467 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4468 is in PARM_LOC. */
4470 tree
4471 process_template_parm (tree list, location_t parm_loc, tree parm,
4472 bool is_non_type, bool is_parameter_pack)
4474 tree decl = 0;
4475 int idx = 0;
4477 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4478 tree defval = TREE_PURPOSE (parm);
4479 tree constr = TREE_TYPE (parm);
4481 if (list)
4483 tree p = tree_last (list);
4485 if (p && TREE_VALUE (p) != error_mark_node)
4487 p = TREE_VALUE (p);
4488 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4489 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4490 else
4491 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4494 ++idx;
4497 if (is_non_type)
4499 parm = TREE_VALUE (parm);
4501 SET_DECL_TEMPLATE_PARM_P (parm);
4503 if (TREE_TYPE (parm) != error_mark_node)
4505 /* [temp.param]
4507 The top-level cv-qualifiers on the template-parameter are
4508 ignored when determining its type. */
4509 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4510 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4511 TREE_TYPE (parm) = error_mark_node;
4512 else if (uses_parameter_packs (TREE_TYPE (parm))
4513 && !is_parameter_pack
4514 /* If we're in a nested template parameter list, the template
4515 template parameter could be a parameter pack. */
4516 && processing_template_parmlist == 1)
4518 /* This template parameter is not a parameter pack, but it
4519 should be. Complain about "bare" parameter packs. */
4520 check_for_bare_parameter_packs (TREE_TYPE (parm));
4522 /* Recover by calling this a parameter pack. */
4523 is_parameter_pack = true;
4527 /* A template parameter is not modifiable. */
4528 TREE_CONSTANT (parm) = 1;
4529 TREE_READONLY (parm) = 1;
4530 decl = build_decl (parm_loc,
4531 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4532 TREE_CONSTANT (decl) = 1;
4533 TREE_READONLY (decl) = 1;
4534 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4535 = build_template_parm_index (idx, processing_template_decl,
4536 processing_template_decl,
4537 decl, TREE_TYPE (parm));
4539 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4540 = is_parameter_pack;
4542 else
4544 tree t;
4545 parm = TREE_VALUE (TREE_VALUE (parm));
4547 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4549 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4550 /* This is for distinguishing between real templates and template
4551 template parameters */
4552 TREE_TYPE (parm) = t;
4553 TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4554 decl = parm;
4556 else
4558 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4559 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4560 decl = build_decl (parm_loc,
4561 TYPE_DECL, parm, t);
4564 TYPE_NAME (t) = decl;
4565 TYPE_STUB_DECL (t) = decl;
4566 parm = decl;
4567 TEMPLATE_TYPE_PARM_INDEX (t)
4568 = build_template_parm_index (idx, processing_template_decl,
4569 processing_template_decl,
4570 decl, TREE_TYPE (parm));
4571 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4572 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4574 DECL_ARTIFICIAL (decl) = 1;
4575 SET_DECL_TEMPLATE_PARM_P (decl);
4577 /* Build requirements for the type/template parameter.
4578 This must be done after SET_DECL_TEMPLATE_PARM_P or
4579 process_template_parm could fail. */
4580 tree reqs = finish_shorthand_constraint (parm, constr);
4582 decl = pushdecl (decl);
4583 if (!is_non_type)
4584 parm = decl;
4586 /* Build the parameter node linking the parameter declaration,
4587 its default argument (if any), and its constraints (if any). */
4588 parm = build_tree_list (defval, parm);
4589 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4591 return chainon (list, parm);
4594 /* The end of a template parameter list has been reached. Process the
4595 tree list into a parameter vector, converting each parameter into a more
4596 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4597 as PARM_DECLs. */
4599 tree
4600 end_template_parm_list (tree parms)
4602 int nparms;
4603 tree parm, next;
4604 tree saved_parmlist = make_tree_vec (list_length (parms));
4606 /* Pop the dummy parameter level and add the real one. */
4607 current_template_parms = TREE_CHAIN (current_template_parms);
4609 current_template_parms
4610 = tree_cons (size_int (processing_template_decl),
4611 saved_parmlist, current_template_parms);
4613 for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4615 next = TREE_CHAIN (parm);
4616 TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4617 TREE_CHAIN (parm) = NULL_TREE;
4620 --processing_template_parmlist;
4622 return saved_parmlist;
4625 // Explicitly indicate the end of the template parameter list. We assume
4626 // that the current template parameters have been constructed and/or
4627 // managed explicitly, as when creating new template template parameters
4628 // from a shorthand constraint.
4629 void
4630 end_template_parm_list ()
4632 --processing_template_parmlist;
4635 /* end_template_decl is called after a template declaration is seen. */
4637 void
4638 end_template_decl (void)
4640 reset_specialization ();
4642 if (! processing_template_decl)
4643 return;
4645 /* This matches the pushlevel in begin_template_parm_list. */
4646 finish_scope ();
4648 --processing_template_decl;
4649 current_template_parms = TREE_CHAIN (current_template_parms);
4652 /* Takes a TREE_LIST representing a template parameter and convert it
4653 into an argument suitable to be passed to the type substitution
4654 functions. Note that If the TREE_LIST contains an error_mark
4655 node, the returned argument is error_mark_node. */
4657 tree
4658 template_parm_to_arg (tree t)
4661 if (t == NULL_TREE
4662 || TREE_CODE (t) != TREE_LIST)
4663 return t;
4665 if (error_operand_p (TREE_VALUE (t)))
4666 return error_mark_node;
4668 t = TREE_VALUE (t);
4670 if (TREE_CODE (t) == TYPE_DECL
4671 || TREE_CODE (t) == TEMPLATE_DECL)
4673 t = TREE_TYPE (t);
4675 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4677 /* Turn this argument into a TYPE_ARGUMENT_PACK
4678 with a single element, which expands T. */
4679 tree vec = make_tree_vec (1);
4680 if (CHECKING_P)
4681 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4683 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4685 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4686 SET_ARGUMENT_PACK_ARGS (t, vec);
4689 else
4691 t = DECL_INITIAL (t);
4693 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4695 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4696 with a single element, which expands T. */
4697 tree vec = make_tree_vec (1);
4698 if (CHECKING_P)
4699 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4701 t = convert_from_reference (t);
4702 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4704 t = make_node (NONTYPE_ARGUMENT_PACK);
4705 SET_ARGUMENT_PACK_ARGS (t, vec);
4707 else
4708 t = convert_from_reference (t);
4710 return t;
4713 /* Given a single level of template parameters (a TREE_VEC), return it
4714 as a set of template arguments. */
4716 tree
4717 template_parms_level_to_args (tree parms)
4719 tree a = copy_node (parms);
4720 TREE_TYPE (a) = NULL_TREE;
4721 for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4722 TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4724 if (CHECKING_P)
4725 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4727 return a;
4730 /* Given a set of template parameters, return them as a set of template
4731 arguments. The template parameters are represented as a TREE_VEC, in
4732 the form documented in cp-tree.h for template arguments. */
4734 tree
4735 template_parms_to_args (tree parms)
4737 tree header;
4738 tree args = NULL_TREE;
4739 int length = TMPL_PARMS_DEPTH (parms);
4740 int l = length;
4742 /* If there is only one level of template parameters, we do not
4743 create a TREE_VEC of TREE_VECs. Instead, we return a single
4744 TREE_VEC containing the arguments. */
4745 if (length > 1)
4746 args = make_tree_vec (length);
4748 for (header = parms; header; header = TREE_CHAIN (header))
4750 tree a = template_parms_level_to_args (TREE_VALUE (header));
4752 if (length > 1)
4753 TREE_VEC_ELT (args, --l) = a;
4754 else
4755 args = a;
4758 return args;
4761 /* Within the declaration of a template, return the currently active
4762 template parameters as an argument TREE_VEC. */
4764 static tree
4765 current_template_args (void)
4767 return template_parms_to_args (current_template_parms);
4770 /* Return the fully generic arguments for of TMPL, i.e. what
4771 current_template_args would be while parsing it. */
4773 tree
4774 generic_targs_for (tree tmpl)
4776 if (tmpl == NULL_TREE)
4777 return NULL_TREE;
4778 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4779 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4780 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4781 template parameter, it has no TEMPLATE_INFO; for a partial
4782 specialization, it has the arguments for the primary template, and we
4783 want the arguments for the partial specialization. */;
4784 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4785 if (tree ti = get_template_info (result))
4786 return TI_ARGS (ti);
4787 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4790 /* Update the declared TYPE by doing any lookups which were thought to be
4791 dependent, but are not now that we know the SCOPE of the declarator. */
4793 tree
4794 maybe_update_decl_type (tree orig_type, tree scope)
4796 tree type = orig_type;
4798 if (type == NULL_TREE)
4799 return type;
4801 if (TREE_CODE (orig_type) == TYPE_DECL)
4802 type = TREE_TYPE (type);
4804 if (scope && TYPE_P (scope) && dependent_type_p (scope)
4805 && dependent_type_p (type)
4806 /* Don't bother building up the args in this case. */
4807 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4809 /* tsubst in the args corresponding to the template parameters,
4810 including auto if present. Most things will be unchanged, but
4811 make_typename_type and tsubst_qualified_id will resolve
4812 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
4813 tree args = current_template_args ();
4814 tree auto_node = type_uses_auto (type);
4815 tree pushed;
4816 if (auto_node)
4818 tree auto_vec = make_tree_vec (1);
4819 TREE_VEC_ELT (auto_vec, 0) = auto_node;
4820 args = add_to_template_args (args, auto_vec);
4822 pushed = push_scope (scope);
4823 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4824 if (pushed)
4825 pop_scope (scope);
4828 if (type == error_mark_node)
4829 return orig_type;
4831 if (TREE_CODE (orig_type) == TYPE_DECL)
4833 if (same_type_p (type, TREE_TYPE (orig_type)))
4834 type = orig_type;
4835 else
4836 type = TYPE_NAME (type);
4838 return type;
4841 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4842 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
4843 the new template is a member template. */
4845 static tree
4846 build_template_decl (tree decl, tree parms, bool member_template_p)
4848 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4849 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4850 DECL_TEMPLATE_PARMS (tmpl) = parms;
4851 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4852 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4853 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4855 return tmpl;
4858 struct template_parm_data
4860 /* The level of the template parameters we are currently
4861 processing. */
4862 int level;
4864 /* The index of the specialization argument we are currently
4865 processing. */
4866 int current_arg;
4868 /* An array whose size is the number of template parameters. The
4869 elements are nonzero if the parameter has been used in any one
4870 of the arguments processed so far. */
4871 int* parms;
4873 /* An array whose size is the number of template arguments. The
4874 elements are nonzero if the argument makes use of template
4875 parameters of this level. */
4876 int* arg_uses_template_parms;
4879 /* Subroutine of push_template_decl used to see if each template
4880 parameter in a partial specialization is used in the explicit
4881 argument list. If T is of the LEVEL given in DATA (which is
4882 treated as a template_parm_data*), then DATA->PARMS is marked
4883 appropriately. */
4885 static int
4886 mark_template_parm (tree t, void* data)
4888 int level;
4889 int idx;
4890 struct template_parm_data* tpd = (struct template_parm_data*) data;
4892 template_parm_level_and_index (t, &level, &idx);
4894 if (level == tpd->level)
4896 tpd->parms[idx] = 1;
4897 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4900 /* In C++17 the type of a non-type argument is a deduced context. */
4901 if (cxx_dialect >= cxx17
4902 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4903 for_each_template_parm (TREE_TYPE (t),
4904 &mark_template_parm,
4905 data,
4906 NULL,
4907 /*include_nondeduced_p=*/false);
4909 /* Return zero so that for_each_template_parm will continue the
4910 traversal of the tree; we want to mark *every* template parm. */
4911 return 0;
4914 /* Process the partial specialization DECL. */
4916 static tree
4917 process_partial_specialization (tree decl)
4919 tree type = TREE_TYPE (decl);
4920 tree tinfo = get_template_info (decl);
4921 tree maintmpl = TI_TEMPLATE (tinfo);
4922 tree specargs = TI_ARGS (tinfo);
4923 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4924 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4925 tree inner_parms;
4926 tree inst;
4927 int nargs = TREE_VEC_LENGTH (inner_args);
4928 int ntparms;
4929 int i;
4930 bool did_error_intro = false;
4931 struct template_parm_data tpd;
4932 struct template_parm_data tpd2;
4934 gcc_assert (current_template_parms);
4936 /* A concept cannot be specialized. */
4937 if (flag_concepts && variable_concept_p (maintmpl))
4939 error ("specialization of variable concept %q#D", maintmpl);
4940 return error_mark_node;
4943 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4944 ntparms = TREE_VEC_LENGTH (inner_parms);
4946 /* We check that each of the template parameters given in the
4947 partial specialization is used in the argument list to the
4948 specialization. For example:
4950 template <class T> struct S;
4951 template <class T> struct S<T*>;
4953 The second declaration is OK because `T*' uses the template
4954 parameter T, whereas
4956 template <class T> struct S<int>;
4958 is no good. Even trickier is:
4960 template <class T>
4961 struct S1
4963 template <class U>
4964 struct S2;
4965 template <class U>
4966 struct S2<T>;
4969 The S2<T> declaration is actually invalid; it is a
4970 full-specialization. Of course,
4972 template <class U>
4973 struct S2<T (*)(U)>;
4975 or some such would have been OK. */
4976 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4977 tpd.parms = XALLOCAVEC (int, ntparms);
4978 memset (tpd.parms, 0, sizeof (int) * ntparms);
4980 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4981 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4982 for (i = 0; i < nargs; ++i)
4984 tpd.current_arg = i;
4985 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4986 &mark_template_parm,
4987 &tpd,
4988 NULL,
4989 /*include_nondeduced_p=*/false);
4991 for (i = 0; i < ntparms; ++i)
4992 if (tpd.parms[i] == 0)
4994 /* One of the template parms was not used in a deduced context in the
4995 specialization. */
4996 if (!did_error_intro)
4998 error ("template parameters not deducible in "
4999 "partial specialization:");
5000 did_error_intro = true;
5003 inform (input_location, " %qD",
5004 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5007 if (did_error_intro)
5008 return error_mark_node;
5010 /* [temp.class.spec]
5012 The argument list of the specialization shall not be identical to
5013 the implicit argument list of the primary template. */
5014 tree main_args
5015 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5016 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5017 && (!flag_concepts
5018 || !strictly_subsumes (current_template_constraints (),
5019 inner_args, maintmpl)))
5021 if (!flag_concepts)
5022 error ("partial specialization %q+D does not specialize "
5023 "any template arguments; to define the primary template, "
5024 "remove the template argument list", decl);
5025 else
5026 error ("partial specialization %q+D does not specialize any "
5027 "template arguments and is not more constrained than "
5028 "the primary template; to define the primary template, "
5029 "remove the template argument list", decl);
5030 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5033 /* A partial specialization that replaces multiple parameters of the
5034 primary template with a pack expansion is less specialized for those
5035 parameters. */
5036 if (nargs < DECL_NTPARMS (maintmpl))
5038 error ("partial specialization is not more specialized than the "
5039 "primary template because it replaces multiple parameters "
5040 "with a pack expansion");
5041 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5042 /* Avoid crash in process_partial_specialization. */
5043 return decl;
5046 /* If we aren't in a dependent class, we can actually try deduction. */
5047 else if (tpd.level == 1
5048 /* FIXME we should be able to handle a partial specialization of a
5049 partial instantiation, but currently we can't (c++/41727). */
5050 && TMPL_ARGS_DEPTH (specargs) == 1
5051 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5053 auto_diagnostic_group d;
5054 if (permerror (input_location, "partial specialization %qD is not "
5055 "more specialized than", decl))
5056 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5057 maintmpl);
5060 /* [temp.class.spec]
5062 A partially specialized non-type argument expression shall not
5063 involve template parameters of the partial specialization except
5064 when the argument expression is a simple identifier.
5066 The type of a template parameter corresponding to a specialized
5067 non-type argument shall not be dependent on a parameter of the
5068 specialization.
5070 Also, we verify that pack expansions only occur at the
5071 end of the argument list. */
5072 gcc_assert (nargs == DECL_NTPARMS (maintmpl));
5073 tpd2.parms = 0;
5074 for (i = 0; i < nargs; ++i)
5076 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5077 tree arg = TREE_VEC_ELT (inner_args, i);
5078 tree packed_args = NULL_TREE;
5079 int j, len = 1;
5081 if (ARGUMENT_PACK_P (arg))
5083 /* Extract the arguments from the argument pack. We'll be
5084 iterating over these in the following loop. */
5085 packed_args = ARGUMENT_PACK_ARGS (arg);
5086 len = TREE_VEC_LENGTH (packed_args);
5089 for (j = 0; j < len; j++)
5091 if (packed_args)
5092 /* Get the Jth argument in the parameter pack. */
5093 arg = TREE_VEC_ELT (packed_args, j);
5095 if (PACK_EXPANSION_P (arg))
5097 /* Pack expansions must come at the end of the
5098 argument list. */
5099 if ((packed_args && j < len - 1)
5100 || (!packed_args && i < nargs - 1))
5102 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5103 error ("parameter pack argument %qE must be at the "
5104 "end of the template argument list", arg);
5105 else
5106 error ("parameter pack argument %qT must be at the "
5107 "end of the template argument list", arg);
5111 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5112 /* We only care about the pattern. */
5113 arg = PACK_EXPANSION_PATTERN (arg);
5115 if (/* These first two lines are the `non-type' bit. */
5116 !TYPE_P (arg)
5117 && TREE_CODE (arg) != TEMPLATE_DECL
5118 /* This next two lines are the `argument expression is not just a
5119 simple identifier' condition and also the `specialized
5120 non-type argument' bit. */
5121 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5122 && !((REFERENCE_REF_P (arg)
5123 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5124 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5126 if ((!packed_args && tpd.arg_uses_template_parms[i])
5127 || (packed_args && uses_template_parms (arg)))
5128 error_at (cp_expr_loc_or_input_loc (arg),
5129 "template argument %qE involves template "
5130 "parameter(s)", arg);
5131 else
5133 /* Look at the corresponding template parameter,
5134 marking which template parameters its type depends
5135 upon. */
5136 tree type = TREE_TYPE (parm);
5138 if (!tpd2.parms)
5140 /* We haven't yet initialized TPD2. Do so now. */
5141 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5142 /* The number of parameters here is the number in the
5143 main template, which, as checked in the assertion
5144 above, is NARGS. */
5145 tpd2.parms = XALLOCAVEC (int, nargs);
5146 tpd2.level =
5147 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5150 /* Mark the template parameters. But this time, we're
5151 looking for the template parameters of the main
5152 template, not in the specialization. */
5153 tpd2.current_arg = i;
5154 tpd2.arg_uses_template_parms[i] = 0;
5155 memset (tpd2.parms, 0, sizeof (int) * nargs);
5156 for_each_template_parm (type,
5157 &mark_template_parm,
5158 &tpd2,
5159 NULL,
5160 /*include_nondeduced_p=*/false);
5162 if (tpd2.arg_uses_template_parms [i])
5164 /* The type depended on some template parameters.
5165 If they are fully specialized in the
5166 specialization, that's OK. */
5167 int j;
5168 int count = 0;
5169 for (j = 0; j < nargs; ++j)
5170 if (tpd2.parms[j] != 0
5171 && tpd.arg_uses_template_parms [j])
5172 ++count;
5173 if (count != 0)
5174 error_n (input_location, count,
5175 "type %qT of template argument %qE depends "
5176 "on a template parameter",
5177 "type %qT of template argument %qE depends "
5178 "on template parameters",
5179 type,
5180 arg);
5187 /* We should only get here once. */
5188 if (TREE_CODE (decl) == TYPE_DECL)
5189 gcc_assert (!COMPLETE_TYPE_P (type));
5191 // Build the template decl.
5192 tree tmpl = build_template_decl (decl, current_template_parms,
5193 DECL_MEMBER_TEMPLATE_P (maintmpl));
5194 TREE_TYPE (tmpl) = type;
5195 DECL_TEMPLATE_RESULT (tmpl) = decl;
5196 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5197 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5198 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5200 /* Give template template parms a DECL_CONTEXT of the template
5201 for which they are a parameter. */
5202 for (i = 0; i < ntparms; ++i)
5204 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5205 if (TREE_CODE (parm) == TEMPLATE_DECL)
5206 DECL_CONTEXT (parm) = tmpl;
5209 if (VAR_P (decl))
5210 /* We didn't register this in check_explicit_specialization so we could
5211 wait until the constraints were set. */
5212 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5213 else
5214 associate_classtype_constraints (type);
5216 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5217 = tree_cons (specargs, tmpl,
5218 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5219 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5221 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5222 inst = TREE_CHAIN (inst))
5224 tree instance = TREE_VALUE (inst);
5225 if (TYPE_P (instance)
5226 ? (COMPLETE_TYPE_P (instance)
5227 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5228 : DECL_TEMPLATE_INSTANTIATION (instance))
5230 tree spec = most_specialized_partial_spec (instance, tf_none);
5231 tree inst_decl = (DECL_P (instance)
5232 ? instance : TYPE_NAME (instance));
5233 if (!spec)
5234 /* OK */;
5235 else if (spec == error_mark_node)
5236 permerror (input_location,
5237 "declaration of %qD ambiguates earlier template "
5238 "instantiation for %qD", decl, inst_decl);
5239 else if (TREE_VALUE (spec) == tmpl)
5240 permerror (input_location,
5241 "partial specialization of %qD after instantiation "
5242 "of %qD", decl, inst_decl);
5246 return decl;
5249 /* PARM is a template parameter of some form; return the corresponding
5250 TEMPLATE_PARM_INDEX. */
5252 static tree
5253 get_template_parm_index (tree parm)
5255 if (TREE_CODE (parm) == PARM_DECL
5256 || TREE_CODE (parm) == CONST_DECL)
5257 parm = DECL_INITIAL (parm);
5258 else if (TREE_CODE (parm) == TYPE_DECL
5259 || TREE_CODE (parm) == TEMPLATE_DECL)
5260 parm = TREE_TYPE (parm);
5261 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5262 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5263 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5264 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5265 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5266 return parm;
5269 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5270 parameter packs used by the template parameter PARM. */
5272 static void
5273 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5275 /* A type parm can't refer to another parm. */
5276 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5277 return;
5278 else if (TREE_CODE (parm) == PARM_DECL)
5280 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5281 ppd, ppd->visited);
5282 return;
5285 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5287 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5288 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5290 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5291 if (template_parameter_pack_p (p))
5292 /* Any packs in the type are expanded by this parameter. */;
5293 else
5294 fixed_parameter_pack_p_1 (p, ppd);
5298 /* PARM is a template parameter pack. Return any parameter packs used in
5299 its type or the type of any of its template parameters. If there are
5300 any such packs, it will be instantiated into a fixed template parameter
5301 list by partial instantiation rather than be fully deduced. */
5303 tree
5304 fixed_parameter_pack_p (tree parm)
5306 /* This can only be true in a member template. */
5307 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5308 return NULL_TREE;
5309 /* This can only be true for a parameter pack. */
5310 if (!template_parameter_pack_p (parm))
5311 return NULL_TREE;
5312 /* A type parm can't refer to another parm. */
5313 if (TREE_CODE (parm) == TYPE_DECL)
5314 return NULL_TREE;
5316 tree parameter_packs = NULL_TREE;
5317 struct find_parameter_pack_data ppd;
5318 ppd.parameter_packs = &parameter_packs;
5319 ppd.visited = new hash_set<tree>;
5320 ppd.type_pack_expansion_p = false;
5322 fixed_parameter_pack_p_1 (parm, &ppd);
5324 delete ppd.visited;
5325 return parameter_packs;
5328 /* Check that a template declaration's use of default arguments and
5329 parameter packs is not invalid. Here, PARMS are the template
5330 parameters. IS_PRIMARY is true if DECL is the thing declared by
5331 a primary template. IS_PARTIAL is true if DECL is a partial
5332 specialization.
5334 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5335 function template declaration or a friend class template
5336 declaration. In the function case, 1 indicates a declaration, 2
5337 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5338 emitted for extraneous default arguments.
5340 Returns TRUE if there were no errors found, FALSE otherwise. */
5342 bool
5343 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5344 bool is_partial, int is_friend_decl)
5346 const char *msg;
5347 int last_level_to_check;
5348 tree parm_level;
5349 bool no_errors = true;
5351 /* [temp.param]
5353 A default template-argument shall not be specified in a
5354 function template declaration or a function template definition, nor
5355 in the template-parameter-list of the definition of a member of a
5356 class template. */
5358 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5359 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5360 /* You can't have a function template declaration in a local
5361 scope, nor you can you define a member of a class template in a
5362 local scope. */
5363 return true;
5365 if ((TREE_CODE (decl) == TYPE_DECL
5366 && TREE_TYPE (decl)
5367 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5368 || (TREE_CODE (decl) == FUNCTION_DECL
5369 && LAMBDA_FUNCTION_P (decl)))
5370 /* A lambda doesn't have an explicit declaration; don't complain
5371 about the parms of the enclosing class. */
5372 return true;
5374 if (current_class_type
5375 && !TYPE_BEING_DEFINED (current_class_type)
5376 && DECL_LANG_SPECIFIC (decl)
5377 && DECL_DECLARES_FUNCTION_P (decl)
5378 /* If this is either a friend defined in the scope of the class
5379 or a member function. */
5380 && (DECL_FUNCTION_MEMBER_P (decl)
5381 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5382 : DECL_FRIEND_CONTEXT (decl)
5383 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5384 : false)
5385 /* And, if it was a member function, it really was defined in
5386 the scope of the class. */
5387 && (!DECL_FUNCTION_MEMBER_P (decl)
5388 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5389 /* We already checked these parameters when the template was
5390 declared, so there's no need to do it again now. This function
5391 was defined in class scope, but we're processing its body now
5392 that the class is complete. */
5393 return true;
5395 /* Core issue 226 (C++0x only): the following only applies to class
5396 templates. */
5397 if (is_primary
5398 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5400 /* [temp.param]
5402 If a template-parameter has a default template-argument, all
5403 subsequent template-parameters shall have a default
5404 template-argument supplied. */
5405 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5407 tree inner_parms = TREE_VALUE (parm_level);
5408 int ntparms = TREE_VEC_LENGTH (inner_parms);
5409 int seen_def_arg_p = 0;
5410 int i;
5412 for (i = 0; i < ntparms; ++i)
5414 tree parm = TREE_VEC_ELT (inner_parms, i);
5416 if (parm == error_mark_node)
5417 continue;
5419 if (TREE_PURPOSE (parm))
5420 seen_def_arg_p = 1;
5421 else if (seen_def_arg_p
5422 && !template_parameter_pack_p (TREE_VALUE (parm)))
5424 error ("no default argument for %qD", TREE_VALUE (parm));
5425 /* For better subsequent error-recovery, we indicate that
5426 there should have been a default argument. */
5427 TREE_PURPOSE (parm) = error_mark_node;
5428 no_errors = false;
5430 else if (!is_partial
5431 && !is_friend_decl
5432 /* Don't complain about an enclosing partial
5433 specialization. */
5434 && parm_level == parms
5435 && TREE_CODE (decl) == TYPE_DECL
5436 && i < ntparms - 1
5437 && template_parameter_pack_p (TREE_VALUE (parm))
5438 /* A fixed parameter pack will be partially
5439 instantiated into a fixed length list. */
5440 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5442 /* A primary class template can only have one
5443 parameter pack, at the end of the template
5444 parameter list. */
5446 error ("parameter pack %q+D must be at the end of the"
5447 " template parameter list", TREE_VALUE (parm));
5449 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5450 = error_mark_node;
5451 no_errors = false;
5457 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5458 || is_partial
5459 || !is_primary
5460 || is_friend_decl)
5461 /* For an ordinary class template, default template arguments are
5462 allowed at the innermost level, e.g.:
5463 template <class T = int>
5464 struct S {};
5465 but, in a partial specialization, they're not allowed even
5466 there, as we have in [temp.class.spec]:
5468 The template parameter list of a specialization shall not
5469 contain default template argument values.
5471 So, for a partial specialization, or for a function template
5472 (in C++98/C++03), we look at all of them. */
5474 else
5475 /* But, for a primary class template that is not a partial
5476 specialization we look at all template parameters except the
5477 innermost ones. */
5478 parms = TREE_CHAIN (parms);
5480 /* Figure out what error message to issue. */
5481 if (is_friend_decl == 2)
5482 msg = G_("default template arguments may not be used in function template "
5483 "friend re-declaration");
5484 else if (is_friend_decl)
5485 msg = G_("default template arguments may not be used in template "
5486 "friend declarations");
5487 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5488 msg = G_("default template arguments may not be used in function templates "
5489 "without %<-std=c++11%> or %<-std=gnu++11%>");
5490 else if (is_partial)
5491 msg = G_("default template arguments may not be used in "
5492 "partial specializations");
5493 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5494 msg = G_("default argument for template parameter for class enclosing %qD");
5495 else
5496 /* Per [temp.param]/9, "A default template-argument shall not be
5497 specified in the template-parameter-lists of the definition of
5498 a member of a class template that appears outside of the member's
5499 class.", thus if we aren't handling a member of a class template
5500 there is no need to examine the parameters. */
5501 return true;
5503 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5504 /* If we're inside a class definition, there's no need to
5505 examine the parameters to the class itself. On the one
5506 hand, they will be checked when the class is defined, and,
5507 on the other, default arguments are valid in things like:
5508 template <class T = double>
5509 struct S { template <class U> void f(U); };
5510 Here the default argument for `S' has no bearing on the
5511 declaration of `f'. */
5512 last_level_to_check = template_class_depth (current_class_type) + 1;
5513 else
5514 /* Check everything. */
5515 last_level_to_check = 0;
5517 for (parm_level = parms;
5518 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5519 parm_level = TREE_CHAIN (parm_level))
5521 tree inner_parms = TREE_VALUE (parm_level);
5522 int i;
5523 int ntparms;
5525 ntparms = TREE_VEC_LENGTH (inner_parms);
5526 for (i = 0; i < ntparms; ++i)
5528 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5529 continue;
5531 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5533 if (msg)
5535 no_errors = false;
5536 if (is_friend_decl == 2)
5537 return no_errors;
5539 error (msg, decl);
5540 msg = 0;
5543 /* Clear out the default argument so that we are not
5544 confused later. */
5545 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5549 /* At this point, if we're still interested in issuing messages,
5550 they must apply to classes surrounding the object declared. */
5551 if (msg)
5552 msg = G_("default argument for template parameter for class "
5553 "enclosing %qD");
5556 return no_errors;
5559 /* Worker for push_template_decl_real, called via
5560 for_each_template_parm. DATA is really an int, indicating the
5561 level of the parameters we are interested in. If T is a template
5562 parameter of that level, return nonzero. */
5564 static int
5565 template_parm_this_level_p (tree t, void* data)
5567 int this_level = *(int *)data;
5568 int level;
5570 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5571 level = TEMPLATE_PARM_LEVEL (t);
5572 else
5573 level = TEMPLATE_TYPE_LEVEL (t);
5574 return level == this_level;
5577 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5578 DATA is really an int, indicating the innermost outer level of parameters.
5579 If T is a template parameter of that level or further out, return
5580 nonzero. */
5582 static int
5583 template_parm_outer_level (tree t, void *data)
5585 int this_level = *(int *)data;
5586 int level;
5588 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5589 level = TEMPLATE_PARM_LEVEL (t);
5590 else
5591 level = TEMPLATE_TYPE_LEVEL (t);
5592 return level <= this_level;
5595 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5596 parameters given by current_template_args, or reuses a
5597 previously existing one, if appropriate. Returns the DECL, or an
5598 equivalent one, if it is replaced via a call to duplicate_decls.
5600 If IS_FRIEND is true, DECL is a friend declaration. */
5602 tree
5603 push_template_decl_real (tree decl, bool is_friend)
5605 tree tmpl;
5606 tree args;
5607 tree info;
5608 tree ctx;
5609 bool is_primary;
5610 bool is_partial;
5611 int new_template_p = 0;
5612 /* True if the template is a member template, in the sense of
5613 [temp.mem]. */
5614 bool member_template_p = false;
5616 if (decl == error_mark_node || !current_template_parms)
5617 return error_mark_node;
5619 /* See if this is a partial specialization. */
5620 is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5621 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5622 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5623 || (VAR_P (decl)
5624 && DECL_LANG_SPECIFIC (decl)
5625 && DECL_TEMPLATE_SPECIALIZATION (decl)
5626 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5628 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5629 is_friend = true;
5631 if (is_friend)
5632 /* For a friend, we want the context of the friend, not
5633 the type of which it is a friend. */
5634 ctx = CP_DECL_CONTEXT (decl);
5635 else if (CP_DECL_CONTEXT (decl)
5636 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5637 /* In the case of a virtual function, we want the class in which
5638 it is defined. */
5639 ctx = CP_DECL_CONTEXT (decl);
5640 else
5641 /* Otherwise, if we're currently defining some class, the DECL
5642 is assumed to be a member of the class. */
5643 ctx = current_scope ();
5645 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5646 ctx = NULL_TREE;
5648 if (!DECL_CONTEXT (decl))
5649 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5651 /* See if this is a primary template. */
5652 if (is_friend && ctx
5653 && uses_template_parms_level (ctx, processing_template_decl))
5654 /* A friend template that specifies a class context, i.e.
5655 template <typename T> friend void A<T>::f();
5656 is not primary. */
5657 is_primary = false;
5658 else if (TREE_CODE (decl) == TYPE_DECL
5659 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5660 is_primary = false;
5661 else
5662 is_primary = template_parm_scope_p ();
5664 if (is_primary)
5666 warning (OPT_Wtemplates, "template %qD declared", decl);
5668 if (DECL_CLASS_SCOPE_P (decl))
5669 member_template_p = true;
5670 if (TREE_CODE (decl) == TYPE_DECL
5671 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5673 error ("template class without a name");
5674 return error_mark_node;
5676 else if (TREE_CODE (decl) == FUNCTION_DECL)
5678 if (member_template_p)
5680 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5681 error ("member template %qD may not have virt-specifiers", decl);
5683 if (DECL_DESTRUCTOR_P (decl))
5685 /* [temp.mem]
5687 A destructor shall not be a member template. */
5688 error_at (DECL_SOURCE_LOCATION (decl),
5689 "destructor %qD declared as member template", decl);
5690 return error_mark_node;
5692 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5693 && (!prototype_p (TREE_TYPE (decl))
5694 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5695 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5696 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5697 == void_list_node)))
5699 /* [basic.stc.dynamic.allocation]
5701 An allocation function can be a function
5702 template. ... Template allocation functions shall
5703 have two or more parameters. */
5704 error ("invalid template declaration of %qD", decl);
5705 return error_mark_node;
5708 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5709 && CLASS_TYPE_P (TREE_TYPE (decl)))
5711 /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS. */
5712 tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5713 for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5715 tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5716 if (TREE_CODE (t) == TYPE_DECL)
5717 t = TREE_TYPE (t);
5718 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5719 TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5722 else if (TREE_CODE (decl) == TYPE_DECL
5723 && TYPE_DECL_ALIAS_P (decl))
5724 /* alias-declaration */
5725 gcc_assert (!DECL_ARTIFICIAL (decl));
5726 else if (VAR_P (decl))
5727 /* C++14 variable template. */;
5728 else if (TREE_CODE (decl) == CONCEPT_DECL)
5729 /* C++2a concept definitions. */;
5730 else
5732 error ("template declaration of %q#D", decl);
5733 return error_mark_node;
5737 /* Check to see that the rules regarding the use of default
5738 arguments are not being violated. We check args for a friend
5739 functions when we know whether it's a definition, introducing
5740 declaration or re-declaration. */
5741 if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5742 check_default_tmpl_args (decl, current_template_parms,
5743 is_primary, is_partial, is_friend);
5745 /* Ensure that there are no parameter packs in the type of this
5746 declaration that have not been expanded. */
5747 if (TREE_CODE (decl) == FUNCTION_DECL)
5749 /* Check each of the arguments individually to see if there are
5750 any bare parameter packs. */
5751 tree type = TREE_TYPE (decl);
5752 tree arg = DECL_ARGUMENTS (decl);
5753 tree argtype = TYPE_ARG_TYPES (type);
5755 while (arg && argtype)
5757 if (!DECL_PACK_P (arg)
5758 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5760 /* This is a PARM_DECL that contains unexpanded parameter
5761 packs. We have already complained about this in the
5762 check_for_bare_parameter_packs call, so just replace
5763 these types with ERROR_MARK_NODE. */
5764 TREE_TYPE (arg) = error_mark_node;
5765 TREE_VALUE (argtype) = error_mark_node;
5768 arg = DECL_CHAIN (arg);
5769 argtype = TREE_CHAIN (argtype);
5772 /* Check for bare parameter packs in the return type and the
5773 exception specifiers. */
5774 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5775 /* Errors were already issued, set return type to int
5776 as the frontend doesn't expect error_mark_node as
5777 the return type. */
5778 TREE_TYPE (type) = integer_type_node;
5779 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5780 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5782 else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5783 && TYPE_DECL_ALIAS_P (decl))
5784 ? DECL_ORIGINAL_TYPE (decl)
5785 : TREE_TYPE (decl)))
5787 TREE_TYPE (decl) = error_mark_node;
5788 return error_mark_node;
5791 if (is_partial)
5792 return process_partial_specialization (decl);
5794 args = current_template_args ();
5796 if (!ctx
5797 || TREE_CODE (ctx) == FUNCTION_DECL
5798 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5799 || (TREE_CODE (decl) == TYPE_DECL
5800 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5801 || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5803 if (DECL_LANG_SPECIFIC (decl)
5804 && DECL_TEMPLATE_INFO (decl)
5805 && DECL_TI_TEMPLATE (decl))
5806 tmpl = DECL_TI_TEMPLATE (decl);
5807 /* If DECL is a TYPE_DECL for a class-template, then there won't
5808 be DECL_LANG_SPECIFIC. The information equivalent to
5809 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
5810 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5811 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5812 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5814 /* Since a template declaration already existed for this
5815 class-type, we must be redeclaring it here. Make sure
5816 that the redeclaration is valid. */
5817 redeclare_class_template (TREE_TYPE (decl),
5818 current_template_parms,
5819 current_template_constraints ());
5820 /* We don't need to create a new TEMPLATE_DECL; just use the
5821 one we already had. */
5822 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5824 else
5826 tmpl = build_template_decl (decl, current_template_parms,
5827 member_template_p);
5828 new_template_p = 1;
5830 if (DECL_LANG_SPECIFIC (decl)
5831 && DECL_TEMPLATE_SPECIALIZATION (decl))
5833 /* A specialization of a member template of a template
5834 class. */
5835 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5836 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5837 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5841 else
5843 tree a, t, current, parms;
5844 int i;
5845 tree tinfo = get_template_info (decl);
5847 if (!tinfo)
5849 error ("template definition of non-template %q#D", decl);
5850 return error_mark_node;
5853 tmpl = TI_TEMPLATE (tinfo);
5855 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5856 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5857 && DECL_TEMPLATE_SPECIALIZATION (decl)
5858 && DECL_MEMBER_TEMPLATE_P (tmpl))
5860 tree new_tmpl;
5862 /* The declaration is a specialization of a member
5863 template, declared outside the class. Therefore, the
5864 innermost template arguments will be NULL, so we
5865 replace them with the arguments determined by the
5866 earlier call to check_explicit_specialization. */
5867 args = DECL_TI_ARGS (decl);
5869 new_tmpl
5870 = build_template_decl (decl, current_template_parms,
5871 member_template_p);
5872 DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5873 TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5874 DECL_TI_TEMPLATE (decl) = new_tmpl;
5875 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5876 DECL_TEMPLATE_INFO (new_tmpl)
5877 = build_template_info (tmpl, args);
5879 register_specialization (new_tmpl,
5880 most_general_template (tmpl),
5881 args,
5882 is_friend, 0);
5883 return decl;
5886 /* Make sure the template headers we got make sense. */
5888 parms = DECL_TEMPLATE_PARMS (tmpl);
5889 i = TMPL_PARMS_DEPTH (parms);
5890 if (TMPL_ARGS_DEPTH (args) != i)
5892 error ("expected %d levels of template parms for %q#D, got %d",
5893 i, decl, TMPL_ARGS_DEPTH (args));
5894 DECL_INTERFACE_KNOWN (decl) = 1;
5895 return error_mark_node;
5897 else
5898 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5900 a = TMPL_ARGS_LEVEL (args, i);
5901 t = INNERMOST_TEMPLATE_PARMS (parms);
5903 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5905 if (current == decl)
5906 error ("got %d template parameters for %q#D",
5907 TREE_VEC_LENGTH (a), decl);
5908 else
5909 error ("got %d template parameters for %q#T",
5910 TREE_VEC_LENGTH (a), current);
5911 error (" but %d required", TREE_VEC_LENGTH (t));
5912 /* Avoid crash in import_export_decl. */
5913 DECL_INTERFACE_KNOWN (decl) = 1;
5914 return error_mark_node;
5917 if (current == decl)
5918 current = ctx;
5919 else if (current == NULL_TREE)
5920 /* Can happen in erroneous input. */
5921 break;
5922 else
5923 current = get_containing_scope (current);
5926 /* Check that the parms are used in the appropriate qualifying scopes
5927 in the declarator. */
5928 if (!comp_template_args
5929 (TI_ARGS (tinfo),
5930 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5932 error ("template arguments to %qD do not match original "
5933 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5934 if (!uses_template_parms (TI_ARGS (tinfo)))
5935 inform (input_location, "use %<template<>%> for"
5936 " an explicit specialization");
5937 /* Avoid crash in import_export_decl. */
5938 DECL_INTERFACE_KNOWN (decl) = 1;
5939 return error_mark_node;
5943 DECL_TEMPLATE_RESULT (tmpl) = decl;
5944 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5946 /* Push template declarations for global functions and types. Note
5947 that we do not try to push a global template friend declared in a
5948 template class; such a thing may well depend on the template
5949 parameters of the class. */
5950 if (new_template_p && !ctx
5951 && !(is_friend && template_class_depth (current_class_type) > 0))
5953 tmpl = pushdecl_namespace_level (tmpl, is_friend);
5954 if (tmpl == error_mark_node)
5955 return error_mark_node;
5957 /* Hide template friend classes that haven't been declared yet. */
5958 if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5960 DECL_ANTICIPATED (tmpl) = 1;
5961 DECL_FRIEND_P (tmpl) = 1;
5965 if (is_primary)
5967 tree parms = DECL_TEMPLATE_PARMS (tmpl);
5969 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5971 /* Give template template parms a DECL_CONTEXT of the template
5972 for which they are a parameter. */
5973 parms = INNERMOST_TEMPLATE_PARMS (parms);
5974 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5976 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5977 if (TREE_CODE (parm) == TEMPLATE_DECL)
5978 DECL_CONTEXT (parm) = tmpl;
5981 if (TREE_CODE (decl) == TYPE_DECL
5982 && TYPE_DECL_ALIAS_P (decl)
5983 && complex_alias_template_p (tmpl))
5984 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5987 /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5988 back to its most general template. If TMPL is a specialization,
5989 ARGS may only have the innermost set of arguments. Add the missing
5990 argument levels if necessary. */
5991 if (DECL_TEMPLATE_INFO (tmpl))
5992 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5994 info = build_template_info (tmpl, args);
5996 if (DECL_IMPLICIT_TYPEDEF_P (decl))
5997 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5998 else
6000 if (is_primary)
6001 retrofit_lang_decl (decl);
6002 if (DECL_LANG_SPECIFIC (decl))
6003 DECL_TEMPLATE_INFO (decl) = info;
6006 if (flag_implicit_templates
6007 && !is_friend
6008 && TREE_PUBLIC (decl)
6009 && VAR_OR_FUNCTION_DECL_P (decl))
6010 /* Set DECL_COMDAT on template instantiations; if we force
6011 them to be emitted by explicit instantiation,
6012 mark_needed will tell cgraph to do the right thing. */
6013 DECL_COMDAT (decl) = true;
6015 return DECL_TEMPLATE_RESULT (tmpl);
6018 tree
6019 push_template_decl (tree decl)
6021 return push_template_decl_real (decl, false);
6024 /* FN is an inheriting constructor that inherits from the constructor
6025 template INHERITED; turn FN into a constructor template with a matching
6026 template header. */
6028 tree
6029 add_inherited_template_parms (tree fn, tree inherited)
6031 tree inner_parms
6032 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6033 inner_parms = copy_node (inner_parms);
6034 tree parms
6035 = tree_cons (size_int (processing_template_decl + 1),
6036 inner_parms, current_template_parms);
6037 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6038 tree args = template_parms_to_args (parms);
6039 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6040 TREE_TYPE (tmpl) = TREE_TYPE (fn);
6041 DECL_TEMPLATE_RESULT (tmpl) = fn;
6042 DECL_ARTIFICIAL (tmpl) = true;
6043 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6044 return tmpl;
6047 /* Called when a class template TYPE is redeclared with the indicated
6048 template PARMS, e.g.:
6050 template <class T> struct S;
6051 template <class T> struct S {}; */
6053 bool
6054 redeclare_class_template (tree type, tree parms, tree cons)
6056 tree tmpl;
6057 tree tmpl_parms;
6058 int i;
6060 if (!TYPE_TEMPLATE_INFO (type))
6062 error ("%qT is not a template type", type);
6063 return false;
6066 tmpl = TYPE_TI_TEMPLATE (type);
6067 if (!PRIMARY_TEMPLATE_P (tmpl))
6068 /* The type is nested in some template class. Nothing to worry
6069 about here; there are no new template parameters for the nested
6070 type. */
6071 return true;
6073 if (!parms)
6075 error ("template specifiers not specified in declaration of %qD",
6076 tmpl);
6077 return false;
6080 parms = INNERMOST_TEMPLATE_PARMS (parms);
6081 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6083 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6085 error_n (input_location, TREE_VEC_LENGTH (parms),
6086 "redeclared with %d template parameter",
6087 "redeclared with %d template parameters",
6088 TREE_VEC_LENGTH (parms));
6089 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6090 "previous declaration %qD used %d template parameter",
6091 "previous declaration %qD used %d template parameters",
6092 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6093 return false;
6096 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6098 tree tmpl_parm;
6099 tree parm;
6100 tree tmpl_default;
6101 tree parm_default;
6103 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6104 || TREE_VEC_ELT (parms, i) == error_mark_node)
6105 continue;
6107 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6108 if (error_operand_p (tmpl_parm))
6109 return false;
6111 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6112 tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
6113 parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
6115 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6116 TEMPLATE_DECL. */
6117 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6118 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6119 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6120 || (TREE_CODE (tmpl_parm) != PARM_DECL
6121 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6122 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6123 || (TREE_CODE (tmpl_parm) == PARM_DECL
6124 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6125 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6127 error ("template parameter %q+#D", tmpl_parm);
6128 error ("redeclared here as %q#D", parm);
6129 return false;
6132 /* The parameters can be declared to introduce different
6133 constraints. */
6134 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6135 tree p2 = TREE_VEC_ELT (parms, i);
6136 if (!template_parameter_constraints_equivalent_p (p1, p2))
6138 error ("declaration of template parameter %q+#D with different "
6139 "constraints", parm);
6140 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6141 "original declaration appeared here");
6142 return false;
6145 if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6147 /* We have in [temp.param]:
6149 A template-parameter may not be given default arguments
6150 by two different declarations in the same scope. */
6151 error_at (input_location, "redefinition of default argument for %q#D", parm);
6152 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6153 "original definition appeared here");
6154 return false;
6157 if (parm_default != NULL_TREE)
6158 /* Update the previous template parameters (which are the ones
6159 that will really count) with the new default value. */
6160 TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6161 else if (tmpl_default != NULL_TREE)
6162 /* Update the new parameters, too; they'll be used as the
6163 parameters for any members. */
6164 TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6166 /* Give each template template parm in this redeclaration a
6167 DECL_CONTEXT of the template for which they are a parameter. */
6168 if (TREE_CODE (parm) == TEMPLATE_DECL)
6170 gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6171 DECL_CONTEXT (parm) = tmpl;
6174 if (TREE_CODE (parm) == TYPE_DECL)
6175 TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6178 tree ci = get_constraints (tmpl);
6179 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6180 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6182 /* Two classes with different constraints declare different entities. */
6183 if (!cp_tree_equal (req1, req2))
6185 error_at (input_location, "redeclaration %q#D with different "
6186 "constraints", tmpl);
6187 inform (DECL_SOURCE_LOCATION (tmpl),
6188 "original declaration appeared here");
6189 return false;
6192 return true;
6195 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6196 to be used when the caller has already checked
6197 (processing_template_decl
6198 && !instantiation_dependent_expression_p (expr)
6199 && potential_constant_expression (expr))
6200 and cleared processing_template_decl. */
6202 tree
6203 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6205 return tsubst_copy_and_build (expr,
6206 /*args=*/NULL_TREE,
6207 complain,
6208 /*in_decl=*/NULL_TREE,
6209 /*function_p=*/false,
6210 /*integral_constant_expression_p=*/true);
6213 /* Simplify EXPR if it is a non-dependent expression. Returns the
6214 (possibly simplified) expression. */
6216 tree
6217 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6219 if (expr == NULL_TREE)
6220 return NULL_TREE;
6222 /* If we're in a template, but EXPR isn't value dependent, simplify
6223 it. We're supposed to treat:
6225 template <typename T> void f(T[1 + 1]);
6226 template <typename T> void f(T[2]);
6228 as two declarations of the same function, for example. */
6229 if (processing_template_decl
6230 && is_nondependent_constant_expression (expr))
6232 processing_template_decl_sentinel s;
6233 expr = instantiate_non_dependent_expr_internal (expr, complain);
6235 return expr;
6238 tree
6239 instantiate_non_dependent_expr (tree expr)
6241 return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6244 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6245 an uninstantiated expression. */
6247 tree
6248 instantiate_non_dependent_or_null (tree expr)
6250 if (expr == NULL_TREE)
6251 return NULL_TREE;
6252 if (processing_template_decl)
6254 if (!is_nondependent_constant_expression (expr))
6255 expr = NULL_TREE;
6256 else
6258 processing_template_decl_sentinel s;
6259 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6262 return expr;
6265 /* True iff T is a specialization of a variable template. */
6267 bool
6268 variable_template_specialization_p (tree t)
6270 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6271 return false;
6272 tree tmpl = DECL_TI_TEMPLATE (t);
6273 return variable_template_p (tmpl);
6276 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6277 template declaration, or a TYPE_DECL for an alias declaration. */
6279 bool
6280 alias_type_or_template_p (tree t)
6282 if (t == NULL_TREE)
6283 return false;
6284 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6285 || (TYPE_P (t)
6286 && TYPE_NAME (t)
6287 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6288 || DECL_ALIAS_TEMPLATE_P (t));
6291 /* Return TRUE iff T is a specialization of an alias template. */
6293 bool
6294 alias_template_specialization_p (const_tree t)
6296 /* It's an alias template specialization if it's an alias and its
6297 TYPE_NAME is a specialization of a primary template. */
6298 if (TYPE_ALIAS_P (t))
6299 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6300 return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6302 return false;
6305 /* An alias template is complex from a SFINAE perspective if a template-id
6306 using that alias can be ill-formed when the expansion is not, as with
6307 the void_t template. We determine this by checking whether the
6308 expansion for the alias template uses all its template parameters. */
6310 struct uses_all_template_parms_data
6312 int level;
6313 bool *seen;
6316 static int
6317 uses_all_template_parms_r (tree t, void *data_)
6319 struct uses_all_template_parms_data &data
6320 = *(struct uses_all_template_parms_data*)data_;
6321 tree idx = get_template_parm_index (t);
6323 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6324 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6325 return 0;
6328 static bool
6329 complex_alias_template_p (const_tree tmpl)
6331 struct uses_all_template_parms_data data;
6332 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6333 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6334 data.level = TMPL_PARMS_DEPTH (parms);
6335 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6336 data.seen = XALLOCAVEC (bool, len);
6337 for (int i = 0; i < len; ++i)
6338 data.seen[i] = false;
6340 for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
6341 for (int i = 0; i < len; ++i)
6342 if (!data.seen[i])
6343 return true;
6344 return false;
6347 /* Return TRUE iff T is a specialization of a complex alias template with
6348 dependent template-arguments. */
6350 bool
6351 dependent_alias_template_spec_p (const_tree t)
6353 if (!alias_template_specialization_p (t))
6354 return false;
6356 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6357 if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6358 return false;
6360 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6361 if (!any_dependent_template_arguments_p (args))
6362 return false;
6364 return true;
6367 /* Return the number of innermost template parameters in TMPL. */
6369 static int
6370 num_innermost_template_parms (tree tmpl)
6372 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6373 return TREE_VEC_LENGTH (parms);
6376 /* Return either TMPL or another template that it is equivalent to under DR
6377 1286: An alias that just changes the name of a template is equivalent to
6378 the other template. */
6380 static tree
6381 get_underlying_template (tree tmpl)
6383 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6384 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6386 /* Determine if the alias is equivalent to an underlying template. */
6387 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6388 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6389 if (!tinfo)
6390 break;
6392 tree underlying = TI_TEMPLATE (tinfo);
6393 if (!PRIMARY_TEMPLATE_P (underlying)
6394 || (num_innermost_template_parms (tmpl)
6395 != num_innermost_template_parms (underlying)))
6396 break;
6398 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6399 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6400 break;
6402 /* Alias is equivalent. Strip it and repeat. */
6403 tmpl = underlying;
6406 return tmpl;
6409 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6410 must be a reference-to-function or a pointer-to-function type, as specified
6411 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6412 and check that the resulting function has external linkage. */
6414 static tree
6415 convert_nontype_argument_function (tree type, tree expr,
6416 tsubst_flags_t complain)
6418 tree fns = expr;
6419 tree fn, fn_no_ptr;
6420 linkage_kind linkage;
6422 fn = instantiate_type (type, fns, tf_none);
6423 if (fn == error_mark_node)
6424 return error_mark_node;
6426 if (value_dependent_expression_p (fn))
6427 goto accept;
6429 fn_no_ptr = strip_fnptr_conv (fn);
6430 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6431 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6432 if (BASELINK_P (fn_no_ptr))
6433 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6435 /* [temp.arg.nontype]/1
6437 A template-argument for a non-type, non-template template-parameter
6438 shall be one of:
6439 [...]
6440 -- the address of an object or function with external [C++11: or
6441 internal] linkage. */
6443 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6444 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6446 if (complain & tf_error)
6448 location_t loc = cp_expr_loc_or_input_loc (expr);
6449 error_at (loc, "%qE is not a valid template argument for type %qT",
6450 expr, type);
6451 if (TYPE_PTR_P (type))
6452 inform (loc, "it must be the address of a function "
6453 "with external linkage");
6454 else
6455 inform (loc, "it must be the name of a function with "
6456 "external linkage");
6458 return NULL_TREE;
6461 linkage = decl_linkage (fn_no_ptr);
6462 if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6464 if (complain & tf_error)
6466 location_t loc = cp_expr_loc_or_input_loc (expr);
6467 if (cxx_dialect >= cxx11)
6468 error_at (loc, "%qE is not a valid template argument for type "
6469 "%qT because %qD has no linkage",
6470 expr, type, fn_no_ptr);
6471 else
6472 error_at (loc, "%qE is not a valid template argument for type "
6473 "%qT because %qD does not have external linkage",
6474 expr, type, fn_no_ptr);
6476 return NULL_TREE;
6479 accept:
6480 if (TYPE_REF_P (type))
6482 if (REFERENCE_REF_P (fn))
6483 fn = TREE_OPERAND (fn, 0);
6484 else
6485 fn = build_address (fn);
6487 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6488 fn = build_nop (type, fn);
6490 return fn;
6493 /* Subroutine of convert_nontype_argument.
6494 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6495 Emit an error otherwise. */
6497 static bool
6498 check_valid_ptrmem_cst_expr (tree type, tree expr,
6499 tsubst_flags_t complain)
6501 tree orig_expr = expr;
6502 STRIP_NOPS (expr);
6503 if (null_ptr_cst_p (expr))
6504 return true;
6505 if (TREE_CODE (expr) == PTRMEM_CST
6506 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6507 PTRMEM_CST_CLASS (expr)))
6508 return true;
6509 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6510 return true;
6511 if (processing_template_decl
6512 && TREE_CODE (expr) == ADDR_EXPR
6513 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6514 return true;
6515 if (complain & tf_error)
6517 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6518 error_at (loc, "%qE is not a valid template argument for type %qT",
6519 orig_expr, type);
6520 if (TREE_CODE (expr) != PTRMEM_CST)
6521 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6522 else
6523 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6525 return false;
6528 /* Returns TRUE iff the address of OP is value-dependent.
6530 14.6.2.4 [temp.dep.temp]:
6531 A non-integral non-type template-argument is dependent if its type is
6532 dependent or it has either of the following forms
6533 qualified-id
6534 & qualified-id
6535 and contains a nested-name-specifier which specifies a class-name that
6536 names a dependent type.
6538 We generalize this to just say that the address of a member of a
6539 dependent class is value-dependent; the above doesn't cover the
6540 address of a static data member named with an unqualified-id. */
6542 static bool
6543 has_value_dependent_address (tree op)
6545 /* We could use get_inner_reference here, but there's no need;
6546 this is only relevant for template non-type arguments, which
6547 can only be expressed as &id-expression. */
6548 if (DECL_P (op))
6550 tree ctx = CP_DECL_CONTEXT (op);
6551 if (TYPE_P (ctx) && dependent_type_p (ctx))
6552 return true;
6555 return false;
6558 /* The next set of functions are used for providing helpful explanatory
6559 diagnostics for failed overload resolution. Their messages should be
6560 indented by two spaces for consistency with the messages in
6561 call.c */
6563 static int
6564 unify_success (bool /*explain_p*/)
6566 return 0;
6569 /* Other failure functions should call this one, to provide a single function
6570 for setting a breakpoint on. */
6572 static int
6573 unify_invalid (bool /*explain_p*/)
6575 return 1;
6578 static int
6579 unify_parameter_deduction_failure (bool explain_p, tree parm)
6581 if (explain_p)
6582 inform (input_location,
6583 " couldn%'t deduce template parameter %qD", parm);
6584 return unify_invalid (explain_p);
6587 static int
6588 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6590 if (explain_p)
6591 inform (input_location,
6592 " types %qT and %qT have incompatible cv-qualifiers",
6593 parm, arg);
6594 return unify_invalid (explain_p);
6597 static int
6598 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6600 if (explain_p)
6601 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6602 return unify_invalid (explain_p);
6605 static int
6606 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6608 if (explain_p)
6609 inform (input_location,
6610 " template parameter %qD is not a parameter pack, but "
6611 "argument %qD is",
6612 parm, arg);
6613 return unify_invalid (explain_p);
6616 static int
6617 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6619 if (explain_p)
6620 inform (input_location,
6621 " template argument %qE does not match "
6622 "pointer-to-member constant %qE",
6623 arg, parm);
6624 return unify_invalid (explain_p);
6627 static int
6628 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6630 if (explain_p)
6631 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6632 return unify_invalid (explain_p);
6635 static int
6636 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6638 if (explain_p)
6639 inform (input_location,
6640 " inconsistent parameter pack deduction with %qT and %qT",
6641 old_arg, new_arg);
6642 return unify_invalid (explain_p);
6645 static int
6646 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6648 if (explain_p)
6650 if (TYPE_P (parm))
6651 inform (input_location,
6652 " deduced conflicting types for parameter %qT (%qT and %qT)",
6653 parm, first, second);
6654 else
6655 inform (input_location,
6656 " deduced conflicting values for non-type parameter "
6657 "%qE (%qE and %qE)", parm, first, second);
6659 return unify_invalid (explain_p);
6662 static int
6663 unify_vla_arg (bool explain_p, tree arg)
6665 if (explain_p)
6666 inform (input_location,
6667 " variable-sized array type %qT is not "
6668 "a valid template argument",
6669 arg);
6670 return unify_invalid (explain_p);
6673 static int
6674 unify_method_type_error (bool explain_p, tree arg)
6676 if (explain_p)
6677 inform (input_location,
6678 " member function type %qT is not a valid template argument",
6679 arg);
6680 return unify_invalid (explain_p);
6683 static int
6684 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6686 if (explain_p)
6688 if (least_p)
6689 inform_n (input_location, wanted,
6690 " candidate expects at least %d argument, %d provided",
6691 " candidate expects at least %d arguments, %d provided",
6692 wanted, have);
6693 else
6694 inform_n (input_location, wanted,
6695 " candidate expects %d argument, %d provided",
6696 " candidate expects %d arguments, %d provided",
6697 wanted, have);
6699 return unify_invalid (explain_p);
6702 static int
6703 unify_too_many_arguments (bool explain_p, int have, int wanted)
6705 return unify_arity (explain_p, have, wanted);
6708 static int
6709 unify_too_few_arguments (bool explain_p, int have, int wanted,
6710 bool least_p = false)
6712 return unify_arity (explain_p, have, wanted, least_p);
6715 static int
6716 unify_arg_conversion (bool explain_p, tree to_type,
6717 tree from_type, tree arg)
6719 if (explain_p)
6720 inform (cp_expr_loc_or_input_loc (arg),
6721 " cannot convert %qE (type %qT) to type %qT",
6722 arg, from_type, to_type);
6723 return unify_invalid (explain_p);
6726 static int
6727 unify_no_common_base (bool explain_p, enum template_base_result r,
6728 tree parm, tree arg)
6730 if (explain_p)
6731 switch (r)
6733 case tbr_ambiguous_baseclass:
6734 inform (input_location, " %qT is an ambiguous base class of %qT",
6735 parm, arg);
6736 break;
6737 default:
6738 inform (input_location, " %qT is not derived from %qT", arg, parm);
6739 break;
6741 return unify_invalid (explain_p);
6744 static int
6745 unify_inconsistent_template_template_parameters (bool explain_p)
6747 if (explain_p)
6748 inform (input_location,
6749 " template parameters of a template template argument are "
6750 "inconsistent with other deduced template arguments");
6751 return unify_invalid (explain_p);
6754 static int
6755 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6757 if (explain_p)
6758 inform (input_location,
6759 " cannot deduce a template for %qT from non-template type %qT",
6760 parm, arg);
6761 return unify_invalid (explain_p);
6764 static int
6765 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6767 if (explain_p)
6768 inform (input_location,
6769 " template argument %qE does not match %qE", arg, parm);
6770 return unify_invalid (explain_p);
6773 /* True if T is a C++20 template parameter object to store the argument for a
6774 template parameter of class type. */
6776 bool
6777 template_parm_object_p (const_tree t)
6779 return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6780 && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6783 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
6784 argument for TYPE, points to an unsuitable object. */
6786 static bool
6787 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
6789 switch (TREE_CODE (expr))
6791 CASE_CONVERT:
6792 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
6793 complain);
6795 case TARGET_EXPR:
6796 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
6797 complain);
6799 case CONSTRUCTOR:
6801 unsigned i; tree elt;
6802 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
6803 if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
6804 return true;
6806 break;
6808 case ADDR_EXPR:
6810 tree decl = TREE_OPERAND (expr, 0);
6812 if (!VAR_P (decl))
6814 if (complain & tf_error)
6815 error_at (cp_expr_loc_or_input_loc (expr),
6816 "%qE is not a valid template argument of type %qT "
6817 "because %qE is not a variable", expr, type, decl);
6818 return true;
6820 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6822 if (complain & tf_error)
6823 error_at (cp_expr_loc_or_input_loc (expr),
6824 "%qE is not a valid template argument of type %qT "
6825 "in C++98 because %qD does not have external linkage",
6826 expr, type, decl);
6827 return true;
6829 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6830 && decl_linkage (decl) == lk_none)
6832 if (complain & tf_error)
6833 error_at (cp_expr_loc_or_input_loc (expr),
6834 "%qE is not a valid template argument of type %qT "
6835 "because %qD has no linkage", expr, type, decl);
6836 return true;
6838 /* C++17: For a non-type template-parameter of reference or pointer
6839 type, the value of the constant expression shall not refer to (or
6840 for a pointer type, shall not be the address of):
6841 * a subobject (4.5),
6842 * a temporary object (15.2),
6843 * a string literal (5.13.5),
6844 * the result of a typeid expression (8.2.8), or
6845 * a predefined __func__ variable (11.4.1). */
6846 else if (DECL_ARTIFICIAL (decl))
6848 if (complain & tf_error)
6849 error ("the address of %qD is not a valid template argument",
6850 decl);
6851 return true;
6853 else if (!same_type_ignoring_top_level_qualifiers_p
6854 (strip_array_types (TREE_TYPE (type)),
6855 strip_array_types (TREE_TYPE (decl))))
6857 if (complain & tf_error)
6858 error ("the address of the %qT subobject of %qD is not a "
6859 "valid template argument", TREE_TYPE (type), decl);
6860 return true;
6862 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6864 if (complain & tf_error)
6865 error ("the address of %qD is not a valid template argument "
6866 "because it does not have static storage duration",
6867 decl);
6868 return true;
6871 break;
6873 default:
6874 if (!INDIRECT_TYPE_P (type))
6875 /* We're only concerned about pointers and references here. */;
6876 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6877 /* Null pointer values are OK in C++11. */;
6878 else
6880 if (VAR_P (expr))
6882 if (complain & tf_error)
6883 error ("%qD is not a valid template argument "
6884 "because %qD is a variable, not the address of "
6885 "a variable", expr, expr);
6886 return true;
6888 else
6890 if (complain & tf_error)
6891 error ("%qE is not a valid template argument for %qT "
6892 "because it is not the address of a variable",
6893 expr, type);
6894 return true;
6898 return false;
6902 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
6903 template argument EXPR. */
6905 static tree
6906 get_template_parm_object (tree expr, tsubst_flags_t complain)
6908 if (TREE_CODE (expr) == TARGET_EXPR)
6909 expr = TARGET_EXPR_INITIAL (expr);
6911 if (!TREE_CONSTANT (expr))
6913 if ((complain & tf_error)
6914 && require_rvalue_constant_expression (expr))
6915 cxx_constant_value (expr);
6916 return error_mark_node;
6918 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
6919 return error_mark_node;
6921 tree name = mangle_template_parm_object (expr);
6922 tree decl = get_global_binding (name);
6923 if (decl)
6924 return decl;
6926 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
6927 decl = create_temporary_var (type);
6928 TREE_STATIC (decl) = true;
6929 DECL_DECLARED_CONSTEXPR_P (decl) = true;
6930 TREE_READONLY (decl) = true;
6931 DECL_NAME (decl) = name;
6932 SET_DECL_ASSEMBLER_NAME (decl, name);
6933 DECL_CONTEXT (decl) = global_namespace;
6934 comdat_linkage (decl);
6935 pushdecl_top_level_and_finish (decl, expr);
6936 return decl;
6939 /* Attempt to convert the non-type template parameter EXPR to the
6940 indicated TYPE. If the conversion is successful, return the
6941 converted value. If the conversion is unsuccessful, return
6942 NULL_TREE if we issued an error message, or error_mark_node if we
6943 did not. We issue error messages for out-and-out bad template
6944 parameters, but not simply because the conversion failed, since we
6945 might be just trying to do argument deduction. Both TYPE and EXPR
6946 must be non-dependent.
6948 The conversion follows the special rules described in
6949 [temp.arg.nontype], and it is much more strict than an implicit
6950 conversion.
6952 This function is called twice for each template argument (see
6953 lookup_template_class for a more accurate description of this
6954 problem). This means that we need to handle expressions which
6955 are not valid in a C++ source, but can be created from the
6956 first call (for instance, casts to perform conversions). These
6957 hacks can go away after we fix the double coercion problem. */
6959 static tree
6960 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6962 tree expr_type;
6963 location_t loc = cp_expr_loc_or_input_loc (expr);
6965 /* Detect immediately string literals as invalid non-type argument.
6966 This special-case is not needed for correctness (we would easily
6967 catch this later), but only to provide better diagnostic for this
6968 common user mistake. As suggested by DR 100, we do not mention
6969 linkage issues in the diagnostic as this is not the point. */
6970 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
6972 if (complain & tf_error)
6973 error ("%qE is not a valid template argument for type %qT "
6974 "because string literals can never be used in this context",
6975 expr, type);
6976 return NULL_TREE;
6979 /* Add the ADDR_EXPR now for the benefit of
6980 value_dependent_expression_p. */
6981 if (TYPE_PTROBV_P (type)
6982 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6984 expr = decay_conversion (expr, complain);
6985 if (expr == error_mark_node)
6986 return error_mark_node;
6989 /* If we are in a template, EXPR may be non-dependent, but still
6990 have a syntactic, rather than semantic, form. For example, EXPR
6991 might be a SCOPE_REF, rather than the VAR_DECL to which the
6992 SCOPE_REF refers. Preserving the qualifying scope is necessary
6993 so that access checking can be performed when the template is
6994 instantiated -- but here we need the resolved form so that we can
6995 convert the argument. */
6996 bool non_dep = false;
6997 if (TYPE_REF_OBJ_P (type)
6998 && has_value_dependent_address (expr))
6999 /* If we want the address and it's value-dependent, don't fold. */;
7000 else if (processing_template_decl
7001 && is_nondependent_constant_expression (expr))
7002 non_dep = true;
7003 if (error_operand_p (expr))
7004 return error_mark_node;
7005 expr_type = TREE_TYPE (expr);
7007 /* If the argument is non-dependent, perform any conversions in
7008 non-dependent context as well. */
7009 processing_template_decl_sentinel s (non_dep);
7010 if (non_dep)
7011 expr = instantiate_non_dependent_expr_internal (expr, complain);
7013 if (value_dependent_expression_p (expr))
7014 expr = canonicalize_expr_argument (expr, complain);
7016 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7017 to a non-type argument of "nullptr". */
7018 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7019 expr = fold_simple (convert (type, expr));
7021 /* In C++11, integral or enumeration non-type template arguments can be
7022 arbitrary constant expressions. Pointer and pointer to
7023 member arguments can be general constant expressions that evaluate
7024 to a null value, but otherwise still need to be of a specific form. */
7025 if (cxx_dialect >= cxx11)
7027 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7028 /* A PTRMEM_CST is already constant, and a valid template
7029 argument for a parameter of pointer to member type, we just want
7030 to leave it in that form rather than lower it to a
7031 CONSTRUCTOR. */;
7032 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7033 || cxx_dialect >= cxx17)
7035 /* Calling build_converted_constant_expr might create a call to
7036 a conversion function with a value-dependent argument, which
7037 could invoke taking the address of a temporary representing
7038 the result of the conversion. */
7039 if (COMPOUND_LITERAL_P (expr)
7040 && CONSTRUCTOR_IS_DEPENDENT (expr)
7041 && MAYBE_CLASS_TYPE_P (expr_type)
7042 && TYPE_HAS_CONVERSION (expr_type))
7044 expr = build1 (IMPLICIT_CONV_EXPR, type, expr);
7045 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7046 return expr;
7048 /* C++17: A template-argument for a non-type template-parameter shall
7049 be a converted constant expression (8.20) of the type of the
7050 template-parameter. */
7051 expr = build_converted_constant_expr (type, expr, complain);
7052 if (expr == error_mark_node)
7053 /* Make sure we return NULL_TREE only if we have really issued
7054 an error, as described above. */
7055 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7056 expr = maybe_constant_value (expr, NULL_TREE,
7057 /*manifestly_const_eval=*/true);
7058 expr = convert_from_reference (expr);
7060 else if (TYPE_PTR_OR_PTRMEM_P (type))
7062 tree folded = maybe_constant_value (expr, NULL_TREE,
7063 /*manifestly_const_eval=*/true);
7064 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7065 : null_member_pointer_value_p (folded))
7066 expr = folded;
7070 if (TYPE_REF_P (type))
7071 expr = mark_lvalue_use (expr);
7072 else
7073 expr = mark_rvalue_use (expr);
7075 /* HACK: Due to double coercion, we can get a
7076 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7077 which is the tree that we built on the first call (see
7078 below when coercing to reference to object or to reference to
7079 function). We just strip everything and get to the arg.
7080 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7081 for examples. */
7082 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7084 tree probe_type, probe = expr;
7085 if (REFERENCE_REF_P (probe))
7086 probe = TREE_OPERAND (probe, 0);
7087 probe_type = TREE_TYPE (probe);
7088 if (TREE_CODE (probe) == NOP_EXPR)
7090 /* ??? Maybe we could use convert_from_reference here, but we
7091 would need to relax its constraints because the NOP_EXPR
7092 could actually change the type to something more cv-qualified,
7093 and this is not folded by convert_from_reference. */
7094 tree addr = TREE_OPERAND (probe, 0);
7095 if (TYPE_REF_P (probe_type)
7096 && TREE_CODE (addr) == ADDR_EXPR
7097 && TYPE_PTR_P (TREE_TYPE (addr))
7098 && (same_type_ignoring_top_level_qualifiers_p
7099 (TREE_TYPE (probe_type),
7100 TREE_TYPE (TREE_TYPE (addr)))))
7102 expr = TREE_OPERAND (addr, 0);
7103 expr_type = TREE_TYPE (probe_type);
7108 /* [temp.arg.nontype]/5, bullet 1
7110 For a non-type template-parameter of integral or enumeration type,
7111 integral promotions (_conv.prom_) and integral conversions
7112 (_conv.integral_) are applied. */
7113 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7115 if (cxx_dialect < cxx11)
7117 tree t = build_converted_constant_expr (type, expr, complain);
7118 t = maybe_constant_value (t);
7119 if (t != error_mark_node)
7120 expr = t;
7123 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7124 return error_mark_node;
7126 /* Notice that there are constant expressions like '4 % 0' which
7127 do not fold into integer constants. */
7128 if (TREE_CODE (expr) != INTEGER_CST
7129 && !value_dependent_expression_p (expr))
7131 if (complain & tf_error)
7133 int errs = errorcount, warns = warningcount + werrorcount;
7134 if (!require_potential_constant_expression (expr))
7135 expr = error_mark_node;
7136 else
7137 expr = cxx_constant_value (expr);
7138 if (errorcount > errs || warningcount + werrorcount > warns)
7139 inform (loc, "in template argument for type %qT", type);
7140 if (expr == error_mark_node)
7141 return NULL_TREE;
7142 /* else cxx_constant_value complained but gave us
7143 a real constant, so go ahead. */
7144 if (TREE_CODE (expr) != INTEGER_CST)
7146 /* Some assemble time constant expressions like
7147 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7148 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7149 as we can emit them into .rodata initializers of
7150 variables, yet they can't fold into an INTEGER_CST at
7151 compile time. Refuse them here. */
7152 gcc_checking_assert (reduced_constant_expression_p (expr));
7153 error_at (loc, "template argument %qE for type %qT not "
7154 "a constant integer", expr, type);
7155 return NULL_TREE;
7158 else
7159 return NULL_TREE;
7162 /* Avoid typedef problems. */
7163 if (TREE_TYPE (expr) != type)
7164 expr = fold_convert (type, expr);
7166 /* [temp.arg.nontype]/5, bullet 2
7168 For a non-type template-parameter of type pointer to object,
7169 qualification conversions (_conv.qual_) and the array-to-pointer
7170 conversion (_conv.array_) are applied. */
7171 else if (TYPE_PTROBV_P (type))
7173 tree decayed = expr;
7175 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7176 decay_conversion or an explicit cast. If it's a problematic cast,
7177 we'll complain about it below. */
7178 if (TREE_CODE (expr) == NOP_EXPR)
7180 tree probe = expr;
7181 STRIP_NOPS (probe);
7182 if (TREE_CODE (probe) == ADDR_EXPR
7183 && TYPE_PTR_P (TREE_TYPE (probe)))
7185 expr = probe;
7186 expr_type = TREE_TYPE (expr);
7190 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7192 A template-argument for a non-type, non-template template-parameter
7193 shall be one of: [...]
7195 -- the name of a non-type template-parameter;
7196 -- the address of an object or function with external linkage, [...]
7197 expressed as "& id-expression" where the & is optional if the name
7198 refers to a function or array, or if the corresponding
7199 template-parameter is a reference.
7201 Here, we do not care about functions, as they are invalid anyway
7202 for a parameter of type pointer-to-object. */
7204 if (value_dependent_expression_p (expr))
7205 /* Non-type template parameters are OK. */
7207 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7208 /* Null pointer values are OK in C++11. */;
7209 else if (TREE_CODE (expr) != ADDR_EXPR
7210 && !INDIRECT_TYPE_P (expr_type))
7211 /* Other values, like integer constants, might be valid
7212 non-type arguments of some other type. */
7213 return error_mark_node;
7214 else if (invalid_tparm_referent_p (type, expr, complain))
7215 return NULL_TREE;
7217 expr = decayed;
7219 expr = perform_qualification_conversions (type, expr);
7220 if (expr == error_mark_node)
7221 return error_mark_node;
7223 /* [temp.arg.nontype]/5, bullet 3
7225 For a non-type template-parameter of type reference to object, no
7226 conversions apply. The type referred to by the reference may be more
7227 cv-qualified than the (otherwise identical) type of the
7228 template-argument. The template-parameter is bound directly to the
7229 template-argument, which must be an lvalue. */
7230 else if (TYPE_REF_OBJ_P (type))
7232 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7233 expr_type))
7234 return error_mark_node;
7236 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7238 if (complain & tf_error)
7239 error ("%qE is not a valid template argument for type %qT "
7240 "because of conflicts in cv-qualification", expr, type);
7241 return NULL_TREE;
7244 if (!lvalue_p (expr))
7246 if (complain & tf_error)
7247 error ("%qE is not a valid template argument for type %qT "
7248 "because it is not an lvalue", expr, type);
7249 return NULL_TREE;
7252 /* [temp.arg.nontype]/1
7254 A template-argument for a non-type, non-template template-parameter
7255 shall be one of: [...]
7257 -- the address of an object or function with external linkage. */
7258 if (INDIRECT_REF_P (expr)
7259 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7261 expr = TREE_OPERAND (expr, 0);
7262 if (DECL_P (expr))
7264 if (complain & tf_error)
7265 error ("%q#D is not a valid template argument for type %qT "
7266 "because a reference variable does not have a constant "
7267 "address", expr, type);
7268 return NULL_TREE;
7272 if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
7273 && value_dependent_expression_p (expr))
7274 /* OK, dependent reference. We don't want to ask whether a DECL is
7275 itself value-dependent, since what we want here is its address. */;
7276 else
7278 expr = build_address (expr);
7280 if (invalid_tparm_referent_p (type, expr, complain))
7281 return NULL_TREE;
7284 if (!same_type_p (type, TREE_TYPE (expr)))
7285 expr = build_nop (type, expr);
7287 /* [temp.arg.nontype]/5, bullet 4
7289 For a non-type template-parameter of type pointer to function, only
7290 the function-to-pointer conversion (_conv.func_) is applied. If the
7291 template-argument represents a set of overloaded functions (or a
7292 pointer to such), the matching function is selected from the set
7293 (_over.over_). */
7294 else if (TYPE_PTRFN_P (type))
7296 /* If the argument is a template-id, we might not have enough
7297 context information to decay the pointer. */
7298 if (!type_unknown_p (expr_type))
7300 expr = decay_conversion (expr, complain);
7301 if (expr == error_mark_node)
7302 return error_mark_node;
7305 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7306 /* Null pointer values are OK in C++11. */
7307 return perform_qualification_conversions (type, expr);
7309 expr = convert_nontype_argument_function (type, expr, complain);
7310 if (!expr || expr == error_mark_node)
7311 return expr;
7313 /* [temp.arg.nontype]/5, bullet 5
7315 For a non-type template-parameter of type reference to function, no
7316 conversions apply. If the template-argument represents a set of
7317 overloaded functions, the matching function is selected from the set
7318 (_over.over_). */
7319 else if (TYPE_REFFN_P (type))
7321 if (TREE_CODE (expr) == ADDR_EXPR)
7323 if (complain & tf_error)
7325 error ("%qE is not a valid template argument for type %qT "
7326 "because it is a pointer", expr, type);
7327 inform (input_location, "try using %qE instead",
7328 TREE_OPERAND (expr, 0));
7330 return NULL_TREE;
7333 expr = convert_nontype_argument_function (type, expr, complain);
7334 if (!expr || expr == error_mark_node)
7335 return expr;
7337 /* [temp.arg.nontype]/5, bullet 6
7339 For a non-type template-parameter of type pointer to member function,
7340 no conversions apply. If the template-argument represents a set of
7341 overloaded member functions, the matching member function is selected
7342 from the set (_over.over_). */
7343 else if (TYPE_PTRMEMFUNC_P (type))
7345 expr = instantiate_type (type, expr, tf_none);
7346 if (expr == error_mark_node)
7347 return error_mark_node;
7349 /* [temp.arg.nontype] bullet 1 says the pointer to member
7350 expression must be a pointer-to-member constant. */
7351 if (!value_dependent_expression_p (expr)
7352 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7353 return NULL_TREE;
7355 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7356 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7357 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7358 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7360 /* [temp.arg.nontype]/5, bullet 7
7362 For a non-type template-parameter of type pointer to data member,
7363 qualification conversions (_conv.qual_) are applied. */
7364 else if (TYPE_PTRDATAMEM_P (type))
7366 /* [temp.arg.nontype] bullet 1 says the pointer to member
7367 expression must be a pointer-to-member constant. */
7368 if (!value_dependent_expression_p (expr)
7369 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7370 return NULL_TREE;
7372 expr = perform_qualification_conversions (type, expr);
7373 if (expr == error_mark_node)
7374 return expr;
7376 else if (NULLPTR_TYPE_P (type))
7378 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7380 if (complain & tf_error)
7381 error ("%qE is not a valid template argument for type %qT "
7382 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7383 return NULL_TREE;
7385 return expr;
7387 else if (CLASS_TYPE_P (type))
7389 /* Replace the argument with a reference to the corresponding template
7390 parameter object. */
7391 if (!value_dependent_expression_p (expr))
7392 expr = get_template_parm_object (expr, complain);
7393 if (expr == error_mark_node)
7394 return NULL_TREE;
7396 /* A template non-type parameter must be one of the above. */
7397 else
7398 gcc_unreachable ();
7400 /* Sanity check: did we actually convert the argument to the
7401 right type? */
7402 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7403 (type, TREE_TYPE (expr)));
7404 return convert_from_reference (expr);
7407 /* Subroutine of coerce_template_template_parms, which returns 1 if
7408 PARM_PARM and ARG_PARM match using the rule for the template
7409 parameters of template template parameters. Both PARM and ARG are
7410 template parameters; the rest of the arguments are the same as for
7411 coerce_template_template_parms.
7413 static int
7414 coerce_template_template_parm (tree parm,
7415 tree arg,
7416 tsubst_flags_t complain,
7417 tree in_decl,
7418 tree outer_args)
7420 if (arg == NULL_TREE || error_operand_p (arg)
7421 || parm == NULL_TREE || error_operand_p (parm))
7422 return 0;
7424 if (TREE_CODE (arg) != TREE_CODE (parm))
7425 return 0;
7427 switch (TREE_CODE (parm))
7429 case TEMPLATE_DECL:
7430 /* We encounter instantiations of templates like
7431 template <template <template <class> class> class TT>
7432 class C; */
7434 tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7435 tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7437 if (!coerce_template_template_parms
7438 (parmparm, argparm, complain, in_decl, outer_args))
7439 return 0;
7441 /* Fall through. */
7443 case TYPE_DECL:
7444 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7445 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7446 /* Argument is a parameter pack but parameter is not. */
7447 return 0;
7448 break;
7450 case PARM_DECL:
7451 /* The tsubst call is used to handle cases such as
7453 template <int> class C {};
7454 template <class T, template <T> class TT> class D {};
7455 D<int, C> d;
7457 i.e. the parameter list of TT depends on earlier parameters. */
7458 if (!uses_template_parms (TREE_TYPE (arg)))
7460 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7461 if (!uses_template_parms (t)
7462 && !same_type_p (t, TREE_TYPE (arg)))
7463 return 0;
7466 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7467 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7468 /* Argument is a parameter pack but parameter is not. */
7469 return 0;
7471 break;
7473 default:
7474 gcc_unreachable ();
7477 return 1;
7480 /* Coerce template argument list ARGLIST for use with template
7481 template-parameter TEMPL. */
7483 static tree
7484 coerce_template_args_for_ttp (tree templ, tree arglist,
7485 tsubst_flags_t complain)
7487 /* Consider an example where a template template parameter declared as
7489 template <class T, class U = std::allocator<T> > class TT
7491 The template parameter level of T and U are one level larger than
7492 of TT. To proper process the default argument of U, say when an
7493 instantiation `TT<int>' is seen, we need to build the full
7494 arguments containing {int} as the innermost level. Outer levels,
7495 available when not appearing as default template argument, can be
7496 obtained from the arguments of the enclosing template.
7498 Suppose that TT is later substituted with std::vector. The above
7499 instantiation is `TT<int, std::allocator<T> >' with TT at
7500 level 1, and T at level 2, while the template arguments at level 1
7501 becomes {std::vector} and the inner level 2 is {int}. */
7503 tree outer = DECL_CONTEXT (templ);
7504 if (outer)
7505 outer = generic_targs_for (outer);
7506 else if (current_template_parms)
7508 /* This is an argument of the current template, so we haven't set
7509 DECL_CONTEXT yet. */
7510 tree relevant_template_parms;
7512 /* Parameter levels that are greater than the level of the given
7513 template template parm are irrelevant. */
7514 relevant_template_parms = current_template_parms;
7515 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7516 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7517 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7519 outer = template_parms_to_args (relevant_template_parms);
7522 if (outer)
7523 arglist = add_to_template_args (outer, arglist);
7525 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7526 return coerce_template_parms (parmlist, arglist, templ,
7527 complain,
7528 /*require_all_args=*/true,
7529 /*use_default_args=*/true);
7532 /* A cache of template template parameters with match-all default
7533 arguments. */
7534 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7536 /* T is a bound template template-parameter. Copy its arguments into default
7537 arguments of the template template-parameter's template parameters. */
7539 static tree
7540 add_defaults_to_ttp (tree otmpl)
7542 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7543 return *c;
7545 tree ntmpl = copy_node (otmpl);
7547 tree ntype = copy_node (TREE_TYPE (otmpl));
7548 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7549 TYPE_MAIN_VARIANT (ntype) = ntype;
7550 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7551 TYPE_NAME (ntype) = ntmpl;
7552 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7554 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7555 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7556 TEMPLATE_PARM_DECL (idx) = ntmpl;
7557 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7559 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7560 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7561 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7562 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7563 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7565 tree o = TREE_VEC_ELT (vec, i);
7566 if (!template_parameter_pack_p (TREE_VALUE (o)))
7568 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7569 TREE_PURPOSE (n) = any_targ_node;
7573 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7574 return ntmpl;
7577 /* ARG is a bound potential template template-argument, and PARGS is a list
7578 of arguments for the corresponding template template-parameter. Adjust
7579 PARGS as appropriate for application to ARG's template, and if ARG is a
7580 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7581 arguments to the template template parameter. */
7583 static tree
7584 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7586 ++processing_template_decl;
7587 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7588 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7590 /* When comparing two template template-parameters in partial ordering,
7591 rewrite the one currently being used as an argument to have default
7592 arguments for all parameters. */
7593 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7594 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7595 if (pargs != error_mark_node)
7596 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7597 TYPE_TI_ARGS (arg));
7599 else
7601 tree aparms
7602 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7603 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7604 /*require_all*/true,
7605 /*use_default*/true);
7607 --processing_template_decl;
7608 return pargs;
7611 /* Subroutine of unify for the case when PARM is a
7612 BOUND_TEMPLATE_TEMPLATE_PARM. */
7614 static int
7615 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7616 bool explain_p)
7618 tree parmvec = TYPE_TI_ARGS (parm);
7619 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7621 /* The template template parm might be variadic and the argument
7622 not, so flatten both argument lists. */
7623 parmvec = expand_template_argument_pack (parmvec);
7624 argvec = expand_template_argument_pack (argvec);
7626 if (flag_new_ttp)
7628 /* In keeping with P0522R0, adjust P's template arguments
7629 to apply to A's template; then flatten it again. */
7630 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7631 nparmvec = expand_template_argument_pack (nparmvec);
7633 if (unify (tparms, targs, nparmvec, argvec,
7634 UNIFY_ALLOW_NONE, explain_p))
7635 return 1;
7637 /* If the P0522 adjustment eliminated a pack expansion, deduce
7638 empty packs. */
7639 if (flag_new_ttp
7640 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7641 && unify_pack_expansion (tparms, targs, parmvec, argvec,
7642 DEDUCE_EXACT, /*sub*/true, explain_p))
7643 return 1;
7645 else
7647 /* Deduce arguments T, i from TT<T> or TT<i>.
7648 We check each element of PARMVEC and ARGVEC individually
7649 rather than the whole TREE_VEC since they can have
7650 different number of elements, which is allowed under N2555. */
7652 int len = TREE_VEC_LENGTH (parmvec);
7654 /* Check if the parameters end in a pack, making them
7655 variadic. */
7656 int parm_variadic_p = 0;
7657 if (len > 0
7658 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7659 parm_variadic_p = 1;
7661 for (int i = 0; i < len - parm_variadic_p; ++i)
7662 /* If the template argument list of P contains a pack
7663 expansion that is not the last template argument, the
7664 entire template argument list is a non-deduced
7665 context. */
7666 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7667 return unify_success (explain_p);
7669 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7670 return unify_too_few_arguments (explain_p,
7671 TREE_VEC_LENGTH (argvec), len);
7673 for (int i = 0; i < len - parm_variadic_p; ++i)
7674 if (unify (tparms, targs,
7675 TREE_VEC_ELT (parmvec, i),
7676 TREE_VEC_ELT (argvec, i),
7677 UNIFY_ALLOW_NONE, explain_p))
7678 return 1;
7680 if (parm_variadic_p
7681 && unify_pack_expansion (tparms, targs,
7682 parmvec, argvec,
7683 DEDUCE_EXACT,
7684 /*subr=*/true, explain_p))
7685 return 1;
7688 return 0;
7691 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7692 template template parameters. Both PARM_PARMS and ARG_PARMS are
7693 vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7694 or PARM_DECL.
7696 Consider the example:
7697 template <class T> class A;
7698 template<template <class U> class TT> class B;
7700 For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7701 the parameters to A, and OUTER_ARGS contains A. */
7703 static int
7704 coerce_template_template_parms (tree parm_parms,
7705 tree arg_parms,
7706 tsubst_flags_t complain,
7707 tree in_decl,
7708 tree outer_args)
7710 int nparms, nargs, i;
7711 tree parm, arg;
7712 int variadic_p = 0;
7714 gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7715 gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7717 nparms = TREE_VEC_LENGTH (parm_parms);
7718 nargs = TREE_VEC_LENGTH (arg_parms);
7720 if (flag_new_ttp)
7722 /* P0522R0: A template template-parameter P is at least as specialized as
7723 a template template-argument A if, given the following rewrite to two
7724 function templates, the function template corresponding to P is at
7725 least as specialized as the function template corresponding to A
7726 according to the partial ordering rules for function templates
7727 ([temp.func.order]). Given an invented class template X with the
7728 template parameter list of A (including default arguments):
7730 * Each of the two function templates has the same template parameters,
7731 respectively, as P or A.
7733 * Each function template has a single function parameter whose type is
7734 a specialization of X with template arguments corresponding to the
7735 template parameters from the respective function template where, for
7736 each template parameter PP in the template parameter list of the
7737 function template, a corresponding template argument AA is formed. If
7738 PP declares a parameter pack, then AA is the pack expansion
7739 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7741 If the rewrite produces an invalid type, then P is not at least as
7742 specialized as A. */
7744 /* So coerce P's args to apply to A's parms, and then deduce between A's
7745 args and the converted args. If that succeeds, A is at least as
7746 specialized as P, so they match.*/
7747 tree pargs = template_parms_level_to_args (parm_parms);
7748 pargs = add_outermost_template_args (outer_args, pargs);
7749 ++processing_template_decl;
7750 pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7751 /*require_all*/true, /*use_default*/true);
7752 --processing_template_decl;
7753 if (pargs != error_mark_node)
7755 tree targs = make_tree_vec (nargs);
7756 tree aargs = template_parms_level_to_args (arg_parms);
7757 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7758 /*explain*/false))
7759 return 1;
7763 /* Determine whether we have a parameter pack at the end of the
7764 template template parameter's template parameter list. */
7765 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7767 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7769 if (error_operand_p (parm))
7770 return 0;
7772 switch (TREE_CODE (parm))
7774 case TEMPLATE_DECL:
7775 case TYPE_DECL:
7776 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7777 variadic_p = 1;
7778 break;
7780 case PARM_DECL:
7781 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7782 variadic_p = 1;
7783 break;
7785 default:
7786 gcc_unreachable ();
7790 if (nargs != nparms
7791 && !(variadic_p && nargs >= nparms - 1))
7792 return 0;
7794 /* Check all of the template parameters except the parameter pack at
7795 the end (if any). */
7796 for (i = 0; i < nparms - variadic_p; ++i)
7798 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7799 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7800 continue;
7802 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7803 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7805 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7806 outer_args))
7807 return 0;
7811 if (variadic_p)
7813 /* Check each of the template parameters in the template
7814 argument against the template parameter pack at the end of
7815 the template template parameter. */
7816 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7817 return 0;
7819 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7821 for (; i < nargs; ++i)
7823 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7824 continue;
7826 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7828 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7829 outer_args))
7830 return 0;
7834 return 1;
7837 /* Verifies that the deduced template arguments (in TARGS) for the
7838 template template parameters (in TPARMS) represent valid bindings,
7839 by comparing the template parameter list of each template argument
7840 to the template parameter list of its corresponding template
7841 template parameter, in accordance with DR150. This
7842 routine can only be called after all template arguments have been
7843 deduced. It will return TRUE if all of the template template
7844 parameter bindings are okay, FALSE otherwise. */
7845 bool
7846 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7848 int i, ntparms = TREE_VEC_LENGTH (tparms);
7849 bool ret = true;
7851 /* We're dealing with template parms in this process. */
7852 ++processing_template_decl;
7854 targs = INNERMOST_TEMPLATE_ARGS (targs);
7856 for (i = 0; i < ntparms; ++i)
7858 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7859 tree targ = TREE_VEC_ELT (targs, i);
7861 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7863 tree packed_args = NULL_TREE;
7864 int idx, len = 1;
7866 if (ARGUMENT_PACK_P (targ))
7868 /* Look inside the argument pack. */
7869 packed_args = ARGUMENT_PACK_ARGS (targ);
7870 len = TREE_VEC_LENGTH (packed_args);
7873 for (idx = 0; idx < len; ++idx)
7875 tree targ_parms = NULL_TREE;
7877 if (packed_args)
7878 /* Extract the next argument from the argument
7879 pack. */
7880 targ = TREE_VEC_ELT (packed_args, idx);
7882 if (PACK_EXPANSION_P (targ))
7883 /* Look at the pattern of the pack expansion. */
7884 targ = PACK_EXPANSION_PATTERN (targ);
7886 /* Extract the template parameters from the template
7887 argument. */
7888 if (TREE_CODE (targ) == TEMPLATE_DECL)
7889 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7890 else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7891 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7893 /* Verify that we can coerce the template template
7894 parameters from the template argument to the template
7895 parameter. This requires an exact match. */
7896 if (targ_parms
7897 && !coerce_template_template_parms
7898 (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7899 targ_parms,
7900 tf_none,
7901 tparm,
7902 targs))
7904 ret = false;
7905 goto out;
7911 out:
7913 --processing_template_decl;
7914 return ret;
7917 /* Since type attributes aren't mangled, we need to strip them from
7918 template type arguments. */
7920 static tree
7921 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7923 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7924 return arg;
7925 bool removed_attributes = false;
7926 tree canon = strip_typedefs (arg, &removed_attributes);
7927 if (removed_attributes
7928 && (complain & tf_warning))
7929 warning (OPT_Wignored_attributes,
7930 "ignoring attributes on template argument %qT", arg);
7931 return canon;
7934 /* And from inside dependent non-type arguments like sizeof(Type). */
7936 static tree
7937 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7939 if (!arg || arg == error_mark_node)
7940 return arg;
7941 bool removed_attributes = false;
7942 tree canon = strip_typedefs_expr (arg, &removed_attributes);
7943 if (removed_attributes
7944 && (complain & tf_warning))
7945 warning (OPT_Wignored_attributes,
7946 "ignoring attributes in template argument %qE", arg);
7947 return canon;
7950 // A template declaration can be substituted for a constrained
7951 // template template parameter only when the argument is more
7952 // constrained than the parameter.
7953 static bool
7954 is_compatible_template_arg (tree parm, tree arg)
7956 tree parm_cons = get_constraints (parm);
7958 /* For now, allow constrained template template arguments
7959 and unconstrained template template parameters. */
7960 if (parm_cons == NULL_TREE)
7961 return true;
7963 /* If the template parameter is constrained, we need to rewrite its
7964 constraints in terms of the ARG's template parameters. This ensures
7965 that all of the template parameter types will have the same depth.
7967 Note that this is only valid when coerce_template_template_parm is
7968 true for the innermost template parameters of PARM and ARG. In other
7969 words, because coercion is successful, this conversion will be valid. */
7970 tree new_args = NULL_TREE;
7971 if (parm_cons)
7973 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7974 new_args = template_parms_level_to_args (aparms);
7975 parm_cons = tsubst_constraint_info (parm_cons, new_args,
7976 tf_none, NULL_TREE);
7977 if (parm_cons == error_mark_node)
7978 return false;
7981 return weakly_subsumes (parm_cons, new_args, arg);
7984 // Convert a placeholder argument into a binding to the original
7985 // parameter. The original parameter is saved as the TREE_TYPE of
7986 // ARG.
7987 static inline tree
7988 convert_wildcard_argument (tree parm, tree arg)
7990 TREE_TYPE (arg) = parm;
7991 return arg;
7994 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7995 because one of them is dependent. But we need to represent the
7996 conversion for the benefit of cp_tree_equal. */
7998 static tree
7999 maybe_convert_nontype_argument (tree type, tree arg)
8001 /* Auto parms get no conversion. */
8002 if (type_uses_auto (type))
8003 return arg;
8004 /* We don't need or want to add this conversion now if we're going to use the
8005 argument for deduction. */
8006 if (value_dependent_expression_p (arg))
8007 return arg;
8009 type = cv_unqualified (type);
8010 tree argtype = TREE_TYPE (arg);
8011 if (same_type_p (type, argtype))
8012 return arg;
8014 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8015 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8016 return arg;
8019 /* Convert the indicated template ARG as necessary to match the
8020 indicated template PARM. Returns the converted ARG, or
8021 error_mark_node if the conversion was unsuccessful. Error and
8022 warning messages are issued under control of COMPLAIN. This
8023 conversion is for the Ith parameter in the parameter list. ARGS is
8024 the full set of template arguments deduced so far. */
8026 static tree
8027 convert_template_argument (tree parm,
8028 tree arg,
8029 tree args,
8030 tsubst_flags_t complain,
8031 int i,
8032 tree in_decl)
8034 tree orig_arg;
8035 tree val;
8036 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8038 if (parm == error_mark_node || error_operand_p (arg))
8039 return error_mark_node;
8041 /* Trivially convert placeholders. */
8042 if (TREE_CODE (arg) == WILDCARD_DECL)
8043 return convert_wildcard_argument (parm, arg);
8045 if (arg == any_targ_node)
8046 return arg;
8048 if (TREE_CODE (arg) == TREE_LIST
8049 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8051 /* The template argument was the name of some
8052 member function. That's usually
8053 invalid, but static members are OK. In any
8054 case, grab the underlying fields/functions
8055 and issue an error later if required. */
8056 TREE_TYPE (arg) = unknown_type_node;
8059 orig_arg = arg;
8061 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8062 requires_type = (TREE_CODE (parm) == TYPE_DECL
8063 || requires_tmpl_type);
8065 /* When determining whether an argument pack expansion is a template,
8066 look at the pattern. */
8067 if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
8068 arg = PACK_EXPANSION_PATTERN (arg);
8070 /* Deal with an injected-class-name used as a template template arg. */
8071 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8073 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8074 if (TREE_CODE (t) == TEMPLATE_DECL)
8076 if (cxx_dialect >= cxx11)
8077 /* OK under DR 1004. */;
8078 else if (complain & tf_warning_or_error)
8079 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8080 " used as template template argument", TYPE_NAME (arg));
8081 else if (flag_pedantic_errors)
8082 t = arg;
8084 arg = t;
8088 is_tmpl_type =
8089 ((TREE_CODE (arg) == TEMPLATE_DECL
8090 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8091 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8092 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8093 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8095 if (is_tmpl_type
8096 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8097 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8098 arg = TYPE_STUB_DECL (arg);
8100 is_type = TYPE_P (arg) || is_tmpl_type;
8102 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8103 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8105 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8107 if (complain & tf_error)
8108 error ("invalid use of destructor %qE as a type", orig_arg);
8109 return error_mark_node;
8112 permerror (input_location,
8113 "to refer to a type member of a template parameter, "
8114 "use %<typename %E%>", orig_arg);
8116 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8117 TREE_OPERAND (arg, 1),
8118 typename_type,
8119 complain);
8120 arg = orig_arg;
8121 is_type = 1;
8123 if (is_type != requires_type)
8125 if (in_decl)
8127 if (complain & tf_error)
8129 error ("type/value mismatch at argument %d in template "
8130 "parameter list for %qD",
8131 i + 1, in_decl);
8132 if (is_type)
8134 /* The template argument is a type, but we're expecting
8135 an expression. */
8136 inform (input_location,
8137 " expected a constant of type %qT, got %qT",
8138 TREE_TYPE (parm),
8139 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8140 /* [temp.arg]/2: "In a template-argument, an ambiguity
8141 between a type-id and an expression is resolved to a
8142 type-id, regardless of the form of the corresponding
8143 template-parameter." So give the user a clue. */
8144 if (TREE_CODE (arg) == FUNCTION_TYPE)
8145 inform (input_location, " ambiguous template argument "
8146 "for non-type template parameter is treated as "
8147 "function type");
8149 else if (requires_tmpl_type)
8150 inform (input_location,
8151 " expected a class template, got %qE", orig_arg);
8152 else
8153 inform (input_location,
8154 " expected a type, got %qE", orig_arg);
8157 return error_mark_node;
8159 if (is_tmpl_type ^ requires_tmpl_type)
8161 if (in_decl && (complain & tf_error))
8163 error ("type/value mismatch at argument %d in template "
8164 "parameter list for %qD",
8165 i + 1, in_decl);
8166 if (is_tmpl_type)
8167 inform (input_location,
8168 " expected a type, got %qT", DECL_NAME (arg));
8169 else
8170 inform (input_location,
8171 " expected a class template, got %qT", orig_arg);
8173 return error_mark_node;
8176 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8177 /* We already did the appropriate conversion when packing args. */
8178 val = orig_arg;
8179 else if (is_type)
8181 if (requires_tmpl_type)
8183 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8184 /* The number of argument required is not known yet.
8185 Just accept it for now. */
8186 val = orig_arg;
8187 else
8189 tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8190 tree argparm;
8192 /* Strip alias templates that are equivalent to another
8193 template. */
8194 arg = get_underlying_template (arg);
8195 argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8197 if (coerce_template_template_parms (parmparm, argparm,
8198 complain, in_decl,
8199 args))
8201 val = arg;
8203 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8204 TEMPLATE_DECL. */
8205 if (val != error_mark_node)
8207 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8208 val = TREE_TYPE (val);
8209 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8210 val = make_pack_expansion (val, complain);
8213 else
8215 if (in_decl && (complain & tf_error))
8217 error ("type/value mismatch at argument %d in "
8218 "template parameter list for %qD",
8219 i + 1, in_decl);
8220 inform (input_location,
8221 " expected a template of type %qD, got %qT",
8222 parm, orig_arg);
8225 val = error_mark_node;
8228 // Check that the constraints are compatible before allowing the
8229 // substitution.
8230 if (val != error_mark_node)
8231 if (!is_compatible_template_arg (parm, arg))
8233 if (in_decl && (complain & tf_error))
8235 error ("constraint mismatch at argument %d in "
8236 "template parameter list for %qD",
8237 i + 1, in_decl);
8238 inform (input_location, " expected %qD but got %qD",
8239 parm, arg);
8241 val = error_mark_node;
8245 else
8246 val = orig_arg;
8247 /* We only form one instance of each template specialization.
8248 Therefore, if we use a non-canonical variant (i.e., a
8249 typedef), any future messages referring to the type will use
8250 the typedef, which is confusing if those future uses do not
8251 themselves also use the typedef. */
8252 if (TYPE_P (val))
8253 val = canonicalize_type_argument (val, complain);
8255 else
8257 tree t = TREE_TYPE (parm);
8259 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8260 > TMPL_ARGS_DEPTH (args))
8261 /* We don't have enough levels of args to do any substitution. This
8262 can happen in the context of -fnew-ttp-matching. */;
8263 else if (tree a = type_uses_auto (t))
8265 t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8266 if (t == error_mark_node)
8267 return error_mark_node;
8269 else
8270 t = tsubst (t, args, complain, in_decl);
8272 if (invalid_nontype_parm_type_p (t, complain))
8273 return error_mark_node;
8275 if (t != TREE_TYPE (parm))
8276 t = canonicalize_type_argument (t, complain);
8278 if (!type_dependent_expression_p (orig_arg)
8279 && !uses_template_parms (t))
8280 /* We used to call digest_init here. However, digest_init
8281 will report errors, which we don't want when complain
8282 is zero. More importantly, digest_init will try too
8283 hard to convert things: for example, `0' should not be
8284 converted to pointer type at this point according to
8285 the standard. Accepting this is not merely an
8286 extension, since deciding whether or not these
8287 conversions can occur is part of determining which
8288 function template to call, or whether a given explicit
8289 argument specification is valid. */
8290 val = convert_nontype_argument (t, orig_arg, complain);
8291 else
8293 val = canonicalize_expr_argument (orig_arg, complain);
8294 val = maybe_convert_nontype_argument (t, val);
8298 if (val == NULL_TREE)
8299 val = error_mark_node;
8300 else if (val == error_mark_node && (complain & tf_error))
8301 error_at (cp_expr_loc_or_input_loc (orig_arg),
8302 "could not convert template argument %qE from %qT to %qT",
8303 orig_arg, TREE_TYPE (orig_arg), t);
8305 if (INDIRECT_REF_P (val))
8307 /* Reject template arguments that are references to built-in
8308 functions with no library fallbacks. */
8309 const_tree inner = TREE_OPERAND (val, 0);
8310 const_tree innertype = TREE_TYPE (inner);
8311 if (innertype
8312 && TYPE_REF_P (innertype)
8313 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8314 && TREE_OPERAND_LENGTH (inner) > 0
8315 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8316 return error_mark_node;
8319 if (TREE_CODE (val) == SCOPE_REF)
8321 /* Strip typedefs from the SCOPE_REF. */
8322 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8323 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8324 complain);
8325 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8326 QUALIFIED_NAME_IS_TEMPLATE (val));
8330 return val;
8333 /* Coerces the remaining template arguments in INNER_ARGS (from
8334 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8335 Returns the coerced argument pack. PARM_IDX is the position of this
8336 parameter in the template parameter list. ARGS is the original
8337 template argument list. */
8338 static tree
8339 coerce_template_parameter_pack (tree parms,
8340 int parm_idx,
8341 tree args,
8342 tree inner_args,
8343 int arg_idx,
8344 tree new_args,
8345 int* lost,
8346 tree in_decl,
8347 tsubst_flags_t complain)
8349 tree parm = TREE_VEC_ELT (parms, parm_idx);
8350 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8351 tree packed_args;
8352 tree argument_pack;
8353 tree packed_parms = NULL_TREE;
8355 if (arg_idx > nargs)
8356 arg_idx = nargs;
8358 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8360 /* When the template parameter is a non-type template parameter pack
8361 or template template parameter pack whose type or template
8362 parameters use parameter packs, we know exactly how many arguments
8363 we are looking for. Build a vector of the instantiated decls for
8364 these template parameters in PACKED_PARMS. */
8365 /* We can't use make_pack_expansion here because it would interpret a
8366 _DECL as a use rather than a declaration. */
8367 tree decl = TREE_VALUE (parm);
8368 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8369 SET_PACK_EXPANSION_PATTERN (exp, decl);
8370 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8371 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8373 TREE_VEC_LENGTH (args)--;
8374 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8375 TREE_VEC_LENGTH (args)++;
8377 if (packed_parms == error_mark_node)
8378 return error_mark_node;
8380 /* If we're doing a partial instantiation of a member template,
8381 verify that all of the types used for the non-type
8382 template parameter pack are, in fact, valid for non-type
8383 template parameters. */
8384 if (arg_idx < nargs
8385 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8387 int j, len = TREE_VEC_LENGTH (packed_parms);
8388 for (j = 0; j < len; ++j)
8390 tree t = TREE_VEC_ELT (packed_parms, j);
8391 if (TREE_CODE (t) == PARM_DECL
8392 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8393 return error_mark_node;
8395 /* We don't know how many args we have yet, just
8396 use the unconverted ones for now. */
8397 return NULL_TREE;
8400 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8402 /* Check if we have a placeholder pack, which indicates we're
8403 in the context of a introduction list. In that case we want
8404 to match this pack to the single placeholder. */
8405 else if (arg_idx < nargs
8406 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8407 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8409 nargs = arg_idx + 1;
8410 packed_args = make_tree_vec (1);
8412 else
8413 packed_args = make_tree_vec (nargs - arg_idx);
8415 /* Convert the remaining arguments, which will be a part of the
8416 parameter pack "parm". */
8417 int first_pack_arg = arg_idx;
8418 for (; arg_idx < nargs; ++arg_idx)
8420 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8421 tree actual_parm = TREE_VALUE (parm);
8422 int pack_idx = arg_idx - first_pack_arg;
8424 if (packed_parms)
8426 /* Once we've packed as many args as we have types, stop. */
8427 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8428 break;
8429 else if (PACK_EXPANSION_P (arg))
8430 /* We don't know how many args we have yet, just
8431 use the unconverted ones for now. */
8432 return NULL_TREE;
8433 else
8434 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8437 if (arg == error_mark_node)
8439 if (complain & tf_error)
8440 error ("template argument %d is invalid", arg_idx + 1);
8442 else
8443 arg = convert_template_argument (actual_parm,
8444 arg, new_args, complain, parm_idx,
8445 in_decl);
8446 if (arg == error_mark_node)
8447 (*lost)++;
8448 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8451 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8452 && TREE_VEC_LENGTH (packed_args) > 0)
8454 if (complain & tf_error)
8455 error ("wrong number of template arguments (%d, should be %d)",
8456 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8457 return error_mark_node;
8460 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8461 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8462 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8463 else
8465 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8466 TREE_CONSTANT (argument_pack) = 1;
8469 SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8470 if (CHECKING_P)
8471 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8472 TREE_VEC_LENGTH (packed_args));
8473 return argument_pack;
8476 /* Returns the number of pack expansions in the template argument vector
8477 ARGS. */
8479 static int
8480 pack_expansion_args_count (tree args)
8482 int i;
8483 int count = 0;
8484 if (args)
8485 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8487 tree elt = TREE_VEC_ELT (args, i);
8488 if (elt && PACK_EXPANSION_P (elt))
8489 ++count;
8491 return count;
8494 /* Convert all template arguments to their appropriate types, and
8495 return a vector containing the innermost resulting template
8496 arguments. If any error occurs, return error_mark_node. Error and
8497 warning messages are issued under control of COMPLAIN.
8499 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8500 for arguments not specified in ARGS. Otherwise, if
8501 USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8502 unspecified arguments. If REQUIRE_ALL_ARGS is true, but
8503 USE_DEFAULT_ARGS is false, then all arguments must be specified in
8504 ARGS. */
8506 static tree
8507 coerce_template_parms (tree parms,
8508 tree args,
8509 tree in_decl,
8510 tsubst_flags_t complain,
8511 bool require_all_args,
8512 bool use_default_args)
8514 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8515 tree orig_inner_args;
8516 tree inner_args;
8517 tree new_args;
8518 tree new_inner_args;
8520 /* When used as a boolean value, indicates whether this is a
8521 variadic template parameter list. Since it's an int, we can also
8522 subtract it from nparms to get the number of non-variadic
8523 parameters. */
8524 int variadic_p = 0;
8525 int variadic_args_p = 0;
8526 int post_variadic_parms = 0;
8528 /* Adjustment to nparms for fixed parameter packs. */
8529 int fixed_pack_adjust = 0;
8530 int fixed_packs = 0;
8531 int missing = 0;
8533 /* Likewise for parameters with default arguments. */
8534 int default_p = 0;
8536 if (args == error_mark_node)
8537 return error_mark_node;
8539 nparms = TREE_VEC_LENGTH (parms);
8541 /* Determine if there are any parameter packs or default arguments. */
8542 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8544 tree parm = TREE_VEC_ELT (parms, parm_idx);
8545 if (variadic_p)
8546 ++post_variadic_parms;
8547 if (template_parameter_pack_p (TREE_VALUE (parm)))
8548 ++variadic_p;
8549 if (TREE_PURPOSE (parm))
8550 ++default_p;
8553 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8554 /* If there are no parameters that follow a parameter pack, we need to
8555 expand any argument packs so that we can deduce a parameter pack from
8556 some non-packed args followed by an argument pack, as in variadic85.C.
8557 If there are such parameters, we need to leave argument packs intact
8558 so the arguments are assigned properly. This can happen when dealing
8559 with a nested class inside a partial specialization of a class
8560 template, as in variadic92.C, or when deducing a template parameter pack
8561 from a sub-declarator, as in variadic114.C. */
8562 if (!post_variadic_parms)
8563 inner_args = expand_template_argument_pack (inner_args);
8565 /* Count any pack expansion args. */
8566 variadic_args_p = pack_expansion_args_count (inner_args);
8568 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8569 if ((nargs - variadic_args_p > nparms && !variadic_p)
8570 || (nargs < nparms - variadic_p
8571 && require_all_args
8572 && !variadic_args_p
8573 && (!use_default_args
8574 || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8575 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8577 bad_nargs:
8578 if (complain & tf_error)
8580 if (variadic_p || default_p)
8582 nparms -= variadic_p + default_p;
8583 error ("wrong number of template arguments "
8584 "(%d, should be at least %d)", nargs, nparms);
8586 else
8587 error ("wrong number of template arguments "
8588 "(%d, should be %d)", nargs, nparms);
8590 if (in_decl)
8591 inform (DECL_SOURCE_LOCATION (in_decl),
8592 "provided for %qD", in_decl);
8595 return error_mark_node;
8597 /* We can't pass a pack expansion to a non-pack parameter of an alias
8598 template (DR 1430). */
8599 else if (in_decl
8600 && (DECL_ALIAS_TEMPLATE_P (in_decl)
8601 || concept_definition_p (in_decl))
8602 && variadic_args_p
8603 && nargs - variadic_args_p < nparms - variadic_p)
8605 if (complain & tf_error)
8607 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8609 tree arg = TREE_VEC_ELT (inner_args, i);
8610 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8612 if (PACK_EXPANSION_P (arg)
8613 && !template_parameter_pack_p (parm))
8615 if (DECL_ALIAS_TEMPLATE_P (in_decl))
8616 error_at (location_of (arg),
8617 "pack expansion argument for non-pack parameter "
8618 "%qD of alias template %qD", parm, in_decl);
8619 else
8620 error_at (location_of (arg),
8621 "pack expansion argument for non-pack parameter "
8622 "%qD of concept %qD", parm, in_decl);
8623 inform (DECL_SOURCE_LOCATION (parm), "declared here");
8624 goto found;
8627 gcc_unreachable ();
8628 found:;
8630 return error_mark_node;
8633 /* We need to evaluate the template arguments, even though this
8634 template-id may be nested within a "sizeof". */
8635 cp_evaluated ev;
8637 new_inner_args = make_tree_vec (nparms);
8638 new_args = add_outermost_template_args (args, new_inner_args);
8639 int pack_adjust = 0;
8640 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8642 tree arg;
8643 tree parm;
8645 /* Get the Ith template parameter. */
8646 parm = TREE_VEC_ELT (parms, parm_idx);
8648 if (parm == error_mark_node)
8650 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8651 continue;
8654 /* Calculate the next argument. */
8655 if (arg_idx < nargs)
8656 arg = TREE_VEC_ELT (inner_args, arg_idx);
8657 else
8658 arg = NULL_TREE;
8660 if (template_parameter_pack_p (TREE_VALUE (parm))
8661 && (arg || require_all_args || !(complain & tf_partial))
8662 && !(arg && ARGUMENT_PACK_P (arg)))
8664 /* Some arguments will be placed in the
8665 template parameter pack PARM. */
8666 arg = coerce_template_parameter_pack (parms, parm_idx, args,
8667 inner_args, arg_idx,
8668 new_args, &lost,
8669 in_decl, complain);
8671 if (arg == NULL_TREE)
8673 /* We don't know how many args we have yet, just use the
8674 unconverted (and still packed) ones for now. */
8675 new_inner_args = orig_inner_args;
8676 arg_idx = nargs;
8677 break;
8680 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8682 /* Store this argument. */
8683 if (arg == error_mark_node)
8685 lost++;
8686 /* We are done with all of the arguments. */
8687 arg_idx = nargs;
8688 break;
8690 else
8692 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8693 arg_idx += pack_adjust;
8694 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8696 ++fixed_packs;
8697 fixed_pack_adjust += pack_adjust;
8701 continue;
8703 else if (arg)
8705 if (PACK_EXPANSION_P (arg))
8707 /* "If every valid specialization of a variadic template
8708 requires an empty template parameter pack, the template is
8709 ill-formed, no diagnostic required." So check that the
8710 pattern works with this parameter. */
8711 tree pattern = PACK_EXPANSION_PATTERN (arg);
8712 tree conv = convert_template_argument (TREE_VALUE (parm),
8713 pattern, new_args,
8714 complain, parm_idx,
8715 in_decl);
8716 if (conv == error_mark_node)
8718 if (complain & tf_error)
8719 inform (input_location, "so any instantiation with a "
8720 "non-empty parameter pack would be ill-formed");
8721 ++lost;
8723 else if (TYPE_P (conv) && !TYPE_P (pattern))
8724 /* Recover from missing typename. */
8725 TREE_VEC_ELT (inner_args, arg_idx)
8726 = make_pack_expansion (conv, complain);
8728 /* We don't know how many args we have yet, just
8729 use the unconverted ones for now. */
8730 new_inner_args = inner_args;
8731 arg_idx = nargs;
8732 break;
8735 else if (require_all_args)
8737 /* There must be a default arg in this case. */
8738 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8739 complain, in_decl);
8740 /* The position of the first default template argument,
8741 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8742 Record that. */
8743 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8744 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8745 arg_idx - pack_adjust);
8747 else
8748 break;
8750 if (arg == error_mark_node)
8752 if (complain & tf_error)
8753 error ("template argument %d is invalid", arg_idx + 1);
8755 else if (!arg)
8757 /* This can occur if there was an error in the template
8758 parameter list itself (which we would already have
8759 reported) that we are trying to recover from, e.g., a class
8760 template with a parameter list such as
8761 template<typename..., typename> (cpp0x/variadic150.C). */
8762 ++lost;
8764 /* This can also happen with a fixed parameter pack (71834). */
8765 if (arg_idx >= nargs)
8766 ++missing;
8768 else
8769 arg = convert_template_argument (TREE_VALUE (parm),
8770 arg, new_args, complain,
8771 parm_idx, in_decl);
8773 if (arg == error_mark_node)
8774 lost++;
8776 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8779 if (missing || arg_idx < nargs - variadic_args_p)
8781 /* If we had fixed parameter packs, we didn't know how many arguments we
8782 actually needed earlier; now we do. */
8783 nparms += fixed_pack_adjust;
8784 variadic_p -= fixed_packs;
8785 goto bad_nargs;
8788 if (arg_idx < nargs)
8790 /* We had some pack expansion arguments that will only work if the packs
8791 are empty, but wait until instantiation time to complain.
8792 See variadic-ttp3.C. */
8794 /* Except that we can't provide empty packs to alias templates or
8795 concepts when there are no corresponding parameters. Basically,
8796 we can get here with this:
8798 template<typename T> concept C = true;
8800 template<typename... Args>
8801 requires C<Args...>
8802 void f();
8804 When parsing C<Args...>, we try to form a concept check of
8805 C<?, Args...>. Without the extra check for substituting an empty
8806 pack past the last parameter, we can accept the check as valid.
8808 FIXME: This may be valid for alias templates (but I doubt it).
8810 FIXME: The error could be better also. */
8811 if (in_decl && concept_definition_p (in_decl))
8813 if (complain & tf_error)
8814 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
8815 "too many arguments");
8816 return error_mark_node;
8819 int len = nparms + (nargs - arg_idx);
8820 tree args = make_tree_vec (len);
8821 int i = 0;
8822 for (; i < nparms; ++i)
8823 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8824 for (; i < len; ++i, ++arg_idx)
8825 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8826 arg_idx - pack_adjust);
8827 new_inner_args = args;
8830 if (lost)
8832 gcc_assert (!(complain & tf_error) || seen_error ());
8833 return error_mark_node;
8836 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8837 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8838 TREE_VEC_LENGTH (new_inner_args));
8840 return new_inner_args;
8843 /* Convert all template arguments to their appropriate types, and
8844 return a vector containing the innermost resulting template
8845 arguments. If any error occurs, return error_mark_node. Error and
8846 warning messages are not issued.
8848 Note that no function argument deduction is performed, and default
8849 arguments are used to fill in unspecified arguments. */
8850 tree
8851 coerce_template_parms (tree parms, tree args, tree in_decl)
8853 return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8856 /* Convert all template arguments to their appropriate type, and
8857 instantiate default arguments as needed. This returns a vector
8858 containing the innermost resulting template arguments, or
8859 error_mark_node if unsuccessful. */
8860 tree
8861 coerce_template_parms (tree parms, tree args, tree in_decl,
8862 tsubst_flags_t complain)
8864 return coerce_template_parms (parms, args, in_decl, complain, true, true);
8867 /* Like coerce_template_parms. If PARMS represents all template
8868 parameters levels, this function returns a vector of vectors
8869 representing all the resulting argument levels. Note that in this
8870 case, only the innermost arguments are coerced because the
8871 outermost ones are supposed to have been coerced already.
8873 Otherwise, if PARMS represents only (the innermost) vector of
8874 parameters, this function returns a vector containing just the
8875 innermost resulting arguments. */
8877 static tree
8878 coerce_innermost_template_parms (tree parms,
8879 tree args,
8880 tree in_decl,
8881 tsubst_flags_t complain,
8882 bool require_all_args,
8883 bool use_default_args)
8885 int parms_depth = TMPL_PARMS_DEPTH (parms);
8886 int args_depth = TMPL_ARGS_DEPTH (args);
8887 tree coerced_args;
8889 if (parms_depth > 1)
8891 coerced_args = make_tree_vec (parms_depth);
8892 tree level;
8893 int cur_depth;
8895 for (level = parms, cur_depth = parms_depth;
8896 parms_depth > 0 && level != NULL_TREE;
8897 level = TREE_CHAIN (level), --cur_depth)
8899 tree l;
8900 if (cur_depth == args_depth)
8901 l = coerce_template_parms (TREE_VALUE (level),
8902 args, in_decl, complain,
8903 require_all_args,
8904 use_default_args);
8905 else
8906 l = TMPL_ARGS_LEVEL (args, cur_depth);
8908 if (l == error_mark_node)
8909 return error_mark_node;
8911 SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8914 else
8915 coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8916 args, in_decl, complain,
8917 require_all_args,
8918 use_default_args);
8919 return coerced_args;
8922 /* Returns 1 if template args OT and NT are equivalent. */
8925 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8927 if (nt == ot)
8928 return 1;
8929 if (nt == NULL_TREE || ot == NULL_TREE)
8930 return false;
8931 if (nt == any_targ_node || ot == any_targ_node)
8932 return true;
8934 if (TREE_CODE (nt) == TREE_VEC)
8935 /* For member templates */
8936 return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8937 else if (PACK_EXPANSION_P (ot))
8938 return (PACK_EXPANSION_P (nt)
8939 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8940 PACK_EXPANSION_PATTERN (nt))
8941 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8942 PACK_EXPANSION_EXTRA_ARGS (nt)));
8943 else if (ARGUMENT_PACK_P (ot))
8945 int i, len;
8946 tree opack, npack;
8948 if (!ARGUMENT_PACK_P (nt))
8949 return 0;
8951 opack = ARGUMENT_PACK_ARGS (ot);
8952 npack = ARGUMENT_PACK_ARGS (nt);
8953 len = TREE_VEC_LENGTH (opack);
8954 if (TREE_VEC_LENGTH (npack) != len)
8955 return 0;
8956 for (i = 0; i < len; ++i)
8957 if (!template_args_equal (TREE_VEC_ELT (opack, i),
8958 TREE_VEC_ELT (npack, i)))
8959 return 0;
8960 return 1;
8962 else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8963 gcc_unreachable ();
8964 else if (TYPE_P (nt))
8966 if (!TYPE_P (ot))
8967 return false;
8968 /* Don't treat an alias template specialization with dependent
8969 arguments as equivalent to its underlying type when used as a
8970 template argument; we need them to be distinct so that we
8971 substitute into the specialization arguments at instantiation
8972 time. And aliases can't be equivalent without being ==, so
8973 we don't need to look any deeper.
8975 During partial ordering, however, we need to treat them normally so
8976 that we can order uses of the same alias with different
8977 cv-qualification (79960). */
8978 if (!partial_order
8979 && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8980 return false;
8981 else
8982 return same_type_p (ot, nt);
8984 else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8985 return 0;
8986 else
8988 /* Try to treat a template non-type argument that has been converted
8989 to the parameter type as equivalent to one that hasn't yet. */
8990 for (enum tree_code code1 = TREE_CODE (ot);
8991 CONVERT_EXPR_CODE_P (code1)
8992 || code1 == NON_LVALUE_EXPR;
8993 code1 = TREE_CODE (ot))
8994 ot = TREE_OPERAND (ot, 0);
8995 for (enum tree_code code2 = TREE_CODE (nt);
8996 CONVERT_EXPR_CODE_P (code2)
8997 || code2 == NON_LVALUE_EXPR;
8998 code2 = TREE_CODE (nt))
8999 nt = TREE_OPERAND (nt, 0);
9001 return cp_tree_equal (ot, nt);
9005 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9006 template arguments. Returns 0 otherwise, and updates OLDARG_PTR and
9007 NEWARG_PTR with the offending arguments if they are non-NULL. */
9010 comp_template_args (tree oldargs, tree newargs,
9011 tree *oldarg_ptr, tree *newarg_ptr,
9012 bool partial_order)
9014 int i;
9016 if (oldargs == newargs)
9017 return 1;
9019 if (!oldargs || !newargs)
9020 return 0;
9022 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9023 return 0;
9025 for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9027 tree nt = TREE_VEC_ELT (newargs, i);
9028 tree ot = TREE_VEC_ELT (oldargs, i);
9030 if (! template_args_equal (ot, nt, partial_order))
9032 if (oldarg_ptr != NULL)
9033 *oldarg_ptr = ot;
9034 if (newarg_ptr != NULL)
9035 *newarg_ptr = nt;
9036 return 0;
9039 return 1;
9042 inline bool
9043 comp_template_args_porder (tree oargs, tree nargs)
9045 return comp_template_args (oargs, nargs, NULL, NULL, true);
9048 /* Implement a freelist interface for objects of type T.
9050 Head is a separate object, rather than a regular member, so that we
9051 can define it as a GTY deletable pointer, which is highly
9052 desirable. A data member could be declared that way, but then the
9053 containing object would implicitly get GTY((user)), which would
9054 prevent us from instantiating freelists as global objects.
9055 Although this way we can create freelist global objects, they're
9056 such thin wrappers that instantiating temporaries at every use
9057 loses nothing and saves permanent storage for the freelist object.
9059 Member functions next, anew, poison and reinit have default
9060 implementations that work for most of the types we're interested
9061 in, but if they don't work for some type, they should be explicitly
9062 specialized. See the comments before them for requirements, and
9063 the example specializations for the tree_list_freelist. */
9064 template <typename T>
9065 class freelist
9067 /* Return the next object in a chain. We could just do type
9068 punning, but if we access the object with its underlying type, we
9069 avoid strict-aliasing trouble. This needs only work between
9070 poison and reinit. */
9071 static T *&next (T *obj) { return obj->next; }
9073 /* Return a newly allocated, uninitialized or minimally-initialized
9074 object of type T. Any initialization performed by anew should
9075 either remain across the life of the object and the execution of
9076 poison, or be redone by reinit. */
9077 static T *anew () { return ggc_alloc<T> (); }
9079 /* Optionally scribble all over the bits holding the object, so that
9080 they become (mostly?) uninitialized memory. This is called while
9081 preparing to make the object part of the free list. */
9082 static void poison (T *obj) {
9083 T *p ATTRIBUTE_UNUSED = obj;
9084 T **q ATTRIBUTE_UNUSED = &next (obj);
9086 #ifdef ENABLE_GC_CHECKING
9087 /* Poison the data, to indicate the data is garbage. */
9088 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9089 memset (p, 0xa5, sizeof (*p));
9090 #endif
9091 /* Let valgrind know the object is free. */
9092 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9094 /* Let valgrind know the next portion of the object is available,
9095 but uninitialized. */
9096 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9099 /* Bring an object that underwent at least one lifecycle after anew
9100 and before the most recent free and poison, back to a usable
9101 state, reinitializing whatever is needed for it to be
9102 functionally equivalent to an object just allocated and returned
9103 by anew. This may poison or clear the next field, used by
9104 freelist housekeeping after poison was called. */
9105 static void reinit (T *obj) {
9106 T **q ATTRIBUTE_UNUSED = &next (obj);
9108 #ifdef ENABLE_GC_CHECKING
9109 memset (q, 0xa5, sizeof (*q));
9110 #endif
9111 /* Let valgrind know the entire object is available, but
9112 uninitialized. */
9113 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9116 /* Reference a GTY-deletable pointer that points to the first object
9117 in the free list proper. */
9118 T *&head;
9119 public:
9120 /* Construct a freelist object chaining objects off of HEAD. */
9121 freelist (T *&head) : head(head) {}
9123 /* Add OBJ to the free object list. The former head becomes OBJ's
9124 successor. */
9125 void free (T *obj)
9127 poison (obj);
9128 next (obj) = head;
9129 head = obj;
9132 /* Take an object from the free list, if one is available, or
9133 allocate a new one. Objects taken from the free list should be
9134 regarded as filled with garbage, except for bits that are
9135 configured to be preserved across free and alloc. */
9136 T *alloc ()
9138 if (head)
9140 T *obj = head;
9141 head = next (head);
9142 reinit (obj);
9143 return obj;
9145 else
9146 return anew ();
9150 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9151 want to allocate a TREE_LIST using the usual interface, and ensure
9152 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9153 build_tree_list logic in reinit, so this could go out of sync. */
9154 template <>
9155 inline tree &
9156 freelist<tree_node>::next (tree obj)
9158 return TREE_CHAIN (obj);
9160 template <>
9161 inline tree
9162 freelist<tree_node>::anew ()
9164 return build_tree_list (NULL, NULL);
9166 template <>
9167 inline void
9168 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9170 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9171 tree p ATTRIBUTE_UNUSED = obj;
9172 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9173 tree *q ATTRIBUTE_UNUSED = &next (obj);
9175 #ifdef ENABLE_GC_CHECKING
9176 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9178 /* Poison the data, to indicate the data is garbage. */
9179 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9180 memset (p, 0xa5, size);
9181 #endif
9182 /* Let valgrind know the object is free. */
9183 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9184 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9185 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9186 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9188 #ifdef ENABLE_GC_CHECKING
9189 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9190 /* Keep TREE_CHAIN functional. */
9191 TREE_SET_CODE (obj, TREE_LIST);
9192 #else
9193 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9194 #endif
9196 template <>
9197 inline void
9198 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9200 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9202 #ifdef ENABLE_GC_CHECKING
9203 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9204 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9205 memset (obj, 0, sizeof (tree_list));
9206 #endif
9208 /* Let valgrind know the entire object is available, but
9209 uninitialized. */
9210 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9212 #ifdef ENABLE_GC_CHECKING
9213 TREE_SET_CODE (obj, TREE_LIST);
9214 #else
9215 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9216 #endif
9219 /* Point to the first object in the TREE_LIST freelist. */
9220 static GTY((deletable)) tree tree_list_freelist_head;
9221 /* Return the/an actual TREE_LIST freelist. */
9222 static inline freelist<tree_node>
9223 tree_list_freelist ()
9225 return tree_list_freelist_head;
9228 /* Point to the first object in the tinst_level freelist. */
9229 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9230 /* Return the/an actual tinst_level freelist. */
9231 static inline freelist<tinst_level>
9232 tinst_level_freelist ()
9234 return tinst_level_freelist_head;
9237 /* Point to the first object in the pending_template freelist. */
9238 static GTY((deletable)) pending_template *pending_template_freelist_head;
9239 /* Return the/an actual pending_template freelist. */
9240 static inline freelist<pending_template>
9241 pending_template_freelist ()
9243 return pending_template_freelist_head;
9246 /* Build the TREE_LIST object out of a split list, store it
9247 permanently, and return it. */
9248 tree
9249 tinst_level::to_list ()
9251 gcc_assert (split_list_p ());
9252 tree ret = tree_list_freelist ().alloc ();
9253 TREE_PURPOSE (ret) = tldcl;
9254 TREE_VALUE (ret) = targs;
9255 tldcl = ret;
9256 targs = NULL;
9257 gcc_assert (tree_list_p ());
9258 return ret;
9261 const unsigned short tinst_level::refcount_infinity;
9263 /* Increment OBJ's refcount unless it is already infinite. */
9264 static tinst_level *
9265 inc_refcount_use (tinst_level *obj)
9267 if (obj && obj->refcount != tinst_level::refcount_infinity)
9268 ++obj->refcount;
9269 return obj;
9272 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9273 void
9274 tinst_level::free (tinst_level *obj)
9276 if (obj->tree_list_p ())
9277 tree_list_freelist ().free (obj->get_node ());
9278 tinst_level_freelist ().free (obj);
9281 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9282 OBJ's DECL and OBJ, and start over with the tinst_level object that
9283 used to be referenced by OBJ's NEXT. */
9284 static void
9285 dec_refcount_use (tinst_level *obj)
9287 while (obj
9288 && obj->refcount != tinst_level::refcount_infinity
9289 && !--obj->refcount)
9291 tinst_level *next = obj->next;
9292 tinst_level::free (obj);
9293 obj = next;
9297 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9298 and of the former PTR. Omitting the second argument is equivalent
9299 to passing (T*)NULL; this is allowed because passing the
9300 zero-valued integral constant NULL confuses type deduction and/or
9301 overload resolution. */
9302 template <typename T>
9303 static void
9304 set_refcount_ptr (T *& ptr, T *obj = NULL)
9306 T *save = ptr;
9307 ptr = inc_refcount_use (obj);
9308 dec_refcount_use (save);
9311 static void
9312 add_pending_template (tree d)
9314 tree ti = (TYPE_P (d)
9315 ? CLASSTYPE_TEMPLATE_INFO (d)
9316 : DECL_TEMPLATE_INFO (d));
9317 struct pending_template *pt;
9318 int level;
9320 if (TI_PENDING_TEMPLATE_FLAG (ti))
9321 return;
9323 /* We are called both from instantiate_decl, where we've already had a
9324 tinst_level pushed, and instantiate_template, where we haven't.
9325 Compensate. */
9326 gcc_assert (TREE_CODE (d) != TREE_LIST);
9327 level = !current_tinst_level
9328 || current_tinst_level->maybe_get_node () != d;
9330 if (level)
9331 push_tinst_level (d);
9333 pt = pending_template_freelist ().alloc ();
9334 pt->next = NULL;
9335 pt->tinst = NULL;
9336 set_refcount_ptr (pt->tinst, current_tinst_level);
9337 if (last_pending_template)
9338 last_pending_template->next = pt;
9339 else
9340 pending_templates = pt;
9342 last_pending_template = pt;
9344 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9346 if (level)
9347 pop_tinst_level ();
9351 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9352 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9353 documentation for TEMPLATE_ID_EXPR. */
9355 tree
9356 lookup_template_function (tree fns, tree arglist)
9358 if (fns == error_mark_node || arglist == error_mark_node)
9359 return error_mark_node;
9361 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9363 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9365 error ("%q#D is not a function template", fns);
9366 return error_mark_node;
9369 if (BASELINK_P (fns))
9371 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9372 unknown_type_node,
9373 BASELINK_FUNCTIONS (fns),
9374 arglist);
9375 return fns;
9378 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9381 /* Within the scope of a template class S<T>, the name S gets bound
9382 (in build_self_reference) to a TYPE_DECL for the class, not a
9383 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9384 or one of its enclosing classes, and that type is a template,
9385 return the associated TEMPLATE_DECL. Otherwise, the original
9386 DECL is returned.
9388 Also handle the case when DECL is a TREE_LIST of ambiguous
9389 injected-class-names from different bases. */
9391 tree
9392 maybe_get_template_decl_from_type_decl (tree decl)
9394 if (decl == NULL_TREE)
9395 return decl;
9397 /* DR 176: A lookup that finds an injected-class-name (10.2
9398 [class.member.lookup]) can result in an ambiguity in certain cases
9399 (for example, if it is found in more than one base class). If all of
9400 the injected-class-names that are found refer to specializations of
9401 the same class template, and if the name is followed by a
9402 template-argument-list, the reference refers to the class template
9403 itself and not a specialization thereof, and is not ambiguous. */
9404 if (TREE_CODE (decl) == TREE_LIST)
9406 tree t, tmpl = NULL_TREE;
9407 for (t = decl; t; t = TREE_CHAIN (t))
9409 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9410 if (!tmpl)
9411 tmpl = elt;
9412 else if (tmpl != elt)
9413 break;
9415 if (tmpl && t == NULL_TREE)
9416 return tmpl;
9417 else
9418 return decl;
9421 return (decl != NULL_TREE
9422 && DECL_SELF_REFERENCE_P (decl)
9423 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9424 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9427 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9428 parameters, find the desired type.
9430 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9432 IN_DECL, if non-NULL, is the template declaration we are trying to
9433 instantiate.
9435 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9436 the class we are looking up.
9438 Issue error and warning messages under control of COMPLAIN.
9440 If the template class is really a local class in a template
9441 function, then the FUNCTION_CONTEXT is the function in which it is
9442 being instantiated.
9444 ??? Note that this function is currently called *twice* for each
9445 template-id: the first time from the parser, while creating the
9446 incomplete type (finish_template_type), and the second type during the
9447 real instantiation (instantiate_template_class). This is surely something
9448 that we want to avoid. It also causes some problems with argument
9449 coercion (see convert_nontype_argument for more information on this). */
9451 static tree
9452 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9453 int entering_scope, tsubst_flags_t complain)
9455 tree templ = NULL_TREE, parmlist;
9456 tree t;
9457 spec_entry **slot;
9458 spec_entry *entry;
9459 spec_entry elt;
9460 hashval_t hash;
9462 if (identifier_p (d1))
9464 tree value = innermost_non_namespace_value (d1);
9465 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9466 templ = value;
9467 else
9469 if (context)
9470 push_decl_namespace (context);
9471 templ = lookup_name (d1);
9472 templ = maybe_get_template_decl_from_type_decl (templ);
9473 if (context)
9474 pop_decl_namespace ();
9476 if (templ)
9477 context = DECL_CONTEXT (templ);
9479 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9481 tree type = TREE_TYPE (d1);
9483 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9484 an implicit typename for the second A. Deal with it. */
9485 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9486 type = TREE_TYPE (type);
9488 if (CLASSTYPE_TEMPLATE_INFO (type))
9490 templ = CLASSTYPE_TI_TEMPLATE (type);
9491 d1 = DECL_NAME (templ);
9494 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9495 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9497 templ = TYPE_TI_TEMPLATE (d1);
9498 d1 = DECL_NAME (templ);
9500 else if (DECL_TYPE_TEMPLATE_P (d1))
9502 templ = d1;
9503 d1 = DECL_NAME (templ);
9504 context = DECL_CONTEXT (templ);
9506 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9508 templ = d1;
9509 d1 = DECL_NAME (templ);
9512 /* Issue an error message if we didn't find a template. */
9513 if (! templ)
9515 if (complain & tf_error)
9516 error ("%qT is not a template", d1);
9517 return error_mark_node;
9520 if (TREE_CODE (templ) != TEMPLATE_DECL
9521 /* Make sure it's a user visible template, if it was named by
9522 the user. */
9523 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9524 && !PRIMARY_TEMPLATE_P (templ)))
9526 if (complain & tf_error)
9528 error ("non-template type %qT used as a template", d1);
9529 if (in_decl)
9530 error ("for template declaration %q+D", in_decl);
9532 return error_mark_node;
9535 complain &= ~tf_user;
9537 /* An alias that just changes the name of a template is equivalent to the
9538 other template, so if any of the arguments are pack expansions, strip
9539 the alias to avoid problems with a pack expansion passed to a non-pack
9540 alias template parameter (DR 1430). */
9541 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9542 templ = get_underlying_template (templ);
9544 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9546 tree parm;
9547 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9548 if (arglist2 == error_mark_node
9549 || (!uses_template_parms (arglist2)
9550 && check_instantiated_args (templ, arglist2, complain)))
9551 return error_mark_node;
9553 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9554 return parm;
9556 else
9558 tree template_type = TREE_TYPE (templ);
9559 tree gen_tmpl;
9560 tree type_decl;
9561 tree found = NULL_TREE;
9562 int arg_depth;
9563 int parm_depth;
9564 int is_dependent_type;
9565 int use_partial_inst_tmpl = false;
9567 if (template_type == error_mark_node)
9568 /* An error occurred while building the template TEMPL, and a
9569 diagnostic has most certainly been emitted for that
9570 already. Let's propagate that error. */
9571 return error_mark_node;
9573 gen_tmpl = most_general_template (templ);
9574 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9575 parm_depth = TMPL_PARMS_DEPTH (parmlist);
9576 arg_depth = TMPL_ARGS_DEPTH (arglist);
9578 if (arg_depth == 1 && parm_depth > 1)
9580 /* We've been given an incomplete set of template arguments.
9581 For example, given:
9583 template <class T> struct S1 {
9584 template <class U> struct S2 {};
9585 template <class U> struct S2<U*> {};
9588 we will be called with an ARGLIST of `U*', but the
9589 TEMPLATE will be `template <class T> template
9590 <class U> struct S1<T>::S2'. We must fill in the missing
9591 arguments. */
9592 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9593 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9594 arg_depth = TMPL_ARGS_DEPTH (arglist);
9597 /* Now we should have enough arguments. */
9598 gcc_assert (parm_depth == arg_depth);
9600 /* From here on, we're only interested in the most general
9601 template. */
9603 /* Calculate the BOUND_ARGS. These will be the args that are
9604 actually tsubst'd into the definition to create the
9605 instantiation. */
9606 arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9607 complain,
9608 /*require_all_args=*/true,
9609 /*use_default_args=*/true);
9611 if (arglist == error_mark_node)
9612 /* We were unable to bind the arguments. */
9613 return error_mark_node;
9615 /* In the scope of a template class, explicit references to the
9616 template class refer to the type of the template, not any
9617 instantiation of it. For example, in:
9619 template <class T> class C { void f(C<T>); }
9621 the `C<T>' is just the same as `C'. Outside of the
9622 class, however, such a reference is an instantiation. */
9623 if (entering_scope
9624 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9625 || currently_open_class (template_type))
9627 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9629 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9630 return template_type;
9633 /* If we already have this specialization, return it. */
9634 elt.tmpl = gen_tmpl;
9635 elt.args = arglist;
9636 elt.spec = NULL_TREE;
9637 hash = spec_hasher::hash (&elt);
9638 entry = type_specializations->find_with_hash (&elt, hash);
9640 if (entry)
9641 return entry->spec;
9643 /* If the the template's constraints are not satisfied,
9644 then we cannot form a valid type.
9646 Note that the check is deferred until after the hash
9647 lookup. This prevents redundant checks on previously
9648 instantiated specializations. */
9649 if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9651 if (complain & tf_error)
9653 auto_diagnostic_group d;
9654 error ("template constraint failure for %qD", gen_tmpl);
9655 diagnose_constraints (input_location, gen_tmpl, arglist);
9657 return error_mark_node;
9660 is_dependent_type = uses_template_parms (arglist);
9662 /* If the deduced arguments are invalid, then the binding
9663 failed. */
9664 if (!is_dependent_type
9665 && check_instantiated_args (gen_tmpl,
9666 INNERMOST_TEMPLATE_ARGS (arglist),
9667 complain))
9668 return error_mark_node;
9670 if (!is_dependent_type
9671 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9672 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9673 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9675 found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9676 DECL_NAME (gen_tmpl),
9677 /*tag_scope=*/ts_global);
9678 return found;
9681 context = DECL_CONTEXT (gen_tmpl);
9682 if (context && TYPE_P (context))
9684 context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9685 context = complete_type (context);
9687 else
9688 context = tsubst (context, arglist, complain, in_decl);
9690 if (context == error_mark_node)
9691 return error_mark_node;
9693 if (!context)
9694 context = global_namespace;
9696 /* Create the type. */
9697 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9699 /* The user referred to a specialization of an alias
9700 template represented by GEN_TMPL.
9702 [temp.alias]/2 says:
9704 When a template-id refers to the specialization of an
9705 alias template, it is equivalent to the associated
9706 type obtained by substitution of its
9707 template-arguments for the template-parameters in the
9708 type-id of the alias template. */
9710 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9711 /* Note that the call above (by indirectly calling
9712 register_specialization in tsubst_decl) registers the
9713 TYPE_DECL representing the specialization of the alias
9714 template. So next time someone substitutes ARGLIST for
9715 the template parms into the alias template (GEN_TMPL),
9716 she'll get that TYPE_DECL back. */
9718 if (t == error_mark_node)
9719 return t;
9721 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9723 if (!is_dependent_type)
9725 set_current_access_from_decl (TYPE_NAME (template_type));
9726 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9727 tsubst (ENUM_UNDERLYING_TYPE (template_type),
9728 arglist, complain, in_decl),
9729 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9730 arglist, complain, in_decl),
9731 SCOPED_ENUM_P (template_type), NULL);
9733 if (t == error_mark_node)
9734 return t;
9736 else
9738 /* We don't want to call start_enum for this type, since
9739 the values for the enumeration constants may involve
9740 template parameters. And, no one should be interested
9741 in the enumeration constants for such a type. */
9742 t = cxx_make_type (ENUMERAL_TYPE);
9743 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9745 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9746 ENUM_FIXED_UNDERLYING_TYPE_P (t)
9747 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9749 else if (CLASS_TYPE_P (template_type))
9751 /* Lambda closures are regenerated in tsubst_lambda_expr, not
9752 instantiated here. */
9753 gcc_assert (!LAMBDA_TYPE_P (template_type));
9755 t = make_class_type (TREE_CODE (template_type));
9756 CLASSTYPE_DECLARED_CLASS (t)
9757 = CLASSTYPE_DECLARED_CLASS (template_type);
9758 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9760 /* A local class. Make sure the decl gets registered properly. */
9761 if (context == current_function_decl)
9762 if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9763 == error_mark_node)
9764 return error_mark_node;
9766 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9767 /* This instantiation is another name for the primary
9768 template type. Set the TYPE_CANONICAL field
9769 appropriately. */
9770 TYPE_CANONICAL (t) = template_type;
9771 else if (any_template_arguments_need_structural_equality_p (arglist))
9772 /* Some of the template arguments require structural
9773 equality testing, so this template class requires
9774 structural equality testing. */
9775 SET_TYPE_STRUCTURAL_EQUALITY (t);
9777 else
9778 gcc_unreachable ();
9780 /* If we called start_enum or pushtag above, this information
9781 will already be set up. */
9782 if (!TYPE_NAME (t))
9784 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9786 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9787 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9788 DECL_SOURCE_LOCATION (type_decl)
9789 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9791 else
9792 type_decl = TYPE_NAME (t);
9794 if (CLASS_TYPE_P (template_type))
9796 TREE_PRIVATE (type_decl)
9797 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9798 TREE_PROTECTED (type_decl)
9799 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9800 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9802 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9803 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9807 if (OVERLOAD_TYPE_P (t)
9808 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9810 static const char *tags[] = {"abi_tag", "may_alias"};
9812 for (unsigned ix = 0; ix != 2; ix++)
9814 tree attributes
9815 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9817 if (attributes)
9818 TYPE_ATTRIBUTES (t)
9819 = tree_cons (TREE_PURPOSE (attributes),
9820 TREE_VALUE (attributes),
9821 TYPE_ATTRIBUTES (t));
9825 /* Let's consider the explicit specialization of a member
9826 of a class template specialization that is implicitly instantiated,
9827 e.g.:
9828 template<class T>
9829 struct S
9831 template<class U> struct M {}; //#0
9834 template<>
9835 template<>
9836 struct S<int>::M<char> //#1
9838 int i;
9840 [temp.expl.spec]/4 says this is valid.
9842 In this case, when we write:
9843 S<int>::M<char> m;
9845 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9846 the one of #0.
9848 When we encounter #1, we want to store the partial instantiation
9849 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9851 For all cases other than this "explicit specialization of member of a
9852 class template", we just want to store the most general template into
9853 the CLASSTYPE_TI_TEMPLATE of M.
9855 This case of "explicit specialization of member of a class template"
9856 only happens when:
9857 1/ the enclosing class is an instantiation of, and therefore not
9858 the same as, the context of the most general template, and
9859 2/ we aren't looking at the partial instantiation itself, i.e.
9860 the innermost arguments are not the same as the innermost parms of
9861 the most general template.
9863 So it's only when 1/ and 2/ happens that we want to use the partial
9864 instantiation of the member template in lieu of its most general
9865 template. */
9867 if (PRIMARY_TEMPLATE_P (gen_tmpl)
9868 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9869 /* the enclosing class must be an instantiation... */
9870 && CLASS_TYPE_P (context)
9871 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9873 TREE_VEC_LENGTH (arglist)--;
9874 ++processing_template_decl;
9875 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9876 tree partial_inst_args =
9877 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9878 arglist, complain, NULL_TREE);
9879 --processing_template_decl;
9880 TREE_VEC_LENGTH (arglist)++;
9881 if (partial_inst_args == error_mark_node)
9882 return error_mark_node;
9883 use_partial_inst_tmpl =
9884 /*...and we must not be looking at the partial instantiation
9885 itself. */
9886 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9887 partial_inst_args);
9890 if (!use_partial_inst_tmpl)
9891 /* This case is easy; there are no member templates involved. */
9892 found = gen_tmpl;
9893 else
9895 /* This is a full instantiation of a member template. Find
9896 the partial instantiation of which this is an instance. */
9898 /* Temporarily reduce by one the number of levels in the ARGLIST
9899 so as to avoid comparing the last set of arguments. */
9900 TREE_VEC_LENGTH (arglist)--;
9901 found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9902 TREE_VEC_LENGTH (arglist)++;
9903 /* FOUND is either a proper class type, or an alias
9904 template specialization. In the later case, it's a
9905 TYPE_DECL, resulting from the substituting of arguments
9906 for parameters in the TYPE_DECL of the alias template
9907 done earlier. So be careful while getting the template
9908 of FOUND. */
9909 found = (TREE_CODE (found) == TEMPLATE_DECL
9910 ? found
9911 : (TREE_CODE (found) == TYPE_DECL
9912 ? DECL_TI_TEMPLATE (found)
9913 : CLASSTYPE_TI_TEMPLATE (found)));
9915 if (DECL_CLASS_TEMPLATE_P (found)
9916 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
9918 /* If this partial instantiation is specialized, we want to
9919 use it for hash table lookup. */
9920 elt.tmpl = found;
9921 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
9922 hash = spec_hasher::hash (&elt);
9926 // Build template info for the new specialization.
9927 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9929 elt.spec = t;
9930 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9931 gcc_checking_assert (*slot == NULL);
9932 entry = ggc_alloc<spec_entry> ();
9933 *entry = elt;
9934 *slot = entry;
9936 /* Note this use of the partial instantiation so we can check it
9937 later in maybe_process_partial_specialization. */
9938 DECL_TEMPLATE_INSTANTIATIONS (found)
9939 = tree_cons (arglist, t,
9940 DECL_TEMPLATE_INSTANTIATIONS (found));
9942 if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9943 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9944 /* Now that the type has been registered on the instantiations
9945 list, we set up the enumerators. Because the enumeration
9946 constants may involve the enumeration type itself, we make
9947 sure to register the type first, and then create the
9948 constants. That way, doing tsubst_expr for the enumeration
9949 constants won't result in recursive calls here; we'll find
9950 the instantiation and exit above. */
9951 tsubst_enum (template_type, t, arglist);
9953 if (CLASS_TYPE_P (template_type) && is_dependent_type)
9954 /* If the type makes use of template parameters, the
9955 code that generates debugging information will crash. */
9956 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9958 /* Possibly limit visibility based on template args. */
9959 TREE_PUBLIC (type_decl) = 1;
9960 determine_visibility (type_decl);
9962 inherit_targ_abi_tags (t);
9964 return t;
9968 /* Wrapper for lookup_template_class_1. */
9970 tree
9971 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9972 int entering_scope, tsubst_flags_t complain)
9974 tree ret;
9975 timevar_push (TV_TEMPLATE_INST);
9976 ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9977 entering_scope, complain);
9978 timevar_pop (TV_TEMPLATE_INST);
9979 return ret;
9982 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
9984 tree
9985 lookup_template_variable (tree templ, tree arglist)
9987 if (flag_concepts && variable_concept_p (templ))
9988 return build_concept_check (templ, arglist, tf_none);
9990 /* The type of the expression is NULL_TREE since the template-id could refer
9991 to an explicit or partial specialization. */
9992 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
9995 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9997 tree
9998 finish_template_variable (tree var, tsubst_flags_t complain)
10000 tree templ = TREE_OPERAND (var, 0);
10001 tree arglist = TREE_OPERAND (var, 1);
10003 tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
10004 arglist = add_outermost_template_args (tmpl_args, arglist);
10006 templ = most_general_template (templ);
10007 tree parms = DECL_TEMPLATE_PARMS (templ);
10008 arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10009 /*req_all*/true,
10010 /*use_default*/true);
10012 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10014 if (complain & tf_error)
10016 auto_diagnostic_group d;
10017 error ("use of invalid variable template %qE", var);
10018 diagnose_constraints (location_of (var), templ, arglist);
10020 return error_mark_node;
10023 return instantiate_template (templ, arglist, complain);
10026 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10027 TARGS template args, and instantiate it if it's not dependent. */
10029 tree
10030 lookup_and_finish_template_variable (tree templ, tree targs,
10031 tsubst_flags_t complain)
10033 templ = lookup_template_variable (templ, targs);
10034 if (!any_dependent_template_arguments_p (targs))
10036 templ = finish_template_variable (templ, complain);
10037 mark_used (templ);
10040 return convert_from_reference (templ);
10044 struct pair_fn_data
10046 tree_fn_t fn;
10047 tree_fn_t any_fn;
10048 void *data;
10049 /* True when we should also visit template parameters that occur in
10050 non-deduced contexts. */
10051 bool include_nondeduced_p;
10052 hash_set<tree> *visited;
10055 /* Called from for_each_template_parm via walk_tree. */
10057 static tree
10058 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10060 tree t = *tp;
10061 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10062 tree_fn_t fn = pfd->fn;
10063 void *data = pfd->data;
10064 tree result = NULL_TREE;
10066 #define WALK_SUBTREE(NODE) \
10067 do \
10069 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10070 pfd->include_nondeduced_p, \
10071 pfd->any_fn); \
10072 if (result) goto out; \
10074 while (0)
10076 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10077 return t;
10079 if (TYPE_P (t)
10080 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10081 WALK_SUBTREE (TYPE_CONTEXT (t));
10083 switch (TREE_CODE (t))
10085 case RECORD_TYPE:
10086 if (TYPE_PTRMEMFUNC_P (t))
10087 break;
10088 /* Fall through. */
10090 case UNION_TYPE:
10091 case ENUMERAL_TYPE:
10092 if (!TYPE_TEMPLATE_INFO (t))
10093 *walk_subtrees = 0;
10094 else
10095 WALK_SUBTREE (TYPE_TI_ARGS (t));
10096 break;
10098 case INTEGER_TYPE:
10099 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10100 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10101 break;
10103 case METHOD_TYPE:
10104 /* Since we're not going to walk subtrees, we have to do this
10105 explicitly here. */
10106 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10107 /* Fall through. */
10109 case FUNCTION_TYPE:
10110 /* Check the return type. */
10111 WALK_SUBTREE (TREE_TYPE (t));
10113 /* Check the parameter types. Since default arguments are not
10114 instantiated until they are needed, the TYPE_ARG_TYPES may
10115 contain expressions that involve template parameters. But,
10116 no-one should be looking at them yet. And, once they're
10117 instantiated, they don't contain template parameters, so
10118 there's no point in looking at them then, either. */
10120 tree parm;
10122 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10123 WALK_SUBTREE (TREE_VALUE (parm));
10125 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10126 want walk_tree walking into them itself. */
10127 *walk_subtrees = 0;
10130 if (flag_noexcept_type)
10132 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10133 if (spec)
10134 WALK_SUBTREE (TREE_PURPOSE (spec));
10136 break;
10138 case TYPEOF_TYPE:
10139 case DECLTYPE_TYPE:
10140 case UNDERLYING_TYPE:
10141 if (pfd->include_nondeduced_p
10142 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10143 pfd->visited,
10144 pfd->include_nondeduced_p,
10145 pfd->any_fn))
10146 return error_mark_node;
10147 *walk_subtrees = false;
10148 break;
10150 case FUNCTION_DECL:
10151 case VAR_DECL:
10152 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10153 WALK_SUBTREE (DECL_TI_ARGS (t));
10154 /* Fall through. */
10156 case PARM_DECL:
10157 case CONST_DECL:
10158 if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10159 WALK_SUBTREE (DECL_INITIAL (t));
10160 if (DECL_CONTEXT (t)
10161 && pfd->include_nondeduced_p)
10162 WALK_SUBTREE (DECL_CONTEXT (t));
10163 break;
10165 case BOUND_TEMPLATE_TEMPLATE_PARM:
10166 /* Record template parameters such as `T' inside `TT<T>'. */
10167 WALK_SUBTREE (TYPE_TI_ARGS (t));
10168 /* Fall through. */
10170 case TEMPLATE_TEMPLATE_PARM:
10171 case TEMPLATE_TYPE_PARM:
10172 case TEMPLATE_PARM_INDEX:
10173 if (fn && (*fn)(t, data))
10174 return t;
10175 else if (!fn)
10176 return t;
10177 break;
10179 case TEMPLATE_DECL:
10180 /* A template template parameter is encountered. */
10181 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10182 WALK_SUBTREE (TREE_TYPE (t));
10184 /* Already substituted template template parameter */
10185 *walk_subtrees = 0;
10186 break;
10188 case TYPENAME_TYPE:
10189 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10190 partial instantiation. */
10191 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10192 break;
10194 case CONSTRUCTOR:
10195 if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10196 && pfd->include_nondeduced_p)
10197 WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10198 break;
10200 case INDIRECT_REF:
10201 case COMPONENT_REF:
10202 /* If there's no type, then this thing must be some expression
10203 involving template parameters. */
10204 if (!fn && !TREE_TYPE (t))
10205 return error_mark_node;
10206 break;
10208 case MODOP_EXPR:
10209 case CAST_EXPR:
10210 case IMPLICIT_CONV_EXPR:
10211 case REINTERPRET_CAST_EXPR:
10212 case CONST_CAST_EXPR:
10213 case STATIC_CAST_EXPR:
10214 case DYNAMIC_CAST_EXPR:
10215 case ARROW_EXPR:
10216 case DOTSTAR_EXPR:
10217 case TYPEID_EXPR:
10218 case PSEUDO_DTOR_EXPR:
10219 if (!fn)
10220 return error_mark_node;
10221 break;
10223 case SCOPE_REF:
10224 if (pfd->include_nondeduced_p)
10225 WALK_SUBTREE (TREE_OPERAND (t, 0));
10226 break;
10228 case REQUIRES_EXPR:
10230 if (!fn)
10231 return error_mark_node;
10233 /* Recursively walk the type of each constraint variable. */
10234 tree p = TREE_OPERAND (t, 0);
10235 while (p)
10237 WALK_SUBTREE (TREE_TYPE (p));
10238 p = TREE_CHAIN (p);
10241 break;
10243 default:
10244 break;
10247 #undef WALK_SUBTREE
10249 /* We didn't find any template parameters we liked. */
10250 out:
10251 return result;
10254 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10255 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10256 call FN with the parameter and the DATA.
10257 If FN returns nonzero, the iteration is terminated, and
10258 for_each_template_parm returns 1. Otherwise, the iteration
10259 continues. If FN never returns a nonzero value, the value
10260 returned by for_each_template_parm is 0. If FN is NULL, it is
10261 considered to be the function which always returns 1.
10263 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10264 parameters that occur in non-deduced contexts. When false, only
10265 visits those template parameters that can be deduced. */
10267 static tree
10268 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10269 hash_set<tree> *visited,
10270 bool include_nondeduced_p,
10271 tree_fn_t any_fn)
10273 struct pair_fn_data pfd;
10274 tree result;
10276 /* Set up. */
10277 pfd.fn = fn;
10278 pfd.any_fn = any_fn;
10279 pfd.data = data;
10280 pfd.include_nondeduced_p = include_nondeduced_p;
10282 /* Walk the tree. (Conceptually, we would like to walk without
10283 duplicates, but for_each_template_parm_r recursively calls
10284 for_each_template_parm, so we would need to reorganize a fair
10285 bit to use walk_tree_without_duplicates, so we keep our own
10286 visited list.) */
10287 if (visited)
10288 pfd.visited = visited;
10289 else
10290 pfd.visited = new hash_set<tree>;
10291 result = cp_walk_tree (&t,
10292 for_each_template_parm_r,
10293 &pfd,
10294 pfd.visited);
10296 /* Clean up. */
10297 if (!visited)
10299 delete pfd.visited;
10300 pfd.visited = 0;
10303 return result;
10306 struct find_template_parameter_info
10308 explicit find_template_parameter_info (int d)
10309 : max_depth (d)
10312 hash_set<tree> visited;
10313 hash_set<tree> parms;
10314 int max_depth;
10317 /* Appends the declaration of T to the list in DATA. */
10319 static int
10320 keep_template_parm (tree t, void* data)
10322 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10324 /* Template parameters declared within the expression are not part of
10325 the parameter mapping. For example, in this concept:
10327 template<typename T>
10328 concept C = requires { <expr> } -> same_as<int>;
10330 the return specifier same_as<int> declares a new decltype parameter
10331 that must not be part of the parameter mapping. The same is true
10332 for generic lambda parameters, lambda template parameters, etc. */
10333 int level;
10334 int index;
10335 template_parm_level_and_index (t, &level, &index);
10336 if (level > ftpi->max_depth)
10337 return 0;
10339 /* Arguments like const T yield parameters like const T. This means that
10340 a template-id like X<T, const T> would yield two distinct parameters:
10341 T and const T. Adjust types to their unqualified versions. */
10342 if (TYPE_P (t))
10343 t = TYPE_MAIN_VARIANT (t);
10344 ftpi->parms.add (t);
10346 return 0;
10349 /* Ensure that we recursively examine certain terms that are not normally
10350 visited in for_each_template_parm_r. */
10352 static int
10353 any_template_parm_r (tree t, void *data)
10355 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10357 #define WALK_SUBTREE(NODE) \
10358 do \
10360 for_each_template_parm (NODE, keep_template_parm, data, \
10361 &ftpi->visited, true, \
10362 any_template_parm_r); \
10364 while (0)
10366 switch (TREE_CODE (t))
10368 case RECORD_TYPE:
10369 case UNION_TYPE:
10370 case ENUMERAL_TYPE:
10371 /* Search for template parameters in type aliases. */
10372 if (alias_template_specialization_p (t))
10374 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
10375 WALK_SUBTREE (TI_ARGS (tinfo));
10377 break;
10379 case TEMPLATE_TYPE_PARM:
10380 /* Type constraints of a placeholder type may contain parameters. */
10381 if (is_auto (t))
10382 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10383 WALK_SUBTREE (constr);
10384 break;
10386 case TEMPLATE_ID_EXPR:
10387 /* Search through references to variable templates. */
10388 WALK_SUBTREE (TREE_OPERAND (t, 0));
10389 WALK_SUBTREE (TREE_OPERAND (t, 1));
10390 break;
10392 case CONSTRUCTOR:
10393 if (TREE_TYPE (t))
10394 WALK_SUBTREE (TREE_TYPE (t));
10395 break;
10396 default:
10397 break;
10400 /* Keep walking. */
10401 return 0;
10404 /* Returns a list of unique template parameters found within T. */
10406 tree
10407 find_template_parameters (tree t, int depth)
10409 find_template_parameter_info ftpi (depth);
10410 for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10411 /*include_nondeduced*/true, any_template_parm_r);
10412 tree list = NULL_TREE;
10413 for (hash_set<tree>::iterator iter = ftpi.parms.begin();
10414 iter != ftpi.parms.end(); ++iter)
10415 list = tree_cons (NULL_TREE, *iter, list);
10416 return list;
10419 /* Returns true if T depends on any template parameter. */
10422 uses_template_parms (tree t)
10424 if (t == NULL_TREE)
10425 return false;
10427 bool dependent_p;
10428 int saved_processing_template_decl;
10430 saved_processing_template_decl = processing_template_decl;
10431 if (!saved_processing_template_decl)
10432 processing_template_decl = 1;
10433 if (TYPE_P (t))
10434 dependent_p = dependent_type_p (t);
10435 else if (TREE_CODE (t) == TREE_VEC)
10436 dependent_p = any_dependent_template_arguments_p (t);
10437 else if (TREE_CODE (t) == TREE_LIST)
10438 dependent_p = (uses_template_parms (TREE_VALUE (t))
10439 || uses_template_parms (TREE_CHAIN (t)));
10440 else if (TREE_CODE (t) == TYPE_DECL)
10441 dependent_p = dependent_type_p (TREE_TYPE (t));
10442 else if (DECL_P (t)
10443 || EXPR_P (t)
10444 || TREE_CODE (t) == TEMPLATE_PARM_INDEX
10445 || TREE_CODE (t) == OVERLOAD
10446 || BASELINK_P (t)
10447 || identifier_p (t)
10448 || TREE_CODE (t) == TRAIT_EXPR
10449 || TREE_CODE (t) == CONSTRUCTOR
10450 || CONSTANT_CLASS_P (t))
10451 dependent_p = (type_dependent_expression_p (t)
10452 || value_dependent_expression_p (t));
10453 else
10455 gcc_assert (t == error_mark_node);
10456 dependent_p = false;
10459 processing_template_decl = saved_processing_template_decl;
10461 return dependent_p;
10464 /* Returns true iff current_function_decl is an incompletely instantiated
10465 template. Useful instead of processing_template_decl because the latter
10466 is set to 0 during instantiate_non_dependent_expr. */
10468 bool
10469 in_template_function (void)
10471 tree fn = current_function_decl;
10472 bool ret;
10473 ++processing_template_decl;
10474 ret = (fn && DECL_LANG_SPECIFIC (fn)
10475 && DECL_TEMPLATE_INFO (fn)
10476 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10477 --processing_template_decl;
10478 return ret;
10481 /* Returns true if T depends on any template parameter with level LEVEL. */
10483 bool
10484 uses_template_parms_level (tree t, int level)
10486 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10487 /*include_nondeduced_p=*/true);
10490 /* Returns true if the signature of DECL depends on any template parameter from
10491 its enclosing class. */
10493 bool
10494 uses_outer_template_parms (tree decl)
10496 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10497 if (depth == 0)
10498 return false;
10499 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10500 &depth, NULL, /*include_nondeduced_p=*/true))
10501 return true;
10502 if (PRIMARY_TEMPLATE_P (decl)
10503 && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10504 (DECL_TEMPLATE_PARMS (decl)),
10505 template_parm_outer_level,
10506 &depth, NULL, /*include_nondeduced_p=*/true))
10507 return true;
10508 tree ci = get_constraints (decl);
10509 if (ci)
10510 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10511 if (ci && for_each_template_parm (ci, template_parm_outer_level,
10512 &depth, NULL, /*nondeduced*/true))
10513 return true;
10514 return false;
10517 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10518 ill-formed translation unit, i.e. a variable or function that isn't
10519 usable in a constant expression. */
10521 static inline bool
10522 neglectable_inst_p (tree d)
10524 return (d && DECL_P (d)
10525 && !undeduced_auto_decl (d)
10526 && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10527 : decl_maybe_constant_var_p (d)));
10530 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10531 neglectable and instantiated from within an erroneous instantiation. */
10533 static bool
10534 limit_bad_template_recursion (tree decl)
10536 struct tinst_level *lev = current_tinst_level;
10537 int errs = errorcount + sorrycount;
10538 if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10539 return false;
10541 for (; lev; lev = lev->next)
10542 if (neglectable_inst_p (lev->maybe_get_node ()))
10543 break;
10545 return (lev && errs > lev->errors);
10548 static int tinst_depth;
10549 extern int max_tinst_depth;
10550 int depth_reached;
10552 static GTY(()) struct tinst_level *last_error_tinst_level;
10554 /* We're starting to instantiate D; record the template instantiation context
10555 at LOC for diagnostics and to restore it later. */
10557 static bool
10558 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10560 struct tinst_level *new_level;
10562 if (tinst_depth >= max_tinst_depth)
10564 /* Tell error.c not to try to instantiate any templates. */
10565 at_eof = 2;
10566 fatal_error (input_location,
10567 "template instantiation depth exceeds maximum of %d"
10568 " (use %<-ftemplate-depth=%> to increase the maximum)",
10569 max_tinst_depth);
10570 return false;
10573 /* If the current instantiation caused problems, don't let it instantiate
10574 anything else. Do allow deduction substitution and decls usable in
10575 constant expressions. */
10576 if (!targs && limit_bad_template_recursion (tldcl))
10577 return false;
10579 /* When not -quiet, dump template instantiations other than functions, since
10580 announce_function will take care of those. */
10581 if (!quiet_flag && !targs
10582 && TREE_CODE (tldcl) != TREE_LIST
10583 && TREE_CODE (tldcl) != FUNCTION_DECL)
10584 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10586 new_level = tinst_level_freelist ().alloc ();
10587 new_level->tldcl = tldcl;
10588 new_level->targs = targs;
10589 new_level->locus = loc;
10590 new_level->errors = errorcount + sorrycount;
10591 new_level->next = NULL;
10592 new_level->refcount = 0;
10593 set_refcount_ptr (new_level->next, current_tinst_level);
10594 set_refcount_ptr (current_tinst_level, new_level);
10596 ++tinst_depth;
10597 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10598 depth_reached = tinst_depth;
10600 return true;
10603 /* We're starting substitution of TMPL<ARGS>; record the template
10604 substitution context for diagnostics and to restore it later. */
10606 static bool
10607 push_tinst_level (tree tmpl, tree args)
10609 return push_tinst_level_loc (tmpl, args, input_location);
10612 /* We're starting to instantiate D; record INPUT_LOCATION and the
10613 template instantiation context for diagnostics and to restore it
10614 later. */
10616 bool
10617 push_tinst_level (tree d)
10619 return push_tinst_level_loc (d, input_location);
10622 /* Likewise, but record LOC as the program location. */
10624 bool
10625 push_tinst_level_loc (tree d, location_t loc)
10627 gcc_assert (TREE_CODE (d) != TREE_LIST);
10628 return push_tinst_level_loc (d, NULL, loc);
10631 /* We're done instantiating this template; return to the instantiation
10632 context. */
10634 void
10635 pop_tinst_level (void)
10637 /* Restore the filename and line number stashed away when we started
10638 this instantiation. */
10639 input_location = current_tinst_level->locus;
10640 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10641 --tinst_depth;
10644 /* We're instantiating a deferred template; restore the template
10645 instantiation context in which the instantiation was requested, which
10646 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
10648 static tree
10649 reopen_tinst_level (struct tinst_level *level)
10651 struct tinst_level *t;
10653 tinst_depth = 0;
10654 for (t = level; t; t = t->next)
10655 ++tinst_depth;
10657 set_refcount_ptr (current_tinst_level, level);
10658 pop_tinst_level ();
10659 if (current_tinst_level)
10660 current_tinst_level->errors = errorcount+sorrycount;
10661 return level->maybe_get_node ();
10664 /* Returns the TINST_LEVEL which gives the original instantiation
10665 context. */
10667 struct tinst_level *
10668 outermost_tinst_level (void)
10670 struct tinst_level *level = current_tinst_level;
10671 if (level)
10672 while (level->next)
10673 level = level->next;
10674 return level;
10677 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
10678 vector of template arguments, as for tsubst.
10680 Returns an appropriate tsubst'd friend declaration. */
10682 static tree
10683 tsubst_friend_function (tree decl, tree args)
10685 tree new_friend;
10687 if (TREE_CODE (decl) == FUNCTION_DECL
10688 && DECL_TEMPLATE_INSTANTIATION (decl)
10689 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10690 /* This was a friend declared with an explicit template
10691 argument list, e.g.:
10693 friend void f<>(T);
10695 to indicate that f was a template instantiation, not a new
10696 function declaration. Now, we have to figure out what
10697 instantiation of what template. */
10699 tree template_id, arglist, fns;
10700 tree new_args;
10701 tree tmpl;
10702 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10704 /* Friend functions are looked up in the containing namespace scope.
10705 We must enter that scope, to avoid finding member functions of the
10706 current class with same name. */
10707 push_nested_namespace (ns);
10708 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10709 tf_warning_or_error, NULL_TREE,
10710 /*integral_constant_expression_p=*/false);
10711 pop_nested_namespace (ns);
10712 arglist = tsubst (DECL_TI_ARGS (decl), args,
10713 tf_warning_or_error, NULL_TREE);
10714 template_id = lookup_template_function (fns, arglist);
10716 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10717 tmpl = determine_specialization (template_id, new_friend,
10718 &new_args,
10719 /*need_member_template=*/0,
10720 TREE_VEC_LENGTH (args),
10721 tsk_none);
10722 return instantiate_template (tmpl, new_args, tf_error);
10725 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10727 /* The NEW_FRIEND will look like an instantiation, to the
10728 compiler, but is not an instantiation from the point of view of
10729 the language. For example, we might have had:
10731 template <class T> struct S {
10732 template <class U> friend void f(T, U);
10735 Then, in S<int>, template <class U> void f(int, U) is not an
10736 instantiation of anything. */
10737 if (new_friend == error_mark_node)
10738 return error_mark_node;
10740 DECL_USE_TEMPLATE (new_friend) = 0;
10741 if (TREE_CODE (decl) == TEMPLATE_DECL)
10743 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10744 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10745 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10747 /* Attach the template requirements to the new declaration
10748 for declaration matching. We need to rebuild the requirements
10749 so that parameter levels match. */
10750 if (tree ci = get_constraints (decl))
10752 tree parms = DECL_TEMPLATE_PARMS (new_friend);
10753 tree args = generic_targs_for (new_friend);
10754 tree treqs = tsubst_constraint (CI_TEMPLATE_REQS (ci), args,
10755 tf_warning_or_error, NULL_TREE);
10756 tree freqs = tsubst_constraint (CI_DECLARATOR_REQS (ci), args,
10757 tf_warning_or_error, NULL_TREE);
10759 /* Update the constraints -- these won't really be valid for
10760 checking, but that's not what we need them for. These ensure
10761 that the declared function can find the friend during
10762 declaration matching. */
10763 tree new_ci = get_constraints (new_friend);
10764 CI_TEMPLATE_REQS (new_ci) = treqs;
10765 CI_DECLARATOR_REQS (new_ci) = freqs;
10767 /* Also update the template parameter list. */
10768 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
10772 /* The mangled name for the NEW_FRIEND is incorrect. The function
10773 is not a template instantiation and should not be mangled like
10774 one. Therefore, we forget the mangling here; we'll recompute it
10775 later if we need it. */
10776 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10778 SET_DECL_RTL (new_friend, NULL);
10779 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10782 if (DECL_NAMESPACE_SCOPE_P (new_friend))
10784 tree old_decl;
10785 tree new_friend_template_info;
10786 tree new_friend_result_template_info;
10787 tree ns;
10788 int new_friend_is_defn;
10790 /* We must save some information from NEW_FRIEND before calling
10791 duplicate decls since that function will free NEW_FRIEND if
10792 possible. */
10793 new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10794 new_friend_is_defn =
10795 (DECL_INITIAL (DECL_TEMPLATE_RESULT
10796 (template_for_substitution (new_friend)))
10797 != NULL_TREE);
10798 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10800 /* This declaration is a `primary' template. */
10801 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10803 new_friend_result_template_info
10804 = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10806 else
10807 new_friend_result_template_info = NULL_TREE;
10809 /* Inside pushdecl_namespace_level, we will push into the
10810 current namespace. However, the friend function should go
10811 into the namespace of the template. */
10812 ns = decl_namespace_context (new_friend);
10813 push_nested_namespace (ns);
10814 old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10815 pop_nested_namespace (ns);
10817 if (old_decl == error_mark_node)
10818 return error_mark_node;
10820 if (old_decl != new_friend)
10822 /* This new friend declaration matched an existing
10823 declaration. For example, given:
10825 template <class T> void f(T);
10826 template <class U> class C {
10827 template <class T> friend void f(T) {}
10830 the friend declaration actually provides the definition
10831 of `f', once C has been instantiated for some type. So,
10832 old_decl will be the out-of-class template declaration,
10833 while new_friend is the in-class definition.
10835 But, if `f' was called before this point, the
10836 instantiation of `f' will have DECL_TI_ARGS corresponding
10837 to `T' but not to `U', references to which might appear
10838 in the definition of `f'. Previously, the most general
10839 template for an instantiation of `f' was the out-of-class
10840 version; now it is the in-class version. Therefore, we
10841 run through all specialization of `f', adding to their
10842 DECL_TI_ARGS appropriately. In particular, they need a
10843 new set of outer arguments, corresponding to the
10844 arguments for this class instantiation.
10846 The same situation can arise with something like this:
10848 friend void f(int);
10849 template <class T> class C {
10850 friend void f(T) {}
10853 when `C<int>' is instantiated. Now, `f(int)' is defined
10854 in the class. */
10856 if (!new_friend_is_defn)
10857 /* On the other hand, if the in-class declaration does
10858 *not* provide a definition, then we don't want to alter
10859 existing definitions. We can just leave everything
10860 alone. */
10862 else
10864 tree new_template = TI_TEMPLATE (new_friend_template_info);
10865 tree new_args = TI_ARGS (new_friend_template_info);
10867 /* Overwrite whatever template info was there before, if
10868 any, with the new template information pertaining to
10869 the declaration. */
10870 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10872 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10874 /* We should have called reregister_specialization in
10875 duplicate_decls. */
10876 gcc_assert (retrieve_specialization (new_template,
10877 new_args, 0)
10878 == old_decl);
10880 /* Instantiate it if the global has already been used. */
10881 if (DECL_ODR_USED (old_decl))
10882 instantiate_decl (old_decl, /*defer_ok=*/true,
10883 /*expl_inst_class_mem_p=*/false);
10885 else
10887 tree t;
10889 /* Indicate that the old function template is a partial
10890 instantiation. */
10891 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10892 = new_friend_result_template_info;
10894 gcc_assert (new_template
10895 == most_general_template (new_template));
10896 gcc_assert (new_template != old_decl);
10898 /* Reassign any specializations already in the hash table
10899 to the new more general template, and add the
10900 additional template args. */
10901 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10902 t != NULL_TREE;
10903 t = TREE_CHAIN (t))
10905 tree spec = TREE_VALUE (t);
10906 spec_entry elt;
10908 elt.tmpl = old_decl;
10909 elt.args = DECL_TI_ARGS (spec);
10910 elt.spec = NULL_TREE;
10912 decl_specializations->remove_elt (&elt);
10914 DECL_TI_ARGS (spec)
10915 = add_outermost_template_args (new_args,
10916 DECL_TI_ARGS (spec));
10918 register_specialization
10919 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
10922 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10926 /* The information from NEW_FRIEND has been merged into OLD_DECL
10927 by duplicate_decls. */
10928 new_friend = old_decl;
10931 else
10933 tree context = DECL_CONTEXT (new_friend);
10934 bool dependent_p;
10936 /* In the code
10937 template <class T> class C {
10938 template <class U> friend void C1<U>::f (); // case 1
10939 friend void C2<T>::f (); // case 2
10941 we only need to make sure CONTEXT is a complete type for
10942 case 2. To distinguish between the two cases, we note that
10943 CONTEXT of case 1 remains dependent type after tsubst while
10944 this isn't true for case 2. */
10945 ++processing_template_decl;
10946 dependent_p = dependent_type_p (context);
10947 --processing_template_decl;
10949 if (!dependent_p
10950 && !complete_type_or_else (context, NULL_TREE))
10951 return error_mark_node;
10953 if (COMPLETE_TYPE_P (context))
10955 tree fn = new_friend;
10956 /* do_friend adds the TEMPLATE_DECL for any member friend
10957 template even if it isn't a member template, i.e.
10958 template <class T> friend A<T>::f();
10959 Look through it in that case. */
10960 if (TREE_CODE (fn) == TEMPLATE_DECL
10961 && !PRIMARY_TEMPLATE_P (fn))
10962 fn = DECL_TEMPLATE_RESULT (fn);
10963 /* Check to see that the declaration is really present, and,
10964 possibly obtain an improved declaration. */
10965 fn = check_classfn (context, fn, NULL_TREE);
10967 if (fn)
10968 new_friend = fn;
10972 return new_friend;
10975 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
10976 template arguments, as for tsubst.
10978 Returns an appropriate tsubst'd friend type or error_mark_node on
10979 failure. */
10981 static tree
10982 tsubst_friend_class (tree friend_tmpl, tree args)
10984 tree tmpl;
10986 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10988 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10989 return TREE_TYPE (tmpl);
10992 tree context = CP_DECL_CONTEXT (friend_tmpl);
10993 if (TREE_CODE (context) == NAMESPACE_DECL)
10994 push_nested_namespace (context);
10995 else
10997 context = tsubst (context, args, tf_error, NULL_TREE);
10998 push_nested_class (context);
11001 tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
11002 /*non_class=*/false, /*block_p=*/false,
11003 /*namespaces_only=*/false, LOOKUP_HIDDEN);
11005 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11007 /* The friend template has already been declared. Just
11008 check to see that the declarations match, and install any new
11009 default parameters. We must tsubst the default parameters,
11010 of course. We only need the innermost template parameters
11011 because that is all that redeclare_class_template will look
11012 at. */
11013 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11014 > TMPL_ARGS_DEPTH (args))
11016 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11017 args, tf_warning_or_error);
11018 location_t saved_input_location = input_location;
11019 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11020 tree cons = get_constraints (tmpl);
11021 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11022 input_location = saved_input_location;
11025 else
11027 /* The friend template has not already been declared. In this
11028 case, the instantiation of the template class will cause the
11029 injection of this template into the namespace scope. */
11030 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11032 if (tmpl != error_mark_node)
11034 /* The new TMPL is not an instantiation of anything, so we
11035 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11036 for the new type because that is supposed to be the
11037 corresponding template decl, i.e., TMPL. */
11038 DECL_USE_TEMPLATE (tmpl) = 0;
11039 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11040 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11041 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11042 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11044 /* It is hidden. */
11045 retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
11046 DECL_ANTICIPATED (tmpl)
11047 = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
11049 /* Inject this template into the enclosing namspace scope. */
11050 tmpl = pushdecl_namespace_level (tmpl, true);
11054 if (TREE_CODE (context) == NAMESPACE_DECL)
11055 pop_nested_namespace (context);
11056 else
11057 pop_nested_class ();
11059 return TREE_TYPE (tmpl);
11062 /* Returns zero if TYPE cannot be completed later due to circularity.
11063 Otherwise returns one. */
11065 static int
11066 can_complete_type_without_circularity (tree type)
11068 if (type == NULL_TREE || type == error_mark_node)
11069 return 0;
11070 else if (COMPLETE_TYPE_P (type))
11071 return 1;
11072 else if (TREE_CODE (type) == ARRAY_TYPE)
11073 return can_complete_type_without_circularity (TREE_TYPE (type));
11074 else if (CLASS_TYPE_P (type)
11075 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11076 return 0;
11077 else
11078 return 1;
11081 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11082 tsubst_flags_t, tree);
11084 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11085 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11087 static tree
11088 tsubst_attribute (tree t, tree *decl_p, tree args,
11089 tsubst_flags_t complain, tree in_decl)
11091 gcc_assert (ATTR_IS_DEPENDENT (t));
11093 tree val = TREE_VALUE (t);
11094 if (val == NULL_TREE)
11095 /* Nothing to do. */;
11096 else if ((flag_openmp || flag_openmp_simd)
11097 && is_attribute_p ("omp declare simd",
11098 get_attribute_name (t)))
11100 tree clauses = TREE_VALUE (val);
11101 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11102 complain, in_decl);
11103 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11104 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11105 tree parms = DECL_ARGUMENTS (*decl_p);
11106 clauses
11107 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11108 if (clauses)
11109 val = build_tree_list (NULL_TREE, clauses);
11110 else
11111 val = NULL_TREE;
11113 /* If the first attribute argument is an identifier, don't
11114 pass it through tsubst. Attributes like mode, format,
11115 cleanup and several target specific attributes expect it
11116 unmodified. */
11117 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11119 tree chain
11120 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11121 /*integral_constant_expression_p=*/false);
11122 if (chain != TREE_CHAIN (val))
11123 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11125 else if (PACK_EXPANSION_P (val))
11127 /* An attribute pack expansion. */
11128 tree purp = TREE_PURPOSE (t);
11129 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11130 if (pack == error_mark_node)
11131 return error_mark_node;
11132 int len = TREE_VEC_LENGTH (pack);
11133 tree list = NULL_TREE;
11134 tree *q = &list;
11135 for (int i = 0; i < len; ++i)
11137 tree elt = TREE_VEC_ELT (pack, i);
11138 *q = build_tree_list (purp, elt);
11139 q = &TREE_CHAIN (*q);
11141 return list;
11143 else
11144 val = tsubst_expr (val, args, complain, in_decl,
11145 /*integral_constant_expression_p=*/false);
11147 if (val != TREE_VALUE (t))
11148 return build_tree_list (TREE_PURPOSE (t), val);
11149 return t;
11152 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11153 unchanged or a new TREE_LIST chain. */
11155 static tree
11156 tsubst_attributes (tree attributes, tree args,
11157 tsubst_flags_t complain, tree in_decl)
11159 tree last_dep = NULL_TREE;
11161 for (tree t = attributes; t; t = TREE_CHAIN (t))
11162 if (ATTR_IS_DEPENDENT (t))
11164 last_dep = t;
11165 attributes = copy_list (attributes);
11166 break;
11169 if (last_dep)
11170 for (tree *p = &attributes; *p; )
11172 tree t = *p;
11173 if (ATTR_IS_DEPENDENT (t))
11175 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11176 if (subst != t)
11178 *p = subst;
11179 while (*p)
11180 p = &TREE_CHAIN (*p);
11181 *p = TREE_CHAIN (t);
11182 continue;
11185 p = &TREE_CHAIN (*p);
11188 return attributes;
11191 /* Apply any attributes which had to be deferred until instantiation
11192 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11193 ARGS, COMPLAIN, IN_DECL are as tsubst. */
11195 static void
11196 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11197 tree args, tsubst_flags_t complain, tree in_decl)
11199 tree last_dep = NULL_TREE;
11200 tree t;
11201 tree *p;
11203 if (attributes == NULL_TREE)
11204 return;
11206 if (DECL_P (*decl_p))
11208 if (TREE_TYPE (*decl_p) == error_mark_node)
11209 return;
11210 p = &DECL_ATTRIBUTES (*decl_p);
11211 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11212 to our attributes parameter. */
11213 gcc_assert (*p == attributes);
11215 else
11217 p = &TYPE_ATTRIBUTES (*decl_p);
11218 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11219 lookup_template_class_1, and should be preserved. */
11220 gcc_assert (*p != attributes);
11221 while (*p)
11222 p = &TREE_CHAIN (*p);
11225 for (t = attributes; t; t = TREE_CHAIN (t))
11226 if (ATTR_IS_DEPENDENT (t))
11228 last_dep = t;
11229 attributes = copy_list (attributes);
11230 break;
11233 *p = attributes;
11234 if (last_dep)
11236 tree late_attrs = NULL_TREE;
11237 tree *q = &late_attrs;
11239 for (; *p; )
11241 t = *p;
11242 if (ATTR_IS_DEPENDENT (t))
11244 *p = TREE_CHAIN (t);
11245 TREE_CHAIN (t) = NULL_TREE;
11246 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11247 while (*q)
11248 q = &TREE_CHAIN (*q);
11250 else
11251 p = &TREE_CHAIN (t);
11254 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11258 /* Perform (or defer) access check for typedefs that were referenced
11259 from within the template TMPL code.
11260 This is a subroutine of instantiate_decl and instantiate_class_template.
11261 TMPL is the template to consider and TARGS is the list of arguments of
11262 that template. */
11264 static void
11265 perform_typedefs_access_check (tree tmpl, tree targs)
11267 unsigned i;
11268 qualified_typedef_usage_t *iter;
11270 if (!tmpl
11271 || (!CLASS_TYPE_P (tmpl)
11272 && TREE_CODE (tmpl) != FUNCTION_DECL))
11273 return;
11275 FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
11277 tree type_decl = iter->typedef_decl;
11278 tree type_scope = iter->context;
11280 if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
11281 continue;
11283 if (uses_template_parms (type_decl))
11284 type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
11285 if (uses_template_parms (type_scope))
11286 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11288 /* Make access check error messages point to the location
11289 of the use of the typedef. */
11290 iloc_sentinel ils (iter->locus);
11291 perform_or_defer_access_check (TYPE_BINFO (type_scope),
11292 type_decl, type_decl,
11293 tf_warning_or_error);
11297 static tree
11298 instantiate_class_template_1 (tree type)
11300 tree templ, args, pattern, t, member;
11301 tree typedecl;
11302 tree pbinfo;
11303 tree base_list;
11304 unsigned int saved_maximum_field_alignment;
11305 tree fn_context;
11307 if (type == error_mark_node)
11308 return error_mark_node;
11310 if (COMPLETE_OR_OPEN_TYPE_P (type)
11311 || uses_template_parms (type))
11312 return type;
11314 /* Figure out which template is being instantiated. */
11315 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11316 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11318 /* Mark the type as in the process of being defined. */
11319 TYPE_BEING_DEFINED (type) = 1;
11321 /* We may be in the middle of deferred access check. Disable
11322 it now. */
11323 deferring_access_check_sentinel acs (dk_no_deferred);
11325 /* Determine what specialization of the original template to
11326 instantiate. */
11327 t = most_specialized_partial_spec (type, tf_warning_or_error);
11328 if (t == error_mark_node)
11329 return error_mark_node;
11330 else if (t)
11332 /* This TYPE is actually an instantiation of a partial
11333 specialization. We replace the innermost set of ARGS with
11334 the arguments appropriate for substitution. For example,
11335 given:
11337 template <class T> struct S {};
11338 template <class T> struct S<T*> {};
11340 and supposing that we are instantiating S<int*>, ARGS will
11341 presently be {int*} -- but we need {int}. */
11342 pattern = TREE_TYPE (t);
11343 args = TREE_PURPOSE (t);
11345 else
11347 pattern = TREE_TYPE (templ);
11348 args = CLASSTYPE_TI_ARGS (type);
11351 /* If the template we're instantiating is incomplete, then clearly
11352 there's nothing we can do. */
11353 if (!COMPLETE_TYPE_P (pattern))
11355 /* We can try again later. */
11356 TYPE_BEING_DEFINED (type) = 0;
11357 return type;
11360 /* If we've recursively instantiated too many templates, stop. */
11361 if (! push_tinst_level (type))
11362 return type;
11364 int saved_unevaluated_operand = cp_unevaluated_operand;
11365 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11367 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11368 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
11369 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11370 fn_context = error_mark_node;
11371 if (!fn_context)
11372 push_to_top_level ();
11373 else
11375 cp_unevaluated_operand = 0;
11376 c_inhibit_evaluation_warnings = 0;
11378 /* Use #pragma pack from the template context. */
11379 saved_maximum_field_alignment = maximum_field_alignment;
11380 maximum_field_alignment = TYPE_PRECISION (pattern);
11382 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11384 /* Set the input location to the most specialized template definition.
11385 This is needed if tsubsting causes an error. */
11386 typedecl = TYPE_MAIN_DECL (pattern);
11387 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11388 DECL_SOURCE_LOCATION (typedecl);
11390 TYPE_PACKED (type) = TYPE_PACKED (pattern);
11391 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11392 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11393 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11394 if (ANON_AGGR_TYPE_P (pattern))
11395 SET_ANON_AGGR_TYPE_P (type);
11396 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11398 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11399 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11400 /* Adjust visibility for template arguments. */
11401 determine_visibility (TYPE_MAIN_DECL (type));
11403 if (CLASS_TYPE_P (type))
11404 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11406 pbinfo = TYPE_BINFO (pattern);
11408 /* We should never instantiate a nested class before its enclosing
11409 class; we need to look up the nested class by name before we can
11410 instantiate it, and that lookup should instantiate the enclosing
11411 class. */
11412 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11413 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11415 base_list = NULL_TREE;
11416 if (BINFO_N_BASE_BINFOS (pbinfo))
11418 tree pbase_binfo;
11419 tree pushed_scope;
11420 int i;
11422 /* We must enter the scope containing the type, as that is where
11423 the accessibility of types named in dependent bases are
11424 looked up from. */
11425 pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
11427 /* Substitute into each of the bases to determine the actual
11428 basetypes. */
11429 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11431 tree base;
11432 tree access = BINFO_BASE_ACCESS (pbinfo, i);
11433 tree expanded_bases = NULL_TREE;
11434 int idx, len = 1;
11436 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11438 expanded_bases =
11439 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11440 args, tf_error, NULL_TREE);
11441 if (expanded_bases == error_mark_node)
11442 continue;
11444 len = TREE_VEC_LENGTH (expanded_bases);
11447 for (idx = 0; idx < len; idx++)
11449 if (expanded_bases)
11450 /* Extract the already-expanded base class. */
11451 base = TREE_VEC_ELT (expanded_bases, idx);
11452 else
11453 /* Substitute to figure out the base class. */
11454 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11455 NULL_TREE);
11457 if (base == error_mark_node)
11458 continue;
11460 base_list = tree_cons (access, base, base_list);
11461 if (BINFO_VIRTUAL_P (pbase_binfo))
11462 TREE_TYPE (base_list) = integer_type_node;
11466 /* The list is now in reverse order; correct that. */
11467 base_list = nreverse (base_list);
11469 if (pushed_scope)
11470 pop_scope (pushed_scope);
11472 /* Now call xref_basetypes to set up all the base-class
11473 information. */
11474 xref_basetypes (type, base_list);
11476 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11477 (int) ATTR_FLAG_TYPE_IN_PLACE,
11478 args, tf_error, NULL_TREE);
11479 fixup_attribute_variants (type);
11481 /* Now that our base classes are set up, enter the scope of the
11482 class, so that name lookups into base classes, etc. will work
11483 correctly. This is precisely analogous to what we do in
11484 begin_class_definition when defining an ordinary non-template
11485 class, except we also need to push the enclosing classes. */
11486 push_nested_class (type);
11488 /* Now members are processed in the order of declaration. */
11489 for (member = CLASSTYPE_DECL_LIST (pattern);
11490 member; member = TREE_CHAIN (member))
11492 tree t = TREE_VALUE (member);
11494 if (TREE_PURPOSE (member))
11496 if (TYPE_P (t))
11498 if (LAMBDA_TYPE_P (t))
11499 /* A closure type for a lambda in an NSDMI or default argument.
11500 Ignore it; it will be regenerated when needed. */
11501 continue;
11503 /* Build new CLASSTYPE_NESTED_UTDS. */
11505 tree newtag;
11506 bool class_template_p;
11508 class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11509 && TYPE_LANG_SPECIFIC (t)
11510 && CLASSTYPE_IS_TEMPLATE (t));
11511 /* If the member is a class template, then -- even after
11512 substitution -- there may be dependent types in the
11513 template argument list for the class. We increment
11514 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11515 that function will assume that no types are dependent
11516 when outside of a template. */
11517 if (class_template_p)
11518 ++processing_template_decl;
11519 newtag = tsubst (t, args, tf_error, NULL_TREE);
11520 if (class_template_p)
11521 --processing_template_decl;
11522 if (newtag == error_mark_node)
11523 continue;
11525 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11527 tree name = TYPE_IDENTIFIER (t);
11529 if (class_template_p)
11530 /* Unfortunately, lookup_template_class sets
11531 CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11532 instantiation (i.e., for the type of a member
11533 template class nested within a template class.)
11534 This behavior is required for
11535 maybe_process_partial_specialization to work
11536 correctly, but is not accurate in this case;
11537 the TAG is not an instantiation of anything.
11538 (The corresponding TEMPLATE_DECL is an
11539 instantiation, but the TYPE is not.) */
11540 CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11542 /* Now, we call pushtag to put this NEWTAG into the scope of
11543 TYPE. We first set up the IDENTIFIER_TYPE_VALUE to avoid
11544 pushtag calling push_template_decl. We don't have to do
11545 this for enums because it will already have been done in
11546 tsubst_enum. */
11547 if (name)
11548 SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11549 pushtag (name, newtag, /*tag_scope=*/ts_current);
11552 else if (DECL_DECLARES_FUNCTION_P (t))
11554 tree r;
11556 if (TREE_CODE (t) == TEMPLATE_DECL)
11557 ++processing_template_decl;
11558 r = tsubst (t, args, tf_error, NULL_TREE);
11559 if (TREE_CODE (t) == TEMPLATE_DECL)
11560 --processing_template_decl;
11561 set_current_access_from_decl (r);
11562 finish_member_declaration (r);
11563 /* Instantiate members marked with attribute used. */
11564 if (r != error_mark_node && DECL_PRESERVE_P (r))
11565 mark_used (r);
11566 if (TREE_CODE (r) == FUNCTION_DECL
11567 && DECL_OMP_DECLARE_REDUCTION_P (r))
11568 cp_check_omp_declare_reduction (r);
11570 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11571 && LAMBDA_TYPE_P (TREE_TYPE (t)))
11572 /* A closure type for a lambda in an NSDMI or default argument.
11573 Ignore it; it will be regenerated when needed. */;
11574 else
11576 /* Build new TYPE_FIELDS. */
11577 if (TREE_CODE (t) == STATIC_ASSERT)
11579 tree condition;
11581 ++c_inhibit_evaluation_warnings;
11582 condition =
11583 tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11584 tf_warning_or_error, NULL_TREE,
11585 /*integral_constant_expression_p=*/true);
11586 --c_inhibit_evaluation_warnings;
11588 finish_static_assert (condition,
11589 STATIC_ASSERT_MESSAGE (t),
11590 STATIC_ASSERT_SOURCE_LOCATION (t),
11591 /*member_p=*/true);
11593 else if (TREE_CODE (t) != CONST_DECL)
11595 tree r;
11596 tree vec = NULL_TREE;
11597 int len = 1;
11599 /* The file and line for this declaration, to
11600 assist in error message reporting. Since we
11601 called push_tinst_level above, we don't need to
11602 restore these. */
11603 input_location = DECL_SOURCE_LOCATION (t);
11605 if (TREE_CODE (t) == TEMPLATE_DECL)
11606 ++processing_template_decl;
11607 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11608 if (TREE_CODE (t) == TEMPLATE_DECL)
11609 --processing_template_decl;
11611 if (TREE_CODE (r) == TREE_VEC)
11613 /* A capture pack became multiple fields. */
11614 vec = r;
11615 len = TREE_VEC_LENGTH (vec);
11618 for (int i = 0; i < len; ++i)
11620 if (vec)
11621 r = TREE_VEC_ELT (vec, i);
11622 if (VAR_P (r))
11624 /* In [temp.inst]:
11626 [t]he initialization (and any associated
11627 side-effects) of a static data member does
11628 not occur unless the static data member is
11629 itself used in a way that requires the
11630 definition of the static data member to
11631 exist.
11633 Therefore, we do not substitute into the
11634 initialized for the static data member here. */
11635 finish_static_data_member_decl
11637 /*init=*/NULL_TREE,
11638 /*init_const_expr_p=*/false,
11639 /*asmspec_tree=*/NULL_TREE,
11640 /*flags=*/0);
11641 /* Instantiate members marked with attribute used. */
11642 if (r != error_mark_node && DECL_PRESERVE_P (r))
11643 mark_used (r);
11645 else if (TREE_CODE (r) == FIELD_DECL)
11647 /* Determine whether R has a valid type and can be
11648 completed later. If R is invalid, then its type
11649 is replaced by error_mark_node. */
11650 tree rtype = TREE_TYPE (r);
11651 if (can_complete_type_without_circularity (rtype))
11652 complete_type (rtype);
11654 if (!complete_or_array_type_p (rtype))
11656 /* If R's type couldn't be completed and
11657 it isn't a flexible array member (whose
11658 type is incomplete by definition) give
11659 an error. */
11660 cxx_incomplete_type_error (r, rtype);
11661 TREE_TYPE (r) = error_mark_node;
11663 else if (TREE_CODE (rtype) == ARRAY_TYPE
11664 && TYPE_DOMAIN (rtype) == NULL_TREE
11665 && (TREE_CODE (type) == UNION_TYPE
11666 || TREE_CODE (type) == QUAL_UNION_TYPE))
11668 error ("flexible array member %qD in union", r);
11669 TREE_TYPE (r) = error_mark_node;
11673 /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11674 such a thing will already have been added to the field
11675 list by tsubst_enum in finish_member_declaration in the
11676 CLASSTYPE_NESTED_UTDS case above. */
11677 if (!(TREE_CODE (r) == TYPE_DECL
11678 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11679 && DECL_ARTIFICIAL (r)))
11681 set_current_access_from_decl (r);
11682 finish_member_declaration (r);
11688 else
11690 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11691 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11693 /* Build new CLASSTYPE_FRIEND_CLASSES. */
11695 tree friend_type = t;
11696 bool adjust_processing_template_decl = false;
11698 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11700 /* template <class T> friend class C; */
11701 friend_type = tsubst_friend_class (friend_type, args);
11702 adjust_processing_template_decl = true;
11704 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11706 /* template <class T> friend class C::D; */
11707 friend_type = tsubst (friend_type, args,
11708 tf_warning_or_error, NULL_TREE);
11709 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11710 friend_type = TREE_TYPE (friend_type);
11711 adjust_processing_template_decl = true;
11713 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11714 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11716 /* This could be either
11718 friend class T::C;
11720 when dependent_type_p is false or
11722 template <class U> friend class T::C;
11724 otherwise. */
11725 /* Bump processing_template_decl in case this is something like
11726 template <class T> friend struct A<T>::B. */
11727 ++processing_template_decl;
11728 friend_type = tsubst (friend_type, args,
11729 tf_warning_or_error, NULL_TREE);
11730 if (dependent_type_p (friend_type))
11731 adjust_processing_template_decl = true;
11732 --processing_template_decl;
11734 else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11735 && !CLASSTYPE_USE_TEMPLATE (friend_type)
11736 && TYPE_HIDDEN_P (friend_type))
11738 /* friend class C;
11740 where C hasn't been declared yet. Let's lookup name
11741 from namespace scope directly, bypassing any name that
11742 come from dependent base class. */
11743 tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
11745 /* The call to xref_tag_from_type does injection for friend
11746 classes. */
11747 push_nested_namespace (ns);
11748 friend_type =
11749 xref_tag_from_type (friend_type, NULL_TREE,
11750 /*tag_scope=*/ts_current);
11751 pop_nested_namespace (ns);
11753 else if (uses_template_parms (friend_type))
11754 /* friend class C<T>; */
11755 friend_type = tsubst (friend_type, args,
11756 tf_warning_or_error, NULL_TREE);
11757 /* Otherwise it's
11759 friend class C;
11761 where C is already declared or
11763 friend class C<int>;
11765 We don't have to do anything in these cases. */
11767 if (adjust_processing_template_decl)
11768 /* Trick make_friend_class into realizing that the friend
11769 we're adding is a template, not an ordinary class. It's
11770 important that we use make_friend_class since it will
11771 perform some error-checking and output cross-reference
11772 information. */
11773 ++processing_template_decl;
11775 if (friend_type != error_mark_node)
11776 make_friend_class (type, friend_type, /*complain=*/false);
11778 if (adjust_processing_template_decl)
11779 --processing_template_decl;
11781 else
11783 /* Build new DECL_FRIENDLIST. */
11784 tree r;
11786 /* The file and line for this declaration, to
11787 assist in error message reporting. Since we
11788 called push_tinst_level above, we don't need to
11789 restore these. */
11790 input_location = DECL_SOURCE_LOCATION (t);
11792 if (TREE_CODE (t) == TEMPLATE_DECL)
11794 ++processing_template_decl;
11795 push_deferring_access_checks (dk_no_check);
11798 r = tsubst_friend_function (t, args);
11799 add_friend (type, r, /*complain=*/false);
11800 if (TREE_CODE (t) == TEMPLATE_DECL)
11802 pop_deferring_access_checks ();
11803 --processing_template_decl;
11809 if (fn_context)
11811 /* Restore these before substituting into the lambda capture
11812 initializers. */
11813 cp_unevaluated_operand = saved_unevaluated_operand;
11814 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11817 /* Set the file and line number information to whatever is given for
11818 the class itself. This puts error messages involving generated
11819 implicit functions at a predictable point, and the same point
11820 that would be used for non-template classes. */
11821 input_location = DECL_SOURCE_LOCATION (typedecl);
11823 unreverse_member_declarations (type);
11824 finish_struct_1 (type);
11825 TYPE_BEING_DEFINED (type) = 0;
11827 /* We don't instantiate default arguments for member functions. 14.7.1:
11829 The implicit instantiation of a class template specialization causes
11830 the implicit instantiation of the declarations, but not of the
11831 definitions or default arguments, of the class member functions,
11832 member classes, static data members and member templates.... */
11834 /* Some typedefs referenced from within the template code need to be access
11835 checked at template instantiation time, i.e now. These types were
11836 added to the template at parsing time. Let's get those and perform
11837 the access checks then. */
11838 perform_typedefs_access_check (pattern, args);
11839 perform_deferred_access_checks (tf_warning_or_error);
11840 pop_nested_class ();
11841 maximum_field_alignment = saved_maximum_field_alignment;
11842 if (!fn_context)
11843 pop_from_top_level ();
11844 pop_tinst_level ();
11846 /* The vtable for a template class can be emitted in any translation
11847 unit in which the class is instantiated. When there is no key
11848 method, however, finish_struct_1 will already have added TYPE to
11849 the keyed_classes. */
11850 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11851 vec_safe_push (keyed_classes, type);
11853 return type;
11856 /* Wrapper for instantiate_class_template_1. */
11858 tree
11859 instantiate_class_template (tree type)
11861 tree ret;
11862 timevar_push (TV_TEMPLATE_INST);
11863 ret = instantiate_class_template_1 (type);
11864 timevar_pop (TV_TEMPLATE_INST);
11865 return ret;
11868 tree
11869 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11871 tree r;
11873 if (!t)
11874 r = t;
11875 else if (TYPE_P (t))
11876 r = tsubst (t, args, complain, in_decl);
11877 else
11879 if (!(complain & tf_warning))
11880 ++c_inhibit_evaluation_warnings;
11881 r = tsubst_expr (t, args, complain, in_decl,
11882 /*integral_constant_expression_p=*/true);
11883 if (!(complain & tf_warning))
11884 --c_inhibit_evaluation_warnings;
11887 return r;
11890 /* Given a function parameter pack TMPL_PARM and some function parameters
11891 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11892 and set *SPEC_P to point at the next point in the list. */
11894 tree
11895 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11897 /* Collect all of the extra "packed" parameters into an
11898 argument pack. */
11899 tree parmvec;
11900 tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11901 tree spec_parm = *spec_p;
11902 int i, len;
11904 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11905 if (tmpl_parm
11906 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11907 break;
11909 /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters. */
11910 parmvec = make_tree_vec (len);
11911 spec_parm = *spec_p;
11912 for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11914 tree elt = spec_parm;
11915 if (DECL_PACK_P (elt))
11916 elt = make_pack_expansion (elt);
11917 TREE_VEC_ELT (parmvec, i) = elt;
11920 /* Build the argument packs. */
11921 SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11922 *spec_p = spec_parm;
11924 return argpack;
11927 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11928 NONTYPE_ARGUMENT_PACK. */
11930 static tree
11931 make_fnparm_pack (tree spec_parm)
11933 return extract_fnparm_pack (NULL_TREE, &spec_parm);
11936 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11937 pack expansion with no extra args, 2 if it has extra args, or 0
11938 if it is not a pack expansion. */
11940 static int
11941 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11943 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
11944 /* We're being called before this happens in tsubst_pack_expansion. */
11945 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
11946 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11947 if (i >= TREE_VEC_LENGTH (vec))
11948 return 0;
11949 tree elt = TREE_VEC_ELT (vec, i);
11950 if (DECL_P (elt))
11951 /* A decl pack is itself an expansion. */
11952 elt = TREE_TYPE (elt);
11953 if (!PACK_EXPANSION_P (elt))
11954 return 0;
11955 if (PACK_EXPANSION_EXTRA_ARGS (elt))
11956 return 2;
11957 return 1;
11961 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
11963 static tree
11964 make_argument_pack_select (tree arg_pack, unsigned index)
11966 tree aps = make_node (ARGUMENT_PACK_SELECT);
11968 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11969 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11971 return aps;
11974 /* This is a subroutine of tsubst_pack_expansion.
11976 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11977 mechanism to store the (non complete list of) arguments of the
11978 substitution and return a non substituted pack expansion, in order
11979 to wait for when we have enough arguments to really perform the
11980 substitution. */
11982 static bool
11983 use_pack_expansion_extra_args_p (tree parm_packs,
11984 int arg_pack_len,
11985 bool has_empty_arg)
11987 /* If one pack has an expansion and another pack has a normal
11988 argument or if one pack has an empty argument and an another
11989 one hasn't then tsubst_pack_expansion cannot perform the
11990 substitution and need to fall back on the
11991 PACK_EXPANSION_EXTRA mechanism. */
11992 if (parm_packs == NULL_TREE)
11993 return false;
11994 else if (has_empty_arg)
11995 return true;
11997 bool has_expansion_arg = false;
11998 for (int i = 0 ; i < arg_pack_len; ++i)
12000 bool has_non_expansion_arg = false;
12001 for (tree parm_pack = parm_packs;
12002 parm_pack;
12003 parm_pack = TREE_CHAIN (parm_pack))
12005 tree arg = TREE_VALUE (parm_pack);
12007 int exp = argument_pack_element_is_expansion_p (arg, i);
12008 if (exp == 2)
12009 /* We can't substitute a pack expansion with extra args into
12010 our pattern. */
12011 return true;
12012 else if (exp)
12013 has_expansion_arg = true;
12014 else
12015 has_non_expansion_arg = true;
12018 if (has_expansion_arg && has_non_expansion_arg)
12019 return true;
12021 return false;
12024 /* [temp.variadic]/6 says that:
12026 The instantiation of a pack expansion [...]
12027 produces a list E1,E2, ..., En, where N is the number of elements
12028 in the pack expansion parameters.
12030 This subroutine of tsubst_pack_expansion produces one of these Ei.
12032 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12033 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12034 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12035 INDEX is the index 'i' of the element Ei to produce. ARGS,
12036 COMPLAIN, and IN_DECL are the same parameters as for the
12037 tsubst_pack_expansion function.
12039 The function returns the resulting Ei upon successful completion,
12040 or error_mark_node.
12042 Note that this function possibly modifies the ARGS parameter, so
12043 it's the responsibility of the caller to restore it. */
12045 static tree
12046 gen_elem_of_pack_expansion_instantiation (tree pattern,
12047 tree parm_packs,
12048 unsigned index,
12049 tree args /* This parm gets
12050 modified. */,
12051 tsubst_flags_t complain,
12052 tree in_decl)
12054 tree t;
12055 bool ith_elem_is_expansion = false;
12057 /* For each parameter pack, change the substitution of the parameter
12058 pack to the ith argument in its argument pack, then expand the
12059 pattern. */
12060 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12062 tree parm = TREE_PURPOSE (pack);
12063 tree arg_pack = TREE_VALUE (pack);
12064 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12066 ith_elem_is_expansion |=
12067 argument_pack_element_is_expansion_p (arg_pack, index);
12069 /* Select the Ith argument from the pack. */
12070 if (TREE_CODE (parm) == PARM_DECL
12071 || VAR_P (parm)
12072 || TREE_CODE (parm) == FIELD_DECL)
12074 if (index == 0)
12076 aps = make_argument_pack_select (arg_pack, index);
12077 if (!mark_used (parm, complain) && !(complain & tf_error))
12078 return error_mark_node;
12079 register_local_specialization (aps, parm);
12081 else
12082 aps = retrieve_local_specialization (parm);
12084 else
12086 int idx, level;
12087 template_parm_level_and_index (parm, &level, &idx);
12089 if (index == 0)
12091 aps = make_argument_pack_select (arg_pack, index);
12092 /* Update the corresponding argument. */
12093 TMPL_ARG (args, level, idx) = aps;
12095 else
12096 /* Re-use the ARGUMENT_PACK_SELECT. */
12097 aps = TMPL_ARG (args, level, idx);
12099 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12102 /* Substitute into the PATTERN with the (possibly altered)
12103 arguments. */
12104 if (pattern == in_decl)
12105 /* Expanding a fixed parameter pack from
12106 coerce_template_parameter_pack. */
12107 t = tsubst_decl (pattern, args, complain);
12108 else if (pattern == error_mark_node)
12109 t = error_mark_node;
12110 else if (!TYPE_P (pattern))
12111 t = tsubst_expr (pattern, args, complain, in_decl,
12112 /*integral_constant_expression_p=*/false);
12113 else
12114 t = tsubst (pattern, args, complain, in_decl);
12116 /* If the Ith argument pack element is a pack expansion, then
12117 the Ith element resulting from the substituting is going to
12118 be a pack expansion as well. */
12119 if (ith_elem_is_expansion)
12120 t = make_pack_expansion (t, complain);
12122 return t;
12125 /* When the unexpanded parameter pack in a fold expression expands to an empty
12126 sequence, the value of the expression is as follows; the program is
12127 ill-formed if the operator is not listed in this table.
12129 && true
12130 || false
12131 , void() */
12133 tree
12134 expand_empty_fold (tree t, tsubst_flags_t complain)
12136 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12137 if (!FOLD_EXPR_MODIFY_P (t))
12138 switch (code)
12140 case TRUTH_ANDIF_EXPR:
12141 return boolean_true_node;
12142 case TRUTH_ORIF_EXPR:
12143 return boolean_false_node;
12144 case COMPOUND_EXPR:
12145 return void_node;
12146 default:
12147 break;
12150 if (complain & tf_error)
12151 error_at (location_of (t),
12152 "fold of empty expansion over %O", code);
12153 return error_mark_node;
12156 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12157 form an expression that combines the two terms using the
12158 operator of T. */
12160 static tree
12161 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12163 tree op = FOLD_EXPR_OP (t);
12164 tree_code code = (tree_code)TREE_INT_CST_LOW (op);
12166 // Handle compound assignment operators.
12167 if (FOLD_EXPR_MODIFY_P (t))
12168 return build_x_modify_expr (input_location, left, code, right, complain);
12170 switch (code)
12172 case COMPOUND_EXPR:
12173 return build_x_compound_expr (input_location, left, right, complain);
12174 default:
12175 return build_x_binary_op (input_location, code,
12176 left, TREE_CODE (left),
12177 right, TREE_CODE (right),
12178 /*overload=*/NULL,
12179 complain);
12183 /* Substitute ARGS into the pack of a fold expression T. */
12185 static inline tree
12186 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12188 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12191 /* Substitute ARGS into the pack of a fold expression T. */
12193 static inline tree
12194 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12196 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12199 /* Expand a PACK of arguments into a grouped as left fold.
12200 Given a pack containing elements A0, A1, ..., An and an
12201 operator @, this builds the expression:
12203 ((A0 @ A1) @ A2) ... @ An
12205 Note that PACK must not be empty.
12207 The operator is defined by the original fold expression T. */
12209 static tree
12210 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12212 tree left = TREE_VEC_ELT (pack, 0);
12213 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12215 tree right = TREE_VEC_ELT (pack, i);
12216 left = fold_expression (t, left, right, complain);
12218 return left;
12221 /* Substitute into a unary left fold expression. */
12223 static tree
12224 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12225 tree in_decl)
12227 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12228 if (pack == error_mark_node)
12229 return error_mark_node;
12230 if (PACK_EXPANSION_P (pack))
12232 tree r = copy_node (t);
12233 FOLD_EXPR_PACK (r) = pack;
12234 return r;
12236 if (TREE_VEC_LENGTH (pack) == 0)
12237 return expand_empty_fold (t, complain);
12238 else
12239 return expand_left_fold (t, pack, complain);
12242 /* Substitute into a binary left fold expression.
12244 Do ths by building a single (non-empty) vector of argumnts and
12245 building the expression from those elements. */
12247 static tree
12248 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12249 tree in_decl)
12251 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12252 if (pack == error_mark_node)
12253 return error_mark_node;
12254 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12255 if (init == error_mark_node)
12256 return error_mark_node;
12258 if (PACK_EXPANSION_P (pack))
12260 tree r = copy_node (t);
12261 FOLD_EXPR_PACK (r) = pack;
12262 FOLD_EXPR_INIT (r) = init;
12263 return r;
12266 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12267 TREE_VEC_ELT (vec, 0) = init;
12268 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12269 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12271 return expand_left_fold (t, vec, complain);
12274 /* Expand a PACK of arguments into a grouped as right fold.
12275 Given a pack containing elementns A0, A1, ..., and an
12276 operator @, this builds the expression:
12278 A0@ ... (An-2 @ (An-1 @ An))
12280 Note that PACK must not be empty.
12282 The operator is defined by the original fold expression T. */
12284 tree
12285 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12287 // Build the expression.
12288 int n = TREE_VEC_LENGTH (pack);
12289 tree right = TREE_VEC_ELT (pack, n - 1);
12290 for (--n; n != 0; --n)
12292 tree left = TREE_VEC_ELT (pack, n - 1);
12293 right = fold_expression (t, left, right, complain);
12295 return right;
12298 /* Substitute into a unary right fold expression. */
12300 static tree
12301 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12302 tree in_decl)
12304 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12305 if (pack == error_mark_node)
12306 return error_mark_node;
12307 if (PACK_EXPANSION_P (pack))
12309 tree r = copy_node (t);
12310 FOLD_EXPR_PACK (r) = pack;
12311 return r;
12313 if (TREE_VEC_LENGTH (pack) == 0)
12314 return expand_empty_fold (t, complain);
12315 else
12316 return expand_right_fold (t, pack, complain);
12319 /* Substitute into a binary right fold expression.
12321 Do ths by building a single (non-empty) vector of arguments and
12322 building the expression from those elements. */
12324 static tree
12325 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12326 tree in_decl)
12328 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12329 if (pack == error_mark_node)
12330 return error_mark_node;
12331 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12332 if (init == error_mark_node)
12333 return error_mark_node;
12335 if (PACK_EXPANSION_P (pack))
12337 tree r = copy_node (t);
12338 FOLD_EXPR_PACK (r) = pack;
12339 FOLD_EXPR_INIT (r) = init;
12340 return r;
12343 int n = TREE_VEC_LENGTH (pack);
12344 tree vec = make_tree_vec (n + 1);
12345 for (int i = 0; i < n; ++i)
12346 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12347 TREE_VEC_ELT (vec, n) = init;
12349 return expand_right_fold (t, vec, complain);
12352 /* Walk through the pattern of a pack expansion, adding everything in
12353 local_specializations to a list. */
12355 class el_data
12357 public:
12358 hash_set<tree> internal;
12359 tree extra;
12360 tsubst_flags_t complain;
12362 el_data (tsubst_flags_t c)
12363 : extra (NULL_TREE), complain (c) {}
12365 static tree
12366 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12368 el_data &data = *reinterpret_cast<el_data*>(data_);
12369 tree *extra = &data.extra;
12370 tsubst_flags_t complain = data.complain;
12372 if (TYPE_P (*tp) && typedef_variant_p (*tp))
12373 /* Remember local typedefs (85214). */
12374 tp = &TYPE_NAME (*tp);
12376 if (TREE_CODE (*tp) == DECL_EXPR)
12377 data.internal.add (DECL_EXPR_DECL (*tp));
12378 else if (tree spec = retrieve_local_specialization (*tp))
12380 if (data.internal.contains (*tp))
12381 /* Don't mess with variables declared within the pattern. */
12382 return NULL_TREE;
12383 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12385 /* Maybe pull out the PARM_DECL for a partial instantiation. */
12386 tree args = ARGUMENT_PACK_ARGS (spec);
12387 if (TREE_VEC_LENGTH (args) == 1)
12389 tree elt = TREE_VEC_ELT (args, 0);
12390 if (PACK_EXPANSION_P (elt))
12391 elt = PACK_EXPANSION_PATTERN (elt);
12392 if (DECL_PACK_P (elt))
12393 spec = elt;
12395 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12397 /* Handle lambda capture here, since we aren't doing any
12398 substitution now, and so tsubst_copy won't call
12399 process_outer_var_ref. */
12400 tree args = ARGUMENT_PACK_ARGS (spec);
12401 int len = TREE_VEC_LENGTH (args);
12402 for (int i = 0; i < len; ++i)
12404 tree arg = TREE_VEC_ELT (args, i);
12405 tree carg = arg;
12406 if (outer_automatic_var_p (arg))
12407 carg = process_outer_var_ref (arg, complain);
12408 if (carg != arg)
12410 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12411 proxies. */
12412 if (i == 0)
12414 spec = copy_node (spec);
12415 args = copy_node (args);
12416 SET_ARGUMENT_PACK_ARGS (spec, args);
12417 register_local_specialization (spec, *tp);
12419 TREE_VEC_ELT (args, i) = carg;
12424 if (outer_automatic_var_p (spec))
12425 spec = process_outer_var_ref (spec, complain);
12426 *extra = tree_cons (*tp, spec, *extra);
12428 return NULL_TREE;
12430 static tree
12431 extract_local_specs (tree pattern, tsubst_flags_t complain)
12433 el_data data (complain);
12434 cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
12435 return data.extra;
12438 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12439 for use in PACK_EXPANSION_EXTRA_ARGS. */
12441 tree
12442 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12444 tree extra = args;
12445 if (local_specializations)
12446 if (tree locals = extract_local_specs (pattern, complain))
12447 extra = tree_cons (NULL_TREE, extra, locals);
12448 return extra;
12451 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12452 normal template args to ARGS. */
12454 tree
12455 add_extra_args (tree extra, tree args)
12457 if (extra && TREE_CODE (extra) == TREE_LIST)
12459 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12461 /* The partial instantiation involved local declarations collected in
12462 extract_local_specs; map from the general template to our local
12463 context. */
12464 tree gen = TREE_PURPOSE (elt);
12465 tree inst = TREE_VALUE (elt);
12466 if (DECL_P (inst))
12467 if (tree local = retrieve_local_specialization (inst))
12468 inst = local;
12469 /* else inst is already a full instantiation of the pack. */
12470 register_local_specialization (inst, gen);
12472 gcc_assert (!TREE_PURPOSE (extra));
12473 extra = TREE_VALUE (extra);
12475 return add_to_template_args (extra, args);
12478 /* Substitute ARGS into T, which is an pack expansion
12479 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12480 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12481 (if only a partial substitution could be performed) or
12482 ERROR_MARK_NODE if there was an error. */
12483 tree
12484 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12485 tree in_decl)
12487 tree pattern;
12488 tree pack, packs = NULL_TREE;
12489 bool unsubstituted_packs = false;
12490 bool unsubstituted_fn_pack = false;
12491 int i, len = -1;
12492 tree result;
12493 hash_map<tree, tree> *saved_local_specializations = NULL;
12494 bool need_local_specializations = false;
12495 int levels;
12497 gcc_assert (PACK_EXPANSION_P (t));
12498 pattern = PACK_EXPANSION_PATTERN (t);
12500 /* Add in any args remembered from an earlier partial instantiation. */
12501 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12503 levels = TMPL_ARGS_DEPTH (args);
12505 /* Determine the argument packs that will instantiate the parameter
12506 packs used in the expansion expression. While we're at it,
12507 compute the number of arguments to be expanded and make sure it
12508 is consistent. */
12509 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12510 pack = TREE_CHAIN (pack))
12512 tree parm_pack = TREE_VALUE (pack);
12513 tree arg_pack = NULL_TREE;
12514 tree orig_arg = NULL_TREE;
12515 int level = 0;
12517 if (TREE_CODE (parm_pack) == BASES)
12519 gcc_assert (parm_pack == pattern);
12520 if (BASES_DIRECT (parm_pack))
12521 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12522 args, complain,
12523 in_decl, false),
12524 complain);
12525 else
12526 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12527 args, complain, in_decl,
12528 false), complain);
12530 else if (builtin_pack_call_p (parm_pack))
12532 if (parm_pack != pattern)
12534 if (complain & tf_error)
12535 sorry ("%qE is not the entire pattern of the pack expansion",
12536 parm_pack);
12537 return error_mark_node;
12539 return expand_builtin_pack_call (parm_pack, args,
12540 complain, in_decl);
12542 else if (TREE_CODE (parm_pack) == PARM_DECL)
12544 /* We know we have correct local_specializations if this
12545 expansion is at function scope, or if we're dealing with a
12546 local parameter in a requires expression; for the latter,
12547 tsubst_requires_expr set it up appropriately. */
12548 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12549 arg_pack = retrieve_local_specialization (parm_pack);
12550 else
12551 /* We can't rely on local_specializations for a parameter
12552 name used later in a function declaration (such as in a
12553 late-specified return type). Even if it exists, it might
12554 have the wrong value for a recursive call. */
12555 need_local_specializations = true;
12557 if (!arg_pack)
12559 /* This parameter pack was used in an unevaluated context. Just
12560 make a dummy decl, since it's only used for its type. */
12561 ++cp_unevaluated_operand;
12562 arg_pack = tsubst_decl (parm_pack, args, complain);
12563 --cp_unevaluated_operand;
12564 if (arg_pack && DECL_PACK_P (arg_pack))
12565 /* Partial instantiation of the parm_pack, we can't build
12566 up an argument pack yet. */
12567 arg_pack = NULL_TREE;
12568 else
12569 arg_pack = make_fnparm_pack (arg_pack);
12571 else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12572 /* This argument pack isn't fully instantiated yet. We set this
12573 flag rather than clear arg_pack because we do want to do the
12574 optimization below, and we don't want to substitute directly
12575 into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12576 where it isn't expected). */
12577 unsubstituted_fn_pack = true;
12579 else if (is_capture_proxy (parm_pack))
12581 arg_pack = retrieve_local_specialization (parm_pack);
12582 if (argument_pack_element_is_expansion_p (arg_pack, 0))
12583 unsubstituted_fn_pack = true;
12585 else
12587 int idx;
12588 template_parm_level_and_index (parm_pack, &level, &idx);
12589 if (level <= levels)
12590 arg_pack = TMPL_ARG (args, level, idx);
12593 orig_arg = arg_pack;
12594 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12595 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12597 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12598 /* This can only happen if we forget to expand an argument
12599 pack somewhere else. Just return an error, silently. */
12601 result = make_tree_vec (1);
12602 TREE_VEC_ELT (result, 0) = error_mark_node;
12603 return result;
12606 if (arg_pack)
12608 int my_len =
12609 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12611 /* Don't bother trying to do a partial substitution with
12612 incomplete packs; we'll try again after deduction. */
12613 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12614 return t;
12616 if (len < 0)
12617 len = my_len;
12618 else if (len != my_len
12619 && !unsubstituted_fn_pack)
12621 if (!(complain & tf_error))
12622 /* Fail quietly. */;
12623 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12624 error ("mismatched argument pack lengths while expanding %qT",
12625 pattern);
12626 else
12627 error ("mismatched argument pack lengths while expanding %qE",
12628 pattern);
12629 return error_mark_node;
12632 /* Keep track of the parameter packs and their corresponding
12633 argument packs. */
12634 packs = tree_cons (parm_pack, arg_pack, packs);
12635 TREE_TYPE (packs) = orig_arg;
12637 else
12639 /* We can't substitute for this parameter pack. We use a flag as
12640 well as the missing_level counter because function parameter
12641 packs don't have a level. */
12642 if (!(processing_template_decl || is_auto (parm_pack)))
12644 gcc_unreachable ();
12646 gcc_assert (processing_template_decl || is_auto (parm_pack));
12647 unsubstituted_packs = true;
12651 /* If the expansion is just T..., return the matching argument pack, unless
12652 we need to call convert_from_reference on all the elements. This is an
12653 important optimization; see c++/68422. */
12654 if (!unsubstituted_packs
12655 && TREE_PURPOSE (packs) == pattern)
12657 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12659 /* If the argument pack is a single pack expansion, pull it out. */
12660 if (TREE_VEC_LENGTH (args) == 1
12661 && pack_expansion_args_count (args))
12662 return TREE_VEC_ELT (args, 0);
12664 /* Types need no adjustment, nor does sizeof..., and if we still have
12665 some pack expansion args we won't do anything yet. */
12666 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12667 || PACK_EXPANSION_SIZEOF_P (t)
12668 || pack_expansion_args_count (args))
12669 return args;
12670 /* Also optimize expression pack expansions if we can tell that the
12671 elements won't have reference type. */
12672 tree type = TREE_TYPE (pattern);
12673 if (type && !TYPE_REF_P (type)
12674 && !PACK_EXPANSION_P (type)
12675 && !WILDCARD_TYPE_P (type))
12676 return args;
12677 /* Otherwise use the normal path so we get convert_from_reference. */
12680 /* We cannot expand this expansion expression, because we don't have
12681 all of the argument packs we need. */
12682 if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12684 /* We got some full packs, but we can't substitute them in until we
12685 have values for all the packs. So remember these until then. */
12687 t = make_pack_expansion (pattern, complain);
12688 PACK_EXPANSION_EXTRA_ARGS (t)
12689 = build_extra_args (pattern, args, complain);
12690 return t;
12692 else if (unsubstituted_packs)
12694 /* There were no real arguments, we're just replacing a parameter
12695 pack with another version of itself. Substitute into the
12696 pattern and return a PACK_EXPANSION_*. The caller will need to
12697 deal with that. */
12698 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12699 t = tsubst_expr (pattern, args, complain, in_decl,
12700 /*integral_constant_expression_p=*/false);
12701 else
12702 t = tsubst (pattern, args, complain, in_decl);
12703 t = make_pack_expansion (t, complain);
12704 return t;
12707 gcc_assert (len >= 0);
12709 if (need_local_specializations)
12711 /* We're in a late-specified return type, so create our own local
12712 specializations map; the current map is either NULL or (in the
12713 case of recursive unification) might have bindings that we don't
12714 want to use or alter. */
12715 saved_local_specializations = local_specializations;
12716 local_specializations = new hash_map<tree, tree>;
12719 /* For each argument in each argument pack, substitute into the
12720 pattern. */
12721 result = make_tree_vec (len);
12722 tree elem_args = copy_template_args (args);
12723 for (i = 0; i < len; ++i)
12725 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12727 elem_args, complain,
12728 in_decl);
12729 TREE_VEC_ELT (result, i) = t;
12730 if (t == error_mark_node)
12732 result = error_mark_node;
12733 break;
12737 /* Update ARGS to restore the substitution from parameter packs to
12738 their argument packs. */
12739 for (pack = packs; pack; pack = TREE_CHAIN (pack))
12741 tree parm = TREE_PURPOSE (pack);
12743 if (TREE_CODE (parm) == PARM_DECL
12744 || VAR_P (parm)
12745 || TREE_CODE (parm) == FIELD_DECL)
12746 register_local_specialization (TREE_TYPE (pack), parm);
12747 else
12749 int idx, level;
12751 if (TREE_VALUE (pack) == NULL_TREE)
12752 continue;
12754 template_parm_level_and_index (parm, &level, &idx);
12756 /* Update the corresponding argument. */
12757 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12758 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12759 TREE_TYPE (pack);
12760 else
12761 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12765 if (need_local_specializations)
12767 delete local_specializations;
12768 local_specializations = saved_local_specializations;
12771 /* If the dependent pack arguments were such that we end up with only a
12772 single pack expansion again, there's no need to keep it in a TREE_VEC. */
12773 if (len == 1 && TREE_CODE (result) == TREE_VEC
12774 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12775 return TREE_VEC_ELT (result, 0);
12777 return result;
12780 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12781 TMPL. We do this using DECL_PARM_INDEX, which should work even with
12782 parameter packs; all parms generated from a function parameter pack will
12783 have the same DECL_PARM_INDEX. */
12785 tree
12786 get_pattern_parm (tree parm, tree tmpl)
12788 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12789 tree patparm;
12791 if (DECL_ARTIFICIAL (parm))
12793 for (patparm = DECL_ARGUMENTS (pattern);
12794 patparm; patparm = DECL_CHAIN (patparm))
12795 if (DECL_ARTIFICIAL (patparm)
12796 && DECL_NAME (parm) == DECL_NAME (patparm))
12797 break;
12799 else
12801 patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12802 patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12803 gcc_assert (DECL_PARM_INDEX (patparm)
12804 == DECL_PARM_INDEX (parm));
12807 return patparm;
12810 /* Make an argument pack out of the TREE_VEC VEC. */
12812 static tree
12813 make_argument_pack (tree vec)
12815 tree pack;
12816 tree elt = TREE_VEC_ELT (vec, 0);
12817 if (TYPE_P (elt))
12818 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12819 else
12821 pack = make_node (NONTYPE_ARGUMENT_PACK);
12822 TREE_CONSTANT (pack) = 1;
12824 SET_ARGUMENT_PACK_ARGS (pack, vec);
12825 return pack;
12828 /* Return an exact copy of template args T that can be modified
12829 independently. */
12831 static tree
12832 copy_template_args (tree t)
12834 if (t == error_mark_node)
12835 return t;
12837 int len = TREE_VEC_LENGTH (t);
12838 tree new_vec = make_tree_vec (len);
12840 for (int i = 0; i < len; ++i)
12842 tree elt = TREE_VEC_ELT (t, i);
12843 if (elt && TREE_CODE (elt) == TREE_VEC)
12844 elt = copy_template_args (elt);
12845 TREE_VEC_ELT (new_vec, i) = elt;
12848 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12849 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12851 return new_vec;
12854 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
12856 tree
12857 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
12858 tree in_decl)
12860 /* Substitute into each of the arguments. */
12861 tree new_arg = TYPE_P (orig_arg)
12862 ? cxx_make_type (TREE_CODE (orig_arg))
12863 : make_node (TREE_CODE (orig_arg));
12865 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12866 args, complain, in_decl);
12867 if (pack_args == error_mark_node)
12868 new_arg = error_mark_node;
12869 else
12870 SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12872 if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12873 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12875 return new_arg;
12878 /* Substitute ARGS into the vector or list of template arguments T. */
12880 tree
12881 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12883 tree orig_t = t;
12884 int len, need_new = 0, i, expanded_len_adjust = 0, out;
12885 tree *elts;
12887 if (t == error_mark_node)
12888 return error_mark_node;
12890 len = TREE_VEC_LENGTH (t);
12891 elts = XALLOCAVEC (tree, len);
12893 for (i = 0; i < len; i++)
12895 tree orig_arg = TREE_VEC_ELT (t, i);
12896 tree new_arg;
12898 if (TREE_CODE (orig_arg) == TREE_VEC)
12899 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12900 else if (PACK_EXPANSION_P (orig_arg))
12902 /* Substitute into an expansion expression. */
12903 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12905 if (TREE_CODE (new_arg) == TREE_VEC)
12906 /* Add to the expanded length adjustment the number of
12907 expanded arguments. We subtract one from this
12908 measurement, because the argument pack expression
12909 itself is already counted as 1 in
12910 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12911 the argument pack is empty. */
12912 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12914 else if (ARGUMENT_PACK_P (orig_arg))
12915 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
12916 else
12917 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12919 if (new_arg == error_mark_node)
12920 return error_mark_node;
12922 elts[i] = new_arg;
12923 if (new_arg != orig_arg)
12924 need_new = 1;
12927 if (!need_new)
12928 return t;
12930 /* Make space for the expanded arguments coming from template
12931 argument packs. */
12932 t = make_tree_vec (len + expanded_len_adjust);
12933 /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12934 arguments for a member template.
12935 In that case each TREE_VEC in ORIG_T represents a level of template
12936 arguments, and ORIG_T won't carry any non defaulted argument count.
12937 It will rather be the nested TREE_VECs that will carry one.
12938 In other words, ORIG_T carries a non defaulted argument count only
12939 if it doesn't contain any nested TREE_VEC. */
12940 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12942 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12943 count += expanded_len_adjust;
12944 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12946 for (i = 0, out = 0; i < len; i++)
12948 if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12949 || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12950 && TREE_CODE (elts[i]) == TREE_VEC)
12952 int idx;
12954 /* Now expand the template argument pack "in place". */
12955 for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12956 TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12958 else
12960 TREE_VEC_ELT (t, out) = elts[i];
12961 out++;
12965 return t;
12968 /* Substitute ARGS into one level PARMS of template parameters. */
12970 static tree
12971 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12973 if (parms == error_mark_node)
12974 return error_mark_node;
12976 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12978 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12980 tree tuple = TREE_VEC_ELT (parms, i);
12982 if (tuple == error_mark_node)
12983 continue;
12985 TREE_VEC_ELT (new_vec, i) =
12986 tsubst_template_parm (tuple, args, complain);
12989 return new_vec;
12992 /* Return the result of substituting ARGS into the template parameters
12993 given by PARMS. If there are m levels of ARGS and m + n levels of
12994 PARMS, then the result will contain n levels of PARMS. For
12995 example, if PARMS is `template <class T> template <class U>
12996 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12997 result will be `template <int*, double, class V>'. */
12999 static tree
13000 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13002 tree r = NULL_TREE;
13003 tree* new_parms;
13005 /* When substituting into a template, we must set
13006 PROCESSING_TEMPLATE_DECL as the template parameters may be
13007 dependent if they are based on one-another, and the dependency
13008 predicates are short-circuit outside of templates. */
13009 ++processing_template_decl;
13011 for (new_parms = &r;
13012 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13013 new_parms = &(TREE_CHAIN (*new_parms)),
13014 parms = TREE_CHAIN (parms))
13016 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13017 args, complain);
13018 *new_parms =
13019 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13020 - TMPL_ARGS_DEPTH (args)),
13021 new_vec, NULL_TREE);
13024 --processing_template_decl;
13026 return r;
13029 /* Return the result of substituting ARGS into one template parameter
13030 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13031 parameter and which TREE_PURPOSE is the default argument of the
13032 template parameter. */
13034 static tree
13035 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13037 tree default_value, parm_decl;
13039 if (args == NULL_TREE
13040 || t == NULL_TREE
13041 || t == error_mark_node)
13042 return t;
13044 gcc_assert (TREE_CODE (t) == TREE_LIST);
13046 default_value = TREE_PURPOSE (t);
13047 parm_decl = TREE_VALUE (t);
13048 tree constraint = TEMPLATE_PARM_CONSTRAINTS (t);
13050 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13051 if (TREE_CODE (parm_decl) == PARM_DECL
13052 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13053 parm_decl = error_mark_node;
13054 default_value = tsubst_template_arg (default_value, args,
13055 complain, NULL_TREE);
13056 constraint = tsubst_constraint (constraint, args, complain, NULL_TREE);
13058 tree r = build_tree_list (default_value, parm_decl);
13059 TEMPLATE_PARM_CONSTRAINTS (r) = constraint;
13060 return r;
13063 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13064 type T. If T is not an aggregate or enumeration type, it is
13065 handled as if by tsubst. IN_DECL is as for tsubst. If
13066 ENTERING_SCOPE is nonzero, T is the context for a template which
13067 we are presently tsubst'ing. Return the substituted value. */
13069 static tree
13070 tsubst_aggr_type (tree t,
13071 tree args,
13072 tsubst_flags_t complain,
13073 tree in_decl,
13074 int entering_scope)
13076 if (t == NULL_TREE)
13077 return NULL_TREE;
13079 switch (TREE_CODE (t))
13081 case RECORD_TYPE:
13082 if (TYPE_PTRMEMFUNC_P (t))
13083 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13085 /* Fall through. */
13086 case ENUMERAL_TYPE:
13087 case UNION_TYPE:
13088 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13090 tree argvec;
13091 tree context;
13092 tree r;
13094 /* In "sizeof(X<I>)" we need to evaluate "I". */
13095 cp_evaluated ev;
13097 /* First, determine the context for the type we are looking
13098 up. */
13099 context = TYPE_CONTEXT (t);
13100 if (context && TYPE_P (context))
13102 context = tsubst_aggr_type (context, args, complain,
13103 in_decl, /*entering_scope=*/1);
13104 /* If context is a nested class inside a class template,
13105 it may still need to be instantiated (c++/33959). */
13106 context = complete_type (context);
13109 /* Then, figure out what arguments are appropriate for the
13110 type we are trying to find. For example, given:
13112 template <class T> struct S;
13113 template <class T, class U> void f(T, U) { S<U> su; }
13115 and supposing that we are instantiating f<int, double>,
13116 then our ARGS will be {int, double}, but, when looking up
13117 S we only want {double}. */
13118 argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13119 complain, in_decl);
13120 if (argvec == error_mark_node)
13121 r = error_mark_node;
13122 else
13124 r = lookup_template_class (t, argvec, in_decl, context,
13125 entering_scope, complain);
13126 r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13129 return r;
13131 else
13132 /* This is not a template type, so there's nothing to do. */
13133 return t;
13135 default:
13136 return tsubst (t, args, complain, in_decl);
13140 static GTY((cache)) tree_cache_map *defarg_inst;
13142 /* Substitute into the default argument ARG (a default argument for
13143 FN), which has the indicated TYPE. */
13145 tree
13146 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13147 tsubst_flags_t complain)
13149 int errs = errorcount + sorrycount;
13151 /* This can happen in invalid code. */
13152 if (TREE_CODE (arg) == DEFERRED_PARSE)
13153 return arg;
13155 tree parm = FUNCTION_FIRST_USER_PARM (fn);
13156 parm = chain_index (parmnum, parm);
13157 tree parmtype = TREE_TYPE (parm);
13158 if (DECL_BY_REFERENCE (parm))
13159 parmtype = TREE_TYPE (parmtype);
13160 if (parmtype == error_mark_node)
13161 return error_mark_node;
13163 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13165 tree *slot;
13166 if (defarg_inst && (slot = defarg_inst->get (parm)))
13167 return *slot;
13169 /* This default argument came from a template. Instantiate the
13170 default argument here, not in tsubst. In the case of
13171 something like:
13173 template <class T>
13174 struct S {
13175 static T t();
13176 void f(T = t());
13179 we must be careful to do name lookup in the scope of S<T>,
13180 rather than in the current class. */
13181 push_to_top_level ();
13182 push_access_scope (fn);
13183 push_deferring_access_checks (dk_no_deferred);
13184 start_lambda_scope (parm);
13186 /* The default argument expression may cause implicitly defined
13187 member functions to be synthesized, which will result in garbage
13188 collection. We must treat this situation as if we were within
13189 the body of function so as to avoid collecting live data on the
13190 stack. */
13191 ++function_depth;
13192 arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13193 complain, NULL_TREE,
13194 /*integral_constant_expression_p=*/false);
13195 --function_depth;
13197 finish_lambda_scope ();
13199 /* Make sure the default argument is reasonable. */
13200 arg = check_default_argument (type, arg, complain);
13202 if (errorcount+sorrycount > errs
13203 && (complain & tf_warning_or_error))
13204 inform (input_location,
13205 " when instantiating default argument for call to %qD", fn);
13207 pop_deferring_access_checks ();
13208 pop_access_scope (fn);
13209 pop_from_top_level ();
13211 if (arg != error_mark_node && !cp_unevaluated_operand)
13213 if (!defarg_inst)
13214 defarg_inst = tree_cache_map::create_ggc (37);
13215 defarg_inst->put (parm, arg);
13218 return arg;
13221 /* Substitute into all the default arguments for FN. */
13223 static void
13224 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13226 tree arg;
13227 tree tmpl_args;
13229 tmpl_args = DECL_TI_ARGS (fn);
13231 /* If this function is not yet instantiated, we certainly don't need
13232 its default arguments. */
13233 if (uses_template_parms (tmpl_args))
13234 return;
13235 /* Don't do this again for clones. */
13236 if (DECL_CLONED_FUNCTION_P (fn))
13237 return;
13239 int i = 0;
13240 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
13241 arg;
13242 arg = TREE_CHAIN (arg), ++i)
13243 if (TREE_PURPOSE (arg))
13244 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
13245 TREE_VALUE (arg),
13246 TREE_PURPOSE (arg),
13247 complain);
13250 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
13251 static GTY((cache)) tree_cache_map *explicit_specifier_map;
13253 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
13255 void
13256 store_explicit_specifier (tree v, tree t)
13258 if (!explicit_specifier_map)
13259 explicit_specifier_map = tree_cache_map::create_ggc (37);
13260 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
13261 explicit_specifier_map->put (v, t);
13264 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
13266 static tree
13267 lookup_explicit_specifier (tree v)
13269 return *explicit_specifier_map->get (v);
13272 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
13274 static tree
13275 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
13276 tree lambda_fntype)
13278 tree gen_tmpl, argvec;
13279 hashval_t hash = 0;
13280 tree in_decl = t;
13282 /* Nobody should be tsubst'ing into non-template functions. */
13283 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
13285 if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
13287 /* If T is not dependent, just return it. */
13288 if (!uses_template_parms (DECL_TI_ARGS (t))
13289 && !LAMBDA_FUNCTION_P (t))
13290 return t;
13292 /* Calculate the most general template of which R is a
13293 specialization. */
13294 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
13296 /* We're substituting a lambda function under tsubst_lambda_expr but not
13297 directly from it; find the matching function we're already inside.
13298 But don't do this if T is a generic lambda with a single level of
13299 template parms, as in that case we're doing a normal instantiation. */
13300 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
13301 && (!generic_lambda_fn_p (t)
13302 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
13303 return enclosing_instantiation_of (t);
13305 /* Calculate the complete set of arguments used to
13306 specialize R. */
13307 argvec = tsubst_template_args (DECL_TI_ARGS
13308 (DECL_TEMPLATE_RESULT
13309 (DECL_TI_TEMPLATE (t))),
13310 args, complain, in_decl);
13311 if (argvec == error_mark_node)
13312 return error_mark_node;
13314 /* Check to see if we already have this specialization. */
13315 if (!lambda_fntype)
13317 hash = hash_tmpl_and_args (gen_tmpl, argvec);
13318 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
13319 return spec;
13322 /* We can see more levels of arguments than parameters if
13323 there was a specialization of a member template, like
13324 this:
13326 template <class T> struct S { template <class U> void f(); }
13327 template <> template <class U> void S<int>::f(U);
13329 Here, we'll be substituting into the specialization,
13330 because that's where we can find the code we actually
13331 want to generate, but we'll have enough arguments for
13332 the most general template.
13334 We also deal with the peculiar case:
13336 template <class T> struct S {
13337 template <class U> friend void f();
13339 template <class U> void f() {}
13340 template S<int>;
13341 template void f<double>();
13343 Here, the ARGS for the instantiation of will be {int,
13344 double}. But, we only need as many ARGS as there are
13345 levels of template parameters in CODE_PATTERN. We are
13346 careful not to get fooled into reducing the ARGS in
13347 situations like:
13349 template <class T> struct S { template <class U> void f(U); }
13350 template <class T> template <> void S<T>::f(int) {}
13352 which we can spot because the pattern will be a
13353 specialization in this case. */
13354 int args_depth = TMPL_ARGS_DEPTH (args);
13355 int parms_depth =
13356 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
13358 if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
13359 args = get_innermost_template_args (args, parms_depth);
13361 else
13363 /* This special case arises when we have something like this:
13365 template <class T> struct S {
13366 friend void f<int>(int, double);
13369 Here, the DECL_TI_TEMPLATE for the friend declaration
13370 will be an IDENTIFIER_NODE. We are being called from
13371 tsubst_friend_function, and we want only to create a
13372 new decl (R) with appropriate types so that we can call
13373 determine_specialization. */
13374 gen_tmpl = NULL_TREE;
13375 argvec = NULL_TREE;
13378 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13379 : NULL_TREE);
13380 tree ctx = closure ? closure : DECL_CONTEXT (t);
13381 bool member = ctx && TYPE_P (ctx);
13383 if (member && !closure)
13384 ctx = tsubst_aggr_type (ctx, args,
13385 complain, t, /*entering_scope=*/1);
13387 tree type = (lambda_fntype ? lambda_fntype
13388 : tsubst (TREE_TYPE (t), args,
13389 complain | tf_fndecl_type, in_decl));
13390 if (type == error_mark_node)
13391 return error_mark_node;
13393 /* If we hit excessive deduction depth, the type is bogus even if
13394 it isn't error_mark_node, so don't build a decl. */
13395 if (excessive_deduction_depth)
13396 return error_mark_node;
13398 /* We do NOT check for matching decls pushed separately at this
13399 point, as they may not represent instantiations of this
13400 template, and in any case are considered separate under the
13401 discrete model. */
13402 tree r = copy_decl (t);
13403 DECL_USE_TEMPLATE (r) = 0;
13404 TREE_TYPE (r) = type;
13405 /* Clear out the mangled name and RTL for the instantiation. */
13406 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13407 SET_DECL_RTL (r, NULL);
13408 /* Leave DECL_INITIAL set on deleted instantiations. */
13409 if (!DECL_DELETED_FN (r))
13410 DECL_INITIAL (r) = NULL_TREE;
13411 DECL_CONTEXT (r) = ctx;
13413 /* Handle explicit(dependent-expr). */
13414 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
13416 tree spec = lookup_explicit_specifier (t);
13417 spec = tsubst_copy_and_build (spec, args, complain, in_decl,
13418 /*function_p=*/false,
13419 /*i_c_e_p=*/true);
13420 spec = build_explicit_specifier (spec, complain);
13421 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
13424 /* OpenMP UDRs have the only argument a reference to the declared
13425 type. We want to diagnose if the declared type is a reference,
13426 which is invalid, but as references to references are usually
13427 quietly merged, diagnose it here. */
13428 if (DECL_OMP_DECLARE_REDUCTION_P (t))
13430 tree argtype
13431 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
13432 argtype = tsubst (argtype, args, complain, in_decl);
13433 if (TYPE_REF_P (argtype))
13434 error_at (DECL_SOURCE_LOCATION (t),
13435 "reference type %qT in "
13436 "%<#pragma omp declare reduction%>", argtype);
13437 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
13438 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
13439 argtype);
13442 if (member && DECL_CONV_FN_P (r))
13443 /* Type-conversion operator. Reconstruct the name, in
13444 case it's the name of one of the template's parameters. */
13445 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
13447 tree parms = DECL_ARGUMENTS (t);
13448 if (closure)
13449 parms = DECL_CHAIN (parms);
13450 parms = tsubst (parms, args, complain, t);
13451 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
13452 DECL_CONTEXT (parm) = r;
13453 if (closure)
13455 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
13456 DECL_CHAIN (tparm) = parms;
13457 parms = tparm;
13459 DECL_ARGUMENTS (r) = parms;
13460 DECL_RESULT (r) = NULL_TREE;
13462 TREE_STATIC (r) = 0;
13463 TREE_PUBLIC (r) = TREE_PUBLIC (t);
13464 DECL_EXTERNAL (r) = 1;
13465 /* If this is an instantiation of a function with internal
13466 linkage, we already know what object file linkage will be
13467 assigned to the instantiation. */
13468 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13469 DECL_DEFER_OUTPUT (r) = 0;
13470 DECL_CHAIN (r) = NULL_TREE;
13471 DECL_PENDING_INLINE_INFO (r) = 0;
13472 DECL_PENDING_INLINE_P (r) = 0;
13473 DECL_SAVED_TREE (r) = NULL_TREE;
13474 DECL_STRUCT_FUNCTION (r) = NULL;
13475 TREE_USED (r) = 0;
13476 /* We'll re-clone as appropriate in instantiate_template. */
13477 DECL_CLONED_FUNCTION (r) = NULL_TREE;
13479 /* If we aren't complaining now, return on error before we register
13480 the specialization so that we'll complain eventually. */
13481 if ((complain & tf_error) == 0
13482 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13483 && !grok_op_properties (r, /*complain=*/false))
13484 return error_mark_node;
13486 /* Associate the constraints directly with the instantiation. We
13487 don't substitute through the constraints; that's only done when
13488 they are checked. */
13489 if (tree ci = get_constraints (t))
13490 set_constraints (r, ci);
13492 if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13493 SET_DECL_FRIEND_CONTEXT (r,
13494 tsubst (DECL_FRIEND_CONTEXT (t),
13495 args, complain, in_decl));
13497 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
13498 this in the special friend case mentioned above where
13499 GEN_TMPL is NULL. */
13500 if (gen_tmpl && !closure)
13502 DECL_TEMPLATE_INFO (r)
13503 = build_template_info (gen_tmpl, argvec);
13504 SET_DECL_IMPLICIT_INSTANTIATION (r);
13506 tree new_r
13507 = register_specialization (r, gen_tmpl, argvec, false, hash);
13508 if (new_r != r)
13509 /* We instantiated this while substituting into
13510 the type earlier (template/friend54.C). */
13511 return new_r;
13513 /* We're not supposed to instantiate default arguments
13514 until they are called, for a template. But, for a
13515 declaration like:
13517 template <class T> void f ()
13518 { extern void g(int i = T()); }
13520 we should do the substitution when the template is
13521 instantiated. We handle the member function case in
13522 instantiate_class_template since the default arguments
13523 might refer to other members of the class. */
13524 if (!member
13525 && !PRIMARY_TEMPLATE_P (gen_tmpl)
13526 && !uses_template_parms (argvec))
13527 tsubst_default_arguments (r, complain);
13529 else
13530 DECL_TEMPLATE_INFO (r) = NULL_TREE;
13532 /* Copy the list of befriending classes. */
13533 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13534 *friends;
13535 friends = &TREE_CHAIN (*friends))
13537 *friends = copy_node (*friends);
13538 TREE_VALUE (*friends)
13539 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13542 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13544 maybe_retrofit_in_chrg (r);
13545 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13546 return error_mark_node;
13547 /* If this is an instantiation of a member template, clone it.
13548 If it isn't, that'll be handled by
13549 clone_constructors_and_destructors. */
13550 if (PRIMARY_TEMPLATE_P (gen_tmpl))
13551 clone_function_decl (r, /*update_methods=*/false);
13553 else if ((complain & tf_error) != 0
13554 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13555 && !grok_op_properties (r, /*complain=*/true))
13556 return error_mark_node;
13558 /* Possibly limit visibility based on template args. */
13559 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13560 if (DECL_VISIBILITY_SPECIFIED (t))
13562 DECL_VISIBILITY_SPECIFIED (r) = 0;
13563 DECL_ATTRIBUTES (r)
13564 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13566 determine_visibility (r);
13567 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13568 && !processing_template_decl)
13569 defaulted_late_check (r);
13571 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13572 args, complain, in_decl);
13573 return r;
13576 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
13578 static tree
13579 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13580 tree lambda_fntype)
13582 /* We can get here when processing a member function template,
13583 member class template, or template template parameter. */
13584 tree decl = DECL_TEMPLATE_RESULT (t);
13585 tree in_decl = t;
13586 tree spec;
13587 tree tmpl_args;
13588 tree full_args;
13589 tree r;
13590 hashval_t hash = 0;
13592 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13594 /* Template template parameter is treated here. */
13595 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13596 if (new_type == error_mark_node)
13597 r = error_mark_node;
13598 /* If we get a real template back, return it. This can happen in
13599 the context of most_specialized_partial_spec. */
13600 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13601 r = new_type;
13602 else
13603 /* The new TEMPLATE_DECL was built in
13604 reduce_template_parm_level. */
13605 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13606 return r;
13609 if (!lambda_fntype)
13611 /* We might already have an instance of this template.
13612 The ARGS are for the surrounding class type, so the
13613 full args contain the tsubst'd args for the context,
13614 plus the innermost args from the template decl. */
13615 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13616 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13617 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13618 /* Because this is a template, the arguments will still be
13619 dependent, even after substitution. If
13620 PROCESSING_TEMPLATE_DECL is not set, the dependency
13621 predicates will short-circuit. */
13622 ++processing_template_decl;
13623 full_args = tsubst_template_args (tmpl_args, args,
13624 complain, in_decl);
13625 --processing_template_decl;
13626 if (full_args == error_mark_node)
13627 return error_mark_node;
13629 /* If this is a default template template argument,
13630 tsubst might not have changed anything. */
13631 if (full_args == tmpl_args)
13632 return t;
13634 hash = hash_tmpl_and_args (t, full_args);
13635 spec = retrieve_specialization (t, full_args, hash);
13636 if (spec != NULL_TREE)
13638 if (TYPE_P (spec))
13639 /* Type partial instantiations are stored as the type by
13640 lookup_template_class_1, not here as the template. */
13641 spec = CLASSTYPE_TI_TEMPLATE (spec);
13642 return spec;
13646 /* Make a new template decl. It will be similar to the
13647 original, but will record the current template arguments.
13648 We also create a new function declaration, which is just
13649 like the old one, but points to this new template, rather
13650 than the old one. */
13651 r = copy_decl (t);
13652 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13653 DECL_CHAIN (r) = NULL_TREE;
13655 // Build new template info linking to the original template decl.
13656 if (!lambda_fntype)
13658 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13659 SET_DECL_IMPLICIT_INSTANTIATION (r);
13661 else
13662 DECL_TEMPLATE_INFO (r) = NULL_TREE;
13664 /* The template parameters for this new template are all the
13665 template parameters for the old template, except the
13666 outermost level of parameters. */
13667 DECL_TEMPLATE_PARMS (r)
13668 = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13669 complain);
13671 if (TREE_CODE (decl) == TYPE_DECL
13672 && !TYPE_DECL_ALIAS_P (decl))
13674 tree new_type;
13675 ++processing_template_decl;
13676 new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13677 --processing_template_decl;
13678 if (new_type == error_mark_node)
13679 return error_mark_node;
13681 TREE_TYPE (r) = new_type;
13682 /* For a partial specialization, we need to keep pointing to
13683 the primary template. */
13684 if (!DECL_TEMPLATE_SPECIALIZATION (t))
13685 CLASSTYPE_TI_TEMPLATE (new_type) = r;
13686 DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13687 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13688 DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13690 else
13692 tree new_decl;
13693 ++processing_template_decl;
13694 if (TREE_CODE (decl) == FUNCTION_DECL)
13695 new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13696 else
13697 new_decl = tsubst (decl, args, complain, in_decl);
13698 --processing_template_decl;
13699 if (new_decl == error_mark_node)
13700 return error_mark_node;
13702 DECL_TEMPLATE_RESULT (r) = new_decl;
13703 TREE_TYPE (r) = TREE_TYPE (new_decl);
13704 DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13705 if (lambda_fntype)
13707 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13708 DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13710 else
13712 DECL_TI_TEMPLATE (new_decl) = r;
13713 DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13717 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13718 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13720 if (PRIMARY_TEMPLATE_P (t))
13721 DECL_PRIMARY_TEMPLATE (r) = r;
13723 if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13724 && !lambda_fntype)
13725 /* Record this non-type partial instantiation. */
13726 register_specialization (r, t,
13727 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13728 false, hash);
13730 return r;
13733 /* True if FN is the op() for a lambda in an uninstantiated template. */
13735 bool
13736 lambda_fn_in_template_p (tree fn)
13738 if (!fn || !LAMBDA_FUNCTION_P (fn))
13739 return false;
13740 tree closure = DECL_CONTEXT (fn);
13741 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13744 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
13745 which the above is true. */
13747 bool
13748 instantiated_lambda_fn_p (tree fn)
13750 if (!fn || !LAMBDA_FUNCTION_P (fn))
13751 return false;
13752 tree closure = DECL_CONTEXT (fn);
13753 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
13754 return LAMBDA_EXPR_INSTANTIATED (lam);
13757 /* We're instantiating a variable from template function TCTX. Return the
13758 corresponding current enclosing scope. This gets complicated because lambda
13759 functions in templates are regenerated rather than instantiated, but generic
13760 lambda functions are subsequently instantiated. */
13762 static tree
13763 enclosing_instantiation_of (tree otctx)
13765 tree tctx = otctx;
13766 tree fn = current_function_decl;
13767 int lambda_count = 0;
13769 for (; tctx && (lambda_fn_in_template_p (tctx)
13770 || instantiated_lambda_fn_p (tctx));
13771 tctx = decl_function_context (tctx))
13772 ++lambda_count;
13773 for (; fn; fn = decl_function_context (fn))
13775 tree ofn = fn;
13776 int flambda_count = 0;
13777 for (; fn && instantiated_lambda_fn_p (fn);
13778 fn = decl_function_context (fn))
13779 ++flambda_count;
13780 if ((fn && DECL_TEMPLATE_INFO (fn))
13781 ? most_general_template (fn) != most_general_template (tctx)
13782 : fn != tctx)
13783 continue;
13784 if (flambda_count != lambda_count)
13786 gcc_assert (flambda_count > lambda_count);
13787 for (; flambda_count > lambda_count; --flambda_count)
13788 ofn = decl_function_context (ofn);
13790 gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13791 || DECL_CONV_FN_P (ofn));
13792 return ofn;
13794 gcc_unreachable ();
13797 /* Substitute the ARGS into the T, which is a _DECL. Return the
13798 result of the substitution. Issue error and warning messages under
13799 control of COMPLAIN. */
13801 static tree
13802 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13804 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13805 location_t saved_loc;
13806 tree r = NULL_TREE;
13807 tree in_decl = t;
13808 hashval_t hash = 0;
13810 /* Set the filename and linenumber to improve error-reporting. */
13811 saved_loc = input_location;
13812 input_location = DECL_SOURCE_LOCATION (t);
13814 switch (TREE_CODE (t))
13816 case TEMPLATE_DECL:
13817 r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13818 break;
13820 case FUNCTION_DECL:
13821 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13822 break;
13824 case PARM_DECL:
13826 tree type = NULL_TREE;
13827 int i, len = 1;
13828 tree expanded_types = NULL_TREE;
13829 tree prev_r = NULL_TREE;
13830 tree first_r = NULL_TREE;
13832 if (DECL_PACK_P (t))
13834 /* If there is a local specialization that isn't a
13835 parameter pack, it means that we're doing a "simple"
13836 substitution from inside tsubst_pack_expansion. Just
13837 return the local specialization (which will be a single
13838 parm). */
13839 tree spec = retrieve_local_specialization (t);
13840 if (spec
13841 && TREE_CODE (spec) == PARM_DECL
13842 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13843 RETURN (spec);
13845 /* Expand the TYPE_PACK_EXPANSION that provides the types for
13846 the parameters in this function parameter pack. */
13847 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13848 complain, in_decl);
13849 if (TREE_CODE (expanded_types) == TREE_VEC)
13851 len = TREE_VEC_LENGTH (expanded_types);
13853 /* Zero-length parameter packs are boring. Just substitute
13854 into the chain. */
13855 if (len == 0)
13856 RETURN (tsubst (TREE_CHAIN (t), args, complain,
13857 TREE_CHAIN (t)));
13859 else
13861 /* All we did was update the type. Make a note of that. */
13862 type = expanded_types;
13863 expanded_types = NULL_TREE;
13867 /* Loop through all of the parameters we'll build. When T is
13868 a function parameter pack, LEN is the number of expanded
13869 types in EXPANDED_TYPES; otherwise, LEN is 1. */
13870 r = NULL_TREE;
13871 for (i = 0; i < len; ++i)
13873 prev_r = r;
13874 r = copy_node (t);
13875 if (DECL_TEMPLATE_PARM_P (t))
13876 SET_DECL_TEMPLATE_PARM_P (r);
13878 if (expanded_types)
13879 /* We're on the Ith parameter of the function parameter
13880 pack. */
13882 /* Get the Ith type. */
13883 type = TREE_VEC_ELT (expanded_types, i);
13885 /* Rename the parameter to include the index. */
13886 DECL_NAME (r)
13887 = make_ith_pack_parameter_name (DECL_NAME (r), i);
13889 else if (!type)
13890 /* We're dealing with a normal parameter. */
13891 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13893 type = type_decays_to (type);
13894 TREE_TYPE (r) = type;
13895 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13897 if (DECL_INITIAL (r))
13899 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13900 DECL_INITIAL (r) = TREE_TYPE (r);
13901 else
13902 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13903 complain, in_decl);
13906 DECL_CONTEXT (r) = NULL_TREE;
13908 if (!DECL_TEMPLATE_PARM_P (r))
13909 DECL_ARG_TYPE (r) = type_passed_as (type);
13911 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13912 args, complain, in_decl);
13914 /* Keep track of the first new parameter we
13915 generate. That's what will be returned to the
13916 caller. */
13917 if (!first_r)
13918 first_r = r;
13920 /* Build a proper chain of parameters when substituting
13921 into a function parameter pack. */
13922 if (prev_r)
13923 DECL_CHAIN (prev_r) = r;
13926 /* If cp_unevaluated_operand is set, we're just looking for a
13927 single dummy parameter, so don't keep going. */
13928 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13929 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13930 complain, DECL_CHAIN (t));
13932 /* FIRST_R contains the start of the chain we've built. */
13933 r = first_r;
13935 break;
13937 case FIELD_DECL:
13939 tree type = NULL_TREE;
13940 tree vec = NULL_TREE;
13941 tree expanded_types = NULL_TREE;
13942 int len = 1;
13944 if (PACK_EXPANSION_P (TREE_TYPE (t)))
13946 /* This field is a lambda capture pack. Return a TREE_VEC of
13947 the expanded fields to instantiate_class_template_1. */
13948 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13949 complain, in_decl);
13950 if (TREE_CODE (expanded_types) == TREE_VEC)
13952 len = TREE_VEC_LENGTH (expanded_types);
13953 vec = make_tree_vec (len);
13955 else
13957 /* All we did was update the type. Make a note of that. */
13958 type = expanded_types;
13959 expanded_types = NULL_TREE;
13963 for (int i = 0; i < len; ++i)
13965 r = copy_decl (t);
13966 if (expanded_types)
13968 type = TREE_VEC_ELT (expanded_types, i);
13969 DECL_NAME (r)
13970 = make_ith_pack_parameter_name (DECL_NAME (r), i);
13972 else if (!type)
13973 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13975 if (type == error_mark_node)
13976 RETURN (error_mark_node);
13977 TREE_TYPE (r) = type;
13978 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13980 if (DECL_C_BIT_FIELD (r))
13981 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13982 number of bits. */
13983 DECL_BIT_FIELD_REPRESENTATIVE (r)
13984 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13985 complain, in_decl,
13986 /*integral_constant_expression_p=*/true);
13987 if (DECL_INITIAL (t))
13989 /* Set up DECL_TEMPLATE_INFO so that we can get at the
13990 NSDMI in perform_member_init. Still set DECL_INITIAL
13991 so that we know there is one. */
13992 DECL_INITIAL (r) = void_node;
13993 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13994 retrofit_lang_decl (r);
13995 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13997 /* We don't have to set DECL_CONTEXT here; it is set by
13998 finish_member_declaration. */
13999 DECL_CHAIN (r) = NULL_TREE;
14001 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14002 args, complain, in_decl);
14004 if (vec)
14005 TREE_VEC_ELT (vec, i) = r;
14008 if (vec)
14009 r = vec;
14011 break;
14013 case USING_DECL:
14014 /* We reach here only for member using decls. We also need to check
14015 uses_template_parms because DECL_DEPENDENT_P is not set for a
14016 using-declaration that designates a member of the current
14017 instantiation (c++/53549). */
14018 if (DECL_DEPENDENT_P (t)
14019 || uses_template_parms (USING_DECL_SCOPE (t)))
14021 tree scope = USING_DECL_SCOPE (t);
14022 tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14023 if (PACK_EXPANSION_P (scope))
14025 tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14026 int len = TREE_VEC_LENGTH (vec);
14027 r = make_tree_vec (len);
14028 for (int i = 0; i < len; ++i)
14030 tree escope = TREE_VEC_ELT (vec, i);
14031 tree elt = do_class_using_decl (escope, name);
14032 if (!elt)
14034 r = error_mark_node;
14035 break;
14037 else
14039 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14040 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14042 TREE_VEC_ELT (r, i) = elt;
14045 else
14047 tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14048 complain, in_decl);
14049 r = do_class_using_decl (inst_scope, name);
14050 if (!r)
14051 r = error_mark_node;
14052 else
14054 TREE_PROTECTED (r) = TREE_PROTECTED (t);
14055 TREE_PRIVATE (r) = TREE_PRIVATE (t);
14059 else
14061 r = copy_node (t);
14062 DECL_CHAIN (r) = NULL_TREE;
14064 break;
14066 case TYPE_DECL:
14067 case VAR_DECL:
14069 tree argvec = NULL_TREE;
14070 tree gen_tmpl = NULL_TREE;
14071 tree spec;
14072 tree tmpl = NULL_TREE;
14073 tree ctx;
14074 tree type = NULL_TREE;
14075 bool local_p;
14077 if (TREE_TYPE (t) == error_mark_node)
14078 RETURN (error_mark_node);
14080 if (TREE_CODE (t) == TYPE_DECL
14081 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14083 /* If this is the canonical decl, we don't have to
14084 mess with instantiations, and often we can't (for
14085 typename, template type parms and such). Note that
14086 TYPE_NAME is not correct for the above test if
14087 we've copied the type for a typedef. */
14088 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14089 if (type == error_mark_node)
14090 RETURN (error_mark_node);
14091 r = TYPE_NAME (type);
14092 break;
14095 /* Check to see if we already have the specialization we
14096 need. */
14097 spec = NULL_TREE;
14098 if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
14100 /* T is a static data member or namespace-scope entity.
14101 We have to substitute into namespace-scope variables
14102 (not just variable templates) because of cases like:
14104 template <class T> void f() { extern T t; }
14106 where the entity referenced is not known until
14107 instantiation time. */
14108 local_p = false;
14109 ctx = DECL_CONTEXT (t);
14110 if (DECL_CLASS_SCOPE_P (t))
14112 ctx = tsubst_aggr_type (ctx, args,
14113 complain,
14114 in_decl, /*entering_scope=*/1);
14115 /* If CTX is unchanged, then T is in fact the
14116 specialization we want. That situation occurs when
14117 referencing a static data member within in its own
14118 class. We can use pointer equality, rather than
14119 same_type_p, because DECL_CONTEXT is always
14120 canonical... */
14121 if (ctx == DECL_CONTEXT (t)
14122 /* ... unless T is a member template; in which
14123 case our caller can be willing to create a
14124 specialization of that template represented
14125 by T. */
14126 && !(DECL_TI_TEMPLATE (t)
14127 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
14128 spec = t;
14131 if (!spec)
14133 tmpl = DECL_TI_TEMPLATE (t);
14134 gen_tmpl = most_general_template (tmpl);
14135 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
14136 if (argvec != error_mark_node)
14137 argvec = (coerce_innermost_template_parms
14138 (DECL_TEMPLATE_PARMS (gen_tmpl),
14139 argvec, t, complain,
14140 /*all*/true, /*defarg*/true));
14141 if (argvec == error_mark_node)
14142 RETURN (error_mark_node);
14143 hash = hash_tmpl_and_args (gen_tmpl, argvec);
14144 spec = retrieve_specialization (gen_tmpl, argvec, hash);
14147 else
14149 /* A local variable. */
14150 local_p = true;
14151 /* Subsequent calls to pushdecl will fill this in. */
14152 ctx = NULL_TREE;
14153 /* Unless this is a reference to a static variable from an
14154 enclosing function, in which case we need to fill it in now. */
14155 if (TREE_STATIC (t))
14157 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
14158 if (fn != current_function_decl)
14159 ctx = fn;
14161 spec = retrieve_local_specialization (t);
14163 /* If we already have the specialization we need, there is
14164 nothing more to do. */
14165 if (spec)
14167 r = spec;
14168 break;
14171 /* Create a new node for the specialization we need. */
14172 if (type == NULL_TREE)
14174 if (is_typedef_decl (t))
14175 type = DECL_ORIGINAL_TYPE (t);
14176 else
14177 type = TREE_TYPE (t);
14178 if (VAR_P (t)
14179 && VAR_HAD_UNKNOWN_BOUND (t)
14180 && type != error_mark_node)
14181 type = strip_array_domain (type);
14182 tree sub_args = args;
14183 if (tree auto_node = type_uses_auto (type))
14185 /* Mask off any template args past the variable's context so we
14186 don't replace the auto with an unrelated argument. */
14187 int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
14188 int extra = TMPL_ARGS_DEPTH (args) - nouter;
14189 if (extra > 0)
14190 /* This should never happen with the new lambda instantiation
14191 model, but keep the handling just in case. */
14192 gcc_assert (!CHECKING_P),
14193 sub_args = strip_innermost_template_args (args, extra);
14195 type = tsubst (type, sub_args, complain, in_decl);
14196 /* Substituting the type might have recursively instantiated this
14197 same alias (c++/86171). */
14198 if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
14199 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
14201 r = spec;
14202 break;
14205 r = copy_decl (t);
14206 if (VAR_P (r))
14208 DECL_INITIALIZED_P (r) = 0;
14209 DECL_TEMPLATE_INSTANTIATED (r) = 0;
14210 if (type == error_mark_node)
14211 RETURN (error_mark_node);
14212 if (TREE_CODE (type) == FUNCTION_TYPE)
14214 /* It may seem that this case cannot occur, since:
14216 typedef void f();
14217 void g() { f x; }
14219 declares a function, not a variable. However:
14221 typedef void f();
14222 template <typename T> void g() { T t; }
14223 template void g<f>();
14225 is an attempt to declare a variable with function
14226 type. */
14227 error ("variable %qD has function type",
14228 /* R is not yet sufficiently initialized, so we
14229 just use its name. */
14230 DECL_NAME (r));
14231 RETURN (error_mark_node);
14233 type = complete_type (type);
14234 /* Wait until cp_finish_decl to set this again, to handle
14235 circular dependency (template/instantiate6.C). */
14236 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
14237 type = check_var_type (DECL_NAME (r), type,
14238 DECL_SOURCE_LOCATION (r));
14239 if (DECL_HAS_VALUE_EXPR_P (t))
14241 tree ve = DECL_VALUE_EXPR (t);
14242 ve = tsubst_expr (ve, args, complain, in_decl,
14243 /*constant_expression_p=*/false);
14244 if (REFERENCE_REF_P (ve))
14246 gcc_assert (TYPE_REF_P (type));
14247 ve = TREE_OPERAND (ve, 0);
14249 SET_DECL_VALUE_EXPR (r, ve);
14251 if (CP_DECL_THREAD_LOCAL_P (r)
14252 && !processing_template_decl)
14253 set_decl_tls_model (r, decl_default_tls_model (r));
14255 else if (DECL_SELF_REFERENCE_P (t))
14256 SET_DECL_SELF_REFERENCE_P (r);
14257 TREE_TYPE (r) = type;
14258 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14259 DECL_CONTEXT (r) = ctx;
14260 /* Clear out the mangled name and RTL for the instantiation. */
14261 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14262 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
14263 SET_DECL_RTL (r, NULL);
14264 /* The initializer must not be expanded until it is required;
14265 see [temp.inst]. */
14266 DECL_INITIAL (r) = NULL_TREE;
14267 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
14268 if (VAR_P (r))
14270 if (DECL_LANG_SPECIFIC (r))
14271 SET_DECL_DEPENDENT_INIT_P (r, false);
14273 SET_DECL_MODE (r, VOIDmode);
14275 /* Possibly limit visibility based on template args. */
14276 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14277 if (DECL_VISIBILITY_SPECIFIED (t))
14279 DECL_VISIBILITY_SPECIFIED (r) = 0;
14280 DECL_ATTRIBUTES (r)
14281 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14283 determine_visibility (r);
14286 if (!local_p)
14288 /* A static data member declaration is always marked
14289 external when it is declared in-class, even if an
14290 initializer is present. We mimic the non-template
14291 processing here. */
14292 DECL_EXTERNAL (r) = 1;
14293 if (DECL_NAMESPACE_SCOPE_P (t))
14294 DECL_NOT_REALLY_EXTERN (r) = 1;
14296 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
14297 SET_DECL_IMPLICIT_INSTANTIATION (r);
14298 /* Remember whether we require constant initialization of
14299 a non-constant template variable. */
14300 TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (r))
14301 = TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (t));
14302 if (!error_operand_p (r) || (complain & tf_error))
14303 register_specialization (r, gen_tmpl, argvec, false, hash);
14305 else
14307 if (DECL_LANG_SPECIFIC (r))
14308 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14309 if (!cp_unevaluated_operand)
14310 register_local_specialization (r, t);
14313 DECL_CHAIN (r) = NULL_TREE;
14315 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
14316 /*flags=*/0,
14317 args, complain, in_decl);
14319 /* Preserve a typedef that names a type. */
14320 if (is_typedef_decl (r) && type != error_mark_node)
14322 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
14323 set_underlying_type (r);
14324 if (TYPE_DECL_ALIAS_P (r))
14325 /* An alias template specialization can be dependent
14326 even if its underlying type is not. */
14327 TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
14330 layout_decl (r, 0);
14332 break;
14334 default:
14335 gcc_unreachable ();
14337 #undef RETURN
14339 out:
14340 /* Restore the file and line information. */
14341 input_location = saved_loc;
14343 return r;
14346 /* Substitute into the complete parameter type list PARMS. */
14348 tree
14349 tsubst_function_parms (tree parms,
14350 tree args,
14351 tsubst_flags_t complain,
14352 tree in_decl)
14354 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
14357 /* Substitute into the ARG_TYPES of a function type.
14358 If END is a TREE_CHAIN, leave it and any following types
14359 un-substituted. */
14361 static tree
14362 tsubst_arg_types (tree arg_types,
14363 tree args,
14364 tree end,
14365 tsubst_flags_t complain,
14366 tree in_decl)
14368 tree remaining_arg_types;
14369 tree type = NULL_TREE;
14370 int i = 1;
14371 tree expanded_args = NULL_TREE;
14372 tree default_arg;
14374 if (!arg_types || arg_types == void_list_node || arg_types == end)
14375 return arg_types;
14377 remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
14378 args, end, complain, in_decl);
14379 if (remaining_arg_types == error_mark_node)
14380 return error_mark_node;
14382 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
14384 /* For a pack expansion, perform substitution on the
14385 entire expression. Later on, we'll handle the arguments
14386 one-by-one. */
14387 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
14388 args, complain, in_decl);
14390 if (TREE_CODE (expanded_args) == TREE_VEC)
14391 /* So that we'll spin through the parameters, one by one. */
14392 i = TREE_VEC_LENGTH (expanded_args);
14393 else
14395 /* We only partially substituted into the parameter
14396 pack. Our type is TYPE_PACK_EXPANSION. */
14397 type = expanded_args;
14398 expanded_args = NULL_TREE;
14402 while (i > 0) {
14403 --i;
14405 if (expanded_args)
14406 type = TREE_VEC_ELT (expanded_args, i);
14407 else if (!type)
14408 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
14410 if (type == error_mark_node)
14411 return error_mark_node;
14412 if (VOID_TYPE_P (type))
14414 if (complain & tf_error)
14416 error ("invalid parameter type %qT", type);
14417 if (in_decl)
14418 error ("in declaration %q+D", in_decl);
14420 return error_mark_node;
14422 /* DR 657. */
14423 if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
14424 return error_mark_node;
14426 /* Do array-to-pointer, function-to-pointer conversion, and ignore
14427 top-level qualifiers as required. */
14428 type = cv_unqualified (type_decays_to (type));
14430 /* We do not substitute into default arguments here. The standard
14431 mandates that they be instantiated only when needed, which is
14432 done in build_over_call. */
14433 default_arg = TREE_PURPOSE (arg_types);
14435 /* Except that we do substitute default arguments under tsubst_lambda_expr,
14436 since the new op() won't have any associated template arguments for us
14437 to refer to later. */
14438 if (lambda_fn_in_template_p (in_decl))
14439 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
14440 false/*fn*/, false/*constexpr*/);
14442 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
14444 /* We've instantiated a template before its default arguments
14445 have been parsed. This can happen for a nested template
14446 class, and is not an error unless we require the default
14447 argument in a call of this function. */
14448 remaining_arg_types =
14449 tree_cons (default_arg, type, remaining_arg_types);
14450 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
14451 remaining_arg_types);
14453 else
14454 remaining_arg_types =
14455 hash_tree_cons (default_arg, type, remaining_arg_types);
14458 return remaining_arg_types;
14461 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
14462 *not* handle the exception-specification for FNTYPE, because the
14463 initial substitution of explicitly provided template parameters
14464 during argument deduction forbids substitution into the
14465 exception-specification:
14467 [temp.deduct]
14469 All references in the function type of the function template to the
14470 corresponding template parameters are replaced by the specified tem-
14471 plate argument values. If a substitution in a template parameter or
14472 in the function type of the function template results in an invalid
14473 type, type deduction fails. [Note: The equivalent substitution in
14474 exception specifications is done only when the function is instanti-
14475 ated, at which point a program is ill-formed if the substitution
14476 results in an invalid type.] */
14478 static tree
14479 tsubst_function_type (tree t,
14480 tree args,
14481 tsubst_flags_t complain,
14482 tree in_decl)
14484 tree return_type;
14485 tree arg_types = NULL_TREE;
14486 tree fntype;
14488 /* The TYPE_CONTEXT is not used for function/method types. */
14489 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
14491 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
14492 failure. */
14493 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14495 if (late_return_type_p)
14497 /* Substitute the argument types. */
14498 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14499 complain, in_decl);
14500 if (arg_types == error_mark_node)
14501 return error_mark_node;
14503 tree save_ccp = current_class_ptr;
14504 tree save_ccr = current_class_ref;
14505 tree this_type = (TREE_CODE (t) == METHOD_TYPE
14506 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
14507 bool do_inject = this_type && CLASS_TYPE_P (this_type);
14508 if (do_inject)
14510 /* DR 1207: 'this' is in scope in the trailing return type. */
14511 inject_this_parameter (this_type, cp_type_quals (this_type));
14514 /* Substitute the return type. */
14515 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14517 if (do_inject)
14519 current_class_ptr = save_ccp;
14520 current_class_ref = save_ccr;
14523 else
14524 /* Substitute the return type. */
14525 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14527 if (return_type == error_mark_node)
14528 return error_mark_node;
14529 /* DR 486 clarifies that creation of a function type with an
14530 invalid return type is a deduction failure. */
14531 if (TREE_CODE (return_type) == ARRAY_TYPE
14532 || TREE_CODE (return_type) == FUNCTION_TYPE)
14534 if (complain & tf_error)
14536 if (TREE_CODE (return_type) == ARRAY_TYPE)
14537 error ("function returning an array");
14538 else
14539 error ("function returning a function");
14541 return error_mark_node;
14543 /* And DR 657. */
14544 if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14545 return error_mark_node;
14547 if (!late_return_type_p)
14549 /* Substitute the argument types. */
14550 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14551 complain, in_decl);
14552 if (arg_types == error_mark_node)
14553 return error_mark_node;
14556 /* Construct a new type node and return it. */
14557 if (TREE_CODE (t) == FUNCTION_TYPE)
14559 fntype = build_function_type (return_type, arg_types);
14560 fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
14562 else
14564 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14565 /* Don't pick up extra function qualifiers from the basetype. */
14566 r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14567 if (! MAYBE_CLASS_TYPE_P (r))
14569 /* [temp.deduct]
14571 Type deduction may fail for any of the following
14572 reasons:
14574 -- Attempting to create "pointer to member of T" when T
14575 is not a class type. */
14576 if (complain & tf_error)
14577 error ("creating pointer to member function of non-class type %qT",
14579 return error_mark_node;
14582 fntype = build_method_type_directly (r, return_type,
14583 TREE_CHAIN (arg_types));
14585 fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14587 /* See comment above. */
14588 tree raises = NULL_TREE;
14589 cp_ref_qualifier rqual = type_memfn_rqual (t);
14590 fntype = build_cp_fntype_variant (fntype, rqual, raises, late_return_type_p);
14592 return fntype;
14595 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
14596 ARGS into that specification, and return the substituted
14597 specification. If there is no specification, return NULL_TREE. */
14599 static tree
14600 tsubst_exception_specification (tree fntype,
14601 tree args,
14602 tsubst_flags_t complain,
14603 tree in_decl,
14604 bool defer_ok)
14606 tree specs;
14607 tree new_specs;
14609 specs = TYPE_RAISES_EXCEPTIONS (fntype);
14610 new_specs = NULL_TREE;
14611 if (specs && TREE_PURPOSE (specs))
14613 /* A noexcept-specifier. */
14614 tree expr = TREE_PURPOSE (specs);
14615 if (TREE_CODE (expr) == INTEGER_CST)
14616 new_specs = expr;
14617 else if (defer_ok)
14619 /* Defer instantiation of noexcept-specifiers to avoid
14620 excessive instantiations (c++/49107). */
14621 new_specs = make_node (DEFERRED_NOEXCEPT);
14622 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14624 /* We already partially instantiated this member template,
14625 so combine the new args with the old. */
14626 DEFERRED_NOEXCEPT_PATTERN (new_specs)
14627 = DEFERRED_NOEXCEPT_PATTERN (expr);
14628 DEFERRED_NOEXCEPT_ARGS (new_specs)
14629 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14631 else
14633 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14634 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14637 else
14639 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14641 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
14642 args);
14643 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
14645 new_specs = tsubst_copy_and_build
14646 (expr, args, complain, in_decl, /*function_p=*/false,
14647 /*integral_constant_expression_p=*/true);
14649 new_specs = build_noexcept_spec (new_specs, complain);
14651 else if (specs)
14653 if (! TREE_VALUE (specs))
14654 new_specs = specs;
14655 else
14656 while (specs)
14658 tree spec;
14659 int i, len = 1;
14660 tree expanded_specs = NULL_TREE;
14662 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14664 /* Expand the pack expansion type. */
14665 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14666 args, complain,
14667 in_decl);
14669 if (expanded_specs == error_mark_node)
14670 return error_mark_node;
14671 else if (TREE_CODE (expanded_specs) == TREE_VEC)
14672 len = TREE_VEC_LENGTH (expanded_specs);
14673 else
14675 /* We're substituting into a member template, so
14676 we got a TYPE_PACK_EXPANSION back. Add that
14677 expansion and move on. */
14678 gcc_assert (TREE_CODE (expanded_specs)
14679 == TYPE_PACK_EXPANSION);
14680 new_specs = add_exception_specifier (new_specs,
14681 expanded_specs,
14682 complain);
14683 specs = TREE_CHAIN (specs);
14684 continue;
14688 for (i = 0; i < len; ++i)
14690 if (expanded_specs)
14691 spec = TREE_VEC_ELT (expanded_specs, i);
14692 else
14693 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14694 if (spec == error_mark_node)
14695 return spec;
14696 new_specs = add_exception_specifier (new_specs, spec,
14697 complain);
14700 specs = TREE_CHAIN (specs);
14703 return new_specs;
14706 /* Take the tree structure T and replace template parameters used
14707 therein with the argument vector ARGS. IN_DECL is an associated
14708 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
14709 Issue error and warning messages under control of COMPLAIN. Note
14710 that we must be relatively non-tolerant of extensions here, in
14711 order to preserve conformance; if we allow substitutions that
14712 should not be allowed, we may allow argument deductions that should
14713 not succeed, and therefore report ambiguous overload situations
14714 where there are none. In theory, we could allow the substitution,
14715 but indicate that it should have failed, and allow our caller to
14716 make sure that the right thing happens, but we don't try to do this
14717 yet.
14719 This function is used for dealing with types, decls and the like;
14720 for expressions, use tsubst_expr or tsubst_copy. */
14722 tree
14723 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14725 enum tree_code code;
14726 tree type, r = NULL_TREE;
14728 if (t == NULL_TREE || t == error_mark_node
14729 || t == integer_type_node
14730 || t == void_type_node
14731 || t == char_type_node
14732 || t == unknown_type_node
14733 || TREE_CODE (t) == NAMESPACE_DECL
14734 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14735 return t;
14737 if (DECL_P (t))
14738 return tsubst_decl (t, args, complain);
14740 if (args == NULL_TREE)
14741 return t;
14743 code = TREE_CODE (t);
14745 if (code == IDENTIFIER_NODE)
14746 type = IDENTIFIER_TYPE_VALUE (t);
14747 else
14748 type = TREE_TYPE (t);
14750 gcc_assert (type != unknown_type_node);
14752 /* Reuse typedefs. We need to do this to handle dependent attributes,
14753 such as attribute aligned. */
14754 if (TYPE_P (t)
14755 && typedef_variant_p (t))
14757 tree decl = TYPE_NAME (t);
14759 if (alias_template_specialization_p (t))
14761 /* DECL represents an alias template and we want to
14762 instantiate it. */
14763 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14764 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14765 r = instantiate_alias_template (tmpl, gen_args, complain);
14767 else if (DECL_CLASS_SCOPE_P (decl)
14768 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14769 && uses_template_parms (DECL_CONTEXT (decl)))
14771 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14772 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14773 r = retrieve_specialization (tmpl, gen_args, 0);
14775 else if (DECL_FUNCTION_SCOPE_P (decl)
14776 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14777 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14778 r = retrieve_local_specialization (decl);
14779 else
14780 /* The typedef is from a non-template context. */
14781 return t;
14783 if (r)
14785 r = TREE_TYPE (r);
14786 r = cp_build_qualified_type_real
14787 (r, cp_type_quals (t) | cp_type_quals (r),
14788 complain | tf_ignore_bad_quals);
14789 return r;
14791 else
14793 /* We don't have an instantiation yet, so drop the typedef. */
14794 int quals = cp_type_quals (t);
14795 t = DECL_ORIGINAL_TYPE (decl);
14796 t = cp_build_qualified_type_real (t, quals,
14797 complain | tf_ignore_bad_quals);
14801 bool fndecl_type = (complain & tf_fndecl_type);
14802 complain &= ~tf_fndecl_type;
14804 if (type
14805 && code != TYPENAME_TYPE
14806 && code != TEMPLATE_TYPE_PARM
14807 && code != TEMPLATE_PARM_INDEX
14808 && code != IDENTIFIER_NODE
14809 && code != FUNCTION_TYPE
14810 && code != METHOD_TYPE)
14811 type = tsubst (type, args, complain, in_decl);
14812 if (type == error_mark_node)
14813 return error_mark_node;
14815 switch (code)
14817 case RECORD_TYPE:
14818 case UNION_TYPE:
14819 case ENUMERAL_TYPE:
14820 return tsubst_aggr_type (t, args, complain, in_decl,
14821 /*entering_scope=*/0);
14823 case ERROR_MARK:
14824 case IDENTIFIER_NODE:
14825 case VOID_TYPE:
14826 case REAL_TYPE:
14827 case COMPLEX_TYPE:
14828 case VECTOR_TYPE:
14829 case BOOLEAN_TYPE:
14830 case NULLPTR_TYPE:
14831 case LANG_TYPE:
14832 return t;
14834 case INTEGER_TYPE:
14835 if (t == integer_type_node)
14836 return t;
14838 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14839 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14840 return t;
14843 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14845 max = tsubst_expr (omax, args, complain, in_decl,
14846 /*integral_constant_expression_p=*/false);
14848 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14849 needed. */
14850 if (TREE_CODE (max) == NOP_EXPR
14851 && TREE_SIDE_EFFECTS (omax)
14852 && !TREE_TYPE (max))
14853 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14855 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
14856 with TREE_SIDE_EFFECTS that indicates this is not an integral
14857 constant expression. */
14858 if (processing_template_decl
14859 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14861 gcc_assert (TREE_CODE (max) == NOP_EXPR);
14862 TREE_SIDE_EFFECTS (max) = 1;
14865 return compute_array_index_type (NULL_TREE, max, complain);
14868 case TEMPLATE_TYPE_PARM:
14869 case TEMPLATE_TEMPLATE_PARM:
14870 case BOUND_TEMPLATE_TEMPLATE_PARM:
14871 case TEMPLATE_PARM_INDEX:
14873 int idx;
14874 int level;
14875 int levels;
14876 tree arg = NULL_TREE;
14878 /* Early in template argument deduction substitution, we don't
14879 want to reduce the level of 'auto', or it will be confused
14880 with a normal template parm in subsequent deduction. */
14881 if (is_auto (t) && (complain & tf_partial))
14882 return t;
14884 r = NULL_TREE;
14886 gcc_assert (TREE_VEC_LENGTH (args) > 0);
14887 template_parm_level_and_index (t, &level, &idx);
14889 levels = TMPL_ARGS_DEPTH (args);
14890 if (level <= levels
14891 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14893 arg = TMPL_ARG (args, level, idx);
14895 /* See through ARGUMENT_PACK_SELECT arguments. */
14896 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14897 arg = argument_pack_select_arg (arg);
14900 if (arg == error_mark_node)
14901 return error_mark_node;
14902 else if (arg != NULL_TREE)
14904 if (ARGUMENT_PACK_P (arg))
14905 /* If ARG is an argument pack, we don't actually want to
14906 perform a substitution here, because substitutions
14907 for argument packs are only done
14908 element-by-element. We can get to this point when
14909 substituting the type of a non-type template
14910 parameter pack, when that type actually contains
14911 template parameter packs from an outer template, e.g.,
14913 template<typename... Types> struct A {
14914 template<Types... Values> struct B { };
14915 }; */
14916 return t;
14918 if (code == TEMPLATE_TYPE_PARM)
14920 int quals;
14922 /* When building concept checks for the purpose of
14923 deducing placeholders, we can end up with wildcards
14924 where types are expected. Adjust this to the deduced
14925 value. */
14926 if (TREE_CODE (arg) == WILDCARD_DECL)
14927 arg = TREE_TYPE (TREE_TYPE (arg));
14929 gcc_assert (TYPE_P (arg));
14931 quals = cp_type_quals (arg) | cp_type_quals (t);
14933 return cp_build_qualified_type_real
14934 (arg, quals, complain | tf_ignore_bad_quals);
14936 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14938 /* We are processing a type constructed from a
14939 template template parameter. */
14940 tree argvec = tsubst (TYPE_TI_ARGS (t),
14941 args, complain, in_decl);
14942 if (argvec == error_mark_node)
14943 return error_mark_node;
14945 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14946 || TREE_CODE (arg) == TEMPLATE_DECL
14947 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14949 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14950 /* Consider this code:
14952 template <template <class> class Template>
14953 struct Internal {
14954 template <class Arg> using Bind = Template<Arg>;
14957 template <template <class> class Template, class Arg>
14958 using Instantiate = Template<Arg>; //#0
14960 template <template <class> class Template,
14961 class Argument>
14962 using Bind =
14963 Instantiate<Internal<Template>::template Bind,
14964 Argument>; //#1
14966 When #1 is parsed, the
14967 BOUND_TEMPLATE_TEMPLATE_PARM representing the
14968 parameter `Template' in #0 matches the
14969 UNBOUND_CLASS_TEMPLATE representing the argument
14970 `Internal<Template>::template Bind'; We then want
14971 to assemble the type `Bind<Argument>' that can't
14972 be fully created right now, because
14973 `Internal<Template>' not being complete, the Bind
14974 template cannot be looked up in that context. So
14975 we need to "store" `Bind<Argument>' for later
14976 when the context of Bind becomes complete. Let's
14977 store that in a TYPENAME_TYPE. */
14978 return make_typename_type (TYPE_CONTEXT (arg),
14979 build_nt (TEMPLATE_ID_EXPR,
14980 TYPE_IDENTIFIER (arg),
14981 argvec),
14982 typename_type,
14983 complain);
14985 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
14986 are resolving nested-types in the signature of a
14987 member function templates. Otherwise ARG is a
14988 TEMPLATE_DECL and is the real template to be
14989 instantiated. */
14990 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14991 arg = TYPE_NAME (arg);
14993 r = lookup_template_class (arg,
14994 argvec, in_decl,
14995 DECL_CONTEXT (arg),
14996 /*entering_scope=*/0,
14997 complain);
14998 return cp_build_qualified_type_real
14999 (r, cp_type_quals (t) | cp_type_quals (r), complain);
15001 else if (code == TEMPLATE_TEMPLATE_PARM)
15002 return arg;
15003 else
15004 /* TEMPLATE_PARM_INDEX. */
15005 return convert_from_reference (unshare_expr (arg));
15008 if (level == 1)
15009 /* This can happen during the attempted tsubst'ing in
15010 unify. This means that we don't yet have any information
15011 about the template parameter in question. */
15012 return t;
15014 /* If we get here, we must have been looking at a parm for a
15015 more deeply nested template. Make a new version of this
15016 template parameter, but with a lower level. */
15017 switch (code)
15019 case TEMPLATE_TYPE_PARM:
15020 case TEMPLATE_TEMPLATE_PARM:
15021 case BOUND_TEMPLATE_TEMPLATE_PARM:
15022 if (cp_type_quals (t))
15024 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
15025 r = cp_build_qualified_type_real
15026 (r, cp_type_quals (t),
15027 complain | (code == TEMPLATE_TYPE_PARM
15028 ? tf_ignore_bad_quals : 0));
15030 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15031 && PLACEHOLDER_TYPE_CONSTRAINTS (t)
15032 && (r = (TEMPLATE_PARM_DESCENDANTS
15033 (TEMPLATE_TYPE_PARM_INDEX (t))))
15034 && (r = TREE_TYPE (r))
15035 && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
15036 /* Break infinite recursion when substituting the constraints
15037 of a constrained placeholder. */;
15038 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15039 && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
15040 && !CLASS_PLACEHOLDER_TEMPLATE (t)
15041 && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
15042 r = TEMPLATE_PARM_DESCENDANTS (arg))
15043 && (TEMPLATE_PARM_LEVEL (r)
15044 == TEMPLATE_PARM_LEVEL (arg) - levels))
15045 /* Cache the simple case of lowering a type parameter. */
15046 r = TREE_TYPE (r);
15047 else
15049 r = copy_type (t);
15050 TEMPLATE_TYPE_PARM_INDEX (r)
15051 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
15052 r, levels, args, complain);
15053 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
15054 TYPE_MAIN_VARIANT (r) = r;
15055 TYPE_POINTER_TO (r) = NULL_TREE;
15056 TYPE_REFERENCE_TO (r) = NULL_TREE;
15058 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
15060 /* Propagate constraints on placeholders since they are
15061 only instantiated during satisfaction. */
15062 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
15063 PLACEHOLDER_TYPE_CONSTRAINTS (r) = constr;
15064 else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
15066 pl = tsubst_copy (pl, args, complain, in_decl);
15067 CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
15071 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
15072 /* We have reduced the level of the template
15073 template parameter, but not the levels of its
15074 template parameters, so canonical_type_parameter
15075 will not be able to find the canonical template
15076 template parameter for this level. Thus, we
15077 require structural equality checking to compare
15078 TEMPLATE_TEMPLATE_PARMs. */
15079 SET_TYPE_STRUCTURAL_EQUALITY (r);
15080 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
15081 SET_TYPE_STRUCTURAL_EQUALITY (r);
15082 else
15083 TYPE_CANONICAL (r) = canonical_type_parameter (r);
15085 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15087 tree tinfo = TYPE_TEMPLATE_INFO (t);
15088 /* We might need to substitute into the types of non-type
15089 template parameters. */
15090 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
15091 complain, in_decl);
15092 if (tmpl == error_mark_node)
15093 return error_mark_node;
15094 tree argvec = tsubst (TI_ARGS (tinfo), args,
15095 complain, in_decl);
15096 if (argvec == error_mark_node)
15097 return error_mark_node;
15099 TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
15100 = build_template_info (tmpl, argvec);
15103 break;
15105 case TEMPLATE_PARM_INDEX:
15106 /* OK, now substitute the type of the non-type parameter. We
15107 couldn't do it earlier because it might be an auto parameter,
15108 and we wouldn't need to if we had an argument. */
15109 type = tsubst (type, args, complain, in_decl);
15110 if (type == error_mark_node)
15111 return error_mark_node;
15112 r = reduce_template_parm_level (t, type, levels, args, complain);
15113 break;
15115 default:
15116 gcc_unreachable ();
15119 return r;
15122 case TREE_LIST:
15124 tree purpose, value, chain;
15126 if (t == void_list_node)
15127 return t;
15129 purpose = TREE_PURPOSE (t);
15130 if (purpose)
15132 purpose = tsubst (purpose, args, complain, in_decl);
15133 if (purpose == error_mark_node)
15134 return error_mark_node;
15136 value = TREE_VALUE (t);
15137 if (value)
15139 value = tsubst (value, args, complain, in_decl);
15140 if (value == error_mark_node)
15141 return error_mark_node;
15143 chain = TREE_CHAIN (t);
15144 if (chain && chain != void_type_node)
15146 chain = tsubst (chain, args, complain, in_decl);
15147 if (chain == error_mark_node)
15148 return error_mark_node;
15150 if (purpose == TREE_PURPOSE (t)
15151 && value == TREE_VALUE (t)
15152 && chain == TREE_CHAIN (t))
15153 return t;
15154 return hash_tree_cons (purpose, value, chain);
15157 case TREE_BINFO:
15158 /* We should never be tsubsting a binfo. */
15159 gcc_unreachable ();
15161 case TREE_VEC:
15162 /* A vector of template arguments. */
15163 gcc_assert (!type);
15164 return tsubst_template_args (t, args, complain, in_decl);
15166 case POINTER_TYPE:
15167 case REFERENCE_TYPE:
15169 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
15170 return t;
15172 /* [temp.deduct]
15174 Type deduction may fail for any of the following
15175 reasons:
15177 -- Attempting to create a pointer to reference type.
15178 -- Attempting to create a reference to a reference type or
15179 a reference to void.
15181 Core issue 106 says that creating a reference to a reference
15182 during instantiation is no longer a cause for failure. We
15183 only enforce this check in strict C++98 mode. */
15184 if ((TYPE_REF_P (type)
15185 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
15186 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
15188 static location_t last_loc;
15190 /* We keep track of the last time we issued this error
15191 message to avoid spewing a ton of messages during a
15192 single bad template instantiation. */
15193 if (complain & tf_error
15194 && last_loc != input_location)
15196 if (VOID_TYPE_P (type))
15197 error ("forming reference to void");
15198 else if (code == POINTER_TYPE)
15199 error ("forming pointer to reference type %qT", type);
15200 else
15201 error ("forming reference to reference type %qT", type);
15202 last_loc = input_location;
15205 return error_mark_node;
15207 else if (TREE_CODE (type) == FUNCTION_TYPE
15208 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
15209 || type_memfn_rqual (type) != REF_QUAL_NONE))
15211 if (complain & tf_error)
15213 if (code == POINTER_TYPE)
15214 error ("forming pointer to qualified function type %qT",
15215 type);
15216 else
15217 error ("forming reference to qualified function type %qT",
15218 type);
15220 return error_mark_node;
15222 else if (code == POINTER_TYPE)
15224 r = build_pointer_type (type);
15225 if (TREE_CODE (type) == METHOD_TYPE)
15226 r = build_ptrmemfunc_type (r);
15228 else if (TYPE_REF_P (type))
15229 /* In C++0x, during template argument substitution, when there is an
15230 attempt to create a reference to a reference type, reference
15231 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
15233 "If a template-argument for a template-parameter T names a type
15234 that is a reference to a type A, an attempt to create the type
15235 'lvalue reference to cv T' creates the type 'lvalue reference to
15236 A,' while an attempt to create the type type rvalue reference to
15237 cv T' creates the type T"
15239 r = cp_build_reference_type
15240 (TREE_TYPE (type),
15241 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
15242 else
15243 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
15244 r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
15246 if (r != error_mark_node)
15247 /* Will this ever be needed for TYPE_..._TO values? */
15248 layout_type (r);
15250 return r;
15252 case OFFSET_TYPE:
15254 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
15255 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
15257 /* [temp.deduct]
15259 Type deduction may fail for any of the following
15260 reasons:
15262 -- Attempting to create "pointer to member of T" when T
15263 is not a class type. */
15264 if (complain & tf_error)
15265 error ("creating pointer to member of non-class type %qT", r);
15266 return error_mark_node;
15268 if (TYPE_REF_P (type))
15270 if (complain & tf_error)
15271 error ("creating pointer to member reference type %qT", type);
15272 return error_mark_node;
15274 if (VOID_TYPE_P (type))
15276 if (complain & tf_error)
15277 error ("creating pointer to member of type void");
15278 return error_mark_node;
15280 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
15281 if (TREE_CODE (type) == FUNCTION_TYPE)
15283 /* The type of the implicit object parameter gets its
15284 cv-qualifiers from the FUNCTION_TYPE. */
15285 tree memptr;
15286 tree method_type
15287 = build_memfn_type (type, r, type_memfn_quals (type),
15288 type_memfn_rqual (type));
15289 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
15290 return cp_build_qualified_type_real (memptr, cp_type_quals (t),
15291 complain);
15293 else
15294 return cp_build_qualified_type_real (build_ptrmem_type (r, type),
15295 cp_type_quals (t),
15296 complain);
15298 case FUNCTION_TYPE:
15299 case METHOD_TYPE:
15301 tree fntype;
15302 tree specs;
15303 fntype = tsubst_function_type (t, args, complain, in_decl);
15304 if (fntype == error_mark_node)
15305 return error_mark_node;
15307 /* Substitute the exception specification. */
15308 specs = tsubst_exception_specification (t, args, complain, in_decl,
15309 /*defer_ok*/fndecl_type);
15310 if (specs == error_mark_node)
15311 return error_mark_node;
15312 if (specs)
15313 fntype = build_exception_variant (fntype, specs);
15314 return fntype;
15316 case ARRAY_TYPE:
15318 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
15319 if (domain == error_mark_node)
15320 return error_mark_node;
15322 /* As an optimization, we avoid regenerating the array type if
15323 it will obviously be the same as T. */
15324 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
15325 return t;
15327 /* These checks should match the ones in create_array_type_for_decl.
15329 [temp.deduct]
15331 The deduction may fail for any of the following reasons:
15333 -- Attempting to create an array with an element type that
15334 is void, a function type, or a reference type, or [DR337]
15335 an abstract class type. */
15336 if (VOID_TYPE_P (type)
15337 || TREE_CODE (type) == FUNCTION_TYPE
15338 || (TREE_CODE (type) == ARRAY_TYPE
15339 && TYPE_DOMAIN (type) == NULL_TREE)
15340 || TYPE_REF_P (type))
15342 if (complain & tf_error)
15343 error ("creating array of %qT", type);
15344 return error_mark_node;
15347 if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
15348 return error_mark_node;
15350 r = build_cplus_array_type (type, domain);
15352 if (!valid_array_size_p (input_location, r, in_decl,
15353 (complain & tf_error)))
15354 return error_mark_node;
15356 if (TYPE_USER_ALIGN (t))
15358 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
15359 TYPE_USER_ALIGN (r) = 1;
15362 return r;
15365 case TYPENAME_TYPE:
15367 tree ctx = TYPE_CONTEXT (t);
15368 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
15370 ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
15371 if (ctx == error_mark_node
15372 || TREE_VEC_LENGTH (ctx) > 1)
15373 return error_mark_node;
15374 if (TREE_VEC_LENGTH (ctx) == 0)
15376 if (complain & tf_error)
15377 error ("%qD is instantiated for an empty pack",
15378 TYPENAME_TYPE_FULLNAME (t));
15379 return error_mark_node;
15381 ctx = TREE_VEC_ELT (ctx, 0);
15383 else
15384 ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
15385 /*entering_scope=*/1);
15386 if (ctx == error_mark_node)
15387 return error_mark_node;
15389 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
15390 complain, in_decl);
15391 if (f == error_mark_node)
15392 return error_mark_node;
15394 if (!MAYBE_CLASS_TYPE_P (ctx))
15396 if (complain & tf_error)
15397 error ("%qT is not a class, struct, or union type", ctx);
15398 return error_mark_node;
15400 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
15402 /* Normally, make_typename_type does not require that the CTX
15403 have complete type in order to allow things like:
15405 template <class T> struct S { typename S<T>::X Y; };
15407 But, such constructs have already been resolved by this
15408 point, so here CTX really should have complete type, unless
15409 it's a partial instantiation. */
15410 ctx = complete_type (ctx);
15411 if (!COMPLETE_TYPE_P (ctx))
15413 if (complain & tf_error)
15414 cxx_incomplete_type_error (NULL_TREE, ctx);
15415 return error_mark_node;
15419 f = make_typename_type (ctx, f, typename_type,
15420 complain | tf_keep_type_decl);
15421 if (f == error_mark_node)
15422 return f;
15423 if (TREE_CODE (f) == TYPE_DECL)
15425 complain |= tf_ignore_bad_quals;
15426 f = TREE_TYPE (f);
15429 if (TREE_CODE (f) != TYPENAME_TYPE)
15431 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
15433 if (complain & tf_error)
15434 error ("%qT resolves to %qT, which is not an enumeration type",
15435 t, f);
15436 else
15437 return error_mark_node;
15439 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
15441 if (complain & tf_error)
15442 error ("%qT resolves to %qT, which is is not a class type",
15443 t, f);
15444 else
15445 return error_mark_node;
15449 return cp_build_qualified_type_real
15450 (f, cp_type_quals (f) | cp_type_quals (t), complain);
15453 case UNBOUND_CLASS_TEMPLATE:
15455 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
15456 in_decl, /*entering_scope=*/1);
15457 tree name = TYPE_IDENTIFIER (t);
15458 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
15460 if (ctx == error_mark_node || name == error_mark_node)
15461 return error_mark_node;
15463 if (parm_list)
15464 parm_list = tsubst_template_parms (parm_list, args, complain);
15465 return make_unbound_class_template (ctx, name, parm_list, complain);
15468 case TYPEOF_TYPE:
15470 tree type;
15472 ++cp_unevaluated_operand;
15473 ++c_inhibit_evaluation_warnings;
15475 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
15476 complain, in_decl,
15477 /*integral_constant_expression_p=*/false);
15479 --cp_unevaluated_operand;
15480 --c_inhibit_evaluation_warnings;
15482 type = finish_typeof (type);
15483 return cp_build_qualified_type_real (type,
15484 cp_type_quals (t)
15485 | cp_type_quals (type),
15486 complain);
15489 case DECLTYPE_TYPE:
15491 tree type;
15493 ++cp_unevaluated_operand;
15494 ++c_inhibit_evaluation_warnings;
15496 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
15497 complain|tf_decltype, in_decl,
15498 /*function_p*/false,
15499 /*integral_constant_expression*/false);
15501 --cp_unevaluated_operand;
15502 --c_inhibit_evaluation_warnings;
15504 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
15505 type = lambda_capture_field_type (type,
15506 false /*explicit_init*/,
15507 DECLTYPE_FOR_REF_CAPTURE (t));
15508 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
15509 type = lambda_proxy_type (type);
15510 else
15512 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
15513 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
15514 && EXPR_P (type))
15515 /* In a template ~id could be either a complement expression
15516 or an unqualified-id naming a destructor; if instantiating
15517 it produces an expression, it's not an id-expression or
15518 member access. */
15519 id = false;
15520 type = finish_decltype_type (type, id, complain);
15522 return cp_build_qualified_type_real (type,
15523 cp_type_quals (t)
15524 | cp_type_quals (type),
15525 complain | tf_ignore_bad_quals);
15528 case UNDERLYING_TYPE:
15530 tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
15531 complain, in_decl);
15532 return finish_underlying_type (type);
15535 case TYPE_ARGUMENT_PACK:
15536 case NONTYPE_ARGUMENT_PACK:
15538 tree r;
15540 if (code == NONTYPE_ARGUMENT_PACK)
15541 r = make_node (code);
15542 else
15543 r = cxx_make_type (code);
15545 tree pack_args = ARGUMENT_PACK_ARGS (t);
15546 pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
15547 SET_ARGUMENT_PACK_ARGS (r, pack_args);
15549 return r;
15552 case VOID_CST:
15553 case INTEGER_CST:
15554 case REAL_CST:
15555 case STRING_CST:
15556 case PLUS_EXPR:
15557 case MINUS_EXPR:
15558 case NEGATE_EXPR:
15559 case NOP_EXPR:
15560 case INDIRECT_REF:
15561 case ADDR_EXPR:
15562 case CALL_EXPR:
15563 case ARRAY_REF:
15564 case SCOPE_REF:
15565 /* We should use one of the expression tsubsts for these codes. */
15566 gcc_unreachable ();
15568 default:
15569 sorry ("use of %qs in template", get_tree_code_name (code));
15570 return error_mark_node;
15574 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
15575 expression on the left-hand side of the "." or "->" operator. We
15576 only do the lookup if we had a dependent BASELINK. Otherwise we
15577 adjust it onto the instantiated heirarchy. */
15579 static tree
15580 tsubst_baselink (tree baselink, tree object_type,
15581 tree args, tsubst_flags_t complain, tree in_decl)
15583 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15584 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15585 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15587 tree optype = BASELINK_OPTYPE (baselink);
15588 optype = tsubst (optype, args, complain, in_decl);
15590 tree template_args = NULL_TREE;
15591 bool template_id_p = false;
15592 tree fns = BASELINK_FUNCTIONS (baselink);
15593 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15595 template_id_p = true;
15596 template_args = TREE_OPERAND (fns, 1);
15597 fns = TREE_OPERAND (fns, 0);
15598 if (template_args)
15599 template_args = tsubst_template_args (template_args, args,
15600 complain, in_decl);
15603 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15604 binfo_type = tsubst (binfo_type, args, complain, in_decl);
15605 bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15607 if (dependent_p)
15609 tree name = OVL_NAME (fns);
15610 if (IDENTIFIER_CONV_OP_P (name))
15611 name = make_conv_op_name (optype);
15613 if (name == complete_dtor_identifier)
15614 /* Treat as-if non-dependent below. */
15615 dependent_p = false;
15617 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15618 if (!baselink)
15620 if ((complain & tf_error)
15621 && constructor_name_p (name, qualifying_scope))
15622 error ("cannot call constructor %<%T::%D%> directly",
15623 qualifying_scope, name);
15624 return error_mark_node;
15627 if (BASELINK_P (baselink))
15628 fns = BASELINK_FUNCTIONS (baselink);
15630 else
15631 /* We're going to overwrite pieces below, make a duplicate. */
15632 baselink = copy_node (baselink);
15634 /* If lookup found a single function, mark it as used at this point.
15635 (If lookup found multiple functions the one selected later by
15636 overload resolution will be marked as used at that point.) */
15637 if (!template_id_p && !really_overloaded_fn (fns))
15639 tree fn = OVL_FIRST (fns);
15640 bool ok = mark_used (fn, complain);
15641 if (!ok && !(complain & tf_error))
15642 return error_mark_node;
15643 if (ok && BASELINK_P (baselink))
15644 /* We might have instantiated an auto function. */
15645 TREE_TYPE (baselink) = TREE_TYPE (fn);
15648 if (BASELINK_P (baselink))
15650 /* Add back the template arguments, if present. */
15651 if (template_id_p)
15652 BASELINK_FUNCTIONS (baselink)
15653 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15655 /* Update the conversion operator type. */
15656 BASELINK_OPTYPE (baselink) = optype;
15659 if (!object_type)
15660 object_type = current_class_type;
15662 if (qualified_p || !dependent_p)
15664 baselink = adjust_result_of_qualified_name_lookup (baselink,
15665 qualifying_scope,
15666 object_type);
15667 if (!qualified_p)
15668 /* We need to call adjust_result_of_qualified_name_lookup in case the
15669 destructor names a base class, but we unset BASELINK_QUALIFIED_P
15670 so that we still get virtual function binding. */
15671 BASELINK_QUALIFIED_P (baselink) = false;
15674 return baselink;
15677 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
15678 true if the qualified-id will be a postfix-expression in-and-of
15679 itself; false if more of the postfix-expression follows the
15680 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
15681 of "&". */
15683 static tree
15684 tsubst_qualified_id (tree qualified_id, tree args,
15685 tsubst_flags_t complain, tree in_decl,
15686 bool done, bool address_p)
15688 tree expr;
15689 tree scope;
15690 tree name;
15691 bool is_template;
15692 tree template_args;
15693 location_t loc = UNKNOWN_LOCATION;
15695 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15697 /* Figure out what name to look up. */
15698 name = TREE_OPERAND (qualified_id, 1);
15699 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15701 is_template = true;
15702 loc = EXPR_LOCATION (name);
15703 template_args = TREE_OPERAND (name, 1);
15704 if (template_args)
15705 template_args = tsubst_template_args (template_args, args,
15706 complain, in_decl);
15707 if (template_args == error_mark_node)
15708 return error_mark_node;
15709 name = TREE_OPERAND (name, 0);
15711 else
15713 is_template = false;
15714 template_args = NULL_TREE;
15717 /* Substitute into the qualifying scope. When there are no ARGS, we
15718 are just trying to simplify a non-dependent expression. In that
15719 case the qualifying scope may be dependent, and, in any case,
15720 substituting will not help. */
15721 scope = TREE_OPERAND (qualified_id, 0);
15722 if (args)
15724 scope = tsubst (scope, args, complain, in_decl);
15725 expr = tsubst_copy (name, args, complain, in_decl);
15727 else
15728 expr = name;
15730 if (dependent_scope_p (scope))
15732 if (is_template)
15733 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15734 tree r = build_qualified_name (NULL_TREE, scope, expr,
15735 QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15736 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15737 return r;
15740 if (!BASELINK_P (name) && !DECL_P (expr))
15742 if (TREE_CODE (expr) == BIT_NOT_EXPR)
15744 /* A BIT_NOT_EXPR is used to represent a destructor. */
15745 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15747 error ("qualifying type %qT does not match destructor name ~%qT",
15748 scope, TREE_OPERAND (expr, 0));
15749 expr = error_mark_node;
15751 else
15752 expr = lookup_qualified_name (scope, complete_dtor_identifier,
15753 /*is_type_p=*/0, false);
15755 else
15756 expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15757 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15758 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15760 if (complain & tf_error)
15762 error ("dependent-name %qE is parsed as a non-type, but "
15763 "instantiation yields a type", qualified_id);
15764 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15766 return error_mark_node;
15770 if (DECL_P (expr))
15772 check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15773 scope);
15774 /* Remember that there was a reference to this entity. */
15775 if (!mark_used (expr, complain) && !(complain & tf_error))
15776 return error_mark_node;
15779 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15781 if (complain & tf_error)
15782 qualified_name_lookup_error (scope,
15783 TREE_OPERAND (qualified_id, 1),
15784 expr, input_location);
15785 return error_mark_node;
15788 if (is_template)
15790 /* We may be repeating a check already done during parsing, but
15791 if it was well-formed and passed then, it will pass again
15792 now, and if it didn't, we wouldn't have got here. The case
15793 we want to catch is when we couldn't tell then, and can now,
15794 namely when templ prior to substitution was an
15795 identifier. */
15796 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15797 return error_mark_node;
15799 if (variable_template_p (expr))
15800 expr = lookup_and_finish_template_variable (expr, template_args,
15801 complain);
15802 else
15803 expr = lookup_template_function (expr, template_args);
15806 if (expr == error_mark_node && complain & tf_error)
15807 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15808 expr, input_location);
15809 else if (TYPE_P (scope))
15811 expr = (adjust_result_of_qualified_name_lookup
15812 (expr, scope, current_nonlambda_class_type ()));
15813 expr = (finish_qualified_id_expr
15814 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15815 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15816 /*template_arg_p=*/false, complain));
15819 /* Expressions do not generally have reference type. */
15820 if (TREE_CODE (expr) != SCOPE_REF
15821 /* However, if we're about to form a pointer-to-member, we just
15822 want the referenced member referenced. */
15823 && TREE_CODE (expr) != OFFSET_REF)
15824 expr = convert_from_reference (expr);
15826 if (REF_PARENTHESIZED_P (qualified_id))
15827 expr = force_paren_expr (expr);
15829 return expr;
15832 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
15833 initializer, DECL is the substituted VAR_DECL. Other arguments are as
15834 for tsubst. */
15836 static tree
15837 tsubst_init (tree init, tree decl, tree args,
15838 tsubst_flags_t complain, tree in_decl)
15840 if (!init)
15841 return NULL_TREE;
15843 init = tsubst_expr (init, args, complain, in_decl, false);
15845 tree type = TREE_TYPE (decl);
15847 if (!init && type != error_mark_node)
15849 if (tree auto_node = type_uses_auto (type))
15851 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
15853 if (complain & tf_error)
15854 error ("initializer for %q#D expands to an empty list "
15855 "of expressions", decl);
15856 return error_mark_node;
15859 else if (!dependent_type_p (type))
15861 /* If we had an initializer but it
15862 instantiated to nothing,
15863 value-initialize the object. This will
15864 only occur when the initializer was a
15865 pack expansion where the parameter packs
15866 used in that expansion were of length
15867 zero. */
15868 init = build_value_init (type, complain);
15869 if (TREE_CODE (init) == AGGR_INIT_EXPR)
15870 init = get_target_expr_sfinae (init, complain);
15871 if (TREE_CODE (init) == TARGET_EXPR)
15872 TARGET_EXPR_DIRECT_INIT_P (init) = true;
15876 return init;
15879 /* Like tsubst, but deals with expressions. This function just replaces
15880 template parms; to finish processing the resultant expression, use
15881 tsubst_copy_and_build or tsubst_expr. */
15883 static tree
15884 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15886 enum tree_code code;
15887 tree r;
15889 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15890 return t;
15892 code = TREE_CODE (t);
15894 switch (code)
15896 case PARM_DECL:
15897 r = retrieve_local_specialization (t);
15899 if (r == NULL_TREE)
15901 /* We get here for a use of 'this' in an NSDMI. */
15902 if (DECL_NAME (t) == this_identifier && current_class_ptr)
15903 return current_class_ptr;
15905 /* This can happen for a parameter name used later in a function
15906 declaration (such as in a late-specified return type). Just
15907 make a dummy decl, since it's only used for its type. */
15908 gcc_assert (cp_unevaluated_operand != 0);
15909 r = tsubst_decl (t, args, complain);
15910 /* Give it the template pattern as its context; its true context
15911 hasn't been instantiated yet and this is good enough for
15912 mangling. */
15913 DECL_CONTEXT (r) = DECL_CONTEXT (t);
15916 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15917 r = argument_pack_select_arg (r);
15918 if (!mark_used (r, complain) && !(complain & tf_error))
15919 return error_mark_node;
15920 return r;
15922 case CONST_DECL:
15924 tree enum_type;
15925 tree v;
15927 if (DECL_TEMPLATE_PARM_P (t))
15928 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15929 /* There is no need to substitute into namespace-scope
15930 enumerators. */
15931 if (DECL_NAMESPACE_SCOPE_P (t))
15932 return t;
15933 /* If ARGS is NULL, then T is known to be non-dependent. */
15934 if (args == NULL_TREE)
15935 return scalar_constant_value (t);
15937 /* Unfortunately, we cannot just call lookup_name here.
15938 Consider:
15940 template <int I> int f() {
15941 enum E { a = I };
15942 struct S { void g() { E e = a; } };
15945 When we instantiate f<7>::S::g(), say, lookup_name is not
15946 clever enough to find f<7>::a. */
15947 enum_type
15948 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15949 /*entering_scope=*/0);
15951 for (v = TYPE_VALUES (enum_type);
15952 v != NULL_TREE;
15953 v = TREE_CHAIN (v))
15954 if (TREE_PURPOSE (v) == DECL_NAME (t))
15955 return TREE_VALUE (v);
15957 /* We didn't find the name. That should never happen; if
15958 name-lookup found it during preliminary parsing, we
15959 should find it again here during instantiation. */
15960 gcc_unreachable ();
15962 return t;
15964 case FIELD_DECL:
15965 if (DECL_CONTEXT (t))
15967 tree ctx;
15969 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15970 /*entering_scope=*/1);
15971 if (ctx != DECL_CONTEXT (t))
15973 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15974 if (!r)
15976 if (complain & tf_error)
15977 error ("using invalid field %qD", t);
15978 return error_mark_node;
15980 return r;
15984 return t;
15986 case VAR_DECL:
15987 case FUNCTION_DECL:
15988 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15989 r = tsubst (t, args, complain, in_decl);
15990 else if (local_variable_p (t)
15991 && uses_template_parms (DECL_CONTEXT (t)))
15993 r = retrieve_local_specialization (t);
15994 if (r == NULL_TREE)
15996 /* First try name lookup to find the instantiation. */
15997 r = lookup_name (DECL_NAME (t));
15998 if (r)
16000 if (!VAR_P (r))
16002 /* During error-recovery we may find a non-variable,
16003 even an OVERLOAD: just bail out and avoid ICEs and
16004 duplicate diagnostics (c++/62207). */
16005 gcc_assert (seen_error ());
16006 return error_mark_node;
16008 if (!is_capture_proxy (r))
16010 /* Make sure the one we found is the one we want. */
16011 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
16012 if (ctx != DECL_CONTEXT (r))
16013 r = NULL_TREE;
16017 if (r)
16018 /* OK */;
16019 else
16021 /* This can happen for a variable used in a
16022 late-specified return type of a local lambda, or for a
16023 local static or constant. Building a new VAR_DECL
16024 should be OK in all those cases. */
16025 r = tsubst_decl (t, args, complain);
16026 if (local_specializations)
16027 /* Avoid infinite recursion (79640). */
16028 register_local_specialization (r, t);
16029 if (decl_maybe_constant_var_p (r))
16031 /* We can't call cp_finish_decl, so handle the
16032 initializer by hand. */
16033 tree init = tsubst_init (DECL_INITIAL (t), r, args,
16034 complain, in_decl);
16035 if (!processing_template_decl)
16036 init = maybe_constant_init (init);
16037 if (processing_template_decl
16038 ? potential_constant_expression (init)
16039 : reduced_constant_expression_p (init))
16040 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
16041 = TREE_CONSTANT (r) = true;
16042 DECL_INITIAL (r) = init;
16043 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
16044 TREE_TYPE (r)
16045 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
16046 complain, adc_variable_type);
16048 gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
16049 || decl_constant_var_p (r)
16050 || seen_error ());
16051 if (!processing_template_decl
16052 && !TREE_STATIC (r))
16053 r = process_outer_var_ref (r, complain);
16055 /* Remember this for subsequent uses. */
16056 if (local_specializations)
16057 register_local_specialization (r, t);
16059 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16060 r = argument_pack_select_arg (r);
16062 else
16063 r = t;
16064 if (!mark_used (r, complain))
16065 return error_mark_node;
16066 return r;
16068 case NAMESPACE_DECL:
16069 return t;
16071 case OVERLOAD:
16072 return t;
16074 case BASELINK:
16075 return tsubst_baselink (t, current_nonlambda_class_type (),
16076 args, complain, in_decl);
16078 case TEMPLATE_DECL:
16079 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
16080 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
16081 args, complain, in_decl);
16082 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
16083 return tsubst (t, args, complain, in_decl);
16084 else if (DECL_CLASS_SCOPE_P (t)
16085 && uses_template_parms (DECL_CONTEXT (t)))
16087 /* Template template argument like the following example need
16088 special treatment:
16090 template <template <class> class TT> struct C {};
16091 template <class T> struct D {
16092 template <class U> struct E {};
16093 C<E> c; // #1
16095 D<int> d; // #2
16097 We are processing the template argument `E' in #1 for
16098 the template instantiation #2. Originally, `E' is a
16099 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
16100 have to substitute this with one having context `D<int>'. */
16102 tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
16103 if (dependent_scope_p (context))
16105 /* When rewriting a constructor into a deduction guide, a
16106 non-dependent name can become dependent, so memtmpl<args>
16107 becomes context::template memtmpl<args>. */
16108 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16109 return build_qualified_name (type, context, DECL_NAME (t),
16110 /*template*/true);
16112 return lookup_field (context, DECL_NAME(t), 0, false);
16114 else
16115 /* Ordinary template template argument. */
16116 return t;
16118 case NON_LVALUE_EXPR:
16119 case VIEW_CONVERT_EXPR:
16121 /* Handle location wrappers by substituting the wrapped node
16122 first, *then* reusing the resulting type. Doing the type
16123 first ensures that we handle template parameters and
16124 parameter pack expansions. */
16125 if (location_wrapper_p (t))
16127 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
16128 complain, in_decl);
16129 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
16131 tree op = TREE_OPERAND (t, 0);
16132 if (code == VIEW_CONVERT_EXPR
16133 && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16135 /* Wrapper to make a C++20 template parameter object const. */
16136 op = tsubst_copy (op, args, complain, in_decl);
16137 if (TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16139 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16140 return build1 (code, type, op);
16142 else
16144 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (op)));
16145 return op;
16148 /* We shouldn't see any other uses of these in templates. */
16149 gcc_unreachable ();
16152 case CAST_EXPR:
16153 case REINTERPRET_CAST_EXPR:
16154 case CONST_CAST_EXPR:
16155 case STATIC_CAST_EXPR:
16156 case DYNAMIC_CAST_EXPR:
16157 case IMPLICIT_CONV_EXPR:
16158 case CONVERT_EXPR:
16159 case NOP_EXPR:
16161 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16162 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16163 return build1 (code, type, op0);
16166 case SIZEOF_EXPR:
16167 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16168 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16170 tree expanded, op = TREE_OPERAND (t, 0);
16171 int len = 0;
16173 if (SIZEOF_EXPR_TYPE_P (t))
16174 op = TREE_TYPE (op);
16176 ++cp_unevaluated_operand;
16177 ++c_inhibit_evaluation_warnings;
16178 /* We only want to compute the number of arguments. */
16179 if (PACK_EXPANSION_P (op))
16180 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
16181 else
16182 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
16183 args, complain, in_decl);
16184 --cp_unevaluated_operand;
16185 --c_inhibit_evaluation_warnings;
16187 if (TREE_CODE (expanded) == TREE_VEC)
16189 len = TREE_VEC_LENGTH (expanded);
16190 /* Set TREE_USED for the benefit of -Wunused. */
16191 for (int i = 0; i < len; i++)
16192 if (DECL_P (TREE_VEC_ELT (expanded, i)))
16193 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
16196 if (expanded == error_mark_node)
16197 return error_mark_node;
16198 else if (PACK_EXPANSION_P (expanded)
16199 || (TREE_CODE (expanded) == TREE_VEC
16200 && pack_expansion_args_count (expanded)))
16203 if (PACK_EXPANSION_P (expanded))
16204 /* OK. */;
16205 else if (TREE_VEC_LENGTH (expanded) == 1)
16206 expanded = TREE_VEC_ELT (expanded, 0);
16207 else
16208 expanded = make_argument_pack (expanded);
16210 if (TYPE_P (expanded))
16211 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
16212 false,
16213 complain & tf_error);
16214 else
16215 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
16216 complain & tf_error);
16218 else
16219 return build_int_cst (size_type_node, len);
16221 if (SIZEOF_EXPR_TYPE_P (t))
16223 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
16224 args, complain, in_decl);
16225 r = build1 (NOP_EXPR, r, error_mark_node);
16226 r = build1 (SIZEOF_EXPR,
16227 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
16228 SIZEOF_EXPR_TYPE_P (r) = 1;
16229 return r;
16231 /* Fall through */
16233 case INDIRECT_REF:
16234 case NEGATE_EXPR:
16235 case TRUTH_NOT_EXPR:
16236 case BIT_NOT_EXPR:
16237 case ADDR_EXPR:
16238 case UNARY_PLUS_EXPR: /* Unary + */
16239 case ALIGNOF_EXPR:
16240 case AT_ENCODE_EXPR:
16241 case ARROW_EXPR:
16242 case THROW_EXPR:
16243 case TYPEID_EXPR:
16244 case REALPART_EXPR:
16245 case IMAGPART_EXPR:
16246 case PAREN_EXPR:
16248 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16249 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16250 r = build1 (code, type, op0);
16251 if (code == ALIGNOF_EXPR)
16252 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
16253 return r;
16256 case COMPONENT_REF:
16258 tree object;
16259 tree name;
16261 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16262 name = TREE_OPERAND (t, 1);
16263 if (TREE_CODE (name) == BIT_NOT_EXPR)
16265 name = tsubst_copy (TREE_OPERAND (name, 0), args,
16266 complain, in_decl);
16267 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16269 else if (TREE_CODE (name) == SCOPE_REF
16270 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
16272 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
16273 complain, in_decl);
16274 name = TREE_OPERAND (name, 1);
16275 name = tsubst_copy (TREE_OPERAND (name, 0), args,
16276 complain, in_decl);
16277 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16278 name = build_qualified_name (/*type=*/NULL_TREE,
16279 base, name,
16280 /*template_p=*/false);
16282 else if (BASELINK_P (name))
16283 name = tsubst_baselink (name,
16284 non_reference (TREE_TYPE (object)),
16285 args, complain,
16286 in_decl);
16287 else
16288 name = tsubst_copy (name, args, complain, in_decl);
16289 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
16292 case PLUS_EXPR:
16293 case MINUS_EXPR:
16294 case MULT_EXPR:
16295 case TRUNC_DIV_EXPR:
16296 case CEIL_DIV_EXPR:
16297 case FLOOR_DIV_EXPR:
16298 case ROUND_DIV_EXPR:
16299 case EXACT_DIV_EXPR:
16300 case BIT_AND_EXPR:
16301 case BIT_IOR_EXPR:
16302 case BIT_XOR_EXPR:
16303 case TRUNC_MOD_EXPR:
16304 case FLOOR_MOD_EXPR:
16305 case TRUTH_ANDIF_EXPR:
16306 case TRUTH_ORIF_EXPR:
16307 case TRUTH_AND_EXPR:
16308 case TRUTH_OR_EXPR:
16309 case RSHIFT_EXPR:
16310 case LSHIFT_EXPR:
16311 case EQ_EXPR:
16312 case NE_EXPR:
16313 case MAX_EXPR:
16314 case MIN_EXPR:
16315 case LE_EXPR:
16316 case GE_EXPR:
16317 case LT_EXPR:
16318 case GT_EXPR:
16319 case COMPOUND_EXPR:
16320 case DOTSTAR_EXPR:
16321 case MEMBER_REF:
16322 case PREDECREMENT_EXPR:
16323 case PREINCREMENT_EXPR:
16324 case POSTDECREMENT_EXPR:
16325 case POSTINCREMENT_EXPR:
16327 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16328 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16329 return build_nt (code, op0, op1);
16332 case SCOPE_REF:
16334 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16335 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16336 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
16337 QUALIFIED_NAME_IS_TEMPLATE (t));
16340 case ARRAY_REF:
16342 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16343 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16344 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
16347 case CALL_EXPR:
16349 int n = VL_EXP_OPERAND_LENGTH (t);
16350 tree result = build_vl_exp (CALL_EXPR, n);
16351 int i;
16352 for (i = 0; i < n; i++)
16353 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
16354 complain, in_decl);
16355 return result;
16358 case COND_EXPR:
16359 case MODOP_EXPR:
16360 case PSEUDO_DTOR_EXPR:
16361 case VEC_PERM_EXPR:
16363 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16364 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16365 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16366 r = build_nt (code, op0, op1, op2);
16367 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16368 return r;
16371 case NEW_EXPR:
16373 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16374 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16375 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16376 r = build_nt (code, op0, op1, op2);
16377 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
16378 return r;
16381 case DELETE_EXPR:
16383 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16384 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16385 r = build_nt (code, op0, op1);
16386 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
16387 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
16388 return r;
16391 case TEMPLATE_ID_EXPR:
16393 /* Substituted template arguments */
16394 tree fn = TREE_OPERAND (t, 0);
16395 tree targs = TREE_OPERAND (t, 1);
16397 fn = tsubst_copy (fn, args, complain, in_decl);
16398 if (targs)
16399 targs = tsubst_template_args (targs, args, complain, in_decl);
16401 return lookup_template_function (fn, targs);
16404 case TREE_LIST:
16406 tree purpose, value, chain;
16408 if (t == void_list_node)
16409 return t;
16411 purpose = TREE_PURPOSE (t);
16412 if (purpose)
16413 purpose = tsubst_copy (purpose, args, complain, in_decl);
16414 value = TREE_VALUE (t);
16415 if (value)
16416 value = tsubst_copy (value, args, complain, in_decl);
16417 chain = TREE_CHAIN (t);
16418 if (chain && chain != void_type_node)
16419 chain = tsubst_copy (chain, args, complain, in_decl);
16420 if (purpose == TREE_PURPOSE (t)
16421 && value == TREE_VALUE (t)
16422 && chain == TREE_CHAIN (t))
16423 return t;
16424 return tree_cons (purpose, value, chain);
16427 case RECORD_TYPE:
16428 case UNION_TYPE:
16429 case ENUMERAL_TYPE:
16430 case INTEGER_TYPE:
16431 case TEMPLATE_TYPE_PARM:
16432 case TEMPLATE_TEMPLATE_PARM:
16433 case BOUND_TEMPLATE_TEMPLATE_PARM:
16434 case TEMPLATE_PARM_INDEX:
16435 case POINTER_TYPE:
16436 case REFERENCE_TYPE:
16437 case OFFSET_TYPE:
16438 case FUNCTION_TYPE:
16439 case METHOD_TYPE:
16440 case ARRAY_TYPE:
16441 case TYPENAME_TYPE:
16442 case UNBOUND_CLASS_TEMPLATE:
16443 case TYPEOF_TYPE:
16444 case DECLTYPE_TYPE:
16445 case TYPE_DECL:
16446 return tsubst (t, args, complain, in_decl);
16448 case USING_DECL:
16449 t = DECL_NAME (t);
16450 /* Fall through. */
16451 case IDENTIFIER_NODE:
16452 if (IDENTIFIER_CONV_OP_P (t))
16454 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16455 return make_conv_op_name (new_type);
16457 else
16458 return t;
16460 case CONSTRUCTOR:
16461 /* This is handled by tsubst_copy_and_build. */
16462 gcc_unreachable ();
16464 case VA_ARG_EXPR:
16466 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16467 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16468 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
16471 case CLEANUP_POINT_EXPR:
16472 /* We shouldn't have built any of these during initial template
16473 generation. Instead, they should be built during instantiation
16474 in response to the saved STMT_IS_FULL_EXPR_P setting. */
16475 gcc_unreachable ();
16477 case OFFSET_REF:
16479 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16480 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16481 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16482 r = build2 (code, type, op0, op1);
16483 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
16484 if (!mark_used (TREE_OPERAND (r, 1), complain)
16485 && !(complain & tf_error))
16486 return error_mark_node;
16487 return r;
16490 case EXPR_PACK_EXPANSION:
16491 error ("invalid use of pack expansion expression");
16492 return error_mark_node;
16494 case NONTYPE_ARGUMENT_PACK:
16495 error ("use %<...%> to expand argument pack");
16496 return error_mark_node;
16498 case VOID_CST:
16499 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
16500 return t;
16502 case INTEGER_CST:
16503 case REAL_CST:
16504 case STRING_CST:
16505 case COMPLEX_CST:
16507 /* Instantiate any typedefs in the type. */
16508 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16509 r = fold_convert (type, t);
16510 gcc_assert (TREE_CODE (r) == code);
16511 return r;
16514 case PTRMEM_CST:
16515 /* These can sometimes show up in a partial instantiation, but never
16516 involve template parms. */
16517 gcc_assert (!uses_template_parms (t));
16518 return t;
16520 case UNARY_LEFT_FOLD_EXPR:
16521 return tsubst_unary_left_fold (t, args, complain, in_decl);
16522 case UNARY_RIGHT_FOLD_EXPR:
16523 return tsubst_unary_right_fold (t, args, complain, in_decl);
16524 case BINARY_LEFT_FOLD_EXPR:
16525 return tsubst_binary_left_fold (t, args, complain, in_decl);
16526 case BINARY_RIGHT_FOLD_EXPR:
16527 return tsubst_binary_right_fold (t, args, complain, in_decl);
16528 case PREDICT_EXPR:
16529 return t;
16531 case DEBUG_BEGIN_STMT:
16532 /* ??? There's no point in copying it for now, but maybe some
16533 day it will contain more information, such as a pointer back
16534 to the containing function, inlined copy or so. */
16535 return t;
16537 default:
16538 /* We shouldn't get here, but keep going if !flag_checking. */
16539 if (flag_checking)
16540 gcc_unreachable ();
16541 return t;
16545 /* Helper function for tsubst_omp_clauses, used for instantiation of
16546 OMP_CLAUSE_DECL of clauses. */
16548 static tree
16549 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
16550 tree in_decl, tree *iterator_cache)
16552 if (decl == NULL_TREE)
16553 return NULL_TREE;
16555 /* Handle OpenMP iterators. */
16556 if (TREE_CODE (decl) == TREE_LIST
16557 && TREE_PURPOSE (decl)
16558 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
16560 tree ret;
16561 if (iterator_cache[0] == TREE_PURPOSE (decl))
16562 ret = iterator_cache[1];
16563 else
16565 tree *tp = &ret;
16566 begin_scope (sk_omp, NULL);
16567 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
16569 *tp = copy_node (it);
16570 TREE_VEC_ELT (*tp, 0)
16571 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
16572 TREE_VEC_ELT (*tp, 1)
16573 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
16574 /*integral_constant_expression_p=*/false);
16575 TREE_VEC_ELT (*tp, 2)
16576 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
16577 /*integral_constant_expression_p=*/false);
16578 TREE_VEC_ELT (*tp, 3)
16579 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
16580 /*integral_constant_expression_p=*/false);
16581 TREE_CHAIN (*tp) = NULL_TREE;
16582 tp = &TREE_CHAIN (*tp);
16584 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
16585 iterator_cache[0] = TREE_PURPOSE (decl);
16586 iterator_cache[1] = ret;
16588 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
16589 args, complain,
16590 in_decl, NULL));
16593 /* Handle an OpenMP array section represented as a TREE_LIST (or
16594 OMP_CLAUSE_DEPEND_KIND). An OMP_CLAUSE_DEPEND (with a depend
16595 kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
16596 TREE_LIST. We can handle it exactly the same as an array section
16597 (purpose, value, and a chain), even though the nomenclature
16598 (low_bound, length, etc) is different. */
16599 if (TREE_CODE (decl) == TREE_LIST)
16601 tree low_bound
16602 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
16603 /*integral_constant_expression_p=*/false);
16604 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
16605 /*integral_constant_expression_p=*/false);
16606 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
16607 in_decl, NULL);
16608 if (TREE_PURPOSE (decl) == low_bound
16609 && TREE_VALUE (decl) == length
16610 && TREE_CHAIN (decl) == chain)
16611 return decl;
16612 tree ret = tree_cons (low_bound, length, chain);
16613 OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
16614 = OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
16615 return ret;
16617 tree ret = tsubst_expr (decl, args, complain, in_decl,
16618 /*integral_constant_expression_p=*/false);
16619 /* Undo convert_from_reference tsubst_expr could have called. */
16620 if (decl
16621 && REFERENCE_REF_P (ret)
16622 && !REFERENCE_REF_P (decl))
16623 ret = TREE_OPERAND (ret, 0);
16624 return ret;
16627 /* Like tsubst_copy, but specifically for OpenMP clauses. */
16629 static tree
16630 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
16631 tree args, tsubst_flags_t complain, tree in_decl)
16633 tree new_clauses = NULL_TREE, nc, oc;
16634 tree linear_no_step = NULL_TREE;
16635 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
16637 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
16639 nc = copy_node (oc);
16640 OMP_CLAUSE_CHAIN (nc) = new_clauses;
16641 new_clauses = nc;
16643 switch (OMP_CLAUSE_CODE (nc))
16645 case OMP_CLAUSE_LASTPRIVATE:
16646 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16648 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16649 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16650 in_decl, /*integral_constant_expression_p=*/false);
16651 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16652 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16654 /* FALLTHRU */
16655 case OMP_CLAUSE_PRIVATE:
16656 case OMP_CLAUSE_SHARED:
16657 case OMP_CLAUSE_FIRSTPRIVATE:
16658 case OMP_CLAUSE_COPYIN:
16659 case OMP_CLAUSE_COPYPRIVATE:
16660 case OMP_CLAUSE_UNIFORM:
16661 case OMP_CLAUSE_DEPEND:
16662 case OMP_CLAUSE_FROM:
16663 case OMP_CLAUSE_TO:
16664 case OMP_CLAUSE_MAP:
16665 case OMP_CLAUSE_NONTEMPORAL:
16666 case OMP_CLAUSE_USE_DEVICE_PTR:
16667 case OMP_CLAUSE_USE_DEVICE_ADDR:
16668 case OMP_CLAUSE_IS_DEVICE_PTR:
16669 case OMP_CLAUSE_INCLUSIVE:
16670 case OMP_CLAUSE_EXCLUSIVE:
16671 OMP_CLAUSE_DECL (nc)
16672 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16673 in_decl, iterator_cache);
16674 break;
16675 case OMP_CLAUSE_TILE:
16676 case OMP_CLAUSE_IF:
16677 case OMP_CLAUSE_NUM_THREADS:
16678 case OMP_CLAUSE_SCHEDULE:
16679 case OMP_CLAUSE_COLLAPSE:
16680 case OMP_CLAUSE_FINAL:
16681 case OMP_CLAUSE_DEVICE:
16682 case OMP_CLAUSE_DIST_SCHEDULE:
16683 case OMP_CLAUSE_NUM_TEAMS:
16684 case OMP_CLAUSE_THREAD_LIMIT:
16685 case OMP_CLAUSE_SAFELEN:
16686 case OMP_CLAUSE_SIMDLEN:
16687 case OMP_CLAUSE_NUM_TASKS:
16688 case OMP_CLAUSE_GRAINSIZE:
16689 case OMP_CLAUSE_PRIORITY:
16690 case OMP_CLAUSE_ORDERED:
16691 case OMP_CLAUSE_HINT:
16692 case OMP_CLAUSE_NUM_GANGS:
16693 case OMP_CLAUSE_NUM_WORKERS:
16694 case OMP_CLAUSE_VECTOR_LENGTH:
16695 case OMP_CLAUSE_WORKER:
16696 case OMP_CLAUSE_VECTOR:
16697 case OMP_CLAUSE_ASYNC:
16698 case OMP_CLAUSE_WAIT:
16699 OMP_CLAUSE_OPERAND (nc, 0)
16700 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16701 in_decl, /*integral_constant_expression_p=*/false);
16702 break;
16703 case OMP_CLAUSE_REDUCTION:
16704 case OMP_CLAUSE_IN_REDUCTION:
16705 case OMP_CLAUSE_TASK_REDUCTION:
16706 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16708 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16709 if (TREE_CODE (placeholder) == SCOPE_REF)
16711 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16712 complain, in_decl);
16713 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16714 = build_qualified_name (NULL_TREE, scope,
16715 TREE_OPERAND (placeholder, 1),
16716 false);
16718 else
16719 gcc_assert (identifier_p (placeholder));
16721 OMP_CLAUSE_DECL (nc)
16722 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16723 in_decl, NULL);
16724 break;
16725 case OMP_CLAUSE_GANG:
16726 case OMP_CLAUSE_ALIGNED:
16727 OMP_CLAUSE_DECL (nc)
16728 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16729 in_decl, NULL);
16730 OMP_CLAUSE_OPERAND (nc, 1)
16731 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16732 in_decl, /*integral_constant_expression_p=*/false);
16733 break;
16734 case OMP_CLAUSE_LINEAR:
16735 OMP_CLAUSE_DECL (nc)
16736 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16737 in_decl, NULL);
16738 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16740 gcc_assert (!linear_no_step);
16741 linear_no_step = nc;
16743 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16744 OMP_CLAUSE_LINEAR_STEP (nc)
16745 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16746 complain, in_decl, NULL);
16747 else
16748 OMP_CLAUSE_LINEAR_STEP (nc)
16749 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16750 in_decl,
16751 /*integral_constant_expression_p=*/false);
16752 break;
16753 case OMP_CLAUSE_NOWAIT:
16754 case OMP_CLAUSE_DEFAULT:
16755 case OMP_CLAUSE_UNTIED:
16756 case OMP_CLAUSE_MERGEABLE:
16757 case OMP_CLAUSE_INBRANCH:
16758 case OMP_CLAUSE_NOTINBRANCH:
16759 case OMP_CLAUSE_PROC_BIND:
16760 case OMP_CLAUSE_FOR:
16761 case OMP_CLAUSE_PARALLEL:
16762 case OMP_CLAUSE_SECTIONS:
16763 case OMP_CLAUSE_TASKGROUP:
16764 case OMP_CLAUSE_NOGROUP:
16765 case OMP_CLAUSE_THREADS:
16766 case OMP_CLAUSE_SIMD:
16767 case OMP_CLAUSE_DEFAULTMAP:
16768 case OMP_CLAUSE_ORDER:
16769 case OMP_CLAUSE_BIND:
16770 case OMP_CLAUSE_INDEPENDENT:
16771 case OMP_CLAUSE_AUTO:
16772 case OMP_CLAUSE_SEQ:
16773 case OMP_CLAUSE_IF_PRESENT:
16774 case OMP_CLAUSE_FINALIZE:
16775 break;
16776 default:
16777 gcc_unreachable ();
16779 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16780 switch (OMP_CLAUSE_CODE (nc))
16782 case OMP_CLAUSE_SHARED:
16783 case OMP_CLAUSE_PRIVATE:
16784 case OMP_CLAUSE_FIRSTPRIVATE:
16785 case OMP_CLAUSE_LASTPRIVATE:
16786 case OMP_CLAUSE_COPYPRIVATE:
16787 case OMP_CLAUSE_LINEAR:
16788 case OMP_CLAUSE_REDUCTION:
16789 case OMP_CLAUSE_IN_REDUCTION:
16790 case OMP_CLAUSE_TASK_REDUCTION:
16791 case OMP_CLAUSE_USE_DEVICE_PTR:
16792 case OMP_CLAUSE_USE_DEVICE_ADDR:
16793 case OMP_CLAUSE_IS_DEVICE_PTR:
16794 case OMP_CLAUSE_INCLUSIVE:
16795 case OMP_CLAUSE_EXCLUSIVE:
16796 /* tsubst_expr on SCOPE_REF results in returning
16797 finish_non_static_data_member result. Undo that here. */
16798 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16799 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16800 == IDENTIFIER_NODE))
16802 tree t = OMP_CLAUSE_DECL (nc);
16803 tree v = t;
16804 while (v)
16805 switch (TREE_CODE (v))
16807 case COMPONENT_REF:
16808 case MEM_REF:
16809 case INDIRECT_REF:
16810 CASE_CONVERT:
16811 case POINTER_PLUS_EXPR:
16812 v = TREE_OPERAND (v, 0);
16813 continue;
16814 case PARM_DECL:
16815 if (DECL_CONTEXT (v) == current_function_decl
16816 && DECL_ARTIFICIAL (v)
16817 && DECL_NAME (v) == this_identifier)
16818 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16819 /* FALLTHRU */
16820 default:
16821 v = NULL_TREE;
16822 break;
16825 else if (VAR_P (OMP_CLAUSE_DECL (oc))
16826 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16827 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16828 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16829 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16831 tree decl = OMP_CLAUSE_DECL (nc);
16832 if (VAR_P (decl))
16834 retrofit_lang_decl (decl);
16835 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16838 break;
16839 default:
16840 break;
16844 new_clauses = nreverse (new_clauses);
16845 if (ort != C_ORT_OMP_DECLARE_SIMD)
16847 new_clauses = finish_omp_clauses (new_clauses, ort);
16848 if (linear_no_step)
16849 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16850 if (nc == linear_no_step)
16852 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16853 break;
16856 return new_clauses;
16859 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
16861 static tree
16862 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16863 tree in_decl)
16865 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16867 tree purpose, value, chain;
16869 if (t == NULL)
16870 return t;
16872 if (TREE_CODE (t) != TREE_LIST)
16873 return tsubst_copy_and_build (t, args, complain, in_decl,
16874 /*function_p=*/false,
16875 /*integral_constant_expression_p=*/false);
16877 if (t == void_list_node)
16878 return t;
16880 purpose = TREE_PURPOSE (t);
16881 if (purpose)
16882 purpose = RECUR (purpose);
16883 value = TREE_VALUE (t);
16884 if (value)
16886 if (TREE_CODE (value) != LABEL_DECL)
16887 value = RECUR (value);
16888 else
16890 value = lookup_label (DECL_NAME (value));
16891 gcc_assert (TREE_CODE (value) == LABEL_DECL);
16892 TREE_USED (value) = 1;
16895 chain = TREE_CHAIN (t);
16896 if (chain && chain != void_type_node)
16897 chain = RECUR (chain);
16898 return tree_cons (purpose, value, chain);
16899 #undef RECUR
16902 /* Used to temporarily communicate the list of #pragma omp parallel
16903 clauses to #pragma omp for instantiation if they are combined
16904 together. */
16906 static tree *omp_parallel_combined_clauses;
16908 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
16909 tree *, unsigned int *);
16911 /* Substitute one OMP_FOR iterator. */
16913 static bool
16914 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
16915 tree initv, tree condv, tree incrv, tree *clauses,
16916 tree args, tsubst_flags_t complain, tree in_decl,
16917 bool integral_constant_expression_p)
16919 #define RECUR(NODE) \
16920 tsubst_expr ((NODE), args, complain, in_decl, \
16921 integral_constant_expression_p)
16922 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
16923 bool ret = false;
16925 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16926 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16928 decl = TREE_OPERAND (init, 0);
16929 init = TREE_OPERAND (init, 1);
16930 tree decl_expr = NULL_TREE;
16931 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
16932 if (range_for)
16934 bool decomp = false;
16935 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
16937 tree v = DECL_VALUE_EXPR (decl);
16938 if (TREE_CODE (v) == ARRAY_REF
16939 && VAR_P (TREE_OPERAND (v, 0))
16940 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
16942 tree decomp_first = NULL_TREE;
16943 unsigned decomp_cnt = 0;
16944 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
16945 maybe_push_decl (d);
16946 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
16947 in_decl, &decomp_first, &decomp_cnt);
16948 decomp = true;
16949 if (d == error_mark_node)
16950 decl = error_mark_node;
16951 else
16952 for (unsigned int i = 0; i < decomp_cnt; i++)
16954 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
16956 tree v = build_nt (ARRAY_REF, d,
16957 size_int (decomp_cnt - i - 1),
16958 NULL_TREE, NULL_TREE);
16959 SET_DECL_VALUE_EXPR (decomp_first, v);
16960 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
16962 fit_decomposition_lang_decl (decomp_first, d);
16963 decomp_first = DECL_CHAIN (decomp_first);
16967 decl = tsubst_decl (decl, args, complain);
16968 if (!decomp)
16969 maybe_push_decl (decl);
16971 else if (init && TREE_CODE (init) == DECL_EXPR)
16973 /* We need to jump through some hoops to handle declarations in the
16974 init-statement, since we might need to handle auto deduction,
16975 but we need to keep control of initialization. */
16976 decl_expr = init;
16977 init = DECL_INITIAL (DECL_EXPR_DECL (init));
16978 decl = tsubst_decl (decl, args, complain);
16980 else
16982 if (TREE_CODE (decl) == SCOPE_REF)
16984 decl = RECUR (decl);
16985 if (TREE_CODE (decl) == COMPONENT_REF)
16987 tree v = decl;
16988 while (v)
16989 switch (TREE_CODE (v))
16991 case COMPONENT_REF:
16992 case MEM_REF:
16993 case INDIRECT_REF:
16994 CASE_CONVERT:
16995 case POINTER_PLUS_EXPR:
16996 v = TREE_OPERAND (v, 0);
16997 continue;
16998 case PARM_DECL:
16999 if (DECL_CONTEXT (v) == current_function_decl
17000 && DECL_ARTIFICIAL (v)
17001 && DECL_NAME (v) == this_identifier)
17003 decl = TREE_OPERAND (decl, 1);
17004 decl = omp_privatize_field (decl, false);
17006 /* FALLTHRU */
17007 default:
17008 v = NULL_TREE;
17009 break;
17013 else
17014 decl = RECUR (decl);
17016 init = RECUR (init);
17018 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17020 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17021 if (TREE_CODE (o) == TREE_LIST)
17022 TREE_VEC_ELT (orig_declv, i)
17023 = tree_cons (RECUR (TREE_PURPOSE (o)),
17024 RECUR (TREE_VALUE (o)),
17025 NULL_TREE);
17026 else
17027 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17030 if (range_for)
17032 tree this_pre_body = NULL_TREE;
17033 tree orig_init = NULL_TREE;
17034 tree orig_decl = NULL_TREE;
17035 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
17036 orig_init, cond, incr);
17037 if (orig_decl)
17039 if (orig_declv == NULL_TREE)
17040 orig_declv = copy_node (declv);
17041 TREE_VEC_ELT (orig_declv, i) = orig_decl;
17042 ret = true;
17044 else if (orig_declv)
17045 TREE_VEC_ELT (orig_declv, i) = decl;
17048 tree auto_node = type_uses_auto (TREE_TYPE (decl));
17049 if (!range_for && auto_node && init)
17050 TREE_TYPE (decl)
17051 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17053 gcc_assert (!type_dependent_expression_p (decl));
17055 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17057 if (decl_expr)
17059 /* Declare the variable, but don't let that initialize it. */
17060 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17061 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17062 RECUR (decl_expr);
17063 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17066 if (!range_for)
17068 cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
17069 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17070 if (TREE_CODE (incr) == MODIFY_EXPR)
17072 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17073 tree rhs = RECUR (TREE_OPERAND (incr, 1));
17074 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17075 NOP_EXPR, rhs, complain);
17077 else
17078 incr = RECUR (incr);
17079 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17080 TREE_VEC_ELT (orig_declv, i) = decl;
17082 TREE_VEC_ELT (declv, i) = decl;
17083 TREE_VEC_ELT (initv, i) = init;
17084 TREE_VEC_ELT (condv, i) = cond;
17085 TREE_VEC_ELT (incrv, i) = incr;
17086 return ret;
17089 if (decl_expr)
17091 /* Declare and initialize the variable. */
17092 RECUR (decl_expr);
17093 init = NULL_TREE;
17095 else if (init)
17097 tree *pc;
17098 int j;
17099 for (j = ((omp_parallel_combined_clauses == NULL
17100 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17102 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17104 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17105 && OMP_CLAUSE_DECL (*pc) == decl)
17106 break;
17107 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17108 && OMP_CLAUSE_DECL (*pc) == decl)
17110 if (j)
17111 break;
17112 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
17113 tree c = *pc;
17114 *pc = OMP_CLAUSE_CHAIN (c);
17115 OMP_CLAUSE_CHAIN (c) = *clauses;
17116 *clauses = c;
17118 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17119 && OMP_CLAUSE_DECL (*pc) == decl)
17121 error ("iteration variable %qD should not be firstprivate",
17122 decl);
17123 *pc = OMP_CLAUSE_CHAIN (*pc);
17125 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17126 && OMP_CLAUSE_DECL (*pc) == decl)
17128 error ("iteration variable %qD should not be reduction",
17129 decl);
17130 *pc = OMP_CLAUSE_CHAIN (*pc);
17132 else
17133 pc = &OMP_CLAUSE_CHAIN (*pc);
17135 if (*pc)
17136 break;
17138 if (*pc == NULL_TREE)
17140 tree c = build_omp_clause (input_location,
17141 TREE_CODE (t) == OMP_LOOP
17142 ? OMP_CLAUSE_LASTPRIVATE
17143 : OMP_CLAUSE_PRIVATE);
17144 OMP_CLAUSE_DECL (c) = decl;
17145 c = finish_omp_clauses (c, C_ORT_OMP);
17146 if (c)
17148 OMP_CLAUSE_CHAIN (c) = *clauses;
17149 *clauses = c;
17153 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17154 if (COMPARISON_CLASS_P (cond))
17156 tree op0 = RECUR (TREE_OPERAND (cond, 0));
17157 tree op1 = RECUR (TREE_OPERAND (cond, 1));
17158 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
17160 else
17161 cond = RECUR (cond);
17162 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17163 switch (TREE_CODE (incr))
17165 case PREINCREMENT_EXPR:
17166 case PREDECREMENT_EXPR:
17167 case POSTINCREMENT_EXPR:
17168 case POSTDECREMENT_EXPR:
17169 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
17170 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
17171 break;
17172 case MODIFY_EXPR:
17173 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17174 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17176 tree rhs = TREE_OPERAND (incr, 1);
17177 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17178 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17179 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17180 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17181 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17182 rhs0, rhs1));
17184 else
17185 incr = RECUR (incr);
17186 break;
17187 case MODOP_EXPR:
17188 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17189 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17191 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17192 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17193 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
17194 TREE_TYPE (decl), lhs,
17195 RECUR (TREE_OPERAND (incr, 2))));
17197 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
17198 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
17199 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
17201 tree rhs = TREE_OPERAND (incr, 2);
17202 tree lhs = RECUR (TREE_OPERAND (incr, 0));
17203 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17204 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17205 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17206 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17207 rhs0, rhs1));
17209 else
17210 incr = RECUR (incr);
17211 break;
17212 default:
17213 incr = RECUR (incr);
17214 break;
17217 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17218 TREE_VEC_ELT (orig_declv, i) = decl;
17219 TREE_VEC_ELT (declv, i) = decl;
17220 TREE_VEC_ELT (initv, i) = init;
17221 TREE_VEC_ELT (condv, i) = cond;
17222 TREE_VEC_ELT (incrv, i) = incr;
17223 return false;
17224 #undef RECUR
17227 /* Helper function of tsubst_expr, find OMP_TEAMS inside
17228 of OMP_TARGET's body. */
17230 static tree
17231 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
17233 *walk_subtrees = 0;
17234 switch (TREE_CODE (*tp))
17236 case OMP_TEAMS:
17237 return *tp;
17238 case BIND_EXPR:
17239 case STATEMENT_LIST:
17240 *walk_subtrees = 1;
17241 break;
17242 default:
17243 break;
17245 return NULL_TREE;
17248 /* Helper function for tsubst_expr. For decomposition declaration
17249 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
17250 also the corresponding decls representing the identifiers
17251 of the decomposition declaration. Return DECL if successful
17252 or error_mark_node otherwise, set *FIRST to the first decl
17253 in the list chained through DECL_CHAIN and *CNT to the number
17254 of such decls. */
17256 static tree
17257 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
17258 tsubst_flags_t complain, tree in_decl, tree *first,
17259 unsigned int *cnt)
17261 tree decl2, decl3, prev = decl;
17262 *cnt = 0;
17263 gcc_assert (DECL_NAME (decl) == NULL_TREE);
17264 for (decl2 = DECL_CHAIN (pattern_decl);
17265 decl2
17266 && VAR_P (decl2)
17267 && DECL_DECOMPOSITION_P (decl2)
17268 && DECL_NAME (decl2);
17269 decl2 = DECL_CHAIN (decl2))
17271 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
17273 gcc_assert (errorcount);
17274 return error_mark_node;
17276 (*cnt)++;
17277 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
17278 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
17279 tree v = DECL_VALUE_EXPR (decl2);
17280 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
17281 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
17282 decl3 = tsubst (decl2, args, complain, in_decl);
17283 SET_DECL_VALUE_EXPR (decl2, v);
17284 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
17285 if (VAR_P (decl3))
17286 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
17287 else
17289 gcc_assert (errorcount);
17290 decl = error_mark_node;
17291 continue;
17293 maybe_push_decl (decl3);
17294 if (error_operand_p (decl3))
17295 decl = error_mark_node;
17296 else if (decl != error_mark_node
17297 && DECL_CHAIN (decl3) != prev
17298 && decl != prev)
17300 gcc_assert (errorcount);
17301 decl = error_mark_node;
17303 else
17304 prev = decl3;
17306 *first = prev;
17307 return decl;
17310 /* Return the proper local_specialization for init-capture pack DECL. */
17312 static tree
17313 lookup_init_capture_pack (tree decl)
17315 /* We handle normal pack captures by forwarding to the specialization of the
17316 captured parameter. We can't do that for pack init-captures; we need them
17317 to have their own local_specialization. We created the individual
17318 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
17319 when we process the DECL_EXPR for the pack init-capture in the template.
17320 So, how do we find them? We don't know the capture proxy pack when
17321 building the individual resulting proxies, and we don't know the
17322 individual proxies when instantiating the pack. What we have in common is
17323 the FIELD_DECL.
17325 So...when we instantiate the FIELD_DECL, we stick the result in
17326 local_specializations. Then at the DECL_EXPR we look up that result, see
17327 how many elements it has, synthesize the names, and look them up. */
17329 tree cname = DECL_NAME (decl);
17330 tree val = DECL_VALUE_EXPR (decl);
17331 tree field = TREE_OPERAND (val, 1);
17332 gcc_assert (TREE_CODE (field) == FIELD_DECL);
17333 tree fpack = retrieve_local_specialization (field);
17334 if (fpack == error_mark_node)
17335 return error_mark_node;
17337 int len = 1;
17338 tree vec = NULL_TREE;
17339 tree r = NULL_TREE;
17340 if (TREE_CODE (fpack) == TREE_VEC)
17342 len = TREE_VEC_LENGTH (fpack);
17343 vec = make_tree_vec (len);
17344 r = make_node (NONTYPE_ARGUMENT_PACK);
17345 SET_ARGUMENT_PACK_ARGS (r, vec);
17347 for (int i = 0; i < len; ++i)
17349 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
17350 tree elt = lookup_name_real (ename, 0, 0, true, 0, LOOKUP_NORMAL);
17351 if (vec)
17352 TREE_VEC_ELT (vec, i) = elt;
17353 else
17354 r = elt;
17356 return r;
17359 /* Like tsubst_copy for expressions, etc. but also does semantic
17360 processing. */
17362 tree
17363 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
17364 bool integral_constant_expression_p)
17366 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
17367 #define RECUR(NODE) \
17368 tsubst_expr ((NODE), args, complain, in_decl, \
17369 integral_constant_expression_p)
17371 tree stmt, tmp;
17372 tree r;
17373 location_t loc;
17375 if (t == NULL_TREE || t == error_mark_node)
17376 return t;
17378 loc = input_location;
17379 if (location_t eloc = cp_expr_location (t))
17380 input_location = eloc;
17381 if (STATEMENT_CODE_P (TREE_CODE (t)))
17382 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
17384 switch (TREE_CODE (t))
17386 case STATEMENT_LIST:
17388 tree_stmt_iterator i;
17389 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
17390 RECUR (tsi_stmt (i));
17391 break;
17394 case CTOR_INITIALIZER:
17395 finish_mem_initializers (tsubst_initializer_list
17396 (TREE_OPERAND (t, 0), args));
17397 break;
17399 case RETURN_EXPR:
17400 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
17401 break;
17403 case EXPR_STMT:
17404 tmp = RECUR (EXPR_STMT_EXPR (t));
17405 if (EXPR_STMT_STMT_EXPR_RESULT (t))
17406 finish_stmt_expr_expr (tmp, cur_stmt_expr);
17407 else
17408 finish_expr_stmt (tmp);
17409 break;
17411 case USING_STMT:
17412 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
17413 break;
17415 case DECL_EXPR:
17417 tree decl, pattern_decl;
17418 tree init;
17420 pattern_decl = decl = DECL_EXPR_DECL (t);
17421 if (TREE_CODE (decl) == LABEL_DECL)
17422 finish_label_decl (DECL_NAME (decl));
17423 else if (TREE_CODE (decl) == USING_DECL)
17425 tree scope = USING_DECL_SCOPE (decl);
17426 tree name = DECL_NAME (decl);
17428 scope = tsubst (scope, args, complain, in_decl);
17429 finish_nonmember_using_decl (scope, name);
17431 else if (is_capture_proxy (decl)
17432 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
17434 /* We're in tsubst_lambda_expr, we've already inserted a new
17435 capture proxy, so look it up and register it. */
17436 tree inst;
17437 if (!DECL_PACK_P (decl))
17439 inst = lookup_name_real (DECL_NAME (decl), /*prefer_type*/0,
17440 /*nonclass*/1, /*block_p=*/true,
17441 /*ns_only*/0, LOOKUP_HIDDEN);
17442 gcc_assert (inst != decl && is_capture_proxy (inst));
17444 else if (is_normal_capture_proxy (decl))
17446 inst = (retrieve_local_specialization
17447 (DECL_CAPTURED_VARIABLE (decl)));
17448 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
17450 else
17451 inst = lookup_init_capture_pack (decl);
17453 register_local_specialization (inst, decl);
17454 break;
17456 else if (DECL_PRETTY_FUNCTION_P (decl))
17457 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
17458 DECL_NAME (decl),
17459 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
17460 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
17461 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
17462 /* Don't copy the old closure; we'll create a new one in
17463 tsubst_lambda_expr. */
17464 break;
17465 else
17467 init = DECL_INITIAL (decl);
17468 /* The following tsubst call will clear the DECL_TEMPLATE_INFO
17469 for local variables, so save if DECL was declared constinit. */
17470 const bool constinit_p
17471 = (VAR_P (decl)
17472 && DECL_LANG_SPECIFIC (decl)
17473 && DECL_TEMPLATE_INFO (decl)
17474 && TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (decl)));
17475 decl = tsubst (decl, args, complain, in_decl);
17476 if (decl != error_mark_node)
17478 /* By marking the declaration as instantiated, we avoid
17479 trying to instantiate it. Since instantiate_decl can't
17480 handle local variables, and since we've already done
17481 all that needs to be done, that's the right thing to
17482 do. */
17483 if (VAR_P (decl))
17484 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17485 if (VAR_P (decl) && !DECL_NAME (decl)
17486 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
17487 /* Anonymous aggregates are a special case. */
17488 finish_anon_union (decl);
17489 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
17491 DECL_CONTEXT (decl) = current_function_decl;
17492 if (DECL_NAME (decl) == this_identifier)
17494 tree lam = DECL_CONTEXT (current_function_decl);
17495 lam = CLASSTYPE_LAMBDA_EXPR (lam);
17496 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
17498 insert_capture_proxy (decl);
17500 else if (DECL_IMPLICIT_TYPEDEF_P (t))
17501 /* We already did a pushtag. */;
17502 else if (TREE_CODE (decl) == FUNCTION_DECL
17503 && DECL_OMP_DECLARE_REDUCTION_P (decl)
17504 && DECL_FUNCTION_SCOPE_P (pattern_decl))
17506 DECL_CONTEXT (decl) = NULL_TREE;
17507 pushdecl (decl);
17508 DECL_CONTEXT (decl) = current_function_decl;
17509 cp_check_omp_declare_reduction (decl);
17511 else
17513 bool const_init = false;
17514 unsigned int cnt = 0;
17515 tree first = NULL_TREE, ndecl = error_mark_node;
17516 maybe_push_decl (decl);
17518 if (VAR_P (decl)
17519 && DECL_DECOMPOSITION_P (decl)
17520 && TREE_TYPE (pattern_decl) != error_mark_node)
17521 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
17522 complain, in_decl, &first,
17523 &cnt);
17525 init = tsubst_init (init, decl, args, complain, in_decl);
17527 if (VAR_P (decl))
17528 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
17529 (pattern_decl));
17531 if (ndecl != error_mark_node)
17532 cp_maybe_mangle_decomp (ndecl, first, cnt);
17534 cp_finish_decl (decl, init, const_init, NULL_TREE,
17535 constinit_p ? LOOKUP_CONSTINIT : 0);
17537 if (ndecl != error_mark_node)
17538 cp_finish_decomp (ndecl, first, cnt);
17543 break;
17546 case FOR_STMT:
17547 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
17548 RECUR (FOR_INIT_STMT (t));
17549 finish_init_stmt (stmt);
17550 tmp = RECUR (FOR_COND (t));
17551 finish_for_cond (tmp, stmt, false, 0);
17552 tmp = RECUR (FOR_EXPR (t));
17553 finish_for_expr (tmp, stmt);
17555 bool prev = note_iteration_stmt_body_start ();
17556 RECUR (FOR_BODY (t));
17557 note_iteration_stmt_body_end (prev);
17559 finish_for_stmt (stmt);
17560 break;
17562 case RANGE_FOR_STMT:
17564 /* Construct another range_for, if this is not a final
17565 substitution (for inside inside a generic lambda of a
17566 template). Otherwise convert to a regular for. */
17567 tree decl, expr;
17568 stmt = (processing_template_decl
17569 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
17570 : begin_for_stmt (NULL_TREE, NULL_TREE));
17571 RECUR (RANGE_FOR_INIT_STMT (t));
17572 decl = RANGE_FOR_DECL (t);
17573 decl = tsubst (decl, args, complain, in_decl);
17574 maybe_push_decl (decl);
17575 expr = RECUR (RANGE_FOR_EXPR (t));
17577 tree decomp_first = NULL_TREE;
17578 unsigned decomp_cnt = 0;
17579 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
17580 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
17581 complain, in_decl,
17582 &decomp_first, &decomp_cnt);
17584 if (processing_template_decl)
17586 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
17587 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
17588 finish_range_for_decl (stmt, decl, expr);
17589 if (decomp_first && decl != error_mark_node)
17590 cp_finish_decomp (decl, decomp_first, decomp_cnt);
17592 else
17594 unsigned short unroll = (RANGE_FOR_UNROLL (t)
17595 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
17596 stmt = cp_convert_range_for (stmt, decl, expr,
17597 decomp_first, decomp_cnt,
17598 RANGE_FOR_IVDEP (t), unroll);
17601 bool prev = note_iteration_stmt_body_start ();
17602 RECUR (RANGE_FOR_BODY (t));
17603 note_iteration_stmt_body_end (prev);
17604 finish_for_stmt (stmt);
17606 break;
17608 case WHILE_STMT:
17609 stmt = begin_while_stmt ();
17610 tmp = RECUR (WHILE_COND (t));
17611 finish_while_stmt_cond (tmp, stmt, false, 0);
17613 bool prev = note_iteration_stmt_body_start ();
17614 RECUR (WHILE_BODY (t));
17615 note_iteration_stmt_body_end (prev);
17617 finish_while_stmt (stmt);
17618 break;
17620 case DO_STMT:
17621 stmt = begin_do_stmt ();
17623 bool prev = note_iteration_stmt_body_start ();
17624 RECUR (DO_BODY (t));
17625 note_iteration_stmt_body_end (prev);
17627 finish_do_body (stmt);
17628 tmp = RECUR (DO_COND (t));
17629 finish_do_stmt (tmp, stmt, false, 0);
17630 break;
17632 case IF_STMT:
17633 stmt = begin_if_stmt ();
17634 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
17635 if (IF_STMT_CONSTEXPR_P (t))
17636 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
17637 tmp = RECUR (IF_COND (t));
17638 tmp = finish_if_stmt_cond (tmp, stmt);
17639 if (IF_STMT_CONSTEXPR_P (t)
17640 && instantiation_dependent_expression_p (tmp))
17642 /* We're partially instantiating a generic lambda, but the condition
17643 of the constexpr if is still dependent. Don't substitute into the
17644 branches now, just remember the template arguments. */
17645 do_poplevel (IF_SCOPE (stmt));
17646 IF_COND (stmt) = IF_COND (t);
17647 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
17648 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
17649 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
17650 add_stmt (stmt);
17651 break;
17653 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
17654 /* Don't instantiate the THEN_CLAUSE. */;
17655 else
17657 tree folded = fold_non_dependent_expr (tmp, complain);
17658 bool inhibit = integer_zerop (folded);
17659 if (inhibit)
17660 ++c_inhibit_evaluation_warnings;
17661 RECUR (THEN_CLAUSE (t));
17662 if (inhibit)
17663 --c_inhibit_evaluation_warnings;
17665 finish_then_clause (stmt);
17667 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
17668 /* Don't instantiate the ELSE_CLAUSE. */;
17669 else if (ELSE_CLAUSE (t))
17671 tree folded = fold_non_dependent_expr (tmp, complain);
17672 bool inhibit = integer_nonzerop (folded);
17673 begin_else_clause (stmt);
17674 if (inhibit)
17675 ++c_inhibit_evaluation_warnings;
17676 RECUR (ELSE_CLAUSE (t));
17677 if (inhibit)
17678 --c_inhibit_evaluation_warnings;
17679 finish_else_clause (stmt);
17682 finish_if_stmt (stmt);
17683 break;
17685 case BIND_EXPR:
17686 if (BIND_EXPR_BODY_BLOCK (t))
17687 stmt = begin_function_body ();
17688 else
17689 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
17690 ? BCS_TRY_BLOCK : 0);
17692 RECUR (BIND_EXPR_BODY (t));
17694 if (BIND_EXPR_BODY_BLOCK (t))
17695 finish_function_body (stmt);
17696 else
17697 finish_compound_stmt (stmt);
17698 break;
17700 case BREAK_STMT:
17701 finish_break_stmt ();
17702 break;
17704 case CONTINUE_STMT:
17705 finish_continue_stmt ();
17706 break;
17708 case SWITCH_STMT:
17709 stmt = begin_switch_stmt ();
17710 tmp = RECUR (SWITCH_STMT_COND (t));
17711 finish_switch_cond (tmp, stmt);
17712 RECUR (SWITCH_STMT_BODY (t));
17713 finish_switch_stmt (stmt);
17714 break;
17716 case CASE_LABEL_EXPR:
17718 tree decl = CASE_LABEL (t);
17719 tree low = RECUR (CASE_LOW (t));
17720 tree high = RECUR (CASE_HIGH (t));
17721 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
17722 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
17724 tree label = CASE_LABEL (l);
17725 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
17726 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
17727 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
17730 break;
17732 case LABEL_EXPR:
17734 tree decl = LABEL_EXPR_LABEL (t);
17735 tree label;
17737 label = finish_label_stmt (DECL_NAME (decl));
17738 if (TREE_CODE (label) == LABEL_DECL)
17739 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
17740 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
17741 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
17743 break;
17745 case GOTO_EXPR:
17746 tmp = GOTO_DESTINATION (t);
17747 if (TREE_CODE (tmp) != LABEL_DECL)
17748 /* Computed goto's must be tsubst'd into. On the other hand,
17749 non-computed gotos must not be; the identifier in question
17750 will have no binding. */
17751 tmp = RECUR (tmp);
17752 else
17753 tmp = DECL_NAME (tmp);
17754 finish_goto_stmt (tmp);
17755 break;
17757 case ASM_EXPR:
17759 tree string = RECUR (ASM_STRING (t));
17760 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
17761 complain, in_decl);
17762 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
17763 complain, in_decl);
17764 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
17765 complain, in_decl);
17766 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
17767 complain, in_decl);
17768 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
17769 outputs, inputs, clobbers, labels,
17770 ASM_INLINE_P (t));
17771 tree asm_expr = tmp;
17772 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
17773 asm_expr = TREE_OPERAND (asm_expr, 0);
17774 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
17776 break;
17778 case TRY_BLOCK:
17779 if (CLEANUP_P (t))
17781 stmt = begin_try_block ();
17782 RECUR (TRY_STMTS (t));
17783 finish_cleanup_try_block (stmt);
17784 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
17786 else
17788 tree compound_stmt = NULL_TREE;
17790 if (FN_TRY_BLOCK_P (t))
17791 stmt = begin_function_try_block (&compound_stmt);
17792 else
17793 stmt = begin_try_block ();
17795 RECUR (TRY_STMTS (t));
17797 if (FN_TRY_BLOCK_P (t))
17798 finish_function_try_block (stmt);
17799 else
17800 finish_try_block (stmt);
17802 RECUR (TRY_HANDLERS (t));
17803 if (FN_TRY_BLOCK_P (t))
17804 finish_function_handler_sequence (stmt, compound_stmt);
17805 else
17806 finish_handler_sequence (stmt);
17808 break;
17810 case HANDLER:
17812 tree decl = HANDLER_PARMS (t);
17814 if (decl)
17816 decl = tsubst (decl, args, complain, in_decl);
17817 /* Prevent instantiate_decl from trying to instantiate
17818 this variable. We've already done all that needs to be
17819 done. */
17820 if (decl != error_mark_node)
17821 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17823 stmt = begin_handler ();
17824 finish_handler_parms (decl, stmt);
17825 RECUR (HANDLER_BODY (t));
17826 finish_handler (stmt);
17828 break;
17830 case TAG_DEFN:
17831 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17832 if (CLASS_TYPE_P (tmp))
17834 /* Local classes are not independent templates; they are
17835 instantiated along with their containing function. And this
17836 way we don't have to deal with pushing out of one local class
17837 to instantiate a member of another local class. */
17838 /* Closures are handled by the LAMBDA_EXPR. */
17839 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17840 complete_type (tmp);
17841 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17842 if ((VAR_P (fld)
17843 || (TREE_CODE (fld) == FUNCTION_DECL
17844 && !DECL_ARTIFICIAL (fld)))
17845 && DECL_TEMPLATE_INSTANTIATION (fld))
17846 instantiate_decl (fld, /*defer_ok=*/false,
17847 /*expl_inst_class=*/false);
17849 break;
17851 case STATIC_ASSERT:
17853 tree condition;
17855 ++c_inhibit_evaluation_warnings;
17856 condition =
17857 tsubst_expr (STATIC_ASSERT_CONDITION (t),
17858 args,
17859 complain, in_decl,
17860 /*integral_constant_expression_p=*/true);
17861 --c_inhibit_evaluation_warnings;
17863 finish_static_assert (condition,
17864 STATIC_ASSERT_MESSAGE (t),
17865 STATIC_ASSERT_SOURCE_LOCATION (t),
17866 /*member_p=*/false);
17868 break;
17870 case OACC_KERNELS:
17871 case OACC_PARALLEL:
17872 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17873 in_decl);
17874 stmt = begin_omp_parallel ();
17875 RECUR (OMP_BODY (t));
17876 finish_omp_construct (TREE_CODE (t), stmt, tmp);
17877 break;
17879 case OMP_PARALLEL:
17880 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17881 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17882 complain, in_decl);
17883 if (OMP_PARALLEL_COMBINED (t))
17884 omp_parallel_combined_clauses = &tmp;
17885 stmt = begin_omp_parallel ();
17886 RECUR (OMP_PARALLEL_BODY (t));
17887 gcc_assert (omp_parallel_combined_clauses == NULL);
17888 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17889 = OMP_PARALLEL_COMBINED (t);
17890 pop_omp_privatization_clauses (r);
17891 break;
17893 case OMP_TASK:
17894 if (OMP_TASK_BODY (t) == NULL_TREE)
17896 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17897 complain, in_decl);
17898 t = copy_node (t);
17899 OMP_TASK_CLAUSES (t) = tmp;
17900 add_stmt (t);
17901 break;
17903 r = push_omp_privatization_clauses (false);
17904 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17905 complain, in_decl);
17906 stmt = begin_omp_task ();
17907 RECUR (OMP_TASK_BODY (t));
17908 finish_omp_task (tmp, stmt);
17909 pop_omp_privatization_clauses (r);
17910 break;
17912 case OMP_FOR:
17913 case OMP_LOOP:
17914 case OMP_SIMD:
17915 case OMP_DISTRIBUTE:
17916 case OMP_TASKLOOP:
17917 case OACC_LOOP:
17919 tree clauses, body, pre_body;
17920 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17921 tree orig_declv = NULL_TREE;
17922 tree incrv = NULL_TREE;
17923 enum c_omp_region_type ort = C_ORT_OMP;
17924 bool any_range_for = false;
17925 int i;
17927 if (TREE_CODE (t) == OACC_LOOP)
17928 ort = C_ORT_ACC;
17930 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17931 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17932 in_decl);
17933 if (OMP_FOR_INIT (t) != NULL_TREE)
17935 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17936 if (OMP_FOR_ORIG_DECLS (t))
17937 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17938 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17939 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17940 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17943 keep_next_level (true);
17944 stmt = begin_omp_structured_block ();
17946 pre_body = push_stmt_list ();
17947 RECUR (OMP_FOR_PRE_BODY (t));
17948 pre_body = pop_stmt_list (pre_body);
17950 if (OMP_FOR_INIT (t) != NULL_TREE)
17951 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17952 any_range_for
17953 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
17954 condv, incrv, &clauses, args,
17955 complain, in_decl,
17956 integral_constant_expression_p);
17957 omp_parallel_combined_clauses = NULL;
17959 if (any_range_for)
17961 gcc_assert (orig_declv);
17962 body = begin_omp_structured_block ();
17963 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17964 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
17965 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
17966 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
17967 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
17968 TREE_VEC_ELT (declv, i));
17970 else
17971 body = push_stmt_list ();
17972 RECUR (OMP_FOR_BODY (t));
17973 if (any_range_for)
17974 body = finish_omp_structured_block (body);
17975 else
17976 body = pop_stmt_list (body);
17978 if (OMP_FOR_INIT (t) != NULL_TREE)
17979 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17980 orig_declv, initv, condv, incrv, body, pre_body,
17981 NULL, clauses);
17982 else
17984 t = make_node (TREE_CODE (t));
17985 TREE_TYPE (t) = void_type_node;
17986 OMP_FOR_BODY (t) = body;
17987 OMP_FOR_PRE_BODY (t) = pre_body;
17988 OMP_FOR_CLAUSES (t) = clauses;
17989 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17990 add_stmt (t);
17993 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
17994 t));
17995 pop_omp_privatization_clauses (r);
17997 break;
17999 case OMP_SECTIONS:
18000 omp_parallel_combined_clauses = NULL;
18001 /* FALLTHRU */
18002 case OMP_SINGLE:
18003 case OMP_TEAMS:
18004 case OMP_CRITICAL:
18005 case OMP_TASKGROUP:
18006 case OMP_SCAN:
18007 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18008 && OMP_TEAMS_COMBINED (t));
18009 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18010 in_decl);
18011 if (TREE_CODE (t) == OMP_TEAMS)
18013 keep_next_level (true);
18014 stmt = begin_omp_structured_block ();
18015 RECUR (OMP_BODY (t));
18016 stmt = finish_omp_structured_block (stmt);
18018 else
18020 stmt = push_stmt_list ();
18021 RECUR (OMP_BODY (t));
18022 stmt = pop_stmt_list (stmt);
18025 t = copy_node (t);
18026 OMP_BODY (t) = stmt;
18027 OMP_CLAUSES (t) = tmp;
18028 add_stmt (t);
18029 pop_omp_privatization_clauses (r);
18030 break;
18032 case OMP_DEPOBJ:
18033 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18034 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18036 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
18037 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18039 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18040 args, complain, in_decl);
18041 if (tmp == NULL_TREE)
18042 tmp = error_mark_node;
18044 else
18046 kind = (enum omp_clause_depend_kind)
18047 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18048 tmp = NULL_TREE;
18050 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18052 else
18053 finish_omp_depobj (EXPR_LOCATION (t), r,
18054 OMP_CLAUSE_DEPEND_SOURCE,
18055 OMP_DEPOBJ_CLAUSES (t));
18056 break;
18058 case OACC_DATA:
18059 case OMP_TARGET_DATA:
18060 case OMP_TARGET:
18061 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
18062 ? C_ORT_ACC : C_ORT_OMP, args, complain,
18063 in_decl);
18064 keep_next_level (true);
18065 stmt = begin_omp_structured_block ();
18067 RECUR (OMP_BODY (t));
18068 stmt = finish_omp_structured_block (stmt);
18070 t = copy_node (t);
18071 OMP_BODY (t) = stmt;
18072 OMP_CLAUSES (t) = tmp;
18073 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18075 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18076 if (teams)
18078 /* For combined target teams, ensure the num_teams and
18079 thread_limit clause expressions are evaluated on the host,
18080 before entering the target construct. */
18081 tree c;
18082 for (c = OMP_TEAMS_CLAUSES (teams);
18083 c; c = OMP_CLAUSE_CHAIN (c))
18084 if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18085 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18086 && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
18088 tree expr = OMP_CLAUSE_OPERAND (c, 0);
18089 expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
18090 if (expr == error_mark_node)
18091 continue;
18092 tmp = TARGET_EXPR_SLOT (expr);
18093 add_stmt (expr);
18094 OMP_CLAUSE_OPERAND (c, 0) = expr;
18095 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
18096 OMP_CLAUSE_FIRSTPRIVATE);
18097 OMP_CLAUSE_DECL (tc) = tmp;
18098 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
18099 OMP_TARGET_CLAUSES (t) = tc;
18103 add_stmt (t);
18104 break;
18106 case OACC_DECLARE:
18107 t = copy_node (t);
18108 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
18109 complain, in_decl);
18110 OACC_DECLARE_CLAUSES (t) = tmp;
18111 add_stmt (t);
18112 break;
18114 case OMP_TARGET_UPDATE:
18115 case OMP_TARGET_ENTER_DATA:
18116 case OMP_TARGET_EXIT_DATA:
18117 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
18118 complain, in_decl);
18119 t = copy_node (t);
18120 OMP_STANDALONE_CLAUSES (t) = tmp;
18121 add_stmt (t);
18122 break;
18124 case OACC_ENTER_DATA:
18125 case OACC_EXIT_DATA:
18126 case OACC_UPDATE:
18127 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
18128 complain, in_decl);
18129 t = copy_node (t);
18130 OMP_STANDALONE_CLAUSES (t) = tmp;
18131 add_stmt (t);
18132 break;
18134 case OMP_ORDERED:
18135 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
18136 complain, in_decl);
18137 stmt = push_stmt_list ();
18138 RECUR (OMP_BODY (t));
18139 stmt = pop_stmt_list (stmt);
18141 t = copy_node (t);
18142 OMP_BODY (t) = stmt;
18143 OMP_ORDERED_CLAUSES (t) = tmp;
18144 add_stmt (t);
18145 break;
18147 case OMP_SECTION:
18148 case OMP_MASTER:
18149 stmt = push_stmt_list ();
18150 RECUR (OMP_BODY (t));
18151 stmt = pop_stmt_list (stmt);
18153 t = copy_node (t);
18154 OMP_BODY (t) = stmt;
18155 add_stmt (t);
18156 break;
18158 case OMP_ATOMIC:
18159 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
18160 tmp = NULL_TREE;
18161 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
18162 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
18163 complain, in_decl);
18164 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
18166 tree op1 = TREE_OPERAND (t, 1);
18167 tree rhs1 = NULL_TREE;
18168 tree lhs, rhs;
18169 if (TREE_CODE (op1) == COMPOUND_EXPR)
18171 rhs1 = RECUR (TREE_OPERAND (op1, 0));
18172 op1 = TREE_OPERAND (op1, 1);
18174 lhs = RECUR (TREE_OPERAND (op1, 0));
18175 rhs = RECUR (TREE_OPERAND (op1, 1));
18176 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
18177 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
18178 OMP_ATOMIC_MEMORY_ORDER (t));
18180 else
18182 tree op1 = TREE_OPERAND (t, 1);
18183 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
18184 tree rhs1 = NULL_TREE;
18185 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
18186 enum tree_code opcode = NOP_EXPR;
18187 if (code == OMP_ATOMIC_READ)
18189 v = RECUR (TREE_OPERAND (op1, 0));
18190 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18192 else if (code == OMP_ATOMIC_CAPTURE_OLD
18193 || code == OMP_ATOMIC_CAPTURE_NEW)
18195 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
18196 v = RECUR (TREE_OPERAND (op1, 0));
18197 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18198 if (TREE_CODE (op11) == COMPOUND_EXPR)
18200 rhs1 = RECUR (TREE_OPERAND (op11, 0));
18201 op11 = TREE_OPERAND (op11, 1);
18203 lhs = RECUR (TREE_OPERAND (op11, 0));
18204 rhs = RECUR (TREE_OPERAND (op11, 1));
18205 opcode = TREE_CODE (op11);
18206 if (opcode == MODIFY_EXPR)
18207 opcode = NOP_EXPR;
18209 else
18211 code = OMP_ATOMIC;
18212 lhs = RECUR (TREE_OPERAND (op1, 0));
18213 rhs = RECUR (TREE_OPERAND (op1, 1));
18215 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
18216 lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
18218 break;
18220 case TRANSACTION_EXPR:
18222 int flags = 0;
18223 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
18224 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
18226 if (TRANSACTION_EXPR_IS_STMT (t))
18228 tree body = TRANSACTION_EXPR_BODY (t);
18229 tree noex = NULL_TREE;
18230 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
18232 noex = MUST_NOT_THROW_COND (body);
18233 if (noex == NULL_TREE)
18234 noex = boolean_true_node;
18235 body = TREE_OPERAND (body, 0);
18237 stmt = begin_transaction_stmt (input_location, NULL, flags);
18238 RECUR (body);
18239 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
18241 else
18243 stmt = build_transaction_expr (EXPR_LOCATION (t),
18244 RECUR (TRANSACTION_EXPR_BODY (t)),
18245 flags, NULL_TREE);
18246 RETURN (stmt);
18249 break;
18251 case MUST_NOT_THROW_EXPR:
18253 tree op0 = RECUR (TREE_OPERAND (t, 0));
18254 tree cond = RECUR (MUST_NOT_THROW_COND (t));
18255 RETURN (build_must_not_throw_expr (op0, cond));
18258 case EXPR_PACK_EXPANSION:
18259 error ("invalid use of pack expansion expression");
18260 RETURN (error_mark_node);
18262 case NONTYPE_ARGUMENT_PACK:
18263 error ("use %<...%> to expand argument pack");
18264 RETURN (error_mark_node);
18266 case COMPOUND_EXPR:
18267 tmp = RECUR (TREE_OPERAND (t, 0));
18268 if (tmp == NULL_TREE)
18269 /* If the first operand was a statement, we're done with it. */
18270 RETURN (RECUR (TREE_OPERAND (t, 1)));
18271 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
18272 RECUR (TREE_OPERAND (t, 1)),
18273 complain));
18275 case ANNOTATE_EXPR:
18276 tmp = RECUR (TREE_OPERAND (t, 0));
18277 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
18278 TREE_TYPE (tmp), tmp,
18279 RECUR (TREE_OPERAND (t, 1)),
18280 RECUR (TREE_OPERAND (t, 2))));
18282 case PREDICT_EXPR:
18283 RETURN (add_stmt (copy_node (t)));
18285 default:
18286 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
18288 RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
18289 /*function_p=*/false,
18290 integral_constant_expression_p));
18293 RETURN (NULL_TREE);
18294 out:
18295 input_location = loc;
18296 return r;
18297 #undef RECUR
18298 #undef RETURN
18301 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
18302 function. For description of the body see comment above
18303 cp_parser_omp_declare_reduction_exprs. */
18305 static void
18306 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18308 if (t == NULL_TREE || t == error_mark_node)
18309 return;
18311 gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
18313 tree_stmt_iterator tsi;
18314 int i;
18315 tree stmts[7];
18316 memset (stmts, 0, sizeof stmts);
18317 for (i = 0, tsi = tsi_start (t);
18318 i < 7 && !tsi_end_p (tsi);
18319 i++, tsi_next (&tsi))
18320 stmts[i] = tsi_stmt (tsi);
18321 gcc_assert (tsi_end_p (tsi));
18323 if (i >= 3)
18325 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
18326 && TREE_CODE (stmts[1]) == DECL_EXPR);
18327 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
18328 args, complain, in_decl);
18329 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
18330 args, complain, in_decl);
18331 DECL_CONTEXT (omp_out) = current_function_decl;
18332 DECL_CONTEXT (omp_in) = current_function_decl;
18333 keep_next_level (true);
18334 tree block = begin_omp_structured_block ();
18335 tsubst_expr (stmts[2], args, complain, in_decl, false);
18336 block = finish_omp_structured_block (block);
18337 block = maybe_cleanup_point_expr_void (block);
18338 add_decl_expr (omp_out);
18339 if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
18340 TREE_NO_WARNING (omp_out) = 1;
18341 add_decl_expr (omp_in);
18342 finish_expr_stmt (block);
18344 if (i >= 6)
18346 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
18347 && TREE_CODE (stmts[4]) == DECL_EXPR);
18348 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
18349 args, complain, in_decl);
18350 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
18351 args, complain, in_decl);
18352 DECL_CONTEXT (omp_priv) = current_function_decl;
18353 DECL_CONTEXT (omp_orig) = current_function_decl;
18354 keep_next_level (true);
18355 tree block = begin_omp_structured_block ();
18356 tsubst_expr (stmts[5], args, complain, in_decl, false);
18357 block = finish_omp_structured_block (block);
18358 block = maybe_cleanup_point_expr_void (block);
18359 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
18360 add_decl_expr (omp_priv);
18361 add_decl_expr (omp_orig);
18362 finish_expr_stmt (block);
18363 if (i == 7)
18364 add_decl_expr (omp_orig);
18368 /* T is a postfix-expression that is not being used in a function
18369 call. Return the substituted version of T. */
18371 static tree
18372 tsubst_non_call_postfix_expression (tree t, tree args,
18373 tsubst_flags_t complain,
18374 tree in_decl)
18376 if (TREE_CODE (t) == SCOPE_REF)
18377 t = tsubst_qualified_id (t, args, complain, in_decl,
18378 /*done=*/false, /*address_p=*/false);
18379 else
18380 t = tsubst_copy_and_build (t, args, complain, in_decl,
18381 /*function_p=*/false,
18382 /*integral_constant_expression_p=*/false);
18384 return t;
18387 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
18388 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
18389 dependent init-capture. */
18391 static void
18392 prepend_one_capture (tree field, tree init, tree &list,
18393 tsubst_flags_t complain)
18395 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
18397 tree type = NULL_TREE;
18398 if (!init)
18400 if (complain & tf_error)
18401 error ("empty initializer in lambda init-capture");
18402 init = error_mark_node;
18404 else if (TREE_CODE (init) == TREE_LIST)
18405 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
18406 if (!type)
18407 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
18408 TREE_TYPE (field) = type;
18409 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
18411 list = tree_cons (field, init, list);
18414 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
18415 instantiation context. Instantiating a pack expansion containing a lambda
18416 might result in multiple lambdas all based on the same lambda in the
18417 template. */
18419 tree
18420 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18422 tree oldfn = lambda_function (t);
18423 in_decl = oldfn;
18425 tree r = build_lambda_expr ();
18427 LAMBDA_EXPR_LOCATION (r)
18428 = LAMBDA_EXPR_LOCATION (t);
18429 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
18430 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
18431 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
18432 LAMBDA_EXPR_INSTANTIATED (r) = true;
18434 if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
18435 /* A lambda in a default argument outside a class gets no
18436 LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI. But
18437 tsubst_default_argument calls start_lambda_scope, so we need to
18438 specifically ignore it here, and use the global scope. */
18439 record_null_lambda_scope (r);
18440 else
18441 record_lambda_scope (r);
18443 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
18444 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
18446 vec<tree,va_gc>* field_packs = NULL;
18448 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
18449 cap = TREE_CHAIN (cap))
18451 tree ofield = TREE_PURPOSE (cap);
18452 if (PACK_EXPANSION_P (ofield))
18453 ofield = PACK_EXPANSION_PATTERN (ofield);
18454 tree field = tsubst_decl (ofield, args, complain);
18456 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
18458 /* Remember these for when we've pushed local_specializations. */
18459 vec_safe_push (field_packs, ofield);
18460 vec_safe_push (field_packs, field);
18463 if (field == error_mark_node)
18464 return error_mark_node;
18466 tree init = TREE_VALUE (cap);
18467 if (PACK_EXPANSION_P (init))
18468 init = tsubst_pack_expansion (init, args, complain, in_decl);
18469 else
18470 init = tsubst_copy_and_build (init, args, complain, in_decl,
18471 /*fn*/false, /*constexpr*/false);
18473 if (TREE_CODE (field) == TREE_VEC)
18475 int len = TREE_VEC_LENGTH (field);
18476 gcc_assert (TREE_CODE (init) == TREE_VEC
18477 && TREE_VEC_LENGTH (init) == len);
18478 for (int i = 0; i < len; ++i)
18479 prepend_one_capture (TREE_VEC_ELT (field, i),
18480 TREE_VEC_ELT (init, i),
18481 LAMBDA_EXPR_CAPTURE_LIST (r),
18482 complain);
18484 else
18486 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
18487 complain);
18489 if (id_equal (DECL_NAME (field), "__this"))
18490 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
18494 tree type = begin_lambda_type (r);
18495 if (type == error_mark_node)
18496 return error_mark_node;
18498 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
18499 determine_visibility (TYPE_NAME (type));
18501 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
18503 tree oldtmpl = (generic_lambda_fn_p (oldfn)
18504 ? DECL_TI_TEMPLATE (oldfn)
18505 : NULL_TREE);
18507 tree fntype = static_fn_type (oldfn);
18508 if (oldtmpl)
18509 ++processing_template_decl;
18510 fntype = tsubst (fntype, args, complain, in_decl);
18511 if (oldtmpl)
18512 --processing_template_decl;
18514 if (fntype == error_mark_node)
18515 r = error_mark_node;
18516 else
18518 /* The body of a lambda-expression is not a subexpression of the
18519 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
18520 which would be skipped if cp_unevaluated_operand. */
18521 cp_evaluated ev;
18523 /* Fix the type of 'this'. */
18524 fntype = build_memfn_type (fntype, type,
18525 type_memfn_quals (fntype),
18526 type_memfn_rqual (fntype));
18527 tree fn, tmpl;
18528 if (oldtmpl)
18530 tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
18531 fn = DECL_TEMPLATE_RESULT (tmpl);
18532 finish_member_declaration (tmpl);
18534 else
18536 tmpl = NULL_TREE;
18537 fn = tsubst_function_decl (oldfn, args, complain, fntype);
18538 finish_member_declaration (fn);
18541 /* Let finish_function set this. */
18542 DECL_DECLARED_CONSTEXPR_P (fn) = false;
18544 bool nested = cfun;
18545 if (nested)
18546 push_function_context ();
18547 else
18548 /* Still increment function_depth so that we don't GC in the
18549 middle of an expression. */
18550 ++function_depth;
18552 local_specialization_stack s (lss_copy);
18554 tree body = start_lambda_function (fn, r);
18556 /* Now record them for lookup_init_capture_pack. */
18557 int fplen = vec_safe_length (field_packs);
18558 for (int i = 0; i < fplen; )
18560 tree pack = (*field_packs)[i++];
18561 tree inst = (*field_packs)[i++];
18562 register_local_specialization (inst, pack);
18564 release_tree_vector (field_packs);
18566 register_parameter_specializations (oldfn, fn);
18568 if (oldtmpl)
18570 /* We might not partially instantiate some parts of the function, so
18571 copy these flags from the original template. */
18572 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
18573 current_function_returns_value = ol->returns_value;
18574 current_function_returns_null = ol->returns_null;
18575 current_function_returns_abnormally = ol->returns_abnormally;
18576 current_function_infinite_loop = ol->infinite_loop;
18579 /* [temp.deduct] A lambda-expression appearing in a function type or a
18580 template parameter is not considered part of the immediate context for
18581 the purposes of template argument deduction. */
18582 complain = tf_warning_or_error;
18584 tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
18585 /*constexpr*/false);
18587 finish_lambda_function (body);
18589 if (nested)
18590 pop_function_context ();
18591 else
18592 --function_depth;
18594 /* The capture list was built up in reverse order; fix that now. */
18595 LAMBDA_EXPR_CAPTURE_LIST (r)
18596 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
18598 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
18600 maybe_add_lambda_conv_op (type);
18603 finish_struct (type, /*attr*/NULL_TREE);
18605 insert_pending_capture_proxies ();
18607 return r;
18610 /* Like tsubst but deals with expressions and performs semantic
18611 analysis. FUNCTION_P is true if T is the "F" in "F (ARGS)". */
18613 tree
18614 tsubst_copy_and_build (tree t,
18615 tree args,
18616 tsubst_flags_t complain,
18617 tree in_decl,
18618 bool function_p,
18619 bool integral_constant_expression_p)
18621 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
18622 #define RECUR(NODE) \
18623 tsubst_copy_and_build (NODE, args, complain, in_decl, \
18624 /*function_p=*/false, \
18625 integral_constant_expression_p)
18627 tree retval, op1;
18628 location_t loc;
18630 if (t == NULL_TREE || t == error_mark_node)
18631 return t;
18633 loc = input_location;
18634 if (location_t eloc = cp_expr_location (t))
18635 input_location = eloc;
18637 /* N3276 decltype magic only applies to calls at the top level or on the
18638 right side of a comma. */
18639 tsubst_flags_t decltype_flag = (complain & tf_decltype);
18640 complain &= ~tf_decltype;
18642 switch (TREE_CODE (t))
18644 case USING_DECL:
18645 t = DECL_NAME (t);
18646 /* Fall through. */
18647 case IDENTIFIER_NODE:
18649 tree decl;
18650 cp_id_kind idk;
18651 bool non_integral_constant_expression_p;
18652 const char *error_msg;
18654 if (IDENTIFIER_CONV_OP_P (t))
18656 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18657 t = make_conv_op_name (new_type);
18660 /* Look up the name. */
18661 decl = lookup_name (t);
18663 /* By convention, expressions use ERROR_MARK_NODE to indicate
18664 failure, not NULL_TREE. */
18665 if (decl == NULL_TREE)
18666 decl = error_mark_node;
18668 decl = finish_id_expression (t, decl, NULL_TREE,
18669 &idk,
18670 integral_constant_expression_p,
18671 /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
18672 &non_integral_constant_expression_p,
18673 /*template_p=*/false,
18674 /*done=*/true,
18675 /*address_p=*/false,
18676 /*template_arg_p=*/false,
18677 &error_msg,
18678 input_location);
18679 if (error_msg)
18680 error (error_msg);
18681 if (!function_p && identifier_p (decl))
18683 if (complain & tf_error)
18684 unqualified_name_lookup_error (decl);
18685 decl = error_mark_node;
18687 RETURN (decl);
18690 case TEMPLATE_ID_EXPR:
18692 tree object;
18693 tree templ = RECUR (TREE_OPERAND (t, 0));
18694 tree targs = TREE_OPERAND (t, 1);
18696 if (targs)
18697 targs = tsubst_template_args (targs, args, complain, in_decl);
18698 if (targs == error_mark_node)
18699 RETURN (error_mark_node);
18701 if (TREE_CODE (templ) == SCOPE_REF)
18703 tree name = TREE_OPERAND (templ, 1);
18704 tree tid = lookup_template_function (name, targs);
18705 TREE_OPERAND (templ, 1) = tid;
18706 RETURN (templ);
18709 if (concept_definition_p (templ))
18711 tree check = build_concept_check (templ, targs, complain);
18712 if (check == error_mark_node)
18713 RETURN (error_mark_node);
18715 tree id = unpack_concept_check (check);
18717 /* If we built a function concept check, return the underlying
18718 template-id. So we can evaluate it as a function call. */
18719 if (function_concept_p (TREE_OPERAND (id, 0)))
18720 RETURN (id);
18722 /* Evaluate the concept, if needed. */
18723 tree args = TREE_OPERAND (id, 1);
18724 if (!uses_template_parms (args)
18725 && !processing_constraint_expression_p ())
18726 RETURN (evaluate_concept_check (check, complain));
18728 RETURN (check);
18731 if (variable_template_p (templ))
18732 RETURN (lookup_and_finish_template_variable (templ, targs, complain));
18734 if (TREE_CODE (templ) == COMPONENT_REF)
18736 object = TREE_OPERAND (templ, 0);
18737 templ = TREE_OPERAND (templ, 1);
18739 else
18740 object = NULL_TREE;
18741 templ = lookup_template_function (templ, targs);
18743 if (object)
18744 RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
18745 object, templ, NULL_TREE));
18746 else
18747 RETURN (baselink_for_fns (templ));
18750 case INDIRECT_REF:
18752 tree r = RECUR (TREE_OPERAND (t, 0));
18754 if (REFERENCE_REF_P (t))
18756 /* A type conversion to reference type will be enclosed in
18757 such an indirect ref, but the substitution of the cast
18758 will have also added such an indirect ref. */
18759 r = convert_from_reference (r);
18761 else
18762 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
18763 complain|decltype_flag);
18765 if (REF_PARENTHESIZED_P (t))
18766 r = force_paren_expr (r);
18768 RETURN (r);
18771 case NOP_EXPR:
18773 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18774 tree op0 = RECUR (TREE_OPERAND (t, 0));
18775 RETURN (build_nop (type, op0));
18778 case IMPLICIT_CONV_EXPR:
18780 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18781 tree expr = RECUR (TREE_OPERAND (t, 0));
18782 if (dependent_type_p (type) || type_dependent_expression_p (expr))
18784 retval = copy_node (t);
18785 TREE_TYPE (retval) = type;
18786 TREE_OPERAND (retval, 0) = expr;
18787 RETURN (retval);
18789 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
18790 /* We'll pass this to convert_nontype_argument again, we don't need
18791 to actually perform any conversion here. */
18792 RETURN (expr);
18793 int flags = LOOKUP_IMPLICIT;
18794 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
18795 flags = LOOKUP_NORMAL;
18796 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
18797 flags |= LOOKUP_NO_NARROWING;
18798 RETURN (perform_implicit_conversion_flags (type, expr, complain,
18799 flags));
18802 case CONVERT_EXPR:
18804 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18805 tree op0 = RECUR (TREE_OPERAND (t, 0));
18806 if (op0 == error_mark_node)
18807 RETURN (error_mark_node);
18808 RETURN (build1 (CONVERT_EXPR, type, op0));
18811 case CAST_EXPR:
18812 case REINTERPRET_CAST_EXPR:
18813 case CONST_CAST_EXPR:
18814 case DYNAMIC_CAST_EXPR:
18815 case STATIC_CAST_EXPR:
18817 tree type;
18818 tree op, r = NULL_TREE;
18820 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18821 if (integral_constant_expression_p
18822 && !cast_valid_in_integral_constant_expression_p (type))
18824 if (complain & tf_error)
18825 error ("a cast to a type other than an integral or "
18826 "enumeration type cannot appear in a constant-expression");
18827 RETURN (error_mark_node);
18830 op = RECUR (TREE_OPERAND (t, 0));
18832 warning_sentinel s(warn_useless_cast);
18833 warning_sentinel s2(warn_ignored_qualifiers);
18834 switch (TREE_CODE (t))
18836 case CAST_EXPR:
18837 r = build_functional_cast (type, op, complain);
18838 break;
18839 case REINTERPRET_CAST_EXPR:
18840 r = build_reinterpret_cast (type, op, complain);
18841 break;
18842 case CONST_CAST_EXPR:
18843 r = build_const_cast (type, op, complain);
18844 break;
18845 case DYNAMIC_CAST_EXPR:
18846 r = build_dynamic_cast (type, op, complain);
18847 break;
18848 case STATIC_CAST_EXPR:
18849 r = build_static_cast (type, op, complain);
18850 break;
18851 default:
18852 gcc_unreachable ();
18855 RETURN (r);
18858 case POSTDECREMENT_EXPR:
18859 case POSTINCREMENT_EXPR:
18860 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18861 args, complain, in_decl);
18862 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
18863 complain|decltype_flag));
18865 case PREDECREMENT_EXPR:
18866 case PREINCREMENT_EXPR:
18867 case NEGATE_EXPR:
18868 case BIT_NOT_EXPR:
18869 case ABS_EXPR:
18870 case TRUTH_NOT_EXPR:
18871 case UNARY_PLUS_EXPR: /* Unary + */
18872 case REALPART_EXPR:
18873 case IMAGPART_EXPR:
18874 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
18875 RECUR (TREE_OPERAND (t, 0)),
18876 complain|decltype_flag));
18878 case FIX_TRUNC_EXPR:
18879 gcc_unreachable ();
18881 case ADDR_EXPR:
18882 op1 = TREE_OPERAND (t, 0);
18883 if (TREE_CODE (op1) == LABEL_DECL)
18884 RETURN (finish_label_address_expr (DECL_NAME (op1),
18885 EXPR_LOCATION (op1)));
18886 if (TREE_CODE (op1) == SCOPE_REF)
18887 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
18888 /*done=*/true, /*address_p=*/true);
18889 else
18890 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
18891 in_decl);
18892 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
18893 complain|decltype_flag));
18895 case PLUS_EXPR:
18896 case MINUS_EXPR:
18897 case MULT_EXPR:
18898 case TRUNC_DIV_EXPR:
18899 case CEIL_DIV_EXPR:
18900 case FLOOR_DIV_EXPR:
18901 case ROUND_DIV_EXPR:
18902 case EXACT_DIV_EXPR:
18903 case BIT_AND_EXPR:
18904 case BIT_IOR_EXPR:
18905 case BIT_XOR_EXPR:
18906 case TRUNC_MOD_EXPR:
18907 case FLOOR_MOD_EXPR:
18908 case TRUTH_ANDIF_EXPR:
18909 case TRUTH_ORIF_EXPR:
18910 case TRUTH_AND_EXPR:
18911 case TRUTH_OR_EXPR:
18912 case RSHIFT_EXPR:
18913 case LSHIFT_EXPR:
18914 case EQ_EXPR:
18915 case NE_EXPR:
18916 case MAX_EXPR:
18917 case MIN_EXPR:
18918 case LE_EXPR:
18919 case GE_EXPR:
18920 case LT_EXPR:
18921 case GT_EXPR:
18922 case MEMBER_REF:
18923 case DOTSTAR_EXPR:
18925 warning_sentinel s1(warn_type_limits);
18926 warning_sentinel s2(warn_div_by_zero);
18927 warning_sentinel s3(warn_logical_op);
18928 warning_sentinel s4(warn_tautological_compare);
18929 tree op0 = RECUR (TREE_OPERAND (t, 0));
18930 tree op1 = RECUR (TREE_OPERAND (t, 1));
18931 tree r = build_x_binary_op
18932 (input_location, TREE_CODE (t),
18933 op0,
18934 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
18935 ? ERROR_MARK
18936 : TREE_CODE (TREE_OPERAND (t, 0))),
18937 op1,
18938 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
18939 ? ERROR_MARK
18940 : TREE_CODE (TREE_OPERAND (t, 1))),
18941 /*overload=*/NULL,
18942 complain|decltype_flag);
18943 if (EXPR_P (r) && TREE_NO_WARNING (t))
18944 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18946 RETURN (r);
18949 case POINTER_PLUS_EXPR:
18951 tree op0 = RECUR (TREE_OPERAND (t, 0));
18952 tree op1 = RECUR (TREE_OPERAND (t, 1));
18953 RETURN (fold_build_pointer_plus (op0, op1));
18956 case SCOPE_REF:
18957 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
18958 /*address_p=*/false));
18959 case ARRAY_REF:
18960 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18961 args, complain, in_decl);
18962 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
18963 RECUR (TREE_OPERAND (t, 1)),
18964 complain|decltype_flag));
18966 case SIZEOF_EXPR:
18967 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
18968 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
18969 RETURN (tsubst_copy (t, args, complain, in_decl));
18970 /* Fall through */
18972 case ALIGNOF_EXPR:
18974 tree r;
18976 op1 = TREE_OPERAND (t, 0);
18977 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18978 op1 = TREE_TYPE (op1);
18979 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18980 && ALIGNOF_EXPR_STD_P (t));
18981 if (!args)
18983 /* When there are no ARGS, we are trying to evaluate a
18984 non-dependent expression from the parser. Trying to do
18985 the substitutions may not work. */
18986 if (!TYPE_P (op1))
18987 op1 = TREE_TYPE (op1);
18989 else
18991 ++cp_unevaluated_operand;
18992 ++c_inhibit_evaluation_warnings;
18993 if (TYPE_P (op1))
18994 op1 = tsubst (op1, args, complain, in_decl);
18995 else
18996 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18997 /*function_p=*/false,
18998 /*integral_constant_expression_p=*/
18999 false);
19000 --cp_unevaluated_operand;
19001 --c_inhibit_evaluation_warnings;
19003 if (TYPE_P (op1))
19004 r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
19005 complain & tf_error);
19006 else
19007 r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
19008 complain & tf_error);
19009 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
19011 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
19013 if (!processing_template_decl && TYPE_P (op1))
19015 r = build_min (SIZEOF_EXPR, size_type_node,
19016 build1 (NOP_EXPR, op1, error_mark_node));
19017 SIZEOF_EXPR_TYPE_P (r) = 1;
19019 else
19020 r = build_min (SIZEOF_EXPR, size_type_node, op1);
19021 TREE_SIDE_EFFECTS (r) = 0;
19022 TREE_READONLY (r) = 1;
19024 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
19026 RETURN (r);
19029 case AT_ENCODE_EXPR:
19031 op1 = TREE_OPERAND (t, 0);
19032 ++cp_unevaluated_operand;
19033 ++c_inhibit_evaluation_warnings;
19034 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19035 /*function_p=*/false,
19036 /*integral_constant_expression_p=*/false);
19037 --cp_unevaluated_operand;
19038 --c_inhibit_evaluation_warnings;
19039 RETURN (objc_build_encode_expr (op1));
19042 case NOEXCEPT_EXPR:
19043 op1 = TREE_OPERAND (t, 0);
19044 ++cp_unevaluated_operand;
19045 ++c_inhibit_evaluation_warnings;
19046 ++cp_noexcept_operand;
19047 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19048 /*function_p=*/false,
19049 /*integral_constant_expression_p=*/false);
19050 --cp_unevaluated_operand;
19051 --c_inhibit_evaluation_warnings;
19052 --cp_noexcept_operand;
19053 RETURN (finish_noexcept_expr (op1, complain));
19055 case MODOP_EXPR:
19057 warning_sentinel s(warn_div_by_zero);
19058 tree lhs = RECUR (TREE_OPERAND (t, 0));
19059 tree rhs = RECUR (TREE_OPERAND (t, 2));
19060 tree r = build_x_modify_expr
19061 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
19062 complain|decltype_flag);
19063 /* TREE_NO_WARNING must be set if either the expression was
19064 parenthesized or it uses an operator such as >>= rather
19065 than plain assignment. In the former case, it was already
19066 set and must be copied. In the latter case,
19067 build_x_modify_expr sets it and it must not be reset
19068 here. */
19069 if (TREE_NO_WARNING (t))
19070 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19072 RETURN (r);
19075 case ARROW_EXPR:
19076 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19077 args, complain, in_decl);
19078 /* Remember that there was a reference to this entity. */
19079 if (DECL_P (op1)
19080 && !mark_used (op1, complain) && !(complain & tf_error))
19081 RETURN (error_mark_node);
19082 RETURN (build_x_arrow (input_location, op1, complain));
19084 case NEW_EXPR:
19086 tree placement = RECUR (TREE_OPERAND (t, 0));
19087 tree init = RECUR (TREE_OPERAND (t, 3));
19088 vec<tree, va_gc> *placement_vec;
19089 vec<tree, va_gc> *init_vec;
19090 tree ret;
19092 if (placement == NULL_TREE)
19093 placement_vec = NULL;
19094 else
19096 placement_vec = make_tree_vector ();
19097 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
19098 vec_safe_push (placement_vec, TREE_VALUE (placement));
19101 /* If there was an initializer in the original tree, but it
19102 instantiated to an empty list, then we should pass a
19103 non-NULL empty vector to tell build_new that it was an
19104 empty initializer() rather than no initializer. This can
19105 only happen when the initializer is a pack expansion whose
19106 parameter packs are of length zero. */
19107 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
19108 init_vec = NULL;
19109 else
19111 init_vec = make_tree_vector ();
19112 if (init == void_node)
19113 gcc_assert (init_vec != NULL);
19114 else
19116 for (; init != NULL_TREE; init = TREE_CHAIN (init))
19117 vec_safe_push (init_vec, TREE_VALUE (init));
19121 /* Avoid passing an enclosing decl to valid_array_size_p. */
19122 in_decl = NULL_TREE;
19124 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
19125 tree op2 = RECUR (TREE_OPERAND (t, 2));
19126 ret = build_new (&placement_vec, op1, op2, &init_vec,
19127 NEW_EXPR_USE_GLOBAL (t),
19128 complain);
19130 if (placement_vec != NULL)
19131 release_tree_vector (placement_vec);
19132 if (init_vec != NULL)
19133 release_tree_vector (init_vec);
19135 RETURN (ret);
19138 case DELETE_EXPR:
19140 tree op0 = RECUR (TREE_OPERAND (t, 0));
19141 tree op1 = RECUR (TREE_OPERAND (t, 1));
19142 RETURN (delete_sanity (op0, op1,
19143 DELETE_EXPR_USE_VEC (t),
19144 DELETE_EXPR_USE_GLOBAL (t),
19145 complain));
19148 case COMPOUND_EXPR:
19150 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19151 complain & ~tf_decltype, in_decl,
19152 /*function_p=*/false,
19153 integral_constant_expression_p);
19154 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
19155 op0,
19156 RECUR (TREE_OPERAND (t, 1)),
19157 complain|decltype_flag));
19160 case CALL_EXPR:
19162 tree function;
19163 unsigned int nargs, i;
19164 bool qualified_p;
19165 bool koenig_p;
19166 tree ret;
19168 function = CALL_EXPR_FN (t);
19169 /* Internal function with no arguments. */
19170 if (function == NULL_TREE && call_expr_nargs (t) == 0)
19171 RETURN (t);
19173 /* When we parsed the expression, we determined whether or
19174 not Koenig lookup should be performed. */
19175 koenig_p = KOENIG_LOOKUP_P (t);
19176 if (function == NULL_TREE)
19178 koenig_p = false;
19179 qualified_p = false;
19181 else if (TREE_CODE (function) == SCOPE_REF)
19183 qualified_p = true;
19184 function = tsubst_qualified_id (function, args, complain, in_decl,
19185 /*done=*/false,
19186 /*address_p=*/false);
19188 else if (koenig_p && identifier_p (function))
19190 /* Do nothing; calling tsubst_copy_and_build on an identifier
19191 would incorrectly perform unqualified lookup again.
19193 Note that we can also have an IDENTIFIER_NODE if the earlier
19194 unqualified lookup found a member function; in that case
19195 koenig_p will be false and we do want to do the lookup
19196 again to find the instantiated member function.
19198 FIXME but doing that causes c++/15272, so we need to stop
19199 using IDENTIFIER_NODE in that situation. */
19200 qualified_p = false;
19202 else
19204 if (TREE_CODE (function) == COMPONENT_REF)
19206 tree op = TREE_OPERAND (function, 1);
19208 qualified_p = (TREE_CODE (op) == SCOPE_REF
19209 || (BASELINK_P (op)
19210 && BASELINK_QUALIFIED_P (op)));
19212 else
19213 qualified_p = false;
19215 if (TREE_CODE (function) == ADDR_EXPR
19216 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
19217 /* Avoid error about taking the address of a constructor. */
19218 function = TREE_OPERAND (function, 0);
19220 function = tsubst_copy_and_build (function, args, complain,
19221 in_decl,
19222 !qualified_p,
19223 integral_constant_expression_p);
19225 if (BASELINK_P (function))
19226 qualified_p = true;
19229 nargs = call_expr_nargs (t);
19230 releasing_vec call_args;
19231 for (i = 0; i < nargs; ++i)
19233 tree arg = CALL_EXPR_ARG (t, i);
19235 if (!PACK_EXPANSION_P (arg))
19236 vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
19237 else
19239 /* Expand the pack expansion and push each entry onto
19240 CALL_ARGS. */
19241 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19242 if (TREE_CODE (arg) == TREE_VEC)
19244 unsigned int len, j;
19246 len = TREE_VEC_LENGTH (arg);
19247 for (j = 0; j < len; ++j)
19249 tree value = TREE_VEC_ELT (arg, j);
19250 if (value != NULL_TREE)
19251 value = convert_from_reference (value);
19252 vec_safe_push (call_args, value);
19255 else
19257 /* A partial substitution. Add one entry. */
19258 vec_safe_push (call_args, arg);
19263 /* Stripped-down processing for a call in a thunk. Specifically, in
19264 the thunk template for a generic lambda. */
19265 if (CALL_FROM_THUNK_P (t))
19267 /* Now that we've expanded any packs, the number of call args
19268 might be different. */
19269 unsigned int cargs = call_args->length ();
19270 tree thisarg = NULL_TREE;
19271 if (TREE_CODE (function) == COMPONENT_REF)
19273 thisarg = TREE_OPERAND (function, 0);
19274 if (TREE_CODE (thisarg) == INDIRECT_REF)
19275 thisarg = TREE_OPERAND (thisarg, 0);
19276 function = TREE_OPERAND (function, 1);
19277 if (TREE_CODE (function) == BASELINK)
19278 function = BASELINK_FUNCTIONS (function);
19280 /* We aren't going to do normal overload resolution, so force the
19281 template-id to resolve. */
19282 function = resolve_nondeduced_context (function, complain);
19283 for (unsigned i = 0; i < cargs; ++i)
19285 /* In a thunk, pass through args directly, without any
19286 conversions. */
19287 tree arg = (*call_args)[i];
19288 while (TREE_CODE (arg) != PARM_DECL)
19289 arg = TREE_OPERAND (arg, 0);
19290 (*call_args)[i] = arg;
19292 if (thisarg)
19294 /* If there are no other args, just push 'this'. */
19295 if (cargs == 0)
19296 vec_safe_push (call_args, thisarg);
19297 else
19299 /* Otherwise, shift the other args over to make room. */
19300 tree last = (*call_args)[cargs - 1];
19301 vec_safe_push (call_args, last);
19302 for (int i = cargs - 1; i > 0; --i)
19303 (*call_args)[i] = (*call_args)[i - 1];
19304 (*call_args)[0] = thisarg;
19307 ret = build_call_a (function, call_args->length (),
19308 call_args->address ());
19309 /* The thunk location is not interesting. */
19310 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
19311 CALL_FROM_THUNK_P (ret) = true;
19312 if (CLASS_TYPE_P (TREE_TYPE (ret)))
19313 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
19315 RETURN (ret);
19318 /* We do not perform argument-dependent lookup if normal
19319 lookup finds a non-function, in accordance with the
19320 expected resolution of DR 218. */
19321 if (koenig_p
19322 && ((is_overloaded_fn (function)
19323 /* If lookup found a member function, the Koenig lookup is
19324 not appropriate, even if an unqualified-name was used
19325 to denote the function. */
19326 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
19327 || identifier_p (function))
19328 /* Only do this when substitution turns a dependent call
19329 into a non-dependent call. */
19330 && type_dependent_expression_p_push (t)
19331 && !any_type_dependent_arguments_p (call_args))
19332 function = perform_koenig_lookup (function, call_args, tf_none);
19334 if (function != NULL_TREE
19335 && identifier_p (function)
19336 && !any_type_dependent_arguments_p (call_args))
19338 if (koenig_p && (complain & tf_warning_or_error))
19340 /* For backwards compatibility and good diagnostics, try
19341 the unqualified lookup again if we aren't in SFINAE
19342 context. */
19343 tree unq = (tsubst_copy_and_build
19344 (function, args, complain, in_decl, true,
19345 integral_constant_expression_p));
19346 if (unq == error_mark_node)
19347 RETURN (error_mark_node);
19349 if (unq != function)
19351 /* In a lambda fn, we have to be careful to not
19352 introduce new this captures. Legacy code can't
19353 be using lambdas anyway, so it's ok to be
19354 stricter. */
19355 bool in_lambda = (current_class_type
19356 && LAMBDA_TYPE_P (current_class_type));
19357 char const *const msg
19358 = G_("%qD was not declared in this scope, "
19359 "and no declarations were found by "
19360 "argument-dependent lookup at the point "
19361 "of instantiation");
19363 bool diag = true;
19364 if (in_lambda)
19365 error_at (cp_expr_loc_or_input_loc (t),
19366 msg, function);
19367 else
19368 diag = permerror (cp_expr_loc_or_input_loc (t),
19369 msg, function);
19370 if (diag)
19372 tree fn = unq;
19374 if (INDIRECT_REF_P (fn))
19375 fn = TREE_OPERAND (fn, 0);
19376 if (is_overloaded_fn (fn))
19377 fn = get_first_fn (fn);
19379 if (!DECL_P (fn))
19380 /* Can't say anything more. */;
19381 else if (DECL_CLASS_SCOPE_P (fn))
19383 location_t loc = cp_expr_loc_or_input_loc (t);
19384 inform (loc,
19385 "declarations in dependent base %qT are "
19386 "not found by unqualified lookup",
19387 DECL_CLASS_CONTEXT (fn));
19388 if (current_class_ptr)
19389 inform (loc,
19390 "use %<this->%D%> instead", function);
19391 else
19392 inform (loc,
19393 "use %<%T::%D%> instead",
19394 current_class_name, function);
19396 else
19397 inform (DECL_SOURCE_LOCATION (fn),
19398 "%qD declared here, later in the "
19399 "translation unit", fn);
19400 if (in_lambda)
19401 RETURN (error_mark_node);
19404 function = unq;
19407 if (identifier_p (function))
19409 if (complain & tf_error)
19410 unqualified_name_lookup_error (function);
19411 RETURN (error_mark_node);
19415 /* Remember that there was a reference to this entity. */
19416 if (function != NULL_TREE
19417 && DECL_P (function)
19418 && !mark_used (function, complain) && !(complain & tf_error))
19419 RETURN (error_mark_node);
19421 /* Put back tf_decltype for the actual call. */
19422 complain |= decltype_flag;
19424 if (function == NULL_TREE)
19425 switch (CALL_EXPR_IFN (t))
19427 case IFN_LAUNDER:
19428 gcc_assert (nargs == 1);
19429 if (vec_safe_length (call_args) != 1)
19431 error_at (cp_expr_loc_or_input_loc (t),
19432 "wrong number of arguments to "
19433 "%<__builtin_launder%>");
19434 ret = error_mark_node;
19436 else
19437 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
19438 (*call_args)[0], complain);
19439 break;
19441 case IFN_VEC_CONVERT:
19442 gcc_assert (nargs == 1);
19443 if (vec_safe_length (call_args) != 1)
19445 error_at (cp_expr_loc_or_input_loc (t),
19446 "wrong number of arguments to "
19447 "%<__builtin_convertvector%>");
19448 ret = error_mark_node;
19449 break;
19451 ret = cp_build_vec_convert ((*call_args)[0], input_location,
19452 tsubst (TREE_TYPE (t), args,
19453 complain, in_decl),
19454 complain);
19455 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
19456 RETURN (ret);
19457 break;
19459 default:
19460 /* Unsupported internal function with arguments. */
19461 gcc_unreachable ();
19463 else if (TREE_CODE (function) == OFFSET_REF
19464 || TREE_CODE (function) == DOTSTAR_EXPR
19465 || TREE_CODE (function) == MEMBER_REF)
19466 ret = build_offset_ref_call_from_tree (function, &call_args,
19467 complain);
19468 else if (TREE_CODE (function) == COMPONENT_REF)
19470 tree instance = TREE_OPERAND (function, 0);
19471 tree fn = TREE_OPERAND (function, 1);
19473 if (processing_template_decl
19474 && (type_dependent_expression_p (instance)
19475 || (!BASELINK_P (fn)
19476 && TREE_CODE (fn) != FIELD_DECL)
19477 || type_dependent_expression_p (fn)
19478 || any_type_dependent_arguments_p (call_args)))
19479 ret = build_min_nt_call_vec (function, call_args);
19480 else if (!BASELINK_P (fn))
19481 ret = finish_call_expr (function, &call_args,
19482 /*disallow_virtual=*/false,
19483 /*koenig_p=*/false,
19484 complain);
19485 else
19486 ret = (build_new_method_call
19487 (instance, fn,
19488 &call_args, NULL_TREE,
19489 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
19490 /*fn_p=*/NULL,
19491 complain));
19493 else if (concept_check_p (function))
19495 /* FUNCTION is a template-id referring to a concept definition. */
19496 tree id = unpack_concept_check (function);
19497 tree tmpl = TREE_OPERAND (id, 0);
19498 tree args = TREE_OPERAND (id, 1);
19500 /* Calls to standard and variable concepts should have been
19501 previously diagnosed. */
19502 gcc_assert (function_concept_p (tmpl));
19504 /* Ensure the result is wrapped as a call expression. */
19505 ret = build_concept_check (tmpl, args, tf_warning_or_error);
19507 /* Possibly evaluate the check if it is non-dependent. */
19508 if (!uses_template_parms (args)
19509 && !processing_constraint_expression_p ())
19510 ret = evaluate_concept_check (ret, complain);
19512 else
19513 ret = finish_call_expr (function, &call_args,
19514 /*disallow_virtual=*/qualified_p,
19515 koenig_p,
19516 complain);
19518 if (ret != error_mark_node)
19520 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
19521 bool ord = CALL_EXPR_ORDERED_ARGS (t);
19522 bool rev = CALL_EXPR_REVERSE_ARGS (t);
19523 if (op || ord || rev)
19525 function = extract_call_expr (ret);
19526 CALL_EXPR_OPERATOR_SYNTAX (function) = op;
19527 CALL_EXPR_ORDERED_ARGS (function) = ord;
19528 CALL_EXPR_REVERSE_ARGS (function) = rev;
19532 RETURN (ret);
19535 case COND_EXPR:
19537 tree cond = RECUR (TREE_OPERAND (t, 0));
19538 cond = mark_rvalue_use (cond);
19539 tree folded_cond = fold_non_dependent_expr (cond, complain);
19540 tree exp1, exp2;
19542 if (TREE_CODE (folded_cond) == INTEGER_CST)
19544 if (integer_zerop (folded_cond))
19546 ++c_inhibit_evaluation_warnings;
19547 exp1 = RECUR (TREE_OPERAND (t, 1));
19548 --c_inhibit_evaluation_warnings;
19549 exp2 = RECUR (TREE_OPERAND (t, 2));
19551 else
19553 exp1 = RECUR (TREE_OPERAND (t, 1));
19554 ++c_inhibit_evaluation_warnings;
19555 exp2 = RECUR (TREE_OPERAND (t, 2));
19556 --c_inhibit_evaluation_warnings;
19558 cond = folded_cond;
19560 else
19562 exp1 = RECUR (TREE_OPERAND (t, 1));
19563 exp2 = RECUR (TREE_OPERAND (t, 2));
19566 warning_sentinel s(warn_duplicated_branches);
19567 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
19568 cond, exp1, exp2, complain));
19571 case PSEUDO_DTOR_EXPR:
19573 tree op0 = RECUR (TREE_OPERAND (t, 0));
19574 tree op1 = RECUR (TREE_OPERAND (t, 1));
19575 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
19576 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
19577 input_location));
19580 case TREE_LIST:
19582 tree purpose, value, chain;
19584 if (t == void_list_node)
19585 RETURN (t);
19587 if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
19588 || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
19590 /* We have pack expansions, so expand those and
19591 create a new list out of it. */
19592 tree purposevec = NULL_TREE;
19593 tree valuevec = NULL_TREE;
19594 tree chain;
19595 int i, len = -1;
19597 /* Expand the argument expressions. */
19598 if (TREE_PURPOSE (t))
19599 purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
19600 complain, in_decl);
19601 if (TREE_VALUE (t))
19602 valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
19603 complain, in_decl);
19605 /* Build the rest of the list. */
19606 chain = TREE_CHAIN (t);
19607 if (chain && chain != void_type_node)
19608 chain = RECUR (chain);
19610 /* Determine the number of arguments. */
19611 if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
19613 len = TREE_VEC_LENGTH (purposevec);
19614 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
19616 else if (TREE_CODE (valuevec) == TREE_VEC)
19617 len = TREE_VEC_LENGTH (valuevec);
19618 else
19620 /* Since we only performed a partial substitution into
19621 the argument pack, we only RETURN (a single list
19622 node. */
19623 if (purposevec == TREE_PURPOSE (t)
19624 && valuevec == TREE_VALUE (t)
19625 && chain == TREE_CHAIN (t))
19626 RETURN (t);
19628 RETURN (tree_cons (purposevec, valuevec, chain));
19631 /* Convert the argument vectors into a TREE_LIST */
19632 i = len;
19633 while (i > 0)
19635 /* Grab the Ith values. */
19636 i--;
19637 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
19638 : NULL_TREE;
19639 value
19640 = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
19641 : NULL_TREE;
19643 /* Build the list (backwards). */
19644 chain = tree_cons (purpose, value, chain);
19647 RETURN (chain);
19650 purpose = TREE_PURPOSE (t);
19651 if (purpose)
19652 purpose = RECUR (purpose);
19653 value = TREE_VALUE (t);
19654 if (value)
19655 value = RECUR (value);
19656 chain = TREE_CHAIN (t);
19657 if (chain && chain != void_type_node)
19658 chain = RECUR (chain);
19659 if (purpose == TREE_PURPOSE (t)
19660 && value == TREE_VALUE (t)
19661 && chain == TREE_CHAIN (t))
19662 RETURN (t);
19663 RETURN (tree_cons (purpose, value, chain));
19666 case COMPONENT_REF:
19668 tree object;
19669 tree object_type;
19670 tree member;
19671 tree r;
19673 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19674 args, complain, in_decl);
19675 /* Remember that there was a reference to this entity. */
19676 if (DECL_P (object)
19677 && !mark_used (object, complain) && !(complain & tf_error))
19678 RETURN (error_mark_node);
19679 object_type = TREE_TYPE (object);
19681 member = TREE_OPERAND (t, 1);
19682 if (BASELINK_P (member))
19683 member = tsubst_baselink (member,
19684 non_reference (TREE_TYPE (object)),
19685 args, complain, in_decl);
19686 else
19687 member = tsubst_copy (member, args, complain, in_decl);
19688 if (member == error_mark_node)
19689 RETURN (error_mark_node);
19691 if (TREE_CODE (member) == FIELD_DECL)
19693 r = finish_non_static_data_member (member, object, NULL_TREE);
19694 if (TREE_CODE (r) == COMPONENT_REF)
19695 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
19696 RETURN (r);
19698 else if (type_dependent_expression_p (object))
19699 /* We can't do much here. */;
19700 else if (!CLASS_TYPE_P (object_type))
19702 if (scalarish_type_p (object_type))
19704 tree s = NULL_TREE;
19705 tree dtor = member;
19707 if (TREE_CODE (dtor) == SCOPE_REF)
19709 s = TREE_OPERAND (dtor, 0);
19710 dtor = TREE_OPERAND (dtor, 1);
19712 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
19714 dtor = TREE_OPERAND (dtor, 0);
19715 if (TYPE_P (dtor))
19716 RETURN (finish_pseudo_destructor_expr
19717 (object, s, dtor, input_location));
19721 else if (TREE_CODE (member) == SCOPE_REF
19722 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
19724 /* Lookup the template functions now that we know what the
19725 scope is. */
19726 tree scope = TREE_OPERAND (member, 0);
19727 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
19728 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
19729 member = lookup_qualified_name (scope, tmpl,
19730 /*is_type_p=*/false,
19731 /*complain=*/false);
19732 if (BASELINK_P (member))
19734 BASELINK_FUNCTIONS (member)
19735 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
19736 args);
19737 member = (adjust_result_of_qualified_name_lookup
19738 (member, BINFO_TYPE (BASELINK_BINFO (member)),
19739 object_type));
19741 else
19743 qualified_name_lookup_error (scope, tmpl, member,
19744 input_location);
19745 RETURN (error_mark_node);
19748 else if (TREE_CODE (member) == SCOPE_REF
19749 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
19750 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
19752 if (complain & tf_error)
19754 if (TYPE_P (TREE_OPERAND (member, 0)))
19755 error ("%qT is not a class or namespace",
19756 TREE_OPERAND (member, 0));
19757 else
19758 error ("%qD is not a class or namespace",
19759 TREE_OPERAND (member, 0));
19761 RETURN (error_mark_node);
19764 r = finish_class_member_access_expr (object, member,
19765 /*template_p=*/false,
19766 complain);
19767 if (TREE_CODE (r) == COMPONENT_REF)
19768 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
19769 RETURN (r);
19772 case THROW_EXPR:
19773 RETURN (build_throw
19774 (RECUR (TREE_OPERAND (t, 0))));
19776 case CONSTRUCTOR:
19778 vec<constructor_elt, va_gc> *n;
19779 constructor_elt *ce;
19780 unsigned HOST_WIDE_INT idx;
19781 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19782 bool process_index_p;
19783 int newlen;
19784 bool need_copy_p = false;
19785 tree r;
19787 if (type == error_mark_node)
19788 RETURN (error_mark_node);
19790 /* We do not want to process the index of aggregate
19791 initializers as they are identifier nodes which will be
19792 looked up by digest_init. */
19793 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
19795 if (null_member_pointer_value_p (t))
19797 gcc_assert (same_type_p (type, TREE_TYPE (t)));
19798 RETURN (t);
19801 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
19802 newlen = vec_safe_length (n);
19803 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
19805 if (ce->index && process_index_p
19806 /* An identifier index is looked up in the type
19807 being initialized, not the current scope. */
19808 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
19809 ce->index = RECUR (ce->index);
19811 if (PACK_EXPANSION_P (ce->value))
19813 /* Substitute into the pack expansion. */
19814 ce->value = tsubst_pack_expansion (ce->value, args, complain,
19815 in_decl);
19817 if (ce->value == error_mark_node
19818 || PACK_EXPANSION_P (ce->value))
19820 else if (TREE_VEC_LENGTH (ce->value) == 1)
19821 /* Just move the argument into place. */
19822 ce->value = TREE_VEC_ELT (ce->value, 0);
19823 else
19825 /* Update the length of the final CONSTRUCTOR
19826 arguments vector, and note that we will need to
19827 copy.*/
19828 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
19829 need_copy_p = true;
19832 else
19833 ce->value = RECUR (ce->value);
19836 if (need_copy_p)
19838 vec<constructor_elt, va_gc> *old_n = n;
19840 vec_alloc (n, newlen);
19841 FOR_EACH_VEC_ELT (*old_n, idx, ce)
19843 if (TREE_CODE (ce->value) == TREE_VEC)
19845 int i, len = TREE_VEC_LENGTH (ce->value);
19846 for (i = 0; i < len; ++i)
19847 CONSTRUCTOR_APPEND_ELT (n, 0,
19848 TREE_VEC_ELT (ce->value, i));
19850 else
19851 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
19855 r = build_constructor (init_list_type_node, n);
19856 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
19857 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
19858 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
19860 if (TREE_HAS_CONSTRUCTOR (t))
19862 fcl_t cl = fcl_functional;
19863 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
19864 cl = fcl_c99;
19865 RETURN (finish_compound_literal (type, r, complain, cl));
19868 TREE_TYPE (r) = type;
19869 RETURN (r);
19872 case TYPEID_EXPR:
19874 tree operand_0 = TREE_OPERAND (t, 0);
19875 if (TYPE_P (operand_0))
19877 operand_0 = tsubst (operand_0, args, complain, in_decl);
19878 RETURN (get_typeid (operand_0, complain));
19880 else
19882 operand_0 = RECUR (operand_0);
19883 RETURN (build_typeid (operand_0, complain));
19887 case VAR_DECL:
19888 if (!args)
19889 RETURN (t);
19890 /* Fall through */
19892 case PARM_DECL:
19894 tree r = tsubst_copy (t, args, complain, in_decl);
19895 /* ??? We're doing a subset of finish_id_expression here. */
19896 if (tree wrap = maybe_get_tls_wrapper_call (r))
19897 /* Replace an evaluated use of the thread_local variable with
19898 a call to its wrapper. */
19899 r = wrap;
19900 else if (outer_automatic_var_p (r))
19901 r = process_outer_var_ref (r, complain);
19903 if (!TYPE_REF_P (TREE_TYPE (t)))
19904 /* If the original type was a reference, we'll be wrapped in
19905 the appropriate INDIRECT_REF. */
19906 r = convert_from_reference (r);
19907 RETURN (r);
19910 case VA_ARG_EXPR:
19912 tree op0 = RECUR (TREE_OPERAND (t, 0));
19913 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19914 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
19917 case OFFSETOF_EXPR:
19919 tree object_ptr
19920 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
19921 in_decl, /*function_p=*/false,
19922 /*integral_constant_expression_p=*/false);
19923 RETURN (finish_offsetof (object_ptr,
19924 RECUR (TREE_OPERAND (t, 0)),
19925 EXPR_LOCATION (t)));
19928 case ADDRESSOF_EXPR:
19929 RETURN (cp_build_addressof (EXPR_LOCATION (t),
19930 RECUR (TREE_OPERAND (t, 0)), complain));
19932 case TRAIT_EXPR:
19934 tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
19935 complain, in_decl);
19937 tree type2 = TRAIT_EXPR_TYPE2 (t);
19938 if (type2 && TREE_CODE (type2) == TREE_LIST)
19939 type2 = RECUR (type2);
19940 else if (type2)
19941 type2 = tsubst (type2, args, complain, in_decl);
19943 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
19944 TRAIT_EXPR_KIND (t), type1, type2));
19947 case STMT_EXPR:
19949 tree old_stmt_expr = cur_stmt_expr;
19950 tree stmt_expr = begin_stmt_expr ();
19952 cur_stmt_expr = stmt_expr;
19953 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
19954 integral_constant_expression_p);
19955 stmt_expr = finish_stmt_expr (stmt_expr, false);
19956 cur_stmt_expr = old_stmt_expr;
19958 /* If the resulting list of expression statement is empty,
19959 fold it further into void_node. */
19960 if (empty_expr_stmt_p (stmt_expr))
19961 stmt_expr = void_node;
19963 RETURN (stmt_expr);
19966 case LAMBDA_EXPR:
19968 if (complain & tf_partial)
19970 /* We don't have a full set of template arguments yet; don't touch
19971 the lambda at all. */
19972 gcc_assert (processing_template_decl);
19973 return t;
19975 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
19977 RETURN (build_lambda_object (r));
19980 case TARGET_EXPR:
19981 /* We can get here for a constant initializer of non-dependent type.
19982 FIXME stop folding in cp_parser_initializer_clause. */
19984 tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
19985 complain);
19986 RETURN (r);
19989 case TRANSACTION_EXPR:
19990 RETURN (tsubst_expr(t, args, complain, in_decl,
19991 integral_constant_expression_p));
19993 case PAREN_EXPR:
19994 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
19996 case VEC_PERM_EXPR:
19998 tree op0 = RECUR (TREE_OPERAND (t, 0));
19999 tree op1 = RECUR (TREE_OPERAND (t, 1));
20000 tree op2 = RECUR (TREE_OPERAND (t, 2));
20001 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
20002 complain));
20005 case REQUIRES_EXPR:
20006 RETURN (tsubst_requires_expr (t, args, complain, in_decl));
20008 case RANGE_EXPR:
20009 /* No need to substitute further, a RANGE_EXPR will always be built
20010 with constant operands. */
20011 RETURN (t);
20013 case NON_LVALUE_EXPR:
20014 case VIEW_CONVERT_EXPR:
20015 if (location_wrapper_p (t))
20016 /* We need to do this here as well as in tsubst_copy so we get the
20017 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
20018 RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
20019 EXPR_LOCATION (t)));
20020 /* fallthrough. */
20022 default:
20023 /* Handle Objective-C++ constructs, if appropriate. */
20025 tree subst
20026 = objcp_tsubst_copy_and_build (t, args, complain,
20027 in_decl, /*function_p=*/false);
20028 if (subst)
20029 RETURN (subst);
20031 RETURN (tsubst_copy (t, args, complain, in_decl));
20034 #undef RECUR
20035 #undef RETURN
20036 out:
20037 input_location = loc;
20038 return retval;
20041 /* Verify that the instantiated ARGS are valid. For type arguments,
20042 make sure that the type's linkage is ok. For non-type arguments,
20043 make sure they are constants if they are integral or enumerations.
20044 Emit an error under control of COMPLAIN, and return TRUE on error. */
20046 static bool
20047 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
20049 if (dependent_template_arg_p (t))
20050 return false;
20051 if (ARGUMENT_PACK_P (t))
20053 tree vec = ARGUMENT_PACK_ARGS (t);
20054 int len = TREE_VEC_LENGTH (vec);
20055 bool result = false;
20056 int i;
20058 for (i = 0; i < len; ++i)
20059 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
20060 result = true;
20061 return result;
20063 else if (TYPE_P (t))
20065 /* [basic.link]: A name with no linkage (notably, the name
20066 of a class or enumeration declared in a local scope)
20067 shall not be used to declare an entity with linkage.
20068 This implies that names with no linkage cannot be used as
20069 template arguments
20071 DR 757 relaxes this restriction for C++0x. */
20072 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
20073 : no_linkage_check (t, /*relaxed_p=*/false));
20075 if (nt)
20077 /* DR 488 makes use of a type with no linkage cause
20078 type deduction to fail. */
20079 if (complain & tf_error)
20081 if (TYPE_UNNAMED_P (nt))
20082 error ("%qT is/uses unnamed type", t);
20083 else
20084 error ("template argument for %qD uses local type %qT",
20085 tmpl, t);
20087 return true;
20089 /* In order to avoid all sorts of complications, we do not
20090 allow variably-modified types as template arguments. */
20091 else if (variably_modified_type_p (t, NULL_TREE))
20093 if (complain & tf_error)
20094 error ("%qT is a variably modified type", t);
20095 return true;
20098 /* Class template and alias template arguments should be OK. */
20099 else if (DECL_TYPE_TEMPLATE_P (t))
20101 /* A non-type argument of integral or enumerated type must be a
20102 constant. */
20103 else if (TREE_TYPE (t)
20104 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
20105 && !REFERENCE_REF_P (t)
20106 && !TREE_CONSTANT (t))
20108 if (complain & tf_error)
20109 error ("integral expression %qE is not constant", t);
20110 return true;
20112 return false;
20115 static bool
20116 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
20118 int ix, len = DECL_NTPARMS (tmpl);
20119 bool result = false;
20121 for (ix = 0; ix != len; ix++)
20123 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
20124 result = true;
20126 if (result && (complain & tf_error))
20127 error (" trying to instantiate %qD", tmpl);
20128 return result;
20131 /* We're out of SFINAE context now, so generate diagnostics for the access
20132 errors we saw earlier when instantiating D from TMPL and ARGS. */
20134 static void
20135 recheck_decl_substitution (tree d, tree tmpl, tree args)
20137 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
20138 tree type = TREE_TYPE (pattern);
20139 location_t loc = input_location;
20141 push_access_scope (d);
20142 push_deferring_access_checks (dk_no_deferred);
20143 input_location = DECL_SOURCE_LOCATION (pattern);
20144 tsubst (type, args, tf_warning_or_error, d);
20145 input_location = loc;
20146 pop_deferring_access_checks ();
20147 pop_access_scope (d);
20150 /* Instantiate the indicated variable, function, or alias template TMPL with
20151 the template arguments in TARG_PTR. */
20153 static tree
20154 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
20156 tree targ_ptr = orig_args;
20157 tree fndecl;
20158 tree gen_tmpl;
20159 tree spec;
20160 bool access_ok = true;
20162 if (tmpl == error_mark_node)
20163 return error_mark_node;
20165 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
20167 /* If this function is a clone, handle it specially. */
20168 if (DECL_CLONED_FUNCTION_P (tmpl))
20170 tree spec;
20171 tree clone;
20173 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
20174 DECL_CLONED_FUNCTION. */
20175 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
20176 targ_ptr, complain);
20177 if (spec == error_mark_node)
20178 return error_mark_node;
20180 /* Look for the clone. */
20181 FOR_EACH_CLONE (clone, spec)
20182 if (DECL_NAME (clone) == DECL_NAME (tmpl))
20183 return clone;
20184 /* We should always have found the clone by now. */
20185 gcc_unreachable ();
20186 return NULL_TREE;
20189 if (targ_ptr == error_mark_node)
20190 return error_mark_node;
20192 /* Check to see if we already have this specialization. */
20193 gen_tmpl = most_general_template (tmpl);
20194 if (TMPL_ARGS_DEPTH (targ_ptr)
20195 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
20196 /* targ_ptr only has the innermost template args, so add the outer ones
20197 from tmpl, which could be either a partial instantiation or gen_tmpl (in
20198 the case of a non-dependent call within a template definition). */
20199 targ_ptr = (add_outermost_template_args
20200 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
20201 targ_ptr));
20203 /* It would be nice to avoid hashing here and then again in tsubst_decl,
20204 but it doesn't seem to be on the hot path. */
20205 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
20207 gcc_assert (tmpl == gen_tmpl
20208 || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
20209 == spec)
20210 || fndecl == NULL_TREE);
20212 if (spec != NULL_TREE)
20214 if (FNDECL_HAS_ACCESS_ERRORS (spec))
20216 if (complain & tf_error)
20217 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
20218 return error_mark_node;
20220 return spec;
20223 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
20224 complain))
20225 return error_mark_node;
20227 /* We are building a FUNCTION_DECL, during which the access of its
20228 parameters and return types have to be checked. However this
20229 FUNCTION_DECL which is the desired context for access checking
20230 is not built yet. We solve this chicken-and-egg problem by
20231 deferring all checks until we have the FUNCTION_DECL. */
20232 push_deferring_access_checks (dk_deferred);
20234 /* Instantiation of the function happens in the context of the function
20235 template, not the context of the overload resolution we're doing. */
20236 push_to_top_level ();
20237 /* If there are dependent arguments, e.g. because we're doing partial
20238 ordering, make sure processing_template_decl stays set. */
20239 if (uses_template_parms (targ_ptr))
20240 ++processing_template_decl;
20241 if (DECL_CLASS_SCOPE_P (gen_tmpl))
20243 tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
20244 complain, gen_tmpl, true);
20245 push_nested_class (ctx);
20248 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
20250 fndecl = NULL_TREE;
20251 if (VAR_P (pattern))
20253 /* We need to determine if we're using a partial or explicit
20254 specialization now, because the type of the variable could be
20255 different. */
20256 tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
20257 tree elt = most_specialized_partial_spec (tid, complain);
20258 if (elt == error_mark_node)
20259 pattern = error_mark_node;
20260 else if (elt)
20262 tree partial_tmpl = TREE_VALUE (elt);
20263 tree partial_args = TREE_PURPOSE (elt);
20264 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
20265 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
20269 /* Substitute template parameters to obtain the specialization. */
20270 if (fndecl == NULL_TREE)
20271 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
20272 if (DECL_CLASS_SCOPE_P (gen_tmpl))
20273 pop_nested_class ();
20274 pop_from_top_level ();
20276 if (fndecl == error_mark_node)
20278 pop_deferring_access_checks ();
20279 return error_mark_node;
20282 /* The DECL_TI_TEMPLATE should always be the immediate parent
20283 template, not the most general template. */
20284 DECL_TI_TEMPLATE (fndecl) = tmpl;
20285 DECL_TI_ARGS (fndecl) = targ_ptr;
20287 /* Now we know the specialization, compute access previously
20288 deferred. Do no access control for inheriting constructors,
20289 as we already checked access for the inherited constructor. */
20290 if (!(flag_new_inheriting_ctors
20291 && DECL_INHERITED_CTOR (fndecl)))
20293 push_access_scope (fndecl);
20294 if (!perform_deferred_access_checks (complain))
20295 access_ok = false;
20296 pop_access_scope (fndecl);
20298 pop_deferring_access_checks ();
20300 /* If we've just instantiated the main entry point for a function,
20301 instantiate all the alternate entry points as well. We do this
20302 by cloning the instantiation of the main entry point, not by
20303 instantiating the template clones. */
20304 if (tree chain = DECL_CHAIN (gen_tmpl))
20305 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
20306 clone_function_decl (fndecl, /*update_methods=*/false);
20308 if (!access_ok)
20310 if (!(complain & tf_error))
20312 /* Remember to reinstantiate when we're out of SFINAE so the user
20313 can see the errors. */
20314 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
20316 return error_mark_node;
20318 return fndecl;
20321 /* Wrapper for instantiate_template_1. */
20323 tree
20324 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
20326 tree ret;
20327 timevar_push (TV_TEMPLATE_INST);
20328 ret = instantiate_template_1 (tmpl, orig_args, complain);
20329 timevar_pop (TV_TEMPLATE_INST);
20330 return ret;
20333 /* Instantiate the alias template TMPL with ARGS. Also push a template
20334 instantiation level, which instantiate_template doesn't do because
20335 functions and variables have sufficient context established by the
20336 callers. */
20338 static tree
20339 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
20341 if (tmpl == error_mark_node || args == error_mark_node)
20342 return error_mark_node;
20343 if (!push_tinst_level (tmpl, args))
20344 return error_mark_node;
20346 args =
20347 coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
20348 args, tmpl, complain,
20349 /*require_all_args=*/true,
20350 /*use_default_args=*/true);
20352 tree r = instantiate_template (tmpl, args, complain);
20353 pop_tinst_level ();
20355 return r;
20358 /* PARM is a template parameter pack for FN. Returns true iff
20359 PARM is used in a deducible way in the argument list of FN. */
20361 static bool
20362 pack_deducible_p (tree parm, tree fn)
20364 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
20365 for (; t; t = TREE_CHAIN (t))
20367 tree type = TREE_VALUE (t);
20368 tree packs;
20369 if (!PACK_EXPANSION_P (type))
20370 continue;
20371 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
20372 packs; packs = TREE_CHAIN (packs))
20373 if (template_args_equal (TREE_VALUE (packs), parm))
20375 /* The template parameter pack is used in a function parameter
20376 pack. If this is the end of the parameter list, the
20377 template parameter pack is deducible. */
20378 if (TREE_CHAIN (t) == void_list_node)
20379 return true;
20380 else
20381 /* Otherwise, not. Well, it could be deduced from
20382 a non-pack parameter, but doing so would end up with
20383 a deduction mismatch, so don't bother. */
20384 return false;
20387 /* The template parameter pack isn't used in any function parameter
20388 packs, but it might be used deeper, e.g. tuple<Args...>. */
20389 return true;
20392 /* Subroutine of fn_type_unification: check non-dependent parms for
20393 convertibility. */
20395 static int
20396 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
20397 tree fn, unification_kind_t strict, int flags,
20398 struct conversion **convs, bool explain_p)
20400 /* Non-constructor methods need to leave a conversion for 'this', which
20401 isn't included in nargs here. */
20402 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
20403 && !DECL_CONSTRUCTOR_P (fn));
20405 for (unsigned ia = 0;
20406 parms && parms != void_list_node && ia < nargs; )
20408 tree parm = TREE_VALUE (parms);
20410 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20411 && (!TREE_CHAIN (parms)
20412 || TREE_CHAIN (parms) == void_list_node))
20413 /* For a function parameter pack that occurs at the end of the
20414 parameter-declaration-list, the type A of each remaining
20415 argument of the call is compared with the type P of the
20416 declarator-id of the function parameter pack. */
20417 break;
20419 parms = TREE_CHAIN (parms);
20421 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20422 /* For a function parameter pack that does not occur at the
20423 end of the parameter-declaration-list, the type of the
20424 parameter pack is a non-deduced context. */
20425 continue;
20427 if (!uses_template_parms (parm))
20429 tree arg = args[ia];
20430 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
20431 int lflags = conv_flags (ia, nargs, fn, arg, flags);
20433 if (check_non_deducible_conversion (parm, arg, strict, lflags,
20434 conv_p, explain_p))
20435 return 1;
20438 ++ia;
20441 return 0;
20444 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
20445 NARGS elements of the arguments that are being used when calling
20446 it. TARGS is a vector into which the deduced template arguments
20447 are placed.
20449 Returns either a FUNCTION_DECL for the matching specialization of FN or
20450 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
20451 true, diagnostics will be printed to explain why it failed.
20453 If FN is a conversion operator, or we are trying to produce a specific
20454 specialization, RETURN_TYPE is the return type desired.
20456 The EXPLICIT_TARGS are explicit template arguments provided via a
20457 template-id.
20459 The parameter STRICT is one of:
20461 DEDUCE_CALL:
20462 We are deducing arguments for a function call, as in
20463 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
20464 deducing arguments for a call to the result of a conversion
20465 function template, as in [over.call.object].
20467 DEDUCE_CONV:
20468 We are deducing arguments for a conversion function, as in
20469 [temp.deduct.conv].
20471 DEDUCE_EXACT:
20472 We are deducing arguments when doing an explicit instantiation
20473 as in [temp.explicit], when determining an explicit specialization
20474 as in [temp.expl.spec], or when taking the address of a function
20475 template, as in [temp.deduct.funcaddr]. */
20477 tree
20478 fn_type_unification (tree fn,
20479 tree explicit_targs,
20480 tree targs,
20481 const tree *args,
20482 unsigned int nargs,
20483 tree return_type,
20484 unification_kind_t strict,
20485 int flags,
20486 struct conversion **convs,
20487 bool explain_p,
20488 bool decltype_p)
20490 tree parms;
20491 tree fntype;
20492 tree decl = NULL_TREE;
20493 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
20494 bool ok;
20495 static int deduction_depth;
20496 /* type_unification_real will pass back any access checks from default
20497 template argument substitution. */
20498 vec<deferred_access_check, va_gc> *checks = NULL;
20499 /* We don't have all the template args yet. */
20500 bool incomplete = true;
20502 tree orig_fn = fn;
20503 if (flag_new_inheriting_ctors)
20504 fn = strip_inheriting_ctors (fn);
20506 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
20507 tree r = error_mark_node;
20509 tree full_targs = targs;
20510 if (TMPL_ARGS_DEPTH (targs)
20511 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
20512 full_targs = (add_outermost_template_args
20513 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
20514 targs));
20516 if (decltype_p)
20517 complain |= tf_decltype;
20519 /* In C++0x, it's possible to have a function template whose type depends
20520 on itself recursively. This is most obvious with decltype, but can also
20521 occur with enumeration scope (c++/48969). So we need to catch infinite
20522 recursion and reject the substitution at deduction time; this function
20523 will return error_mark_node for any repeated substitution.
20525 This also catches excessive recursion such as when f<N> depends on
20526 f<N-1> across all integers, and returns error_mark_node for all the
20527 substitutions back up to the initial one.
20529 This is, of course, not reentrant. */
20530 if (excessive_deduction_depth)
20531 return error_mark_node;
20532 ++deduction_depth;
20534 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
20536 fntype = TREE_TYPE (fn);
20537 if (explicit_targs)
20539 /* [temp.deduct]
20541 The specified template arguments must match the template
20542 parameters in kind (i.e., type, nontype, template), and there
20543 must not be more arguments than there are parameters;
20544 otherwise type deduction fails.
20546 Nontype arguments must match the types of the corresponding
20547 nontype template parameters, or must be convertible to the
20548 types of the corresponding nontype parameters as specified in
20549 _temp.arg.nontype_, otherwise type deduction fails.
20551 All references in the function type of the function template
20552 to the corresponding template parameters are replaced by the
20553 specified template argument values. If a substitution in a
20554 template parameter or in the function type of the function
20555 template results in an invalid type, type deduction fails. */
20556 int i, len = TREE_VEC_LENGTH (tparms);
20557 location_t loc = input_location;
20558 incomplete = false;
20560 if (explicit_targs == error_mark_node)
20561 goto fail;
20563 if (TMPL_ARGS_DEPTH (explicit_targs)
20564 < TMPL_ARGS_DEPTH (full_targs))
20565 explicit_targs = add_outermost_template_args (full_targs,
20566 explicit_targs);
20568 /* Adjust any explicit template arguments before entering the
20569 substitution context. */
20570 explicit_targs
20571 = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
20572 complain|tf_partial,
20573 /*require_all_args=*/false,
20574 /*use_default_args=*/false));
20575 if (explicit_targs == error_mark_node)
20576 goto fail;
20578 /* Substitute the explicit args into the function type. This is
20579 necessary so that, for instance, explicitly declared function
20580 arguments can match null pointed constants. If we were given
20581 an incomplete set of explicit args, we must not do semantic
20582 processing during substitution as we could create partial
20583 instantiations. */
20584 for (i = 0; i < len; i++)
20586 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
20587 bool parameter_pack = false;
20588 tree targ = TREE_VEC_ELT (explicit_targs, i);
20590 /* Dig out the actual parm. */
20591 if (TREE_CODE (parm) == TYPE_DECL
20592 || TREE_CODE (parm) == TEMPLATE_DECL)
20594 parm = TREE_TYPE (parm);
20595 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
20597 else if (TREE_CODE (parm) == PARM_DECL)
20599 parm = DECL_INITIAL (parm);
20600 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
20603 if (targ == NULL_TREE)
20604 /* No explicit argument for this template parameter. */
20605 incomplete = true;
20606 else if (parameter_pack && pack_deducible_p (parm, fn))
20608 /* Mark the argument pack as "incomplete". We could
20609 still deduce more arguments during unification.
20610 We remove this mark in type_unification_real. */
20611 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
20612 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
20613 = ARGUMENT_PACK_ARGS (targ);
20615 /* We have some incomplete argument packs. */
20616 incomplete = true;
20620 if (incomplete)
20622 if (!push_tinst_level (fn, explicit_targs))
20624 excessive_deduction_depth = true;
20625 goto fail;
20627 ++processing_template_decl;
20628 input_location = DECL_SOURCE_LOCATION (fn);
20629 /* Ignore any access checks; we'll see them again in
20630 instantiate_template and they might have the wrong
20631 access path at this point. */
20632 push_deferring_access_checks (dk_deferred);
20633 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
20634 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
20635 pop_deferring_access_checks ();
20636 input_location = loc;
20637 --processing_template_decl;
20638 pop_tinst_level ();
20640 if (fntype == error_mark_node)
20641 goto fail;
20644 /* Place the explicitly specified arguments in TARGS. */
20645 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
20646 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
20647 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
20648 if (!incomplete && CHECKING_P
20649 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20650 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
20651 (targs, NUM_TMPL_ARGS (explicit_targs));
20654 if (return_type && strict != DEDUCE_CALL)
20656 tree *new_args = XALLOCAVEC (tree, nargs + 1);
20657 new_args[0] = return_type;
20658 memcpy (new_args + 1, args, nargs * sizeof (tree));
20659 args = new_args;
20660 ++nargs;
20663 if (!incomplete)
20664 goto deduced;
20666 /* Never do unification on the 'this' parameter. */
20667 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
20669 if (return_type && strict == DEDUCE_CALL)
20671 /* We're deducing for a call to the result of a template conversion
20672 function. The parms we really want are in return_type. */
20673 if (INDIRECT_TYPE_P (return_type))
20674 return_type = TREE_TYPE (return_type);
20675 parms = TYPE_ARG_TYPES (return_type);
20677 else if (return_type)
20679 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
20682 /* We allow incomplete unification without an error message here
20683 because the standard doesn't seem to explicitly prohibit it. Our
20684 callers must be ready to deal with unification failures in any
20685 event. */
20687 /* If we aren't explaining yet, push tinst context so we can see where
20688 any errors (e.g. from class instantiations triggered by instantiation
20689 of default template arguments) come from. If we are explaining, this
20690 context is redundant. */
20691 if (!explain_p && !push_tinst_level (fn, targs))
20693 excessive_deduction_depth = true;
20694 goto fail;
20697 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20698 full_targs, parms, args, nargs, /*subr=*/0,
20699 strict, &checks, explain_p);
20700 if (!explain_p)
20701 pop_tinst_level ();
20702 if (!ok)
20703 goto fail;
20705 /* Now that we have bindings for all of the template arguments,
20706 ensure that the arguments deduced for the template template
20707 parameters have compatible template parameter lists. We cannot
20708 check this property before we have deduced all template
20709 arguments, because the template parameter types of a template
20710 template parameter might depend on prior template parameters
20711 deduced after the template template parameter. The following
20712 ill-formed example illustrates this issue:
20714 template<typename T, template<T> class C> void f(C<5>, T);
20716 template<int N> struct X {};
20718 void g() {
20719 f(X<5>(), 5l); // error: template argument deduction fails
20722 The template parameter list of 'C' depends on the template type
20723 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
20724 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
20725 time that we deduce 'C'. */
20726 if (!template_template_parm_bindings_ok_p
20727 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
20729 unify_inconsistent_template_template_parameters (explain_p);
20730 goto fail;
20733 /* DR 1391: All parameters have args, now check non-dependent parms for
20734 convertibility. */
20735 if (check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
20736 convs, explain_p))
20737 goto fail;
20739 deduced:
20740 /* All is well so far. Now, check:
20742 [temp.deduct]
20744 When all template arguments have been deduced, all uses of
20745 template parameters in nondeduced contexts are replaced with
20746 the corresponding deduced argument values. If the
20747 substitution results in an invalid type, as described above,
20748 type deduction fails. */
20749 if (!push_tinst_level (fn, targs))
20751 excessive_deduction_depth = true;
20752 goto fail;
20755 /* Also collect access checks from the instantiation. */
20756 reopen_deferring_access_checks (checks);
20758 decl = instantiate_template (fn, targs, complain);
20760 checks = get_deferred_access_checks ();
20761 pop_deferring_access_checks ();
20763 pop_tinst_level ();
20765 if (decl == error_mark_node)
20766 goto fail;
20768 /* Now perform any access checks encountered during substitution. */
20769 push_access_scope (decl);
20770 ok = perform_access_checks (checks, complain);
20771 pop_access_scope (decl);
20772 if (!ok)
20773 goto fail;
20775 /* If we're looking for an exact match, check that what we got
20776 is indeed an exact match. It might not be if some template
20777 parameters are used in non-deduced contexts. But don't check
20778 for an exact match if we have dependent template arguments;
20779 in that case we're doing partial ordering, and we already know
20780 that we have two candidates that will provide the actual type. */
20781 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
20783 tree substed = TREE_TYPE (decl);
20784 unsigned int i;
20786 tree sarg
20787 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
20788 if (return_type)
20789 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
20790 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
20791 if (!same_type_p (args[i], TREE_VALUE (sarg)))
20793 unify_type_mismatch (explain_p, args[i],
20794 TREE_VALUE (sarg));
20795 goto fail;
20799 /* After doing deduction with the inherited constructor, actually return an
20800 instantiation of the inheriting constructor. */
20801 if (orig_fn != fn)
20802 decl = instantiate_template (orig_fn, targs, complain);
20804 r = decl;
20806 fail:
20807 --deduction_depth;
20808 if (excessive_deduction_depth)
20810 if (deduction_depth == 0)
20811 /* Reset once we're all the way out. */
20812 excessive_deduction_depth = false;
20815 return r;
20818 /* Adjust types before performing type deduction, as described in
20819 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
20820 sections are symmetric. PARM is the type of a function parameter
20821 or the return type of the conversion function. ARG is the type of
20822 the argument passed to the call, or the type of the value
20823 initialized with the result of the conversion function.
20824 ARG_EXPR is the original argument expression, which may be null. */
20826 static int
20827 maybe_adjust_types_for_deduction (unification_kind_t strict,
20828 tree* parm,
20829 tree* arg,
20830 tree arg_expr)
20832 int result = 0;
20834 switch (strict)
20836 case DEDUCE_CALL:
20837 break;
20839 case DEDUCE_CONV:
20840 /* Swap PARM and ARG throughout the remainder of this
20841 function; the handling is precisely symmetric since PARM
20842 will initialize ARG rather than vice versa. */
20843 std::swap (parm, arg);
20844 break;
20846 case DEDUCE_EXACT:
20847 /* Core issue #873: Do the DR606 thing (see below) for these cases,
20848 too, but here handle it by stripping the reference from PARM
20849 rather than by adding it to ARG. */
20850 if (TYPE_REF_P (*parm)
20851 && TYPE_REF_IS_RVALUE (*parm)
20852 && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
20853 && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
20854 && TYPE_REF_P (*arg)
20855 && !TYPE_REF_IS_RVALUE (*arg))
20856 *parm = TREE_TYPE (*parm);
20857 /* Nothing else to do in this case. */
20858 return 0;
20860 default:
20861 gcc_unreachable ();
20864 if (!TYPE_REF_P (*parm))
20866 /* [temp.deduct.call]
20868 If P is not a reference type:
20870 --If A is an array type, the pointer type produced by the
20871 array-to-pointer standard conversion (_conv.array_) is
20872 used in place of A for type deduction; otherwise,
20874 --If A is a function type, the pointer type produced by
20875 the function-to-pointer standard conversion
20876 (_conv.func_) is used in place of A for type deduction;
20877 otherwise,
20879 --If A is a cv-qualified type, the top level
20880 cv-qualifiers of A's type are ignored for type
20881 deduction. */
20882 if (TREE_CODE (*arg) == ARRAY_TYPE)
20883 *arg = build_pointer_type (TREE_TYPE (*arg));
20884 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
20885 *arg = build_pointer_type (*arg);
20886 else
20887 *arg = TYPE_MAIN_VARIANT (*arg);
20890 /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
20891 reference to a cv-unqualified template parameter that does not represent a
20892 template parameter of a class template (during class template argument
20893 deduction (13.3.1.8)). If P is a forwarding reference and the argument is
20894 an lvalue, the type "lvalue reference to A" is used in place of A for type
20895 deduction. */
20896 if (TYPE_REF_P (*parm)
20897 && TYPE_REF_IS_RVALUE (*parm)
20898 && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
20899 && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
20900 && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
20901 && (arg_expr ? lvalue_p (arg_expr)
20902 /* try_one_overload doesn't provide an arg_expr, but
20903 functions are always lvalues. */
20904 : TREE_CODE (*arg) == FUNCTION_TYPE))
20905 *arg = build_reference_type (*arg);
20907 /* [temp.deduct.call]
20909 If P is a cv-qualified type, the top level cv-qualifiers
20910 of P's type are ignored for type deduction. If P is a
20911 reference type, the type referred to by P is used for
20912 type deduction. */
20913 *parm = TYPE_MAIN_VARIANT (*parm);
20914 if (TYPE_REF_P (*parm))
20916 *parm = TREE_TYPE (*parm);
20917 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
20920 /* DR 322. For conversion deduction, remove a reference type on parm
20921 too (which has been swapped into ARG). */
20922 if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
20923 *arg = TREE_TYPE (*arg);
20925 return result;
20928 /* Subroutine of fn_type_unification. PARM is a function parameter of a
20929 template which doesn't contain any deducible template parameters; check if
20930 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
20931 unify_one_argument. */
20933 static int
20934 check_non_deducible_conversion (tree parm, tree arg, int strict,
20935 int flags, struct conversion **conv_p,
20936 bool explain_p)
20938 tree type;
20940 if (!TYPE_P (arg))
20941 type = TREE_TYPE (arg);
20942 else
20943 type = arg;
20945 if (same_type_p (parm, type))
20946 return unify_success (explain_p);
20948 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
20949 if (strict == DEDUCE_CONV)
20951 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
20952 return unify_success (explain_p);
20954 else if (strict != DEDUCE_EXACT)
20956 bool ok = false;
20957 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
20958 if (conv_p)
20959 /* Avoid recalculating this in add_function_candidate. */
20960 ok = (*conv_p
20961 = good_conversion (parm, type, conv_arg, flags, complain));
20962 else
20963 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
20964 if (ok)
20965 return unify_success (explain_p);
20968 if (strict == DEDUCE_EXACT)
20969 return unify_type_mismatch (explain_p, parm, arg);
20970 else
20971 return unify_arg_conversion (explain_p, parm, type, arg);
20974 static bool uses_deducible_template_parms (tree type);
20976 /* Returns true iff the expression EXPR is one from which a template
20977 argument can be deduced. In other words, if it's an undecorated
20978 use of a template non-type parameter. */
20980 static bool
20981 deducible_expression (tree expr)
20983 /* Strip implicit conversions. */
20984 while (CONVERT_EXPR_P (expr))
20985 expr = TREE_OPERAND (expr, 0);
20986 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
20989 /* Returns true iff the array domain DOMAIN uses a template parameter in a
20990 deducible way; that is, if it has a max value of <PARM> - 1. */
20992 static bool
20993 deducible_array_bound (tree domain)
20995 if (domain == NULL_TREE)
20996 return false;
20998 tree max = TYPE_MAX_VALUE (domain);
20999 if (TREE_CODE (max) != MINUS_EXPR)
21000 return false;
21002 return deducible_expression (TREE_OPERAND (max, 0));
21005 /* Returns true iff the template arguments ARGS use a template parameter
21006 in a deducible way. */
21008 static bool
21009 deducible_template_args (tree args)
21011 for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
21013 bool deducible;
21014 tree elt = TREE_VEC_ELT (args, i);
21015 if (ARGUMENT_PACK_P (elt))
21016 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
21017 else
21019 if (PACK_EXPANSION_P (elt))
21020 elt = PACK_EXPANSION_PATTERN (elt);
21021 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
21022 deducible = true;
21023 else if (TYPE_P (elt))
21024 deducible = uses_deducible_template_parms (elt);
21025 else
21026 deducible = deducible_expression (elt);
21028 if (deducible)
21029 return true;
21031 return false;
21034 /* Returns true iff TYPE contains any deducible references to template
21035 parameters, as per 14.8.2.5. */
21037 static bool
21038 uses_deducible_template_parms (tree type)
21040 if (PACK_EXPANSION_P (type))
21041 type = PACK_EXPANSION_PATTERN (type);
21043 /* T
21044 cv-list T
21045 TT<T>
21046 TT<i>
21047 TT<> */
21048 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
21049 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
21050 return true;
21052 /* T*
21054 T&& */
21055 if (INDIRECT_TYPE_P (type))
21056 return uses_deducible_template_parms (TREE_TYPE (type));
21058 /* T[integer-constant ]
21059 type [i] */
21060 if (TREE_CODE (type) == ARRAY_TYPE)
21061 return (uses_deducible_template_parms (TREE_TYPE (type))
21062 || deducible_array_bound (TYPE_DOMAIN (type)));
21064 /* T type ::*
21065 type T::*
21066 T T::*
21067 T (type ::*)()
21068 type (T::*)()
21069 type (type ::*)(T)
21070 type (T::*)(T)
21071 T (type ::*)(T)
21072 T (T::*)()
21073 T (T::*)(T) */
21074 if (TYPE_PTRMEM_P (type))
21075 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
21076 || (uses_deducible_template_parms
21077 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
21079 /* template-name <T> (where template-name refers to a class template)
21080 template-name <i> (where template-name refers to a class template) */
21081 if (CLASS_TYPE_P (type)
21082 && CLASSTYPE_TEMPLATE_INFO (type)
21083 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
21084 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
21085 (CLASSTYPE_TI_ARGS (type)));
21087 /* type (T)
21089 T(T) */
21090 if (FUNC_OR_METHOD_TYPE_P (type))
21092 if (uses_deducible_template_parms (TREE_TYPE (type)))
21093 return true;
21094 tree parm = TYPE_ARG_TYPES (type);
21095 if (TREE_CODE (type) == METHOD_TYPE)
21096 parm = TREE_CHAIN (parm);
21097 for (; parm; parm = TREE_CHAIN (parm))
21098 if (uses_deducible_template_parms (TREE_VALUE (parm)))
21099 return true;
21102 return false;
21105 /* Subroutine of type_unification_real and unify_pack_expansion to
21106 handle unification of a single P/A pair. Parameters are as
21107 for those functions. */
21109 static int
21110 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
21111 int subr, unification_kind_t strict,
21112 bool explain_p)
21114 tree arg_expr = NULL_TREE;
21115 int arg_strict;
21117 if (arg == error_mark_node || parm == error_mark_node)
21118 return unify_invalid (explain_p);
21119 if (arg == unknown_type_node)
21120 /* We can't deduce anything from this, but we might get all the
21121 template args from other function args. */
21122 return unify_success (explain_p);
21124 /* Implicit conversions (Clause 4) will be performed on a function
21125 argument to convert it to the type of the corresponding function
21126 parameter if the parameter type contains no template-parameters that
21127 participate in template argument deduction. */
21128 if (strict != DEDUCE_EXACT
21129 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
21130 /* For function parameters with no deducible template parameters,
21131 just return. We'll check non-dependent conversions later. */
21132 return unify_success (explain_p);
21134 switch (strict)
21136 case DEDUCE_CALL:
21137 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
21138 | UNIFY_ALLOW_MORE_CV_QUAL
21139 | UNIFY_ALLOW_DERIVED);
21140 break;
21142 case DEDUCE_CONV:
21143 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
21144 break;
21146 case DEDUCE_EXACT:
21147 arg_strict = UNIFY_ALLOW_NONE;
21148 break;
21150 default:
21151 gcc_unreachable ();
21154 /* We only do these transformations if this is the top-level
21155 parameter_type_list in a call or declaration matching; in other
21156 situations (nested function declarators, template argument lists) we
21157 won't be comparing a type to an expression, and we don't do any type
21158 adjustments. */
21159 if (!subr)
21161 if (!TYPE_P (arg))
21163 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
21164 if (type_unknown_p (arg))
21166 /* [temp.deduct.type] A template-argument can be
21167 deduced from a pointer to function or pointer
21168 to member function argument if the set of
21169 overloaded functions does not contain function
21170 templates and at most one of a set of
21171 overloaded functions provides a unique
21172 match. */
21173 resolve_overloaded_unification (tparms, targs, parm,
21174 arg, strict,
21175 arg_strict, explain_p);
21176 /* If a unique match was not found, this is a
21177 non-deduced context, so we still succeed. */
21178 return unify_success (explain_p);
21181 arg_expr = arg;
21182 arg = unlowered_expr_type (arg);
21183 if (arg == error_mark_node)
21184 return unify_invalid (explain_p);
21187 arg_strict |=
21188 maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
21190 else
21191 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
21192 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
21193 return unify_template_argument_mismatch (explain_p, parm, arg);
21195 /* For deduction from an init-list we need the actual list. */
21196 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
21197 arg = arg_expr;
21198 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
21201 /* for_each_template_parm callback that always returns 0. */
21203 static int
21204 zero_r (tree, void *)
21206 return 0;
21209 /* for_each_template_parm any_fn callback to handle deduction of a template
21210 type argument from the type of an array bound. */
21212 static int
21213 array_deduction_r (tree t, void *data)
21215 tree_pair_p d = (tree_pair_p)data;
21216 tree &tparms = d->purpose;
21217 tree &targs = d->value;
21219 if (TREE_CODE (t) == ARRAY_TYPE)
21220 if (tree dom = TYPE_DOMAIN (t))
21221 if (tree max = TYPE_MAX_VALUE (dom))
21223 if (TREE_CODE (max) == MINUS_EXPR)
21224 max = TREE_OPERAND (max, 0);
21225 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
21226 unify (tparms, targs, TREE_TYPE (max), size_type_node,
21227 UNIFY_ALLOW_NONE, /*explain*/false);
21230 /* Keep walking. */
21231 return 0;
21234 /* Try to deduce any not-yet-deduced template type arguments from the type of
21235 an array bound. This is handled separately from unify because 14.8.2.5 says
21236 "The type of a type parameter is only deduced from an array bound if it is
21237 not otherwise deduced." */
21239 static void
21240 try_array_deduction (tree tparms, tree targs, tree parm)
21242 tree_pair_s data = { tparms, targs };
21243 hash_set<tree> visited;
21244 for_each_template_parm (parm, zero_r, &data, &visited,
21245 /*nondeduced*/false, array_deduction_r);
21248 /* Most parms like fn_type_unification.
21250 If SUBR is 1, we're being called recursively (to unify the
21251 arguments of a function or method parameter of a function
21252 template).
21254 CHECKS is a pointer to a vector of access checks encountered while
21255 substituting default template arguments. */
21257 static int
21258 type_unification_real (tree tparms,
21259 tree full_targs,
21260 tree xparms,
21261 const tree *xargs,
21262 unsigned int xnargs,
21263 int subr,
21264 unification_kind_t strict,
21265 vec<deferred_access_check, va_gc> **checks,
21266 bool explain_p)
21268 tree parm, arg;
21269 int i;
21270 int ntparms = TREE_VEC_LENGTH (tparms);
21271 int saw_undeduced = 0;
21272 tree parms;
21273 const tree *args;
21274 unsigned int nargs;
21275 unsigned int ia;
21277 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
21278 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
21279 gcc_assert (ntparms > 0);
21281 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
21283 /* Reset the number of non-defaulted template arguments contained
21284 in TARGS. */
21285 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
21287 again:
21288 parms = xparms;
21289 args = xargs;
21290 nargs = xnargs;
21292 ia = 0;
21293 while (parms && parms != void_list_node
21294 && ia < nargs)
21296 parm = TREE_VALUE (parms);
21298 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21299 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
21300 /* For a function parameter pack that occurs at the end of the
21301 parameter-declaration-list, the type A of each remaining
21302 argument of the call is compared with the type P of the
21303 declarator-id of the function parameter pack. */
21304 break;
21306 parms = TREE_CHAIN (parms);
21308 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21309 /* For a function parameter pack that does not occur at the
21310 end of the parameter-declaration-list, the type of the
21311 parameter pack is a non-deduced context. */
21312 continue;
21314 arg = args[ia];
21315 ++ia;
21317 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
21318 explain_p))
21319 return 1;
21322 if (parms
21323 && parms != void_list_node
21324 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
21326 /* Unify the remaining arguments with the pack expansion type. */
21327 tree argvec;
21328 tree parmvec = make_tree_vec (1);
21330 /* Allocate a TREE_VEC and copy in all of the arguments */
21331 argvec = make_tree_vec (nargs - ia);
21332 for (i = 0; ia < nargs; ++ia, ++i)
21333 TREE_VEC_ELT (argvec, i) = args[ia];
21335 /* Copy the parameter into parmvec. */
21336 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
21337 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
21338 /*subr=*/subr, explain_p))
21339 return 1;
21341 /* Advance to the end of the list of parameters. */
21342 parms = TREE_CHAIN (parms);
21345 /* Fail if we've reached the end of the parm list, and more args
21346 are present, and the parm list isn't variadic. */
21347 if (ia < nargs && parms == void_list_node)
21348 return unify_too_many_arguments (explain_p, nargs, ia);
21349 /* Fail if parms are left and they don't have default values and
21350 they aren't all deduced as empty packs (c++/57397). This is
21351 consistent with sufficient_parms_p. */
21352 if (parms && parms != void_list_node
21353 && TREE_PURPOSE (parms) == NULL_TREE)
21355 unsigned int count = nargs;
21356 tree p = parms;
21357 bool type_pack_p;
21360 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
21361 if (!type_pack_p)
21362 count++;
21363 p = TREE_CHAIN (p);
21365 while (p && p != void_list_node);
21366 if (count != nargs)
21367 return unify_too_few_arguments (explain_p, ia, count,
21368 type_pack_p);
21371 if (!subr)
21373 tsubst_flags_t complain = (explain_p
21374 ? tf_warning_or_error
21375 : tf_none);
21376 bool tried_array_deduction = (cxx_dialect < cxx17);
21378 for (i = 0; i < ntparms; i++)
21380 tree targ = TREE_VEC_ELT (targs, i);
21381 tree tparm = TREE_VEC_ELT (tparms, i);
21383 /* Clear the "incomplete" flags on all argument packs now so that
21384 substituting them into later default arguments works. */
21385 if (targ && ARGUMENT_PACK_P (targ))
21387 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
21388 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
21391 if (targ || tparm == error_mark_node)
21392 continue;
21393 tparm = TREE_VALUE (tparm);
21395 if (TREE_CODE (tparm) == TYPE_DECL
21396 && !tried_array_deduction)
21398 try_array_deduction (tparms, targs, xparms);
21399 tried_array_deduction = true;
21400 if (TREE_VEC_ELT (targs, i))
21401 continue;
21404 /* If this is an undeduced nontype parameter that depends on
21405 a type parameter, try another pass; its type may have been
21406 deduced from a later argument than the one from which
21407 this parameter can be deduced. */
21408 if (TREE_CODE (tparm) == PARM_DECL
21409 && uses_template_parms (TREE_TYPE (tparm))
21410 && saw_undeduced < 2)
21412 saw_undeduced = 1;
21413 continue;
21416 /* Core issue #226 (C++0x) [temp.deduct]:
21418 If a template argument has not been deduced, its
21419 default template argument, if any, is used.
21421 When we are in C++98 mode, TREE_PURPOSE will either
21422 be NULL_TREE or ERROR_MARK_NODE, so we do not need
21423 to explicitly check cxx_dialect here. */
21424 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
21425 /* OK, there is a default argument. Wait until after the
21426 conversion check to do substitution. */
21427 continue;
21429 /* If the type parameter is a parameter pack, then it will
21430 be deduced to an empty parameter pack. */
21431 if (template_parameter_pack_p (tparm))
21433 tree arg;
21435 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
21437 arg = make_node (NONTYPE_ARGUMENT_PACK);
21438 TREE_CONSTANT (arg) = 1;
21440 else
21441 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
21443 SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
21445 TREE_VEC_ELT (targs, i) = arg;
21446 continue;
21449 return unify_parameter_deduction_failure (explain_p, tparm);
21452 /* Now substitute into the default template arguments. */
21453 for (i = 0; i < ntparms; i++)
21455 tree targ = TREE_VEC_ELT (targs, i);
21456 tree tparm = TREE_VEC_ELT (tparms, i);
21458 if (targ || tparm == error_mark_node)
21459 continue;
21460 tree parm = TREE_VALUE (tparm);
21461 tree arg = TREE_PURPOSE (tparm);
21462 reopen_deferring_access_checks (*checks);
21463 location_t save_loc = input_location;
21464 if (DECL_P (parm))
21465 input_location = DECL_SOURCE_LOCATION (parm);
21467 if (saw_undeduced == 1
21468 && TREE_CODE (parm) == PARM_DECL
21469 && uses_template_parms (TREE_TYPE (parm)))
21471 /* The type of this non-type parameter depends on undeduced
21472 parameters. Don't try to use its default argument yet,
21473 since we might deduce an argument for it on the next pass,
21474 but do check whether the arguments we already have cause
21475 substitution failure, so that that happens before we try
21476 later default arguments (78489). */
21477 ++processing_template_decl;
21478 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
21479 NULL_TREE);
21480 --processing_template_decl;
21481 if (type == error_mark_node)
21482 arg = error_mark_node;
21483 else
21484 arg = NULL_TREE;
21486 else
21488 /* Even if the call is happening in template context, getting
21489 here means it's non-dependent, and a default argument is
21490 considered a separate definition under [temp.decls], so we can
21491 do this substitution without processing_template_decl. This
21492 is important if the default argument contains something that
21493 might be instantiation-dependent like access (87480). */
21494 processing_template_decl_sentinel s;
21495 tree substed = NULL_TREE;
21496 if (saw_undeduced == 1)
21498 /* First instatiate in template context, in case we still
21499 depend on undeduced template parameters. */
21500 ++processing_template_decl;
21501 substed = tsubst_template_arg (arg, full_targs, complain,
21502 NULL_TREE);
21503 --processing_template_decl;
21504 if (substed != error_mark_node
21505 && !uses_template_parms (substed))
21506 /* We replaced all the tparms, substitute again out of
21507 template context. */
21508 substed = NULL_TREE;
21510 if (!substed)
21511 substed = tsubst_template_arg (arg, full_targs, complain,
21512 NULL_TREE);
21514 if (!uses_template_parms (substed))
21515 arg = convert_template_argument (parm, substed, full_targs,
21516 complain, i, NULL_TREE);
21517 else if (saw_undeduced == 1)
21518 arg = NULL_TREE;
21519 else
21520 arg = error_mark_node;
21523 input_location = save_loc;
21524 *checks = get_deferred_access_checks ();
21525 pop_deferring_access_checks ();
21527 if (arg == error_mark_node)
21528 return 1;
21529 else if (arg)
21531 TREE_VEC_ELT (targs, i) = arg;
21532 /* The position of the first default template argument,
21533 is also the number of non-defaulted arguments in TARGS.
21534 Record that. */
21535 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21536 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
21540 if (saw_undeduced++ == 1)
21541 goto again;
21544 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21545 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
21547 return unify_success (explain_p);
21550 /* Subroutine of type_unification_real. Args are like the variables
21551 at the call site. ARG is an overloaded function (or template-id);
21552 we try deducing template args from each of the overloads, and if
21553 only one succeeds, we go with that. Modifies TARGS and returns
21554 true on success. */
21556 static bool
21557 resolve_overloaded_unification (tree tparms,
21558 tree targs,
21559 tree parm,
21560 tree arg,
21561 unification_kind_t strict,
21562 int sub_strict,
21563 bool explain_p)
21565 tree tempargs = copy_node (targs);
21566 int good = 0;
21567 tree goodfn = NULL_TREE;
21568 bool addr_p;
21570 if (TREE_CODE (arg) == ADDR_EXPR)
21572 arg = TREE_OPERAND (arg, 0);
21573 addr_p = true;
21575 else
21576 addr_p = false;
21578 if (TREE_CODE (arg) == COMPONENT_REF)
21579 /* Handle `&x' where `x' is some static or non-static member
21580 function name. */
21581 arg = TREE_OPERAND (arg, 1);
21583 if (TREE_CODE (arg) == OFFSET_REF)
21584 arg = TREE_OPERAND (arg, 1);
21586 /* Strip baselink information. */
21587 if (BASELINK_P (arg))
21588 arg = BASELINK_FUNCTIONS (arg);
21590 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
21592 /* If we got some explicit template args, we need to plug them into
21593 the affected templates before we try to unify, in case the
21594 explicit args will completely resolve the templates in question. */
21596 int ok = 0;
21597 tree expl_subargs = TREE_OPERAND (arg, 1);
21598 arg = TREE_OPERAND (arg, 0);
21600 for (lkp_iterator iter (arg); iter; ++iter)
21602 tree fn = *iter;
21603 tree subargs, elem;
21605 if (TREE_CODE (fn) != TEMPLATE_DECL)
21606 continue;
21608 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21609 expl_subargs, NULL_TREE, tf_none,
21610 /*require_all_args=*/true,
21611 /*use_default_args=*/true);
21612 if (subargs != error_mark_node
21613 && !any_dependent_template_arguments_p (subargs))
21615 elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
21616 if (try_one_overload (tparms, targs, tempargs, parm,
21617 elem, strict, sub_strict, addr_p, explain_p)
21618 && (!goodfn || !same_type_p (goodfn, elem)))
21620 goodfn = elem;
21621 ++good;
21624 else if (subargs)
21625 ++ok;
21627 /* If no templates (or more than one) are fully resolved by the
21628 explicit arguments, this template-id is a non-deduced context; it
21629 could still be OK if we deduce all template arguments for the
21630 enclosing call through other arguments. */
21631 if (good != 1)
21632 good = ok;
21634 else if (!OVL_P (arg))
21635 /* If ARG is, for example, "(0, &f)" then its type will be unknown
21636 -- but the deduction does not succeed because the expression is
21637 not just the function on its own. */
21638 return false;
21639 else
21640 for (lkp_iterator iter (arg); iter; ++iter)
21642 tree fn = *iter;
21643 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
21644 strict, sub_strict, addr_p, explain_p)
21645 && (!goodfn || !decls_match (goodfn, fn)))
21647 goodfn = fn;
21648 ++good;
21652 /* [temp.deduct.type] A template-argument can be deduced from a pointer
21653 to function or pointer to member function argument if the set of
21654 overloaded functions does not contain function templates and at most
21655 one of a set of overloaded functions provides a unique match.
21657 So if we found multiple possibilities, we return success but don't
21658 deduce anything. */
21660 if (good == 1)
21662 int i = TREE_VEC_LENGTH (targs);
21663 for (; i--; )
21664 if (TREE_VEC_ELT (tempargs, i))
21666 tree old = TREE_VEC_ELT (targs, i);
21667 tree new_ = TREE_VEC_ELT (tempargs, i);
21668 if (new_ && old && ARGUMENT_PACK_P (old)
21669 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
21670 /* Don't forget explicit template arguments in a pack. */
21671 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
21672 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
21673 TREE_VEC_ELT (targs, i) = new_;
21676 if (good)
21677 return true;
21679 return false;
21682 /* Core DR 115: In contexts where deduction is done and fails, or in
21683 contexts where deduction is not done, if a template argument list is
21684 specified and it, along with any default template arguments, identifies
21685 a single function template specialization, then the template-id is an
21686 lvalue for the function template specialization. */
21688 tree
21689 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
21691 tree expr, offset, baselink;
21692 bool addr;
21694 if (!type_unknown_p (orig_expr))
21695 return orig_expr;
21697 expr = orig_expr;
21698 addr = false;
21699 offset = NULL_TREE;
21700 baselink = NULL_TREE;
21702 if (TREE_CODE (expr) == ADDR_EXPR)
21704 expr = TREE_OPERAND (expr, 0);
21705 addr = true;
21707 if (TREE_CODE (expr) == OFFSET_REF)
21709 offset = expr;
21710 expr = TREE_OPERAND (expr, 1);
21712 if (BASELINK_P (expr))
21714 baselink = expr;
21715 expr = BASELINK_FUNCTIONS (expr);
21718 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
21720 int good = 0;
21721 tree goodfn = NULL_TREE;
21723 /* If we got some explicit template args, we need to plug them into
21724 the affected templates before we try to unify, in case the
21725 explicit args will completely resolve the templates in question. */
21727 tree expl_subargs = TREE_OPERAND (expr, 1);
21728 tree arg = TREE_OPERAND (expr, 0);
21729 tree badfn = NULL_TREE;
21730 tree badargs = NULL_TREE;
21732 for (lkp_iterator iter (arg); iter; ++iter)
21734 tree fn = *iter;
21735 tree subargs, elem;
21737 if (TREE_CODE (fn) != TEMPLATE_DECL)
21738 continue;
21740 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21741 expl_subargs, NULL_TREE, tf_none,
21742 /*require_all_args=*/true,
21743 /*use_default_args=*/true);
21744 if (subargs != error_mark_node
21745 && !any_dependent_template_arguments_p (subargs))
21747 elem = instantiate_template (fn, subargs, tf_none);
21748 if (elem == error_mark_node)
21750 badfn = fn;
21751 badargs = subargs;
21753 else if (elem && (!goodfn || !decls_match (goodfn, elem)))
21755 goodfn = elem;
21756 ++good;
21760 if (good == 1)
21762 mark_used (goodfn);
21763 expr = goodfn;
21764 if (baselink)
21765 expr = build_baselink (BASELINK_BINFO (baselink),
21766 BASELINK_ACCESS_BINFO (baselink),
21767 expr, BASELINK_OPTYPE (baselink));
21768 if (offset)
21770 tree base
21771 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
21772 expr = build_offset_ref (base, expr, addr, complain);
21774 if (addr)
21775 expr = cp_build_addr_expr (expr, complain);
21776 return expr;
21778 else if (good == 0 && badargs && (complain & tf_error))
21779 /* There were no good options and at least one bad one, so let the
21780 user know what the problem is. */
21781 instantiate_template (badfn, badargs, complain);
21783 return orig_expr;
21786 /* As above, but error out if the expression remains overloaded. */
21788 tree
21789 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
21791 exp = resolve_nondeduced_context (exp, complain);
21792 if (type_unknown_p (exp))
21794 if (complain & tf_error)
21795 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
21796 return error_mark_node;
21798 return exp;
21801 /* Subroutine of resolve_overloaded_unification; does deduction for a single
21802 overload. Fills TARGS with any deduced arguments, or error_mark_node if
21803 different overloads deduce different arguments for a given parm.
21804 ADDR_P is true if the expression for which deduction is being
21805 performed was of the form "& fn" rather than simply "fn".
21807 Returns 1 on success. */
21809 static int
21810 try_one_overload (tree tparms,
21811 tree orig_targs,
21812 tree targs,
21813 tree parm,
21814 tree arg,
21815 unification_kind_t strict,
21816 int sub_strict,
21817 bool addr_p,
21818 bool explain_p)
21820 int nargs;
21821 tree tempargs;
21822 int i;
21824 if (arg == error_mark_node)
21825 return 0;
21827 /* [temp.deduct.type] A template-argument can be deduced from a pointer
21828 to function or pointer to member function argument if the set of
21829 overloaded functions does not contain function templates and at most
21830 one of a set of overloaded functions provides a unique match.
21832 So if this is a template, just return success. */
21834 if (uses_template_parms (arg))
21835 return 1;
21837 if (TREE_CODE (arg) == METHOD_TYPE)
21838 arg = build_ptrmemfunc_type (build_pointer_type (arg));
21839 else if (addr_p)
21840 arg = build_pointer_type (arg);
21842 sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
21844 /* We don't copy orig_targs for this because if we have already deduced
21845 some template args from previous args, unify would complain when we
21846 try to deduce a template parameter for the same argument, even though
21847 there isn't really a conflict. */
21848 nargs = TREE_VEC_LENGTH (targs);
21849 tempargs = make_tree_vec (nargs);
21851 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
21852 return 0;
21854 /* First make sure we didn't deduce anything that conflicts with
21855 explicitly specified args. */
21856 for (i = nargs; i--; )
21858 tree elt = TREE_VEC_ELT (tempargs, i);
21859 tree oldelt = TREE_VEC_ELT (orig_targs, i);
21861 if (!elt)
21862 /*NOP*/;
21863 else if (uses_template_parms (elt))
21864 /* Since we're unifying against ourselves, we will fill in
21865 template args used in the function parm list with our own
21866 template parms. Discard them. */
21867 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
21868 else if (oldelt && ARGUMENT_PACK_P (oldelt))
21870 /* Check that the argument at each index of the deduced argument pack
21871 is equivalent to the corresponding explicitly specified argument.
21872 We may have deduced more arguments than were explicitly specified,
21873 and that's OK. */
21875 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
21876 that's wrong if we deduce the same argument pack from multiple
21877 function arguments: it's only incomplete the first time. */
21879 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
21880 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
21882 if (TREE_VEC_LENGTH (deduced_pack)
21883 < TREE_VEC_LENGTH (explicit_pack))
21884 return 0;
21886 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
21887 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
21888 TREE_VEC_ELT (deduced_pack, j)))
21889 return 0;
21891 else if (oldelt && !template_args_equal (oldelt, elt))
21892 return 0;
21895 for (i = nargs; i--; )
21897 tree elt = TREE_VEC_ELT (tempargs, i);
21899 if (elt)
21900 TREE_VEC_ELT (targs, i) = elt;
21903 return 1;
21906 /* PARM is a template class (perhaps with unbound template
21907 parameters). ARG is a fully instantiated type. If ARG can be
21908 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
21909 TARGS are as for unify. */
21911 static tree
21912 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
21913 bool explain_p)
21915 tree copy_of_targs;
21917 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21918 return NULL_TREE;
21919 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21920 /* Matches anything. */;
21921 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
21922 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
21923 return NULL_TREE;
21925 /* We need to make a new template argument vector for the call to
21926 unify. If we used TARGS, we'd clutter it up with the result of
21927 the attempted unification, even if this class didn't work out.
21928 We also don't want to commit ourselves to all the unifications
21929 we've already done, since unification is supposed to be done on
21930 an argument-by-argument basis. In other words, consider the
21931 following pathological case:
21933 template <int I, int J, int K>
21934 struct S {};
21936 template <int I, int J>
21937 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
21939 template <int I, int J, int K>
21940 void f(S<I, J, K>, S<I, I, I>);
21942 void g() {
21943 S<0, 0, 0> s0;
21944 S<0, 1, 2> s2;
21946 f(s0, s2);
21949 Now, by the time we consider the unification involving `s2', we
21950 already know that we must have `f<0, 0, 0>'. But, even though
21951 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
21952 because there are two ways to unify base classes of S<0, 1, 2>
21953 with S<I, I, I>. If we kept the already deduced knowledge, we
21954 would reject the possibility I=1. */
21955 copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
21957 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21959 if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
21960 return NULL_TREE;
21961 return arg;
21964 /* If unification failed, we're done. */
21965 if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
21966 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
21967 return NULL_TREE;
21969 return arg;
21972 /* Given a template type PARM and a class type ARG, find the unique
21973 base type in ARG that is an instance of PARM. We do not examine
21974 ARG itself; only its base-classes. If there is not exactly one
21975 appropriate base class, return NULL_TREE. PARM may be the type of
21976 a partial specialization, as well as a plain template type. Used
21977 by unify. */
21979 static enum template_base_result
21980 get_template_base (tree tparms, tree targs, tree parm, tree arg,
21981 bool explain_p, tree *result)
21983 tree rval = NULL_TREE;
21984 tree binfo;
21986 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
21988 binfo = TYPE_BINFO (complete_type (arg));
21989 if (!binfo)
21991 /* The type could not be completed. */
21992 *result = NULL_TREE;
21993 return tbr_incomplete_type;
21996 /* Walk in inheritance graph order. The search order is not
21997 important, and this avoids multiple walks of virtual bases. */
21998 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
22000 tree r = try_class_unification (tparms, targs, parm,
22001 BINFO_TYPE (binfo), explain_p);
22003 if (r)
22005 /* If there is more than one satisfactory baseclass, then:
22007 [temp.deduct.call]
22009 If they yield more than one possible deduced A, the type
22010 deduction fails.
22012 applies. */
22013 if (rval && !same_type_p (r, rval))
22015 *result = NULL_TREE;
22016 return tbr_ambiguous_baseclass;
22019 rval = r;
22023 *result = rval;
22024 return tbr_success;
22027 /* Returns the level of DECL, which declares a template parameter. */
22029 static int
22030 template_decl_level (tree decl)
22032 switch (TREE_CODE (decl))
22034 case TYPE_DECL:
22035 case TEMPLATE_DECL:
22036 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
22038 case PARM_DECL:
22039 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
22041 default:
22042 gcc_unreachable ();
22044 return 0;
22047 /* Decide whether ARG can be unified with PARM, considering only the
22048 cv-qualifiers of each type, given STRICT as documented for unify.
22049 Returns nonzero iff the unification is OK on that basis. */
22051 static int
22052 check_cv_quals_for_unify (int strict, tree arg, tree parm)
22054 int arg_quals = cp_type_quals (arg);
22055 int parm_quals = cp_type_quals (parm);
22057 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22058 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22060 /* Although a CVR qualifier is ignored when being applied to a
22061 substituted template parameter ([8.3.2]/1 for example), that
22062 does not allow us to unify "const T" with "int&" because both
22063 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
22064 It is ok when we're allowing additional CV qualifiers
22065 at the outer level [14.8.2.1]/3,1st bullet. */
22066 if ((TYPE_REF_P (arg)
22067 || FUNC_OR_METHOD_TYPE_P (arg))
22068 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
22069 return 0;
22071 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
22072 && (parm_quals & TYPE_QUAL_RESTRICT))
22073 return 0;
22076 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22077 && (arg_quals & parm_quals) != parm_quals)
22078 return 0;
22080 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
22081 && (parm_quals & arg_quals) != arg_quals)
22082 return 0;
22084 return 1;
22087 /* Determines the LEVEL and INDEX for the template parameter PARM. */
22088 void
22089 template_parm_level_and_index (tree parm, int* level, int* index)
22091 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22092 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22093 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22095 *index = TEMPLATE_TYPE_IDX (parm);
22096 *level = TEMPLATE_TYPE_LEVEL (parm);
22098 else
22100 *index = TEMPLATE_PARM_IDX (parm);
22101 *level = TEMPLATE_PARM_LEVEL (parm);
22105 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
22106 do { \
22107 if (unify (TP, TA, P, A, S, EP)) \
22108 return 1; \
22109 } while (0)
22111 /* Unifies the remaining arguments in PACKED_ARGS with the pack
22112 expansion at the end of PACKED_PARMS. Returns 0 if the type
22113 deduction succeeds, 1 otherwise. STRICT is the same as in
22114 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
22115 function call argument list. We'll need to adjust the arguments to make them
22116 types. SUBR tells us if this is from a recursive call to
22117 type_unification_real, or for comparing two template argument
22118 lists. */
22120 static int
22121 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
22122 tree packed_args, unification_kind_t strict,
22123 bool subr, bool explain_p)
22125 tree parm
22126 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
22127 tree pattern = PACK_EXPANSION_PATTERN (parm);
22128 tree pack, packs = NULL_TREE;
22129 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
22131 /* Add in any args remembered from an earlier partial instantiation. */
22132 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
22133 int levels = TMPL_ARGS_DEPTH (targs);
22135 packed_args = expand_template_argument_pack (packed_args);
22137 int len = TREE_VEC_LENGTH (packed_args);
22139 /* Determine the parameter packs we will be deducing from the
22140 pattern, and record their current deductions. */
22141 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
22142 pack; pack = TREE_CHAIN (pack))
22144 tree parm_pack = TREE_VALUE (pack);
22145 int idx, level;
22147 /* Only template parameter packs can be deduced, not e.g. function
22148 parameter packs or __bases or __integer_pack. */
22149 if (!TEMPLATE_PARM_P (parm_pack))
22150 continue;
22152 /* Determine the index and level of this parameter pack. */
22153 template_parm_level_and_index (parm_pack, &level, &idx);
22154 if (level < levels)
22155 continue;
22157 /* Keep track of the parameter packs and their corresponding
22158 argument packs. */
22159 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
22160 TREE_TYPE (packs) = make_tree_vec (len - start);
22163 /* Loop through all of the arguments that have not yet been
22164 unified and unify each with the pattern. */
22165 for (i = start; i < len; i++)
22167 tree parm;
22168 bool any_explicit = false;
22169 tree arg = TREE_VEC_ELT (packed_args, i);
22171 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
22172 or the element of its argument pack at the current index if
22173 this argument was explicitly specified. */
22174 for (pack = packs; pack; pack = TREE_CHAIN (pack))
22176 int idx, level;
22177 tree arg, pargs;
22178 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22180 arg = NULL_TREE;
22181 if (TREE_VALUE (pack)
22182 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
22183 && (i - start < TREE_VEC_LENGTH (pargs)))
22185 any_explicit = true;
22186 arg = TREE_VEC_ELT (pargs, i - start);
22188 TMPL_ARG (targs, level, idx) = arg;
22191 /* If we had explicit template arguments, substitute them into the
22192 pattern before deduction. */
22193 if (any_explicit)
22195 /* Some arguments might still be unspecified or dependent. */
22196 bool dependent;
22197 ++processing_template_decl;
22198 dependent = any_dependent_template_arguments_p (targs);
22199 if (!dependent)
22200 --processing_template_decl;
22201 parm = tsubst (pattern, targs,
22202 explain_p ? tf_warning_or_error : tf_none,
22203 NULL_TREE);
22204 if (dependent)
22205 --processing_template_decl;
22206 if (parm == error_mark_node)
22207 return 1;
22209 else
22210 parm = pattern;
22212 /* Unify the pattern with the current argument. */
22213 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
22214 explain_p))
22215 return 1;
22217 /* For each parameter pack, collect the deduced value. */
22218 for (pack = packs; pack; pack = TREE_CHAIN (pack))
22220 int idx, level;
22221 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22223 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
22224 TMPL_ARG (targs, level, idx);
22228 /* Verify that the results of unification with the parameter packs
22229 produce results consistent with what we've seen before, and make
22230 the deduced argument packs available. */
22231 for (pack = packs; pack; pack = TREE_CHAIN (pack))
22233 tree old_pack = TREE_VALUE (pack);
22234 tree new_args = TREE_TYPE (pack);
22235 int i, len = TREE_VEC_LENGTH (new_args);
22236 int idx, level;
22237 bool nondeduced_p = false;
22239 /* By default keep the original deduced argument pack.
22240 If necessary, more specific code is going to update the
22241 resulting deduced argument later down in this function. */
22242 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22243 TMPL_ARG (targs, level, idx) = old_pack;
22245 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
22246 actually deduce anything. */
22247 for (i = 0; i < len && !nondeduced_p; ++i)
22248 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
22249 nondeduced_p = true;
22250 if (nondeduced_p)
22251 continue;
22253 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
22255 /* If we had fewer function args than explicit template args,
22256 just use the explicits. */
22257 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
22258 int explicit_len = TREE_VEC_LENGTH (explicit_args);
22259 if (len < explicit_len)
22260 new_args = explicit_args;
22263 if (!old_pack)
22265 tree result;
22266 /* Build the deduced *_ARGUMENT_PACK. */
22267 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
22269 result = make_node (NONTYPE_ARGUMENT_PACK);
22270 TREE_CONSTANT (result) = 1;
22272 else
22273 result = cxx_make_type (TYPE_ARGUMENT_PACK);
22275 SET_ARGUMENT_PACK_ARGS (result, new_args);
22277 /* Note the deduced argument packs for this parameter
22278 pack. */
22279 TMPL_ARG (targs, level, idx) = result;
22281 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
22282 && (ARGUMENT_PACK_ARGS (old_pack)
22283 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
22285 /* We only had the explicitly-provided arguments before, but
22286 now we have a complete set of arguments. */
22287 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
22289 SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
22290 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
22291 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
22293 else
22295 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
22296 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
22298 if (!comp_template_args (old_args, new_args,
22299 &bad_old_arg, &bad_new_arg))
22300 /* Inconsistent unification of this parameter pack. */
22301 return unify_parameter_pack_inconsistent (explain_p,
22302 bad_old_arg,
22303 bad_new_arg);
22307 return unify_success (explain_p);
22310 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
22311 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
22312 parameters and return value are as for unify. */
22314 static int
22315 unify_array_domain (tree tparms, tree targs,
22316 tree parm_dom, tree arg_dom,
22317 bool explain_p)
22319 tree parm_max;
22320 tree arg_max;
22321 bool parm_cst;
22322 bool arg_cst;
22324 /* Our representation of array types uses "N - 1" as the
22325 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
22326 not an integer constant. We cannot unify arbitrarily
22327 complex expressions, so we eliminate the MINUS_EXPRs
22328 here. */
22329 parm_max = TYPE_MAX_VALUE (parm_dom);
22330 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
22331 if (!parm_cst)
22333 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
22334 parm_max = TREE_OPERAND (parm_max, 0);
22336 arg_max = TYPE_MAX_VALUE (arg_dom);
22337 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
22338 if (!arg_cst)
22340 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
22341 trying to unify the type of a variable with the type
22342 of a template parameter. For example:
22344 template <unsigned int N>
22345 void f (char (&) [N]);
22346 int g();
22347 void h(int i) {
22348 char a[g(i)];
22349 f(a);
22352 Here, the type of the ARG will be "int [g(i)]", and
22353 may be a SAVE_EXPR, etc. */
22354 if (TREE_CODE (arg_max) != MINUS_EXPR)
22355 return unify_vla_arg (explain_p, arg_dom);
22356 arg_max = TREE_OPERAND (arg_max, 0);
22359 /* If only one of the bounds used a MINUS_EXPR, compensate
22360 by adding one to the other bound. */
22361 if (parm_cst && !arg_cst)
22362 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
22363 integer_type_node,
22364 parm_max,
22365 integer_one_node);
22366 else if (arg_cst && !parm_cst)
22367 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
22368 integer_type_node,
22369 arg_max,
22370 integer_one_node);
22372 return unify (tparms, targs, parm_max, arg_max,
22373 UNIFY_ALLOW_INTEGER, explain_p);
22376 /* Returns whether T, a P or A in unify, is a type, template or expression. */
22378 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
22380 static pa_kind_t
22381 pa_kind (tree t)
22383 if (PACK_EXPANSION_P (t))
22384 t = PACK_EXPANSION_PATTERN (t);
22385 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
22386 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
22387 || DECL_TYPE_TEMPLATE_P (t))
22388 return pa_tmpl;
22389 else if (TYPE_P (t))
22390 return pa_type;
22391 else
22392 return pa_expr;
22395 /* Deduce the value of template parameters. TPARMS is the (innermost)
22396 set of template parameters to a template. TARGS is the bindings
22397 for those template parameters, as determined thus far; TARGS may
22398 include template arguments for outer levels of template parameters
22399 as well. PARM is a parameter to a template function, or a
22400 subcomponent of that parameter; ARG is the corresponding argument.
22401 This function attempts to match PARM with ARG in a manner
22402 consistent with the existing assignments in TARGS. If more values
22403 are deduced, then TARGS is updated.
22405 Returns 0 if the type deduction succeeds, 1 otherwise. The
22406 parameter STRICT is a bitwise or of the following flags:
22408 UNIFY_ALLOW_NONE:
22409 Require an exact match between PARM and ARG.
22410 UNIFY_ALLOW_MORE_CV_QUAL:
22411 Allow the deduced ARG to be more cv-qualified (by qualification
22412 conversion) than ARG.
22413 UNIFY_ALLOW_LESS_CV_QUAL:
22414 Allow the deduced ARG to be less cv-qualified than ARG.
22415 UNIFY_ALLOW_DERIVED:
22416 Allow the deduced ARG to be a template base class of ARG,
22417 or a pointer to a template base class of the type pointed to by
22418 ARG.
22419 UNIFY_ALLOW_INTEGER:
22420 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
22421 case for more information.
22422 UNIFY_ALLOW_OUTER_LEVEL:
22423 This is the outermost level of a deduction. Used to determine validity
22424 of qualification conversions. A valid qualification conversion must
22425 have const qualified pointers leading up to the inner type which
22426 requires additional CV quals, except at the outer level, where const
22427 is not required [conv.qual]. It would be normal to set this flag in
22428 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
22429 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
22430 This is the outermost level of a deduction, and PARM can be more CV
22431 qualified at this point.
22432 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
22433 This is the outermost level of a deduction, and PARM can be less CV
22434 qualified at this point. */
22436 static int
22437 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
22438 bool explain_p)
22440 int idx;
22441 tree targ;
22442 tree tparm;
22443 int strict_in = strict;
22444 tsubst_flags_t complain = (explain_p
22445 ? tf_warning_or_error
22446 : tf_none);
22448 /* I don't think this will do the right thing with respect to types.
22449 But the only case I've seen it in so far has been array bounds, where
22450 signedness is the only information lost, and I think that will be
22451 okay. */
22452 while (CONVERT_EXPR_P (parm))
22453 parm = TREE_OPERAND (parm, 0);
22455 if (arg == error_mark_node)
22456 return unify_invalid (explain_p);
22457 if (arg == unknown_type_node
22458 || arg == init_list_type_node)
22459 /* We can't deduce anything from this, but we might get all the
22460 template args from other function args. */
22461 return unify_success (explain_p);
22463 if (parm == any_targ_node || arg == any_targ_node)
22464 return unify_success (explain_p);
22466 /* If PARM uses template parameters, then we can't bail out here,
22467 even if ARG == PARM, since we won't record unifications for the
22468 template parameters. We might need them if we're trying to
22469 figure out which of two things is more specialized. */
22470 if (arg == parm && !uses_template_parms (parm))
22471 return unify_success (explain_p);
22473 /* Handle init lists early, so the rest of the function can assume
22474 we're dealing with a type. */
22475 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
22477 tree elt, elttype;
22478 unsigned i;
22479 tree orig_parm = parm;
22481 if (!is_std_init_list (parm)
22482 && TREE_CODE (parm) != ARRAY_TYPE)
22483 /* We can only deduce from an initializer list argument if the
22484 parameter is std::initializer_list or an array; otherwise this
22485 is a non-deduced context. */
22486 return unify_success (explain_p);
22488 if (TREE_CODE (parm) == ARRAY_TYPE)
22489 elttype = TREE_TYPE (parm);
22490 else
22492 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
22493 /* Deduction is defined in terms of a single type, so just punt
22494 on the (bizarre) std::initializer_list<T...>. */
22495 if (PACK_EXPANSION_P (elttype))
22496 return unify_success (explain_p);
22499 if (strict != DEDUCE_EXACT
22500 && TYPE_P (elttype)
22501 && !uses_deducible_template_parms (elttype))
22502 /* If ELTTYPE has no deducible template parms, skip deduction from
22503 the list elements. */;
22504 else
22505 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
22507 int elt_strict = strict;
22509 if (elt == error_mark_node)
22510 return unify_invalid (explain_p);
22512 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
22514 tree type = TREE_TYPE (elt);
22515 if (type == error_mark_node)
22516 return unify_invalid (explain_p);
22517 /* It should only be possible to get here for a call. */
22518 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
22519 elt_strict |= maybe_adjust_types_for_deduction
22520 (DEDUCE_CALL, &elttype, &type, elt);
22521 elt = type;
22524 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
22525 explain_p);
22528 if (TREE_CODE (parm) == ARRAY_TYPE
22529 && deducible_array_bound (TYPE_DOMAIN (parm)))
22531 /* Also deduce from the length of the initializer list. */
22532 tree max = size_int (CONSTRUCTOR_NELTS (arg));
22533 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
22534 if (idx == error_mark_node)
22535 return unify_invalid (explain_p);
22536 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
22537 idx, explain_p);
22540 /* If the std::initializer_list<T> deduction worked, replace the
22541 deduced A with std::initializer_list<A>. */
22542 if (orig_parm != parm)
22544 idx = TEMPLATE_TYPE_IDX (orig_parm);
22545 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
22546 targ = listify (targ);
22547 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
22549 return unify_success (explain_p);
22552 /* If parm and arg aren't the same kind of thing (template, type, or
22553 expression), fail early. */
22554 if (pa_kind (parm) != pa_kind (arg))
22555 return unify_invalid (explain_p);
22557 /* Immediately reject some pairs that won't unify because of
22558 cv-qualification mismatches. */
22559 if (TREE_CODE (arg) == TREE_CODE (parm)
22560 && TYPE_P (arg)
22561 /* It is the elements of the array which hold the cv quals of an array
22562 type, and the elements might be template type parms. We'll check
22563 when we recurse. */
22564 && TREE_CODE (arg) != ARRAY_TYPE
22565 /* We check the cv-qualifiers when unifying with template type
22566 parameters below. We want to allow ARG `const T' to unify with
22567 PARM `T' for example, when computing which of two templates
22568 is more specialized, for example. */
22569 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
22570 && !check_cv_quals_for_unify (strict_in, arg, parm))
22571 return unify_cv_qual_mismatch (explain_p, parm, arg);
22573 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
22574 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
22575 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
22576 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
22577 strict &= ~UNIFY_ALLOW_DERIVED;
22578 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22579 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
22581 switch (TREE_CODE (parm))
22583 case TYPENAME_TYPE:
22584 case SCOPE_REF:
22585 case UNBOUND_CLASS_TEMPLATE:
22586 /* In a type which contains a nested-name-specifier, template
22587 argument values cannot be deduced for template parameters used
22588 within the nested-name-specifier. */
22589 return unify_success (explain_p);
22591 case TEMPLATE_TYPE_PARM:
22592 case TEMPLATE_TEMPLATE_PARM:
22593 case BOUND_TEMPLATE_TEMPLATE_PARM:
22594 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
22595 if (error_operand_p (tparm))
22596 return unify_invalid (explain_p);
22598 if (TEMPLATE_TYPE_LEVEL (parm)
22599 != template_decl_level (tparm))
22600 /* The PARM is not one we're trying to unify. Just check
22601 to see if it matches ARG. */
22603 if (TREE_CODE (arg) == TREE_CODE (parm)
22604 && (is_auto (parm) ? is_auto (arg)
22605 : same_type_p (parm, arg)))
22606 return unify_success (explain_p);
22607 else
22608 return unify_type_mismatch (explain_p, parm, arg);
22610 idx = TEMPLATE_TYPE_IDX (parm);
22611 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
22612 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
22613 if (error_operand_p (tparm))
22614 return unify_invalid (explain_p);
22616 /* Check for mixed types and values. */
22617 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22618 && TREE_CODE (tparm) != TYPE_DECL)
22619 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22620 && TREE_CODE (tparm) != TEMPLATE_DECL))
22621 gcc_unreachable ();
22623 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22625 if ((strict_in & UNIFY_ALLOW_DERIVED)
22626 && CLASS_TYPE_P (arg))
22628 /* First try to match ARG directly. */
22629 tree t = try_class_unification (tparms, targs, parm, arg,
22630 explain_p);
22631 if (!t)
22633 /* Otherwise, look for a suitable base of ARG, as below. */
22634 enum template_base_result r;
22635 r = get_template_base (tparms, targs, parm, arg,
22636 explain_p, &t);
22637 if (!t)
22638 return unify_no_common_base (explain_p, r, parm, arg);
22639 arg = t;
22642 /* ARG must be constructed from a template class or a template
22643 template parameter. */
22644 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
22645 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22646 return unify_template_deduction_failure (explain_p, parm, arg);
22648 /* Deduce arguments T, i from TT<T> or TT<i>. */
22649 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
22650 return 1;
22652 arg = TYPE_TI_TEMPLATE (arg);
22654 /* Fall through to deduce template name. */
22657 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22658 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22660 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
22662 /* Simple cases: Value already set, does match or doesn't. */
22663 if (targ != NULL_TREE && template_args_equal (targ, arg))
22664 return unify_success (explain_p);
22665 else if (targ)
22666 return unify_inconsistency (explain_p, parm, targ, arg);
22668 else
22670 /* If PARM is `const T' and ARG is only `int', we don't have
22671 a match unless we are allowing additional qualification.
22672 If ARG is `const int' and PARM is just `T' that's OK;
22673 that binds `const int' to `T'. */
22674 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
22675 arg, parm))
22676 return unify_cv_qual_mismatch (explain_p, parm, arg);
22678 /* Consider the case where ARG is `const volatile int' and
22679 PARM is `const T'. Then, T should be `volatile int'. */
22680 arg = cp_build_qualified_type_real
22681 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
22682 if (arg == error_mark_node)
22683 return unify_invalid (explain_p);
22685 /* Simple cases: Value already set, does match or doesn't. */
22686 if (targ != NULL_TREE && same_type_p (targ, arg))
22687 return unify_success (explain_p);
22688 else if (targ)
22689 return unify_inconsistency (explain_p, parm, targ, arg);
22691 /* Make sure that ARG is not a variable-sized array. (Note
22692 that were talking about variable-sized arrays (like
22693 `int[n]'), rather than arrays of unknown size (like
22694 `int[]').) We'll get very confused by such a type since
22695 the bound of the array is not constant, and therefore
22696 not mangleable. Besides, such types are not allowed in
22697 ISO C++, so we can do as we please here. We do allow
22698 them for 'auto' deduction, since that isn't ABI-exposed. */
22699 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
22700 return unify_vla_arg (explain_p, arg);
22702 /* Strip typedefs as in convert_template_argument. */
22703 arg = canonicalize_type_argument (arg, tf_none);
22706 /* If ARG is a parameter pack or an expansion, we cannot unify
22707 against it unless PARM is also a parameter pack. */
22708 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
22709 && !template_parameter_pack_p (parm))
22710 return unify_parameter_pack_mismatch (explain_p, parm, arg);
22712 /* If the argument deduction results is a METHOD_TYPE,
22713 then there is a problem.
22714 METHOD_TYPE doesn't map to any real C++ type the result of
22715 the deduction cannot be of that type. */
22716 if (TREE_CODE (arg) == METHOD_TYPE)
22717 return unify_method_type_error (explain_p, arg);
22719 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
22720 return unify_success (explain_p);
22722 case TEMPLATE_PARM_INDEX:
22723 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
22724 if (error_operand_p (tparm))
22725 return unify_invalid (explain_p);
22727 if (TEMPLATE_PARM_LEVEL (parm)
22728 != template_decl_level (tparm))
22730 /* The PARM is not one we're trying to unify. Just check
22731 to see if it matches ARG. */
22732 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
22733 && cp_tree_equal (parm, arg));
22734 if (result)
22735 unify_expression_unequal (explain_p, parm, arg);
22736 return result;
22739 idx = TEMPLATE_PARM_IDX (parm);
22740 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
22742 if (targ)
22744 if ((strict & UNIFY_ALLOW_INTEGER)
22745 && TREE_TYPE (targ) && TREE_TYPE (arg)
22746 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
22747 /* We're deducing from an array bound, the type doesn't matter. */
22748 arg = fold_convert (TREE_TYPE (targ), arg);
22749 int x = !cp_tree_equal (targ, arg);
22750 if (x)
22751 unify_inconsistency (explain_p, parm, targ, arg);
22752 return x;
22755 /* [temp.deduct.type] If, in the declaration of a function template
22756 with a non-type template-parameter, the non-type
22757 template-parameter is used in an expression in the function
22758 parameter-list and, if the corresponding template-argument is
22759 deduced, the template-argument type shall match the type of the
22760 template-parameter exactly, except that a template-argument
22761 deduced from an array bound may be of any integral type.
22762 The non-type parameter might use already deduced type parameters. */
22763 tparm = TREE_TYPE (parm);
22764 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
22765 /* We don't have enough levels of args to do any substitution. This
22766 can happen in the context of -fnew-ttp-matching. */;
22767 else
22769 ++processing_template_decl;
22770 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
22771 --processing_template_decl;
22773 if (tree a = type_uses_auto (tparm))
22775 tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
22776 if (tparm == error_mark_node)
22777 return 1;
22781 if (!TREE_TYPE (arg))
22782 /* Template-parameter dependent expression. Just accept it for now.
22783 It will later be processed in convert_template_argument. */
22785 else if (same_type_ignoring_top_level_qualifiers_p
22786 (non_reference (TREE_TYPE (arg)),
22787 non_reference (tparm)))
22788 /* OK. Ignore top-level quals here because a class-type template
22789 parameter object is const. */;
22790 else if ((strict & UNIFY_ALLOW_INTEGER)
22791 && CP_INTEGRAL_TYPE_P (tparm))
22792 /* Convert the ARG to the type of PARM; the deduced non-type
22793 template argument must exactly match the types of the
22794 corresponding parameter. */
22795 arg = fold (build_nop (tparm, arg));
22796 else if (uses_template_parms (tparm))
22798 /* We haven't deduced the type of this parameter yet. */
22799 if (cxx_dialect >= cxx17
22800 /* We deduce from array bounds in try_array_deduction. */
22801 && !(strict & UNIFY_ALLOW_INTEGER))
22803 /* Deduce it from the non-type argument. */
22804 tree atype = TREE_TYPE (arg);
22805 RECUR_AND_CHECK_FAILURE (tparms, targs,
22806 tparm, atype,
22807 UNIFY_ALLOW_NONE, explain_p);
22809 else
22810 /* Try again later. */
22811 return unify_success (explain_p);
22813 else
22814 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
22816 /* If ARG is a parameter pack or an expansion, we cannot unify
22817 against it unless PARM is also a parameter pack. */
22818 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
22819 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
22820 return unify_parameter_pack_mismatch (explain_p, parm, arg);
22823 bool removed_attr = false;
22824 arg = strip_typedefs_expr (arg, &removed_attr);
22826 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
22827 return unify_success (explain_p);
22829 case PTRMEM_CST:
22831 /* A pointer-to-member constant can be unified only with
22832 another constant. */
22833 if (TREE_CODE (arg) != PTRMEM_CST)
22834 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
22836 /* Just unify the class member. It would be useless (and possibly
22837 wrong, depending on the strict flags) to unify also
22838 PTRMEM_CST_CLASS, because we want to be sure that both parm and
22839 arg refer to the same variable, even if through different
22840 classes. For instance:
22842 struct A { int x; };
22843 struct B : A { };
22845 Unification of &A::x and &B::x must succeed. */
22846 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
22847 PTRMEM_CST_MEMBER (arg), strict, explain_p);
22850 case POINTER_TYPE:
22852 if (!TYPE_PTR_P (arg))
22853 return unify_type_mismatch (explain_p, parm, arg);
22855 /* [temp.deduct.call]
22857 A can be another pointer or pointer to member type that can
22858 be converted to the deduced A via a qualification
22859 conversion (_conv.qual_).
22861 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
22862 This will allow for additional cv-qualification of the
22863 pointed-to types if appropriate. */
22865 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
22866 /* The derived-to-base conversion only persists through one
22867 level of pointers. */
22868 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
22870 return unify (tparms, targs, TREE_TYPE (parm),
22871 TREE_TYPE (arg), strict, explain_p);
22874 case REFERENCE_TYPE:
22875 if (!TYPE_REF_P (arg))
22876 return unify_type_mismatch (explain_p, parm, arg);
22877 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22878 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
22880 case ARRAY_TYPE:
22881 if (TREE_CODE (arg) != ARRAY_TYPE)
22882 return unify_type_mismatch (explain_p, parm, arg);
22883 if ((TYPE_DOMAIN (parm) == NULL_TREE)
22884 != (TYPE_DOMAIN (arg) == NULL_TREE))
22885 return unify_type_mismatch (explain_p, parm, arg);
22886 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22887 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
22888 if (TYPE_DOMAIN (parm) != NULL_TREE)
22889 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
22890 TYPE_DOMAIN (arg), explain_p);
22891 return unify_success (explain_p);
22893 case REAL_TYPE:
22894 case COMPLEX_TYPE:
22895 case VECTOR_TYPE:
22896 case INTEGER_TYPE:
22897 case BOOLEAN_TYPE:
22898 case ENUMERAL_TYPE:
22899 case VOID_TYPE:
22900 case NULLPTR_TYPE:
22901 if (TREE_CODE (arg) != TREE_CODE (parm))
22902 return unify_type_mismatch (explain_p, parm, arg);
22904 /* We have already checked cv-qualification at the top of the
22905 function. */
22906 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
22907 return unify_type_mismatch (explain_p, parm, arg);
22909 /* As far as unification is concerned, this wins. Later checks
22910 will invalidate it if necessary. */
22911 return unify_success (explain_p);
22913 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
22914 /* Type INTEGER_CST can come from ordinary constant template args. */
22915 case INTEGER_CST:
22916 while (CONVERT_EXPR_P (arg))
22917 arg = TREE_OPERAND (arg, 0);
22919 if (TREE_CODE (arg) != INTEGER_CST)
22920 return unify_template_argument_mismatch (explain_p, parm, arg);
22921 return (tree_int_cst_equal (parm, arg)
22922 ? unify_success (explain_p)
22923 : unify_template_argument_mismatch (explain_p, parm, arg));
22925 case TREE_VEC:
22927 int i, len, argslen;
22928 int parm_variadic_p = 0;
22930 if (TREE_CODE (arg) != TREE_VEC)
22931 return unify_template_argument_mismatch (explain_p, parm, arg);
22933 len = TREE_VEC_LENGTH (parm);
22934 argslen = TREE_VEC_LENGTH (arg);
22936 /* Check for pack expansions in the parameters. */
22937 for (i = 0; i < len; ++i)
22939 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
22941 if (i == len - 1)
22942 /* We can unify against something with a trailing
22943 parameter pack. */
22944 parm_variadic_p = 1;
22945 else
22946 /* [temp.deduct.type]/9: If the template argument list of
22947 P contains a pack expansion that is not the last
22948 template argument, the entire template argument list
22949 is a non-deduced context. */
22950 return unify_success (explain_p);
22954 /* If we don't have enough arguments to satisfy the parameters
22955 (not counting the pack expression at the end), or we have
22956 too many arguments for a parameter list that doesn't end in
22957 a pack expression, we can't unify. */
22958 if (parm_variadic_p
22959 ? argslen < len - parm_variadic_p
22960 : argslen != len)
22961 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
22963 /* Unify all of the parameters that precede the (optional)
22964 pack expression. */
22965 for (i = 0; i < len - parm_variadic_p; ++i)
22967 RECUR_AND_CHECK_FAILURE (tparms, targs,
22968 TREE_VEC_ELT (parm, i),
22969 TREE_VEC_ELT (arg, i),
22970 UNIFY_ALLOW_NONE, explain_p);
22972 if (parm_variadic_p)
22973 return unify_pack_expansion (tparms, targs, parm, arg,
22974 DEDUCE_EXACT,
22975 /*subr=*/true, explain_p);
22976 return unify_success (explain_p);
22979 case RECORD_TYPE:
22980 case UNION_TYPE:
22981 if (TREE_CODE (arg) != TREE_CODE (parm))
22982 return unify_type_mismatch (explain_p, parm, arg);
22984 if (TYPE_PTRMEMFUNC_P (parm))
22986 if (!TYPE_PTRMEMFUNC_P (arg))
22987 return unify_type_mismatch (explain_p, parm, arg);
22989 return unify (tparms, targs,
22990 TYPE_PTRMEMFUNC_FN_TYPE (parm),
22991 TYPE_PTRMEMFUNC_FN_TYPE (arg),
22992 strict, explain_p);
22994 else if (TYPE_PTRMEMFUNC_P (arg))
22995 return unify_type_mismatch (explain_p, parm, arg);
22997 if (CLASSTYPE_TEMPLATE_INFO (parm))
22999 tree t = NULL_TREE;
23001 if (strict_in & UNIFY_ALLOW_DERIVED)
23003 /* First, we try to unify the PARM and ARG directly. */
23004 t = try_class_unification (tparms, targs,
23005 parm, arg, explain_p);
23007 if (!t)
23009 /* Fallback to the special case allowed in
23010 [temp.deduct.call]:
23012 If P is a class, and P has the form
23013 template-id, then A can be a derived class of
23014 the deduced A. Likewise, if P is a pointer to
23015 a class of the form template-id, A can be a
23016 pointer to a derived class pointed to by the
23017 deduced A. */
23018 enum template_base_result r;
23019 r = get_template_base (tparms, targs, parm, arg,
23020 explain_p, &t);
23022 if (!t)
23024 /* Don't give the derived diagnostic if we're
23025 already dealing with the same template. */
23026 bool same_template
23027 = (CLASSTYPE_TEMPLATE_INFO (arg)
23028 && (CLASSTYPE_TI_TEMPLATE (parm)
23029 == CLASSTYPE_TI_TEMPLATE (arg)));
23030 return unify_no_common_base (explain_p && !same_template,
23031 r, parm, arg);
23035 else if (CLASSTYPE_TEMPLATE_INFO (arg)
23036 && (CLASSTYPE_TI_TEMPLATE (parm)
23037 == CLASSTYPE_TI_TEMPLATE (arg)))
23038 /* Perhaps PARM is something like S<U> and ARG is S<int>.
23039 Then, we should unify `int' and `U'. */
23040 t = arg;
23041 else
23042 /* There's no chance of unification succeeding. */
23043 return unify_type_mismatch (explain_p, parm, arg);
23045 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23046 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
23048 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
23049 return unify_type_mismatch (explain_p, parm, arg);
23050 return unify_success (explain_p);
23052 case METHOD_TYPE:
23053 case FUNCTION_TYPE:
23055 unsigned int nargs;
23056 tree *args;
23057 tree a;
23058 unsigned int i;
23060 if (TREE_CODE (arg) != TREE_CODE (parm))
23061 return unify_type_mismatch (explain_p, parm, arg);
23063 /* CV qualifications for methods can never be deduced, they must
23064 match exactly. We need to check them explicitly here,
23065 because type_unification_real treats them as any other
23066 cv-qualified parameter. */
23067 if (TREE_CODE (parm) == METHOD_TYPE
23068 && (!check_cv_quals_for_unify
23069 (UNIFY_ALLOW_NONE,
23070 class_of_this_parm (arg),
23071 class_of_this_parm (parm))))
23072 return unify_cv_qual_mismatch (explain_p, parm, arg);
23073 if (TREE_CODE (arg) == FUNCTION_TYPE
23074 && type_memfn_quals (parm) != type_memfn_quals (arg))
23075 return unify_cv_qual_mismatch (explain_p, parm, arg);
23076 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
23077 return unify_type_mismatch (explain_p, parm, arg);
23079 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
23080 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
23082 nargs = list_length (TYPE_ARG_TYPES (arg));
23083 args = XALLOCAVEC (tree, nargs);
23084 for (a = TYPE_ARG_TYPES (arg), i = 0;
23085 a != NULL_TREE && a != void_list_node;
23086 a = TREE_CHAIN (a), ++i)
23087 args[i] = TREE_VALUE (a);
23088 nargs = i;
23090 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
23091 args, nargs, 1, DEDUCE_EXACT,
23092 NULL, explain_p))
23093 return 1;
23095 if (flag_noexcept_type)
23097 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
23098 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
23099 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
23100 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
23101 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
23102 && uses_template_parms (TREE_PURPOSE (pspec)))
23103 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
23104 TREE_PURPOSE (aspec),
23105 UNIFY_ALLOW_NONE, explain_p);
23106 else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
23107 return unify_type_mismatch (explain_p, parm, arg);
23110 return 0;
23113 case OFFSET_TYPE:
23114 /* Unify a pointer to member with a pointer to member function, which
23115 deduces the type of the member as a function type. */
23116 if (TYPE_PTRMEMFUNC_P (arg))
23118 /* Check top-level cv qualifiers */
23119 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
23120 return unify_cv_qual_mismatch (explain_p, parm, arg);
23122 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23123 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
23124 UNIFY_ALLOW_NONE, explain_p);
23126 /* Determine the type of the function we are unifying against. */
23127 tree fntype = static_fn_type (arg);
23129 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
23132 if (TREE_CODE (arg) != OFFSET_TYPE)
23133 return unify_type_mismatch (explain_p, parm, arg);
23134 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23135 TYPE_OFFSET_BASETYPE (arg),
23136 UNIFY_ALLOW_NONE, explain_p);
23137 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23138 strict, explain_p);
23140 case CONST_DECL:
23141 if (DECL_TEMPLATE_PARM_P (parm))
23142 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
23143 if (arg != scalar_constant_value (parm))
23144 return unify_template_argument_mismatch (explain_p, parm, arg);
23145 return unify_success (explain_p);
23147 case FIELD_DECL:
23148 case TEMPLATE_DECL:
23149 /* Matched cases are handled by the ARG == PARM test above. */
23150 return unify_template_argument_mismatch (explain_p, parm, arg);
23152 case VAR_DECL:
23153 /* We might get a variable as a non-type template argument in parm if the
23154 corresponding parameter is type-dependent. Make any necessary
23155 adjustments based on whether arg is a reference. */
23156 if (CONSTANT_CLASS_P (arg))
23157 parm = fold_non_dependent_expr (parm, complain);
23158 else if (REFERENCE_REF_P (arg))
23160 tree sub = TREE_OPERAND (arg, 0);
23161 STRIP_NOPS (sub);
23162 if (TREE_CODE (sub) == ADDR_EXPR)
23163 arg = TREE_OPERAND (sub, 0);
23165 /* Now use the normal expression code to check whether they match. */
23166 goto expr;
23168 case TYPE_ARGUMENT_PACK:
23169 case NONTYPE_ARGUMENT_PACK:
23170 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
23171 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
23173 case TYPEOF_TYPE:
23174 case DECLTYPE_TYPE:
23175 case UNDERLYING_TYPE:
23176 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
23177 or UNDERLYING_TYPE nodes. */
23178 return unify_success (explain_p);
23180 case ERROR_MARK:
23181 /* Unification fails if we hit an error node. */
23182 return unify_invalid (explain_p);
23184 case INDIRECT_REF:
23185 if (REFERENCE_REF_P (parm))
23187 bool pexp = PACK_EXPANSION_P (arg);
23188 if (pexp)
23189 arg = PACK_EXPANSION_PATTERN (arg);
23190 if (REFERENCE_REF_P (arg))
23191 arg = TREE_OPERAND (arg, 0);
23192 if (pexp)
23193 arg = make_pack_expansion (arg, complain);
23194 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
23195 strict, explain_p);
23197 /* FALLTHRU */
23199 default:
23200 /* An unresolved overload is a nondeduced context. */
23201 if (is_overloaded_fn (parm) || type_unknown_p (parm))
23202 return unify_success (explain_p);
23203 gcc_assert (EXPR_P (parm)
23204 || COMPOUND_LITERAL_P (parm)
23205 || TREE_CODE (parm) == TRAIT_EXPR);
23206 expr:
23207 /* We must be looking at an expression. This can happen with
23208 something like:
23210 template <int I>
23211 void foo(S<I>, S<I + 2>);
23215 template<typename T>
23216 void foo(A<T, T{}>);
23218 This is a "non-deduced context":
23220 [deduct.type]
23222 The non-deduced contexts are:
23224 --A non-type template argument or an array bound in which
23225 a subexpression references a template parameter.
23227 In these cases, we assume deduction succeeded, but don't
23228 actually infer any unifications. */
23230 if (!uses_template_parms (parm)
23231 && !template_args_equal (parm, arg))
23232 return unify_expression_unequal (explain_p, parm, arg);
23233 else
23234 return unify_success (explain_p);
23237 #undef RECUR_AND_CHECK_FAILURE
23239 /* Note that DECL can be defined in this translation unit, if
23240 required. */
23242 static void
23243 mark_definable (tree decl)
23245 tree clone;
23246 DECL_NOT_REALLY_EXTERN (decl) = 1;
23247 FOR_EACH_CLONE (clone, decl)
23248 DECL_NOT_REALLY_EXTERN (clone) = 1;
23251 /* Called if RESULT is explicitly instantiated, or is a member of an
23252 explicitly instantiated class. */
23254 void
23255 mark_decl_instantiated (tree result, int extern_p)
23257 SET_DECL_EXPLICIT_INSTANTIATION (result);
23259 /* If this entity has already been written out, it's too late to
23260 make any modifications. */
23261 if (TREE_ASM_WRITTEN (result))
23262 return;
23264 /* For anonymous namespace we don't need to do anything. */
23265 if (decl_anon_ns_mem_p (result))
23267 gcc_assert (!TREE_PUBLIC (result));
23268 return;
23271 if (TREE_CODE (result) != FUNCTION_DECL)
23272 /* The TREE_PUBLIC flag for function declarations will have been
23273 set correctly by tsubst. */
23274 TREE_PUBLIC (result) = 1;
23276 /* This might have been set by an earlier implicit instantiation. */
23277 DECL_COMDAT (result) = 0;
23279 if (extern_p)
23280 DECL_NOT_REALLY_EXTERN (result) = 0;
23281 else
23283 mark_definable (result);
23284 mark_needed (result);
23285 /* Always make artificials weak. */
23286 if (DECL_ARTIFICIAL (result) && flag_weak)
23287 comdat_linkage (result);
23288 /* For WIN32 we also want to put explicit instantiations in
23289 linkonce sections. */
23290 else if (TREE_PUBLIC (result))
23291 maybe_make_one_only (result);
23292 if (TREE_CODE (result) == FUNCTION_DECL
23293 && DECL_TEMPLATE_INSTANTIATED (result))
23294 /* If the function has already been instantiated, clear DECL_EXTERNAL,
23295 since start_preparsed_function wouldn't have if we had an earlier
23296 extern explicit instantiation. */
23297 DECL_EXTERNAL (result) = 0;
23300 /* If EXTERN_P, then this function will not be emitted -- unless
23301 followed by an explicit instantiation, at which point its linkage
23302 will be adjusted. If !EXTERN_P, then this function will be
23303 emitted here. In neither circumstance do we want
23304 import_export_decl to adjust the linkage. */
23305 DECL_INTERFACE_KNOWN (result) = 1;
23308 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
23309 important template arguments. If any are missing, we check whether
23310 they're important by using error_mark_node for substituting into any
23311 args that were used for partial ordering (the ones between ARGS and END)
23312 and seeing if it bubbles up. */
23314 static bool
23315 check_undeduced_parms (tree targs, tree args, tree end)
23317 bool found = false;
23318 int i;
23319 for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
23320 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
23322 found = true;
23323 TREE_VEC_ELT (targs, i) = error_mark_node;
23325 if (found)
23327 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
23328 if (substed == error_mark_node)
23329 return true;
23331 return false;
23334 /* Given two function templates PAT1 and PAT2, return:
23336 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
23337 -1 if PAT2 is more specialized than PAT1.
23338 0 if neither is more specialized.
23340 LEN indicates the number of parameters we should consider
23341 (defaulted parameters should not be considered).
23343 The 1998 std underspecified function template partial ordering, and
23344 DR214 addresses the issue. We take pairs of arguments, one from
23345 each of the templates, and deduce them against each other. One of
23346 the templates will be more specialized if all the *other*
23347 template's arguments deduce against its arguments and at least one
23348 of its arguments *does* *not* deduce against the other template's
23349 corresponding argument. Deduction is done as for class templates.
23350 The arguments used in deduction have reference and top level cv
23351 qualifiers removed. Iff both arguments were originally reference
23352 types *and* deduction succeeds in both directions, an lvalue reference
23353 wins against an rvalue reference and otherwise the template
23354 with the more cv-qualified argument wins for that pairing (if
23355 neither is more cv-qualified, they both are equal). Unlike regular
23356 deduction, after all the arguments have been deduced in this way,
23357 we do *not* verify the deduced template argument values can be
23358 substituted into non-deduced contexts.
23360 The logic can be a bit confusing here, because we look at deduce1 and
23361 targs1 to see if pat2 is at least as specialized, and vice versa; if we
23362 can find template arguments for pat1 to make arg1 look like arg2, that
23363 means that arg2 is at least as specialized as arg1. */
23366 more_specialized_fn (tree pat1, tree pat2, int len)
23368 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
23369 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
23370 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
23371 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
23372 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
23373 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
23374 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
23375 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
23376 tree origs1, origs2;
23377 bool lose1 = false;
23378 bool lose2 = false;
23380 /* Remove the this parameter from non-static member functions. If
23381 one is a non-static member function and the other is not a static
23382 member function, remove the first parameter from that function
23383 also. This situation occurs for operator functions where we
23384 locate both a member function (with this pointer) and non-member
23385 operator (with explicit first operand). */
23386 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
23388 len--; /* LEN is the number of significant arguments for DECL1 */
23389 args1 = TREE_CHAIN (args1);
23390 if (!DECL_STATIC_FUNCTION_P (decl2))
23391 args2 = TREE_CHAIN (args2);
23393 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
23395 args2 = TREE_CHAIN (args2);
23396 if (!DECL_STATIC_FUNCTION_P (decl1))
23398 len--;
23399 args1 = TREE_CHAIN (args1);
23403 /* If only one is a conversion operator, they are unordered. */
23404 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
23405 return 0;
23407 /* Consider the return type for a conversion function */
23408 if (DECL_CONV_FN_P (decl1))
23410 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
23411 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
23412 len++;
23415 processing_template_decl++;
23417 origs1 = args1;
23418 origs2 = args2;
23420 while (len--
23421 /* Stop when an ellipsis is seen. */
23422 && args1 != NULL_TREE && args2 != NULL_TREE)
23424 tree arg1 = TREE_VALUE (args1);
23425 tree arg2 = TREE_VALUE (args2);
23426 int deduce1, deduce2;
23427 int quals1 = -1;
23428 int quals2 = -1;
23429 int ref1 = 0;
23430 int ref2 = 0;
23432 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
23433 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
23435 /* When both arguments are pack expansions, we need only
23436 unify the patterns themselves. */
23437 arg1 = PACK_EXPANSION_PATTERN (arg1);
23438 arg2 = PACK_EXPANSION_PATTERN (arg2);
23440 /* This is the last comparison we need to do. */
23441 len = 0;
23444 /* DR 1847: If a particular P contains no template-parameters that
23445 participate in template argument deduction, that P is not used to
23446 determine the ordering. */
23447 if (!uses_deducible_template_parms (arg1)
23448 && !uses_deducible_template_parms (arg2))
23449 goto next;
23451 if (TYPE_REF_P (arg1))
23453 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
23454 arg1 = TREE_TYPE (arg1);
23455 quals1 = cp_type_quals (arg1);
23458 if (TYPE_REF_P (arg2))
23460 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
23461 arg2 = TREE_TYPE (arg2);
23462 quals2 = cp_type_quals (arg2);
23465 arg1 = TYPE_MAIN_VARIANT (arg1);
23466 arg2 = TYPE_MAIN_VARIANT (arg2);
23468 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
23470 int i, len2 = remaining_arguments (args2);
23471 tree parmvec = make_tree_vec (1);
23472 tree argvec = make_tree_vec (len2);
23473 tree ta = args2;
23475 /* Setup the parameter vector, which contains only ARG1. */
23476 TREE_VEC_ELT (parmvec, 0) = arg1;
23478 /* Setup the argument vector, which contains the remaining
23479 arguments. */
23480 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
23481 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
23483 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
23484 argvec, DEDUCE_EXACT,
23485 /*subr=*/true, /*explain_p=*/false)
23486 == 0);
23488 /* We cannot deduce in the other direction, because ARG1 is
23489 a pack expansion but ARG2 is not. */
23490 deduce2 = 0;
23492 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
23494 int i, len1 = remaining_arguments (args1);
23495 tree parmvec = make_tree_vec (1);
23496 tree argvec = make_tree_vec (len1);
23497 tree ta = args1;
23499 /* Setup the parameter vector, which contains only ARG1. */
23500 TREE_VEC_ELT (parmvec, 0) = arg2;
23502 /* Setup the argument vector, which contains the remaining
23503 arguments. */
23504 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
23505 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
23507 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
23508 argvec, DEDUCE_EXACT,
23509 /*subr=*/true, /*explain_p=*/false)
23510 == 0);
23512 /* We cannot deduce in the other direction, because ARG2 is
23513 a pack expansion but ARG1 is not.*/
23514 deduce1 = 0;
23517 else
23519 /* The normal case, where neither argument is a pack
23520 expansion. */
23521 deduce1 = (unify (tparms1, targs1, arg1, arg2,
23522 UNIFY_ALLOW_NONE, /*explain_p=*/false)
23523 == 0);
23524 deduce2 = (unify (tparms2, targs2, arg2, arg1,
23525 UNIFY_ALLOW_NONE, /*explain_p=*/false)
23526 == 0);
23529 /* If we couldn't deduce arguments for tparms1 to make arg1 match
23530 arg2, then arg2 is not as specialized as arg1. */
23531 if (!deduce1)
23532 lose2 = true;
23533 if (!deduce2)
23534 lose1 = true;
23536 /* "If, for a given type, deduction succeeds in both directions
23537 (i.e., the types are identical after the transformations above)
23538 and both P and A were reference types (before being replaced with
23539 the type referred to above):
23540 - if the type from the argument template was an lvalue reference and
23541 the type from the parameter template was not, the argument type is
23542 considered to be more specialized than the other; otherwise,
23543 - if the type from the argument template is more cv-qualified
23544 than the type from the parameter template (as described above),
23545 the argument type is considered to be more specialized than the other;
23546 otherwise,
23547 - neither type is more specialized than the other." */
23549 if (deduce1 && deduce2)
23551 if (ref1 && ref2 && ref1 != ref2)
23553 if (ref1 > ref2)
23554 lose1 = true;
23555 else
23556 lose2 = true;
23558 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
23560 if ((quals1 & quals2) == quals2)
23561 lose2 = true;
23562 if ((quals1 & quals2) == quals1)
23563 lose1 = true;
23567 if (lose1 && lose2)
23568 /* We've failed to deduce something in either direction.
23569 These must be unordered. */
23570 break;
23572 next:
23574 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
23575 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
23576 /* We have already processed all of the arguments in our
23577 handing of the pack expansion type. */
23578 len = 0;
23580 args1 = TREE_CHAIN (args1);
23581 args2 = TREE_CHAIN (args2);
23584 /* "In most cases, all template parameters must have values in order for
23585 deduction to succeed, but for partial ordering purposes a template
23586 parameter may remain without a value provided it is not used in the
23587 types being used for partial ordering."
23589 Thus, if we are missing any of the targs1 we need to substitute into
23590 origs1, then pat2 is not as specialized as pat1. This can happen when
23591 there is a nondeduced context. */
23592 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
23593 lose2 = true;
23594 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
23595 lose1 = true;
23597 processing_template_decl--;
23599 /* If both deductions succeed, the partial ordering selects the more
23600 constrained template. */
23601 if (!lose1 && !lose2)
23603 int winner = more_constrained (decl1, decl2);
23604 if (winner > 0)
23605 lose2 = true;
23606 else if (winner < 0)
23607 lose1 = true;
23610 /* All things being equal, if the next argument is a pack expansion
23611 for one function but not for the other, prefer the
23612 non-variadic function. FIXME this is bogus; see c++/41958. */
23613 if (lose1 == lose2
23614 && args1 && TREE_VALUE (args1)
23615 && args2 && TREE_VALUE (args2))
23617 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
23618 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
23621 if (lose1 == lose2)
23622 return 0;
23623 else if (!lose1)
23624 return 1;
23625 else
23626 return -1;
23629 /* Determine which of two partial specializations of TMPL is more
23630 specialized.
23632 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
23633 to the first partial specialization. The TREE_PURPOSE is the
23634 innermost set of template parameters for the partial
23635 specialization. PAT2 is similar, but for the second template.
23637 Return 1 if the first partial specialization is more specialized;
23638 -1 if the second is more specialized; 0 if neither is more
23639 specialized.
23641 See [temp.class.order] for information about determining which of
23642 two templates is more specialized. */
23644 static int
23645 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
23647 tree targs;
23648 int winner = 0;
23649 bool any_deductions = false;
23651 tree tmpl1 = TREE_VALUE (pat1);
23652 tree tmpl2 = TREE_VALUE (pat2);
23653 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
23654 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
23656 /* Just like what happens for functions, if we are ordering between
23657 different template specializations, we may encounter dependent
23658 types in the arguments, and we need our dependency check functions
23659 to behave correctly. */
23660 ++processing_template_decl;
23661 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
23662 if (targs)
23664 --winner;
23665 any_deductions = true;
23668 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
23669 if (targs)
23671 ++winner;
23672 any_deductions = true;
23674 --processing_template_decl;
23676 /* If both deductions succeed, the partial ordering selects the more
23677 constrained template. */
23678 if (!winner && any_deductions)
23679 winner = more_constrained (tmpl1, tmpl2);
23681 /* In the case of a tie where at least one of the templates
23682 has a parameter pack at the end, the template with the most
23683 non-packed parameters wins. */
23684 if (winner == 0
23685 && any_deductions
23686 && (template_args_variadic_p (TREE_PURPOSE (pat1))
23687 || template_args_variadic_p (TREE_PURPOSE (pat2))))
23689 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
23690 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
23691 int len1 = TREE_VEC_LENGTH (args1);
23692 int len2 = TREE_VEC_LENGTH (args2);
23694 /* We don't count the pack expansion at the end. */
23695 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
23696 --len1;
23697 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
23698 --len2;
23700 if (len1 > len2)
23701 return 1;
23702 else if (len1 < len2)
23703 return -1;
23706 return winner;
23709 /* Return the template arguments that will produce the function signature
23710 DECL from the function template FN, with the explicit template
23711 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
23712 also match. Return NULL_TREE if no satisfactory arguments could be
23713 found. */
23715 static tree
23716 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
23718 int ntparms = DECL_NTPARMS (fn);
23719 tree targs = make_tree_vec (ntparms);
23720 tree decl_type = TREE_TYPE (decl);
23721 tree decl_arg_types;
23722 tree *args;
23723 unsigned int nargs, ix;
23724 tree arg;
23726 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
23728 /* Never do unification on the 'this' parameter. */
23729 decl_arg_types = skip_artificial_parms_for (decl,
23730 TYPE_ARG_TYPES (decl_type));
23732 nargs = list_length (decl_arg_types);
23733 args = XALLOCAVEC (tree, nargs);
23734 for (arg = decl_arg_types, ix = 0;
23735 arg != NULL_TREE && arg != void_list_node;
23736 arg = TREE_CHAIN (arg), ++ix)
23737 args[ix] = TREE_VALUE (arg);
23739 if (fn_type_unification (fn, explicit_args, targs,
23740 args, ix,
23741 (check_rettype || DECL_CONV_FN_P (fn)
23742 ? TREE_TYPE (decl_type) : NULL_TREE),
23743 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
23744 /*explain_p=*/false,
23745 /*decltype*/false)
23746 == error_mark_node)
23747 return NULL_TREE;
23749 return targs;
23752 /* Return the innermost template arguments that, when applied to a partial
23753 specialization SPEC_TMPL of TMPL, yield the ARGS.
23755 For example, suppose we have:
23757 template <class T, class U> struct S {};
23758 template <class T> struct S<T*, int> {};
23760 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
23761 partial specialization and the ARGS will be {double*, int}. The resulting
23762 vector will be {double}, indicating that `T' is bound to `double'. */
23764 static tree
23765 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
23767 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
23768 tree spec_args
23769 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
23770 int i, ntparms = TREE_VEC_LENGTH (tparms);
23771 tree deduced_args;
23772 tree innermost_deduced_args;
23774 innermost_deduced_args = make_tree_vec (ntparms);
23775 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
23777 deduced_args = copy_node (args);
23778 SET_TMPL_ARGS_LEVEL (deduced_args,
23779 TMPL_ARGS_DEPTH (deduced_args),
23780 innermost_deduced_args);
23782 else
23783 deduced_args = innermost_deduced_args;
23785 bool tried_array_deduction = (cxx_dialect < cxx17);
23786 again:
23787 if (unify (tparms, deduced_args,
23788 INNERMOST_TEMPLATE_ARGS (spec_args),
23789 INNERMOST_TEMPLATE_ARGS (args),
23790 UNIFY_ALLOW_NONE, /*explain_p=*/false))
23791 return NULL_TREE;
23793 for (i = 0; i < ntparms; ++i)
23794 if (! TREE_VEC_ELT (innermost_deduced_args, i))
23796 if (!tried_array_deduction)
23798 try_array_deduction (tparms, innermost_deduced_args,
23799 INNERMOST_TEMPLATE_ARGS (spec_args));
23800 tried_array_deduction = true;
23801 if (TREE_VEC_ELT (innermost_deduced_args, i))
23802 goto again;
23804 return NULL_TREE;
23807 if (!push_tinst_level (spec_tmpl, deduced_args))
23809 excessive_deduction_depth = true;
23810 return NULL_TREE;
23813 /* Verify that nondeduced template arguments agree with the type
23814 obtained from argument deduction.
23816 For example:
23818 struct A { typedef int X; };
23819 template <class T, class U> struct C {};
23820 template <class T> struct C<T, typename T::X> {};
23822 Then with the instantiation `C<A, int>', we can deduce that
23823 `T' is `A' but unify () does not check whether `typename T::X'
23824 is `int'. */
23825 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
23827 if (spec_args != error_mark_node)
23828 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
23829 INNERMOST_TEMPLATE_ARGS (spec_args),
23830 tmpl, tf_none, false, false);
23832 pop_tinst_level ();
23834 if (spec_args == error_mark_node
23835 /* We only need to check the innermost arguments; the other
23836 arguments will always agree. */
23837 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
23838 INNERMOST_TEMPLATE_ARGS (args)))
23839 return NULL_TREE;
23841 /* Now that we have bindings for all of the template arguments,
23842 ensure that the arguments deduced for the template template
23843 parameters have compatible template parameter lists. See the use
23844 of template_template_parm_bindings_ok_p in fn_type_unification
23845 for more information. */
23846 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
23847 return NULL_TREE;
23849 return deduced_args;
23852 // Compare two function templates T1 and T2 by deducing bindings
23853 // from one against the other. If both deductions succeed, compare
23854 // constraints to see which is more constrained.
23855 static int
23856 more_specialized_inst (tree t1, tree t2)
23858 int fate = 0;
23859 int count = 0;
23861 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
23863 --fate;
23864 ++count;
23867 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
23869 ++fate;
23870 ++count;
23873 // If both deductions succeed, then one may be more constrained.
23874 if (count == 2 && fate == 0)
23875 fate = more_constrained (t1, t2);
23877 return fate;
23880 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
23881 Return the TREE_LIST node with the most specialized template, if
23882 any. If there is no most specialized template, the error_mark_node
23883 is returned.
23885 Note that this function does not look at, or modify, the
23886 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
23887 returned is one of the elements of INSTANTIATIONS, callers may
23888 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
23889 and retrieve it from the value returned. */
23891 tree
23892 most_specialized_instantiation (tree templates)
23894 tree fn, champ;
23896 ++processing_template_decl;
23898 champ = templates;
23899 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
23901 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
23902 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
23903 if (fate == -1)
23904 champ = fn;
23905 else if (!fate)
23907 /* Equally specialized, move to next function. If there
23908 is no next function, nothing's most specialized. */
23909 fn = TREE_CHAIN (fn);
23910 champ = fn;
23911 if (!fn)
23912 break;
23916 if (champ)
23917 /* Now verify that champ is better than everything earlier in the
23918 instantiation list. */
23919 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
23920 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
23922 champ = NULL_TREE;
23923 break;
23927 processing_template_decl--;
23929 if (!champ)
23930 return error_mark_node;
23932 return champ;
23935 /* If DECL is a specialization of some template, return the most
23936 general such template. Otherwise, returns NULL_TREE.
23938 For example, given:
23940 template <class T> struct S { template <class U> void f(U); };
23942 if TMPL is `template <class U> void S<int>::f(U)' this will return
23943 the full template. This function will not trace past partial
23944 specializations, however. For example, given in addition:
23946 template <class T> struct S<T*> { template <class U> void f(U); };
23948 if TMPL is `template <class U> void S<int*>::f(U)' this will return
23949 `template <class T> template <class U> S<T*>::f(U)'. */
23951 tree
23952 most_general_template (tree decl)
23954 if (TREE_CODE (decl) != TEMPLATE_DECL)
23956 if (tree tinfo = get_template_info (decl))
23957 decl = TI_TEMPLATE (tinfo);
23958 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
23959 template friend, or a FIELD_DECL for a capture pack. */
23960 if (TREE_CODE (decl) != TEMPLATE_DECL)
23961 return NULL_TREE;
23964 /* Look for more and more general templates. */
23965 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
23967 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
23968 (See cp-tree.h for details.) */
23969 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
23970 break;
23972 if (CLASS_TYPE_P (TREE_TYPE (decl))
23973 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
23974 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
23975 break;
23977 /* Stop if we run into an explicitly specialized class template. */
23978 if (!DECL_NAMESPACE_SCOPE_P (decl)
23979 && DECL_CONTEXT (decl)
23980 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
23981 break;
23983 decl = DECL_TI_TEMPLATE (decl);
23986 return decl;
23989 /* Return the most specialized of the template partial specializations
23990 which can produce TARGET, a specialization of some class or variable
23991 template. The value returned is actually a TREE_LIST; the TREE_VALUE is
23992 a TEMPLATE_DECL node corresponding to the partial specialization, while
23993 the TREE_PURPOSE is the set of template arguments that must be
23994 substituted into the template pattern in order to generate TARGET.
23996 If the choice of partial specialization is ambiguous, a diagnostic
23997 is issued, and the error_mark_node is returned. If there are no
23998 partial specializations matching TARGET, then NULL_TREE is
23999 returned, indicating that the primary template should be used. */
24001 static tree
24002 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
24004 tree list = NULL_TREE;
24005 tree t;
24006 tree champ;
24007 int fate;
24008 bool ambiguous_p;
24009 tree outer_args = NULL_TREE;
24010 tree tmpl, args;
24012 if (TYPE_P (target))
24014 tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
24015 tmpl = TI_TEMPLATE (tinfo);
24016 args = TI_ARGS (tinfo);
24018 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
24020 tmpl = TREE_OPERAND (target, 0);
24021 args = TREE_OPERAND (target, 1);
24023 else if (VAR_P (target))
24025 tree tinfo = DECL_TEMPLATE_INFO (target);
24026 tmpl = TI_TEMPLATE (tinfo);
24027 args = TI_ARGS (tinfo);
24029 else
24030 gcc_unreachable ();
24032 tree main_tmpl = most_general_template (tmpl);
24034 /* For determining which partial specialization to use, only the
24035 innermost args are interesting. */
24036 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24038 outer_args = strip_innermost_template_args (args, 1);
24039 args = INNERMOST_TEMPLATE_ARGS (args);
24042 /* The caller hasn't called push_to_top_level yet, but we need
24043 get_partial_spec_bindings to be done in non-template context so that we'll
24044 fully resolve everything. */
24045 processing_template_decl_sentinel ptds;
24047 for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
24049 tree spec_args;
24050 tree spec_tmpl = TREE_VALUE (t);
24052 if (outer_args)
24054 /* Substitute in the template args from the enclosing class. */
24055 ++processing_template_decl;
24056 spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
24057 --processing_template_decl;
24060 if (spec_tmpl == error_mark_node)
24061 return error_mark_node;
24063 spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
24064 if (spec_args)
24066 if (outer_args)
24067 spec_args = add_to_template_args (outer_args, spec_args);
24069 /* Keep the candidate only if the constraints are satisfied,
24070 or if we're not compiling with concepts. */
24071 if (!flag_concepts
24072 || constraints_satisfied_p (spec_tmpl, spec_args))
24074 list = tree_cons (spec_args, TREE_VALUE (t), list);
24075 TREE_TYPE (list) = TREE_TYPE (t);
24080 if (! list)
24081 return NULL_TREE;
24083 ambiguous_p = false;
24084 t = list;
24085 champ = t;
24086 t = TREE_CHAIN (t);
24087 for (; t; t = TREE_CHAIN (t))
24089 fate = more_specialized_partial_spec (tmpl, champ, t);
24090 if (fate == 1)
24092 else
24094 if (fate == 0)
24096 t = TREE_CHAIN (t);
24097 if (! t)
24099 ambiguous_p = true;
24100 break;
24103 champ = t;
24107 if (!ambiguous_p)
24108 for (t = list; t && t != champ; t = TREE_CHAIN (t))
24110 fate = more_specialized_partial_spec (tmpl, champ, t);
24111 if (fate != 1)
24113 ambiguous_p = true;
24114 break;
24118 if (ambiguous_p)
24120 const char *str;
24121 char *spaces = NULL;
24122 if (!(complain & tf_error))
24123 return error_mark_node;
24124 if (TYPE_P (target))
24125 error ("ambiguous template instantiation for %q#T", target);
24126 else
24127 error ("ambiguous template instantiation for %q#D", target);
24128 str = ngettext ("candidate is:", "candidates are:", list_length (list));
24129 for (t = list; t; t = TREE_CHAIN (t))
24131 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
24132 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
24133 "%s %#qS", spaces ? spaces : str, subst);
24134 spaces = spaces ? spaces : get_spaces (str);
24136 free (spaces);
24137 return error_mark_node;
24140 return champ;
24143 /* Explicitly instantiate DECL. */
24145 void
24146 do_decl_instantiation (tree decl, tree storage)
24148 tree result = NULL_TREE;
24149 int extern_p = 0;
24151 if (!decl || decl == error_mark_node)
24152 /* An error occurred, for which grokdeclarator has already issued
24153 an appropriate message. */
24154 return;
24155 else if (! DECL_LANG_SPECIFIC (decl))
24157 error ("explicit instantiation of non-template %q#D", decl);
24158 return;
24160 else if (DECL_DECLARED_CONCEPT_P (decl))
24162 if (VAR_P (decl))
24163 error ("explicit instantiation of variable concept %q#D", decl);
24164 else
24165 error ("explicit instantiation of function concept %q#D", decl);
24166 return;
24169 bool var_templ = (DECL_TEMPLATE_INFO (decl)
24170 && variable_template_p (DECL_TI_TEMPLATE (decl)));
24172 if (VAR_P (decl) && !var_templ)
24174 /* There is an asymmetry here in the way VAR_DECLs and
24175 FUNCTION_DECLs are handled by grokdeclarator. In the case of
24176 the latter, the DECL we get back will be marked as a
24177 template instantiation, and the appropriate
24178 DECL_TEMPLATE_INFO will be set up. This does not happen for
24179 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
24180 should handle VAR_DECLs as it currently handles
24181 FUNCTION_DECLs. */
24182 if (!DECL_CLASS_SCOPE_P (decl))
24184 error ("%qD is not a static data member of a class template", decl);
24185 return;
24187 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
24188 if (!result || !VAR_P (result))
24190 error ("no matching template for %qD found", decl);
24191 return;
24193 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
24195 error ("type %qT for explicit instantiation %qD does not match "
24196 "declared type %qT", TREE_TYPE (result), decl,
24197 TREE_TYPE (decl));
24198 return;
24201 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
24203 error ("explicit instantiation of %q#D", decl);
24204 return;
24206 else
24207 result = decl;
24209 /* Check for various error cases. Note that if the explicit
24210 instantiation is valid the RESULT will currently be marked as an
24211 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
24212 until we get here. */
24214 if (DECL_TEMPLATE_SPECIALIZATION (result))
24216 /* DR 259 [temp.spec].
24218 Both an explicit instantiation and a declaration of an explicit
24219 specialization shall not appear in a program unless the explicit
24220 instantiation follows a declaration of the explicit specialization.
24222 For a given set of template parameters, if an explicit
24223 instantiation of a template appears after a declaration of an
24224 explicit specialization for that template, the explicit
24225 instantiation has no effect. */
24226 return;
24228 else if (DECL_EXPLICIT_INSTANTIATION (result))
24230 /* [temp.spec]
24232 No program shall explicitly instantiate any template more
24233 than once.
24235 We check DECL_NOT_REALLY_EXTERN so as not to complain when
24236 the first instantiation was `extern' and the second is not,
24237 and EXTERN_P for the opposite case. */
24238 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
24239 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
24240 /* If an "extern" explicit instantiation follows an ordinary
24241 explicit instantiation, the template is instantiated. */
24242 if (extern_p)
24243 return;
24245 else if (!DECL_IMPLICIT_INSTANTIATION (result))
24247 error ("no matching template for %qD found", result);
24248 return;
24250 else if (!DECL_TEMPLATE_INFO (result))
24252 permerror (input_location, "explicit instantiation of non-template %q#D", result);
24253 return;
24256 if (storage == NULL_TREE)
24258 else if (storage == ridpointers[(int) RID_EXTERN])
24260 if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
24261 pedwarn (input_location, OPT_Wpedantic,
24262 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
24263 "instantiations");
24264 extern_p = 1;
24266 else
24267 error ("storage class %qD applied to template instantiation", storage);
24269 check_explicit_instantiation_namespace (result);
24270 mark_decl_instantiated (result, extern_p);
24271 if (! extern_p)
24272 instantiate_decl (result, /*defer_ok=*/true,
24273 /*expl_inst_class_mem_p=*/false);
24276 static void
24277 mark_class_instantiated (tree t, int extern_p)
24279 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
24280 SET_CLASSTYPE_INTERFACE_KNOWN (t);
24281 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
24282 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
24283 if (! extern_p)
24285 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
24286 rest_of_type_compilation (t, 1);
24290 /* Called from do_type_instantiation through binding_table_foreach to
24291 do recursive instantiation for the type bound in ENTRY. */
24292 static void
24293 bt_instantiate_type_proc (binding_entry entry, void *data)
24295 tree storage = *(tree *) data;
24297 if (MAYBE_CLASS_TYPE_P (entry->type)
24298 && CLASSTYPE_TEMPLATE_INFO (entry->type)
24299 && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
24300 do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
24303 /* Perform an explicit instantiation of template class T. STORAGE, if
24304 non-null, is the RID for extern, inline or static. COMPLAIN is
24305 nonzero if this is called from the parser, zero if called recursively,
24306 since the standard is unclear (as detailed below). */
24308 void
24309 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
24311 int extern_p = 0;
24312 int nomem_p = 0;
24313 int static_p = 0;
24314 int previous_instantiation_extern_p = 0;
24316 if (TREE_CODE (t) == TYPE_DECL)
24317 t = TREE_TYPE (t);
24319 if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
24321 tree tmpl =
24322 (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
24323 if (tmpl)
24324 error ("explicit instantiation of non-class template %qD", tmpl);
24325 else
24326 error ("explicit instantiation of non-template type %qT", t);
24327 return;
24330 complete_type (t);
24332 if (!COMPLETE_TYPE_P (t))
24334 if (complain & tf_error)
24335 error ("explicit instantiation of %q#T before definition of template",
24337 return;
24340 if (storage != NULL_TREE)
24342 if (!in_system_header_at (input_location))
24344 if (storage == ridpointers[(int) RID_EXTERN])
24346 if (cxx_dialect == cxx98)
24347 pedwarn (input_location, OPT_Wpedantic,
24348 "ISO C++ 1998 forbids the use of %<extern%> on "
24349 "explicit instantiations");
24351 else
24352 pedwarn (input_location, OPT_Wpedantic,
24353 "ISO C++ forbids the use of %qE"
24354 " on explicit instantiations", storage);
24357 if (storage == ridpointers[(int) RID_INLINE])
24358 nomem_p = 1;
24359 else if (storage == ridpointers[(int) RID_EXTERN])
24360 extern_p = 1;
24361 else if (storage == ridpointers[(int) RID_STATIC])
24362 static_p = 1;
24363 else
24365 error ("storage class %qD applied to template instantiation",
24366 storage);
24367 extern_p = 0;
24371 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
24373 /* DR 259 [temp.spec].
24375 Both an explicit instantiation and a declaration of an explicit
24376 specialization shall not appear in a program unless the explicit
24377 instantiation follows a declaration of the explicit specialization.
24379 For a given set of template parameters, if an explicit
24380 instantiation of a template appears after a declaration of an
24381 explicit specialization for that template, the explicit
24382 instantiation has no effect. */
24383 return;
24385 else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
24387 /* [temp.spec]
24389 No program shall explicitly instantiate any template more
24390 than once.
24392 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
24393 instantiation was `extern'. If EXTERN_P then the second is.
24394 These cases are OK. */
24395 previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
24397 if (!previous_instantiation_extern_p && !extern_p
24398 && (complain & tf_error))
24399 permerror (input_location, "duplicate explicit instantiation of %q#T", t);
24401 /* If we've already instantiated the template, just return now. */
24402 if (!CLASSTYPE_INTERFACE_ONLY (t))
24403 return;
24406 check_explicit_instantiation_namespace (TYPE_NAME (t));
24407 mark_class_instantiated (t, extern_p);
24409 if (nomem_p)
24410 return;
24412 /* In contrast to implicit instantiation, where only the
24413 declarations, and not the definitions, of members are
24414 instantiated, we have here:
24416 [temp.explicit]
24418 The explicit instantiation of a class template specialization
24419 implies the instantiation of all of its members not
24420 previously explicitly specialized in the translation unit
24421 containing the explicit instantiation.
24423 Of course, we can't instantiate member template classes, since we
24424 don't have any arguments for them. Note that the standard is
24425 unclear on whether the instantiation of the members are
24426 *explicit* instantiations or not. However, the most natural
24427 interpretation is that it should be an explicit
24428 instantiation. */
24429 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
24430 if ((VAR_P (fld)
24431 || (TREE_CODE (fld) == FUNCTION_DECL
24432 && !static_p
24433 && user_provided_p (fld)))
24434 && DECL_TEMPLATE_INSTANTIATION (fld))
24436 mark_decl_instantiated (fld, extern_p);
24437 if (! extern_p)
24438 instantiate_decl (fld, /*defer_ok=*/true,
24439 /*expl_inst_class_mem_p=*/true);
24442 if (CLASSTYPE_NESTED_UTDS (t))
24443 binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
24444 bt_instantiate_type_proc, &storage);
24447 /* Given a function DECL, which is a specialization of TMPL, modify
24448 DECL to be a re-instantiation of TMPL with the same template
24449 arguments. TMPL should be the template into which tsubst'ing
24450 should occur for DECL, not the most general template.
24452 One reason for doing this is a scenario like this:
24454 template <class T>
24455 void f(const T&, int i);
24457 void g() { f(3, 7); }
24459 template <class T>
24460 void f(const T& t, const int i) { }
24462 Note that when the template is first instantiated, with
24463 instantiate_template, the resulting DECL will have no name for the
24464 first parameter, and the wrong type for the second. So, when we go
24465 to instantiate the DECL, we regenerate it. */
24467 static void
24468 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
24470 /* The arguments used to instantiate DECL, from the most general
24471 template. */
24472 tree code_pattern;
24474 code_pattern = DECL_TEMPLATE_RESULT (tmpl);
24476 /* Make sure that we can see identifiers, and compute access
24477 correctly. */
24478 push_access_scope (decl);
24480 if (TREE_CODE (decl) == FUNCTION_DECL)
24482 tree decl_parm;
24483 tree pattern_parm;
24484 tree specs;
24485 int args_depth;
24486 int parms_depth;
24488 args_depth = TMPL_ARGS_DEPTH (args);
24489 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
24490 if (args_depth > parms_depth)
24491 args = get_innermost_template_args (args, parms_depth);
24493 /* Instantiate a dynamic exception-specification. noexcept will be
24494 handled below. */
24495 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
24496 if (TREE_VALUE (raises))
24498 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
24499 args, tf_error, NULL_TREE,
24500 /*defer_ok*/false);
24501 if (specs && specs != error_mark_node)
24502 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
24503 specs);
24506 /* Merge parameter declarations. */
24507 decl_parm = skip_artificial_parms_for (decl,
24508 DECL_ARGUMENTS (decl));
24509 pattern_parm
24510 = skip_artificial_parms_for (code_pattern,
24511 DECL_ARGUMENTS (code_pattern));
24512 while (decl_parm && !DECL_PACK_P (pattern_parm))
24514 tree parm_type;
24515 tree attributes;
24517 if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
24518 DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
24519 parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
24520 NULL_TREE);
24521 parm_type = type_decays_to (parm_type);
24522 if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
24523 TREE_TYPE (decl_parm) = parm_type;
24524 attributes = DECL_ATTRIBUTES (pattern_parm);
24525 if (DECL_ATTRIBUTES (decl_parm) != attributes)
24527 DECL_ATTRIBUTES (decl_parm) = attributes;
24528 cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
24530 decl_parm = DECL_CHAIN (decl_parm);
24531 pattern_parm = DECL_CHAIN (pattern_parm);
24533 /* Merge any parameters that match with the function parameter
24534 pack. */
24535 if (pattern_parm && DECL_PACK_P (pattern_parm))
24537 int i, len;
24538 tree expanded_types;
24539 /* Expand the TYPE_PACK_EXPANSION that provides the types for
24540 the parameters in this function parameter pack. */
24541 expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
24542 args, tf_error, NULL_TREE);
24543 len = TREE_VEC_LENGTH (expanded_types);
24544 for (i = 0; i < len; i++)
24546 tree parm_type;
24547 tree attributes;
24549 if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
24550 /* Rename the parameter to include the index. */
24551 DECL_NAME (decl_parm) =
24552 make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
24553 parm_type = TREE_VEC_ELT (expanded_types, i);
24554 parm_type = type_decays_to (parm_type);
24555 if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
24556 TREE_TYPE (decl_parm) = parm_type;
24557 attributes = DECL_ATTRIBUTES (pattern_parm);
24558 if (DECL_ATTRIBUTES (decl_parm) != attributes)
24560 DECL_ATTRIBUTES (decl_parm) = attributes;
24561 cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
24563 decl_parm = DECL_CHAIN (decl_parm);
24566 /* Merge additional specifiers from the CODE_PATTERN. */
24567 if (DECL_DECLARED_INLINE_P (code_pattern)
24568 && !DECL_DECLARED_INLINE_P (decl))
24569 DECL_DECLARED_INLINE_P (decl) = 1;
24571 maybe_instantiate_noexcept (decl, tf_error);
24573 else if (VAR_P (decl))
24575 start_lambda_scope (decl);
24576 DECL_INITIAL (decl) =
24577 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
24578 tf_error, DECL_TI_TEMPLATE (decl));
24579 finish_lambda_scope ();
24580 if (VAR_HAD_UNKNOWN_BOUND (decl))
24581 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
24582 tf_error, DECL_TI_TEMPLATE (decl));
24584 else
24585 gcc_unreachable ();
24587 pop_access_scope (decl);
24590 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
24591 substituted to get DECL. */
24593 tree
24594 template_for_substitution (tree decl)
24596 tree tmpl = DECL_TI_TEMPLATE (decl);
24598 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
24599 for the instantiation. This is not always the most general
24600 template. Consider, for example:
24602 template <class T>
24603 struct S { template <class U> void f();
24604 template <> void f<int>(); };
24606 and an instantiation of S<double>::f<int>. We want TD to be the
24607 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
24608 while (/* An instantiation cannot have a definition, so we need a
24609 more general template. */
24610 DECL_TEMPLATE_INSTANTIATION (tmpl)
24611 /* We must also deal with friend templates. Given:
24613 template <class T> struct S {
24614 template <class U> friend void f() {};
24617 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
24618 so far as the language is concerned, but that's still
24619 where we get the pattern for the instantiation from. On
24620 other hand, if the definition comes outside the class, say:
24622 template <class T> struct S {
24623 template <class U> friend void f();
24625 template <class U> friend void f() {}
24627 we don't need to look any further. That's what the check for
24628 DECL_INITIAL is for. */
24629 || (TREE_CODE (decl) == FUNCTION_DECL
24630 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
24631 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
24633 /* The present template, TD, should not be a definition. If it
24634 were a definition, we should be using it! Note that we
24635 cannot restructure the loop to just keep going until we find
24636 a template with a definition, since that might go too far if
24637 a specialization was declared, but not defined. */
24639 /* Fetch the more general template. */
24640 tmpl = DECL_TI_TEMPLATE (tmpl);
24643 return tmpl;
24646 /* Returns true if we need to instantiate this template instance even if we
24647 know we aren't going to emit it. */
24649 bool
24650 always_instantiate_p (tree decl)
24652 /* We always instantiate inline functions so that we can inline them. An
24653 explicit instantiation declaration prohibits implicit instantiation of
24654 non-inline functions. With high levels of optimization, we would
24655 normally inline non-inline functions -- but we're not allowed to do
24656 that for "extern template" functions. Therefore, we check
24657 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
24658 return ((TREE_CODE (decl) == FUNCTION_DECL
24659 && (DECL_DECLARED_INLINE_P (decl)
24660 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
24661 /* And we need to instantiate static data members so that
24662 their initializers are available in integral constant
24663 expressions. */
24664 || (VAR_P (decl)
24665 && decl_maybe_constant_var_p (decl)));
24668 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
24669 instantiate it now, modifying TREE_TYPE (fn). Returns false on
24670 error, true otherwise. */
24672 bool
24673 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
24675 tree fntype, spec, noex, clone;
24677 /* Don't instantiate a noexcept-specification from template context. */
24678 if (processing_template_decl
24679 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
24680 return true;
24682 if (DECL_CLONED_FUNCTION_P (fn))
24683 fn = DECL_CLONED_FUNCTION (fn);
24685 tree orig_fn = NULL_TREE;
24686 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
24687 its FUNCTION_DECL for the rest of this function -- push_access_scope
24688 doesn't accept TEMPLATE_DECLs. */
24689 if (DECL_FUNCTION_TEMPLATE_P (fn))
24691 orig_fn = fn;
24692 fn = DECL_TEMPLATE_RESULT (fn);
24695 fntype = TREE_TYPE (fn);
24696 spec = TYPE_RAISES_EXCEPTIONS (fntype);
24698 if (!spec || !TREE_PURPOSE (spec))
24699 return true;
24701 noex = TREE_PURPOSE (spec);
24703 if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
24705 static hash_set<tree>* fns = new hash_set<tree>;
24706 bool added = false;
24707 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
24709 spec = get_defaulted_eh_spec (fn, complain);
24710 if (spec == error_mark_node)
24711 /* This might have failed because of an unparsed DMI, so
24712 let's try again later. */
24713 return false;
24715 else if (!(added = !fns->add (fn)))
24717 /* If hash_set::add returns true, the element was already there. */
24718 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
24719 DECL_SOURCE_LOCATION (fn));
24720 error_at (loc,
24721 "exception specification of %qD depends on itself",
24722 fn);
24723 spec = noexcept_false_spec;
24725 else if (push_tinst_level (fn))
24727 push_to_top_level ();
24728 push_access_scope (fn);
24729 push_deferring_access_checks (dk_no_deferred);
24730 input_location = DECL_SOURCE_LOCATION (fn);
24732 /* If needed, set current_class_ptr for the benefit of
24733 tsubst_copy/PARM_DECL. */
24734 tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
24735 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
24737 tree this_parm = DECL_ARGUMENTS (tdecl);
24738 current_class_ptr = NULL_TREE;
24739 current_class_ref = cp_build_fold_indirect_ref (this_parm);
24740 current_class_ptr = this_parm;
24743 /* If this function is represented by a TEMPLATE_DECL, then
24744 the deferred noexcept-specification might still contain
24745 dependent types, even after substitution. And we need the
24746 dependency check functions to work in build_noexcept_spec. */
24747 if (orig_fn)
24748 ++processing_template_decl;
24750 /* Do deferred instantiation of the noexcept-specifier. */
24751 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
24752 DEFERRED_NOEXCEPT_ARGS (noex),
24753 tf_warning_or_error, fn,
24754 /*function_p=*/false,
24755 /*i_c_e_p=*/true);
24757 /* Build up the noexcept-specification. */
24758 spec = build_noexcept_spec (noex, tf_warning_or_error);
24760 if (orig_fn)
24761 --processing_template_decl;
24763 pop_deferring_access_checks ();
24764 pop_access_scope (fn);
24765 pop_tinst_level ();
24766 pop_from_top_level ();
24768 else
24769 spec = noexcept_false_spec;
24771 if (added)
24772 fns->remove (fn);
24774 if (spec == error_mark_node)
24776 /* This failed with a hard error, so let's go with false. */
24777 gcc_assert (seen_error ());
24778 spec = noexcept_false_spec;
24781 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
24782 if (orig_fn)
24783 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
24786 FOR_EACH_CLONE (clone, fn)
24788 if (TREE_TYPE (clone) == fntype)
24789 TREE_TYPE (clone) = TREE_TYPE (fn);
24790 else
24791 TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
24794 return true;
24797 /* We're starting to process the function INST, an instantiation of PATTERN;
24798 add their parameters to local_specializations. */
24800 static void
24801 register_parameter_specializations (tree pattern, tree inst)
24803 tree tmpl_parm = DECL_ARGUMENTS (pattern);
24804 tree spec_parm = DECL_ARGUMENTS (inst);
24805 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
24807 register_local_specialization (spec_parm, tmpl_parm);
24808 spec_parm = skip_artificial_parms_for (inst, spec_parm);
24809 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
24811 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
24813 if (!DECL_PACK_P (tmpl_parm))
24815 register_local_specialization (spec_parm, tmpl_parm);
24816 spec_parm = DECL_CHAIN (spec_parm);
24818 else
24820 /* Register the (value) argument pack as a specialization of
24821 TMPL_PARM, then move on. */
24822 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
24823 register_local_specialization (argpack, tmpl_parm);
24826 gcc_assert (!spec_parm);
24829 /* Produce the definition of D, a _DECL generated from a template. If
24830 DEFER_OK is true, then we don't have to actually do the
24831 instantiation now; we just have to do it sometime. Normally it is
24832 an error if this is an explicit instantiation but D is undefined.
24833 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
24834 instantiated class template. */
24836 tree
24837 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
24839 tree tmpl = DECL_TI_TEMPLATE (d);
24840 tree gen_args;
24841 tree args;
24842 tree td;
24843 tree code_pattern;
24844 tree spec;
24845 tree gen_tmpl;
24846 bool pattern_defined;
24847 location_t saved_loc = input_location;
24848 int saved_unevaluated_operand = cp_unevaluated_operand;
24849 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
24850 bool external_p;
24851 bool deleted_p;
24853 /* This function should only be used to instantiate templates for
24854 functions and static member variables. */
24855 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
24857 /* A concept is never instantiated. */
24858 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
24860 /* Variables are never deferred; if instantiation is required, they
24861 are instantiated right away. That allows for better code in the
24862 case that an expression refers to the value of the variable --
24863 if the variable has a constant value the referring expression can
24864 take advantage of that fact. */
24865 if (VAR_P (d))
24866 defer_ok = false;
24868 /* Don't instantiate cloned functions. Instead, instantiate the
24869 functions they cloned. */
24870 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
24871 d = DECL_CLONED_FUNCTION (d);
24873 if (DECL_TEMPLATE_INSTANTIATED (d)
24874 || (TREE_CODE (d) == FUNCTION_DECL
24875 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
24876 || DECL_TEMPLATE_SPECIALIZATION (d))
24877 /* D has already been instantiated or explicitly specialized, so
24878 there's nothing for us to do here.
24880 It might seem reasonable to check whether or not D is an explicit
24881 instantiation, and, if so, stop here. But when an explicit
24882 instantiation is deferred until the end of the compilation,
24883 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
24884 the instantiation. */
24885 return d;
24887 /* Check to see whether we know that this template will be
24888 instantiated in some other file, as with "extern template"
24889 extension. */
24890 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
24892 /* In general, we do not instantiate such templates. */
24893 if (external_p && !always_instantiate_p (d))
24894 return d;
24896 gen_tmpl = most_general_template (tmpl);
24897 gen_args = DECL_TI_ARGS (d);
24899 if (tmpl != gen_tmpl)
24900 /* We should already have the extra args. */
24901 gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
24902 == TMPL_ARGS_DEPTH (gen_args));
24903 /* And what's in the hash table should match D. */
24904 gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
24905 || spec == NULL_TREE);
24907 /* This needs to happen before any tsubsting. */
24908 if (! push_tinst_level (d))
24909 return d;
24911 timevar_push (TV_TEMPLATE_INST);
24913 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
24914 for the instantiation. */
24915 td = template_for_substitution (d);
24916 args = gen_args;
24918 if (VAR_P (d))
24920 /* Look up an explicit specialization, if any. */
24921 tree tid = lookup_template_variable (gen_tmpl, gen_args);
24922 tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
24923 if (elt && elt != error_mark_node)
24925 td = TREE_VALUE (elt);
24926 args = TREE_PURPOSE (elt);
24930 code_pattern = DECL_TEMPLATE_RESULT (td);
24932 /* We should never be trying to instantiate a member of a class
24933 template or partial specialization. */
24934 gcc_assert (d != code_pattern);
24936 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
24937 || DECL_TEMPLATE_SPECIALIZATION (td))
24938 /* In the case of a friend template whose definition is provided
24939 outside the class, we may have too many arguments. Drop the
24940 ones we don't need. The same is true for specializations. */
24941 args = get_innermost_template_args
24942 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
24944 if (TREE_CODE (d) == FUNCTION_DECL)
24946 deleted_p = DECL_DELETED_FN (code_pattern);
24947 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
24948 && DECL_INITIAL (code_pattern) != error_mark_node)
24949 || DECL_DEFAULTED_FN (code_pattern)
24950 || deleted_p);
24952 else
24954 deleted_p = false;
24955 if (DECL_CLASS_SCOPE_P (code_pattern))
24956 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
24957 else
24958 pattern_defined = ! DECL_EXTERNAL (code_pattern);
24961 /* We may be in the middle of deferred access check. Disable it now. */
24962 push_deferring_access_checks (dk_no_deferred);
24964 /* Unless an explicit instantiation directive has already determined
24965 the linkage of D, remember that a definition is available for
24966 this entity. */
24967 if (pattern_defined
24968 && !DECL_INTERFACE_KNOWN (d)
24969 && !DECL_NOT_REALLY_EXTERN (d))
24970 mark_definable (d);
24972 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
24973 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
24974 input_location = DECL_SOURCE_LOCATION (d);
24976 /* If D is a member of an explicitly instantiated class template,
24977 and no definition is available, treat it like an implicit
24978 instantiation. */
24979 if (!pattern_defined && expl_inst_class_mem_p
24980 && DECL_EXPLICIT_INSTANTIATION (d))
24982 /* Leave linkage flags alone on instantiations with anonymous
24983 visibility. */
24984 if (TREE_PUBLIC (d))
24986 DECL_NOT_REALLY_EXTERN (d) = 0;
24987 DECL_INTERFACE_KNOWN (d) = 0;
24989 SET_DECL_IMPLICIT_INSTANTIATION (d);
24992 /* Defer all other templates, unless we have been explicitly
24993 forbidden from doing so. */
24994 if (/* If there is no definition, we cannot instantiate the
24995 template. */
24996 ! pattern_defined
24997 /* If it's OK to postpone instantiation, do so. */
24998 || defer_ok
24999 /* If this is a static data member that will be defined
25000 elsewhere, we don't want to instantiate the entire data
25001 member, but we do want to instantiate the initializer so that
25002 we can substitute that elsewhere. */
25003 || (external_p && VAR_P (d))
25004 /* Handle here a deleted function too, avoid generating
25005 its body (c++/61080). */
25006 || deleted_p)
25008 /* The definition of the static data member is now required so
25009 we must substitute the initializer. */
25010 if (VAR_P (d)
25011 && !DECL_INITIAL (d)
25012 && DECL_INITIAL (code_pattern))
25014 tree ns;
25015 tree init;
25016 bool const_init = false;
25017 bool enter_context = DECL_CLASS_SCOPE_P (d);
25019 ns = decl_namespace_context (d);
25020 push_nested_namespace (ns);
25021 if (enter_context)
25022 push_nested_class (DECL_CONTEXT (d));
25023 init = tsubst_expr (DECL_INITIAL (code_pattern),
25024 args,
25025 tf_warning_or_error, NULL_TREE,
25026 /*integral_constant_expression_p=*/false);
25027 /* If instantiating the initializer involved instantiating this
25028 again, don't call cp_finish_decl twice. */
25029 if (!DECL_INITIAL (d))
25031 /* Make sure the initializer is still constant, in case of
25032 circular dependency (template/instantiate6.C). */
25033 const_init
25034 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25035 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
25036 /*asmspec_tree=*/NULL_TREE,
25037 LOOKUP_ONLYCONVERTING);
25039 if (enter_context)
25040 pop_nested_class ();
25041 pop_nested_namespace (ns);
25044 /* We restore the source position here because it's used by
25045 add_pending_template. */
25046 input_location = saved_loc;
25048 if (at_eof && !pattern_defined
25049 && DECL_EXPLICIT_INSTANTIATION (d)
25050 && DECL_NOT_REALLY_EXTERN (d))
25051 /* [temp.explicit]
25053 The definition of a non-exported function template, a
25054 non-exported member function template, or a non-exported
25055 member function or static data member of a class template
25056 shall be present in every translation unit in which it is
25057 explicitly instantiated. */
25058 permerror (input_location, "explicit instantiation of %qD "
25059 "but no definition available", d);
25061 /* If we're in unevaluated context, we just wanted to get the
25062 constant value; this isn't an odr use, so don't queue
25063 a full instantiation. */
25064 if (cp_unevaluated_operand != 0)
25065 goto out;
25066 /* ??? Historically, we have instantiated inline functions, even
25067 when marked as "extern template". */
25068 if (!(external_p && VAR_P (d)))
25069 add_pending_template (d);
25070 goto out;
25073 bool push_to_top, nested;
25074 tree fn_context;
25075 fn_context = decl_function_context (d);
25076 if (LAMBDA_FUNCTION_P (d))
25077 /* tsubst_lambda_expr resolved any references to enclosing functions. */
25078 fn_context = NULL_TREE;
25079 nested = current_function_decl != NULL_TREE;
25080 push_to_top = !(nested && fn_context == current_function_decl);
25082 vec<tree> omp_privatization_save;
25083 if (nested)
25084 save_omp_privatization_clauses (omp_privatization_save);
25086 if (push_to_top)
25087 push_to_top_level ();
25088 else
25090 gcc_assert (!processing_template_decl);
25091 push_function_context ();
25092 cp_unevaluated_operand = 0;
25093 c_inhibit_evaluation_warnings = 0;
25096 /* Mark D as instantiated so that recursive calls to
25097 instantiate_decl do not try to instantiate it again. */
25098 DECL_TEMPLATE_INSTANTIATED (d) = 1;
25100 /* Regenerate the declaration in case the template has been modified
25101 by a subsequent redeclaration. */
25102 regenerate_decl_from_template (d, td, args);
25104 /* We already set the file and line above. Reset them now in case
25105 they changed as a result of calling regenerate_decl_from_template. */
25106 input_location = DECL_SOURCE_LOCATION (d);
25108 if (VAR_P (d))
25110 tree init;
25111 bool const_init = false;
25113 /* Clear out DECL_RTL; whatever was there before may not be right
25114 since we've reset the type of the declaration. */
25115 SET_DECL_RTL (d, NULL);
25116 DECL_IN_AGGR_P (d) = 0;
25118 /* The initializer is placed in DECL_INITIAL by
25119 regenerate_decl_from_template so we don't need to
25120 push/pop_access_scope again here. Pull it out so that
25121 cp_finish_decl can process it. */
25122 init = DECL_INITIAL (d);
25123 DECL_INITIAL (d) = NULL_TREE;
25124 DECL_INITIALIZED_P (d) = 0;
25126 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
25127 initializer. That function will defer actual emission until
25128 we have a chance to determine linkage. */
25129 DECL_EXTERNAL (d) = 0;
25131 /* Enter the scope of D so that access-checking works correctly. */
25132 bool enter_context = DECL_CLASS_SCOPE_P (d);
25133 if (enter_context)
25134 push_nested_class (DECL_CONTEXT (d));
25136 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25137 int flags = (TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (d))
25138 ? LOOKUP_CONSTINIT : 0);
25139 cp_finish_decl (d, init, const_init, NULL_TREE, flags);
25141 if (enter_context)
25142 pop_nested_class ();
25144 if (variable_template_p (gen_tmpl))
25145 note_variable_template_instantiation (d);
25147 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
25148 synthesize_method (d);
25149 else if (TREE_CODE (d) == FUNCTION_DECL)
25151 /* Set up the list of local specializations. */
25152 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
25153 tree block = NULL_TREE;
25155 /* Set up context. */
25156 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25157 && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25158 block = push_stmt_list ();
25159 else
25160 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
25162 /* Some typedefs referenced from within the template code need to be
25163 access checked at template instantiation time, i.e now. These
25164 types were added to the template at parsing time. Let's get those
25165 and perform the access checks then. */
25166 perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
25167 args);
25169 /* Create substitution entries for the parameters. */
25170 register_parameter_specializations (code_pattern, d);
25172 /* Substitute into the body of the function. */
25173 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25174 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
25175 tf_warning_or_error, tmpl);
25176 else
25178 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
25179 tf_warning_or_error, tmpl,
25180 /*integral_constant_expression_p=*/false);
25182 /* Set the current input_location to the end of the function
25183 so that finish_function knows where we are. */
25184 input_location
25185 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
25187 /* Remember if we saw an infinite loop in the template. */
25188 current_function_infinite_loop
25189 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
25192 /* Finish the function. */
25193 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25194 && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25195 DECL_SAVED_TREE (d) = pop_stmt_list (block);
25196 else
25198 d = finish_function (/*inline_p=*/false);
25199 expand_or_defer_fn (d);
25202 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25203 cp_check_omp_declare_reduction (d);
25206 /* We're not deferring instantiation any more. */
25207 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
25209 if (push_to_top)
25210 pop_from_top_level ();
25211 else
25212 pop_function_context ();
25214 if (nested)
25215 restore_omp_privatization_clauses (omp_privatization_save);
25217 out:
25218 pop_deferring_access_checks ();
25219 timevar_pop (TV_TEMPLATE_INST);
25220 pop_tinst_level ();
25221 input_location = saved_loc;
25222 cp_unevaluated_operand = saved_unevaluated_operand;
25223 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
25225 return d;
25228 /* Run through the list of templates that we wish we could
25229 instantiate, and instantiate any we can. RETRIES is the
25230 number of times we retry pending template instantiation. */
25232 void
25233 instantiate_pending_templates (int retries)
25235 int reconsider;
25236 location_t saved_loc = input_location;
25238 /* Instantiating templates may trigger vtable generation. This in turn
25239 may require further template instantiations. We place a limit here
25240 to avoid infinite loop. */
25241 if (pending_templates && retries >= max_tinst_depth)
25243 tree decl = pending_templates->tinst->maybe_get_node ();
25245 fatal_error (input_location,
25246 "template instantiation depth exceeds maximum of %d"
25247 " instantiating %q+D, possibly from virtual table generation"
25248 " (use %<-ftemplate-depth=%> to increase the maximum)",
25249 max_tinst_depth, decl);
25250 if (TREE_CODE (decl) == FUNCTION_DECL)
25251 /* Pretend that we defined it. */
25252 DECL_INITIAL (decl) = error_mark_node;
25253 return;
25258 struct pending_template **t = &pending_templates;
25259 struct pending_template *last = NULL;
25260 reconsider = 0;
25261 while (*t)
25263 tree instantiation = reopen_tinst_level ((*t)->tinst);
25264 bool complete = false;
25266 if (TYPE_P (instantiation))
25268 if (!COMPLETE_TYPE_P (instantiation))
25270 instantiate_class_template (instantiation);
25271 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
25272 for (tree fld = TYPE_FIELDS (instantiation);
25273 fld; fld = TREE_CHAIN (fld))
25274 if ((VAR_P (fld)
25275 || (TREE_CODE (fld) == FUNCTION_DECL
25276 && !DECL_ARTIFICIAL (fld)))
25277 && DECL_TEMPLATE_INSTANTIATION (fld))
25278 instantiate_decl (fld,
25279 /*defer_ok=*/false,
25280 /*expl_inst_class_mem_p=*/false);
25282 if (COMPLETE_TYPE_P (instantiation))
25283 reconsider = 1;
25286 complete = COMPLETE_TYPE_P (instantiation);
25288 else
25290 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
25291 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
25293 instantiation
25294 = instantiate_decl (instantiation,
25295 /*defer_ok=*/false,
25296 /*expl_inst_class_mem_p=*/false);
25297 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
25298 reconsider = 1;
25301 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
25302 || DECL_TEMPLATE_INSTANTIATED (instantiation));
25305 if (complete)
25307 /* If INSTANTIATION has been instantiated, then we don't
25308 need to consider it again in the future. */
25309 struct pending_template *drop = *t;
25310 *t = (*t)->next;
25311 set_refcount_ptr (drop->tinst);
25312 pending_template_freelist ().free (drop);
25314 else
25316 last = *t;
25317 t = &(*t)->next;
25319 tinst_depth = 0;
25320 set_refcount_ptr (current_tinst_level);
25322 last_pending_template = last;
25324 while (reconsider);
25326 input_location = saved_loc;
25329 /* Substitute ARGVEC into T, which is a list of initializers for
25330 either base class or a non-static data member. The TREE_PURPOSEs
25331 are DECLs, and the TREE_VALUEs are the initializer values. Used by
25332 instantiate_decl. */
25334 static tree
25335 tsubst_initializer_list (tree t, tree argvec)
25337 tree inits = NULL_TREE;
25338 tree target_ctor = error_mark_node;
25340 for (; t; t = TREE_CHAIN (t))
25342 tree decl;
25343 tree init;
25344 tree expanded_bases = NULL_TREE;
25345 tree expanded_arguments = NULL_TREE;
25346 int i, len = 1;
25348 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
25350 tree expr;
25351 tree arg;
25353 /* Expand the base class expansion type into separate base
25354 classes. */
25355 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
25356 tf_warning_or_error,
25357 NULL_TREE);
25358 if (expanded_bases == error_mark_node)
25359 continue;
25361 /* We'll be building separate TREE_LISTs of arguments for
25362 each base. */
25363 len = TREE_VEC_LENGTH (expanded_bases);
25364 expanded_arguments = make_tree_vec (len);
25365 for (i = 0; i < len; i++)
25366 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
25368 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
25369 expand each argument in the TREE_VALUE of t. */
25370 expr = make_node (EXPR_PACK_EXPANSION);
25371 PACK_EXPANSION_LOCAL_P (expr) = true;
25372 PACK_EXPANSION_PARAMETER_PACKS (expr) =
25373 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
25375 if (TREE_VALUE (t) == void_type_node)
25376 /* VOID_TYPE_NODE is used to indicate
25377 value-initialization. */
25379 for (i = 0; i < len; i++)
25380 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
25382 else
25384 /* Substitute parameter packs into each argument in the
25385 TREE_LIST. */
25386 in_base_initializer = 1;
25387 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
25389 tree expanded_exprs;
25391 /* Expand the argument. */
25392 SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
25393 expanded_exprs
25394 = tsubst_pack_expansion (expr, argvec,
25395 tf_warning_or_error,
25396 NULL_TREE);
25397 if (expanded_exprs == error_mark_node)
25398 continue;
25400 /* Prepend each of the expanded expressions to the
25401 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
25402 for (i = 0; i < len; i++)
25404 TREE_VEC_ELT (expanded_arguments, i) =
25405 tree_cons (NULL_TREE,
25406 TREE_VEC_ELT (expanded_exprs, i),
25407 TREE_VEC_ELT (expanded_arguments, i));
25410 in_base_initializer = 0;
25412 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
25413 since we built them backwards. */
25414 for (i = 0; i < len; i++)
25416 TREE_VEC_ELT (expanded_arguments, i) =
25417 nreverse (TREE_VEC_ELT (expanded_arguments, i));
25422 for (i = 0; i < len; ++i)
25424 if (expanded_bases)
25426 decl = TREE_VEC_ELT (expanded_bases, i);
25427 decl = expand_member_init (decl);
25428 init = TREE_VEC_ELT (expanded_arguments, i);
25430 else
25432 tree tmp;
25433 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
25434 tf_warning_or_error, NULL_TREE);
25436 decl = expand_member_init (decl);
25437 if (decl && !DECL_P (decl))
25438 in_base_initializer = 1;
25440 init = TREE_VALUE (t);
25441 tmp = init;
25442 if (init != void_type_node)
25443 init = tsubst_expr (init, argvec,
25444 tf_warning_or_error, NULL_TREE,
25445 /*integral_constant_expression_p=*/false);
25446 if (init == NULL_TREE && tmp != NULL_TREE)
25447 /* If we had an initializer but it instantiated to nothing,
25448 value-initialize the object. This will only occur when
25449 the initializer was a pack expansion where the parameter
25450 packs used in that expansion were of length zero. */
25451 init = void_type_node;
25452 in_base_initializer = 0;
25455 if (target_ctor != error_mark_node
25456 && init != error_mark_node)
25458 error ("mem-initializer for %qD follows constructor delegation",
25459 decl);
25460 return inits;
25462 /* Look for a target constructor. */
25463 if (init != error_mark_node
25464 && decl && CLASS_TYPE_P (decl)
25465 && same_type_p (decl, current_class_type))
25467 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
25468 if (inits)
25470 error ("constructor delegation follows mem-initializer for %qD",
25471 TREE_PURPOSE (inits));
25472 continue;
25474 target_ctor = init;
25477 if (decl)
25479 init = build_tree_list (decl, init);
25480 TREE_CHAIN (init) = inits;
25481 inits = init;
25485 return inits;
25488 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL. */
25490 static void
25491 set_current_access_from_decl (tree decl)
25493 if (TREE_PRIVATE (decl))
25494 current_access_specifier = access_private_node;
25495 else if (TREE_PROTECTED (decl))
25496 current_access_specifier = access_protected_node;
25497 else
25498 current_access_specifier = access_public_node;
25501 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
25502 is the instantiation (which should have been created with
25503 start_enum) and ARGS are the template arguments to use. */
25505 static void
25506 tsubst_enum (tree tag, tree newtag, tree args)
25508 tree e;
25510 if (SCOPED_ENUM_P (newtag))
25511 begin_scope (sk_scoped_enum, newtag);
25513 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
25515 tree value;
25516 tree decl;
25518 decl = TREE_VALUE (e);
25519 /* Note that in a template enum, the TREE_VALUE is the
25520 CONST_DECL, not the corresponding INTEGER_CST. */
25521 value = tsubst_expr (DECL_INITIAL (decl),
25522 args, tf_warning_or_error, NULL_TREE,
25523 /*integral_constant_expression_p=*/true);
25525 /* Give this enumeration constant the correct access. */
25526 set_current_access_from_decl (decl);
25528 /* Actually build the enumerator itself. Here we're assuming that
25529 enumerators can't have dependent attributes. */
25530 build_enumerator (DECL_NAME (decl), value, newtag,
25531 DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
25534 if (SCOPED_ENUM_P (newtag))
25535 finish_scope ();
25537 finish_enum_value_list (newtag);
25538 finish_enum (newtag);
25540 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
25541 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
25544 /* DECL is a FUNCTION_DECL that is a template specialization. Return
25545 its type -- but without substituting the innermost set of template
25546 arguments. So, innermost set of template parameters will appear in
25547 the type. */
25549 tree
25550 get_mostly_instantiated_function_type (tree decl)
25552 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
25553 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
25556 /* Return truthvalue if we're processing a template different from
25557 the last one involved in diagnostics. */
25558 bool
25559 problematic_instantiation_changed (void)
25561 return current_tinst_level != last_error_tinst_level;
25564 /* Remember current template involved in diagnostics. */
25565 void
25566 record_last_problematic_instantiation (void)
25568 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
25571 struct tinst_level *
25572 current_instantiation (void)
25574 return current_tinst_level;
25577 /* Return TRUE if current_function_decl is being instantiated, false
25578 otherwise. */
25580 bool
25581 instantiating_current_function_p (void)
25583 return (current_instantiation ()
25584 && (current_instantiation ()->maybe_get_node ()
25585 == current_function_decl));
25588 /* [temp.param] Check that template non-type parm TYPE is of an allowable
25589 type. Return false for ok, true for disallowed. Issue error and
25590 inform messages under control of COMPLAIN. */
25592 static bool
25593 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
25595 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
25596 return false;
25597 else if (TYPE_PTR_P (type))
25598 return false;
25599 else if (TYPE_REF_P (type)
25600 && !TYPE_REF_IS_RVALUE (type))
25601 return false;
25602 else if (TYPE_PTRMEM_P (type))
25603 return false;
25604 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
25605 return false;
25606 else if (TREE_CODE (type) == TYPENAME_TYPE)
25607 return false;
25608 else if (TREE_CODE (type) == DECLTYPE_TYPE)
25609 return false;
25610 else if (TREE_CODE (type) == NULLPTR_TYPE)
25611 return false;
25612 /* A bound template template parm could later be instantiated to have a valid
25613 nontype parm type via an alias template. */
25614 else if (cxx_dialect >= cxx11
25615 && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
25616 return false;
25617 else if (CLASS_TYPE_P (type))
25619 if (cxx_dialect < cxx2a)
25621 if (complain & tf_error)
25622 error ("non-type template parameters of class type only available "
25623 "with %<-std=c++2a%> or %<-std=gnu++2a%>");
25624 return true;
25626 if (dependent_type_p (type))
25627 return false;
25628 if (!complete_type_or_else (type, NULL_TREE))
25629 return true;
25630 if (!literal_type_p (type))
25632 error ("%qT is not a valid type for a template non-type parameter "
25633 "because it is not literal", type);
25634 explain_non_literal_class (type);
25635 return true;
25637 if (cp_has_mutable_p (type))
25639 error ("%qT is not a valid type for a template non-type parameter "
25640 "because it has a mutable member", type);
25641 return true;
25643 /* FIXME check op<=> and strong structural equality once spaceship is
25644 implemented. */
25645 return false;
25648 if (complain & tf_error)
25650 if (type == error_mark_node)
25651 inform (input_location, "invalid template non-type parameter");
25652 else
25653 error ("%q#T is not a valid type for a template non-type parameter",
25654 type);
25656 return true;
25659 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
25660 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
25662 static bool
25663 dependent_type_p_r (tree type)
25665 tree scope;
25667 /* [temp.dep.type]
25669 A type is dependent if it is:
25671 -- a template parameter. Template template parameters are types
25672 for us (since TYPE_P holds true for them) so we handle
25673 them here. */
25674 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
25675 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
25676 return true;
25677 /* -- a qualified-id with a nested-name-specifier which contains a
25678 class-name that names a dependent type or whose unqualified-id
25679 names a dependent type. */
25680 if (TREE_CODE (type) == TYPENAME_TYPE)
25681 return true;
25683 /* An alias template specialization can be dependent even if the
25684 resulting type is not. */
25685 if (dependent_alias_template_spec_p (type))
25686 return true;
25688 /* -- a cv-qualified type where the cv-unqualified type is
25689 dependent.
25690 No code is necessary for this bullet; the code below handles
25691 cv-qualified types, and we don't want to strip aliases with
25692 TYPE_MAIN_VARIANT because of DR 1558. */
25693 /* -- a compound type constructed from any dependent type. */
25694 if (TYPE_PTRMEM_P (type))
25695 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
25696 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
25697 (type)));
25698 else if (INDIRECT_TYPE_P (type))
25699 return dependent_type_p (TREE_TYPE (type));
25700 else if (FUNC_OR_METHOD_TYPE_P (type))
25702 tree arg_type;
25704 if (dependent_type_p (TREE_TYPE (type)))
25705 return true;
25706 for (arg_type = TYPE_ARG_TYPES (type);
25707 arg_type;
25708 arg_type = TREE_CHAIN (arg_type))
25709 if (dependent_type_p (TREE_VALUE (arg_type)))
25710 return true;
25711 if (cxx_dialect >= cxx17)
25712 /* A value-dependent noexcept-specifier makes the type dependent. */
25713 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
25714 if (tree noex = TREE_PURPOSE (spec))
25715 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
25716 affect overload resolution and treating it as dependent breaks
25717 things. Same for an unparsed noexcept expression. */
25718 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
25719 && TREE_CODE (noex) != DEFERRED_PARSE
25720 && value_dependent_expression_p (noex))
25721 return true;
25722 return false;
25724 /* -- an array type constructed from any dependent type or whose
25725 size is specified by a constant expression that is
25726 value-dependent.
25728 We checked for type- and value-dependence of the bounds in
25729 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
25730 if (TREE_CODE (type) == ARRAY_TYPE)
25732 if (TYPE_DOMAIN (type)
25733 && dependent_type_p (TYPE_DOMAIN (type)))
25734 return true;
25735 return dependent_type_p (TREE_TYPE (type));
25738 /* -- a template-id in which either the template name is a template
25739 parameter ... */
25740 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
25741 return true;
25742 /* ... or any of the template arguments is a dependent type or
25743 an expression that is type-dependent or value-dependent. */
25744 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
25745 && (any_dependent_template_arguments_p
25746 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
25747 return true;
25749 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
25750 dependent; if the argument of the `typeof' expression is not
25751 type-dependent, then it should already been have resolved. */
25752 if (TREE_CODE (type) == TYPEOF_TYPE
25753 || TREE_CODE (type) == DECLTYPE_TYPE
25754 || TREE_CODE (type) == UNDERLYING_TYPE)
25755 return true;
25757 /* A template argument pack is dependent if any of its packed
25758 arguments are. */
25759 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
25761 tree args = ARGUMENT_PACK_ARGS (type);
25762 int i, len = TREE_VEC_LENGTH (args);
25763 for (i = 0; i < len; ++i)
25764 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25765 return true;
25768 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
25769 be template parameters. */
25770 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
25771 return true;
25773 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
25774 return true;
25776 /* The standard does not specifically mention types that are local
25777 to template functions or local classes, but they should be
25778 considered dependent too. For example:
25780 template <int I> void f() {
25781 enum E { a = I };
25782 S<sizeof (E)> s;
25785 The size of `E' cannot be known until the value of `I' has been
25786 determined. Therefore, `E' must be considered dependent. */
25787 scope = TYPE_CONTEXT (type);
25788 if (scope && TYPE_P (scope))
25789 return dependent_type_p (scope);
25790 /* Don't use type_dependent_expression_p here, as it can lead
25791 to infinite recursion trying to determine whether a lambda
25792 nested in a lambda is dependent (c++/47687). */
25793 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
25794 && DECL_LANG_SPECIFIC (scope)
25795 && DECL_TEMPLATE_INFO (scope)
25796 && (any_dependent_template_arguments_p
25797 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
25798 return true;
25800 /* Other types are non-dependent. */
25801 return false;
25804 /* Returns TRUE if TYPE is dependent, in the sense of
25805 [temp.dep.type]. Note that a NULL type is considered dependent. */
25807 bool
25808 dependent_type_p (tree type)
25810 /* If there are no template parameters in scope, then there can't be
25811 any dependent types. */
25812 if (!processing_template_decl)
25814 /* If we are not processing a template, then nobody should be
25815 providing us with a dependent type. */
25816 gcc_assert (type);
25817 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
25818 return false;
25821 /* If the type is NULL, we have not computed a type for the entity
25822 in question; in that case, the type is dependent. */
25823 if (!type)
25824 return true;
25826 /* Erroneous types can be considered non-dependent. */
25827 if (type == error_mark_node)
25828 return false;
25830 /* Getting here with global_type_node means we improperly called this
25831 function on the TREE_TYPE of an IDENTIFIER_NODE. */
25832 gcc_checking_assert (type != global_type_node);
25834 /* If we have not already computed the appropriate value for TYPE,
25835 do so now. */
25836 if (!TYPE_DEPENDENT_P_VALID (type))
25838 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
25839 TYPE_DEPENDENT_P_VALID (type) = 1;
25842 return TYPE_DEPENDENT_P (type);
25845 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
25846 lookup. In other words, a dependent type that is not the current
25847 instantiation. */
25849 bool
25850 dependent_scope_p (tree scope)
25852 return (scope && TYPE_P (scope) && dependent_type_p (scope)
25853 && !currently_open_class (scope));
25856 /* T is a SCOPE_REF. Return whether it represents a non-static member of
25857 an unknown base of 'this' (and is therefore instantiation-dependent). */
25859 static bool
25860 unknown_base_ref_p (tree t)
25862 if (!current_class_ptr)
25863 return false;
25865 tree mem = TREE_OPERAND (t, 1);
25866 if (shared_member_p (mem))
25867 return false;
25869 tree cur = current_nonlambda_class_type ();
25870 if (!any_dependent_bases_p (cur))
25871 return false;
25873 tree ctx = TREE_OPERAND (t, 0);
25874 if (DERIVED_FROM_P (ctx, cur))
25875 return false;
25877 return true;
25880 /* T is a SCOPE_REF; return whether we need to consider it
25881 instantiation-dependent so that we can check access at instantiation
25882 time even though we know which member it resolves to. */
25884 static bool
25885 instantiation_dependent_scope_ref_p (tree t)
25887 if (DECL_P (TREE_OPERAND (t, 1))
25888 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
25889 && !unknown_base_ref_p (t)
25890 && accessible_in_template_p (TREE_OPERAND (t, 0),
25891 TREE_OPERAND (t, 1)))
25892 return false;
25893 else
25894 return true;
25897 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
25898 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
25899 expression. */
25901 /* Note that this predicate is not appropriate for general expressions;
25902 only constant expressions (that satisfy potential_constant_expression)
25903 can be tested for value dependence. */
25905 bool
25906 value_dependent_expression_p (tree expression)
25908 if (!processing_template_decl || expression == NULL_TREE)
25909 return false;
25911 /* A type-dependent expression is also value-dependent. */
25912 if (type_dependent_expression_p (expression))
25913 return true;
25915 switch (TREE_CODE (expression))
25917 case BASELINK:
25918 /* A dependent member function of the current instantiation. */
25919 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
25921 case FUNCTION_DECL:
25922 /* A dependent member function of the current instantiation. */
25923 if (DECL_CLASS_SCOPE_P (expression)
25924 && dependent_type_p (DECL_CONTEXT (expression)))
25925 return true;
25926 break;
25928 case IDENTIFIER_NODE:
25929 /* A name that has not been looked up -- must be dependent. */
25930 return true;
25932 case TEMPLATE_PARM_INDEX:
25933 /* A non-type template parm. */
25934 return true;
25936 case CONST_DECL:
25937 /* A non-type template parm. */
25938 if (DECL_TEMPLATE_PARM_P (expression))
25939 return true;
25940 return value_dependent_expression_p (DECL_INITIAL (expression));
25942 case VAR_DECL:
25943 /* A constant with literal type and is initialized
25944 with an expression that is value-dependent. */
25945 if (DECL_DEPENDENT_INIT_P (expression)
25946 /* FIXME cp_finish_decl doesn't fold reference initializers. */
25947 || TYPE_REF_P (TREE_TYPE (expression)))
25948 return true;
25949 if (DECL_HAS_VALUE_EXPR_P (expression))
25951 tree value_expr = DECL_VALUE_EXPR (expression);
25952 if (value_dependent_expression_p (value_expr)
25953 /* __PRETTY_FUNCTION__ inside a template function is dependent
25954 on the name of the function. */
25955 || (DECL_PRETTY_FUNCTION_P (expression)
25956 /* It might be used in a template, but not a template
25957 function, in which case its DECL_VALUE_EXPR will be
25958 "top level". */
25959 && value_expr == error_mark_node))
25960 return true;
25962 return false;
25964 case DYNAMIC_CAST_EXPR:
25965 case STATIC_CAST_EXPR:
25966 case CONST_CAST_EXPR:
25967 case REINTERPRET_CAST_EXPR:
25968 case CAST_EXPR:
25969 case IMPLICIT_CONV_EXPR:
25970 /* These expressions are value-dependent if the type to which
25971 the cast occurs is dependent or the expression being casted
25972 is value-dependent. */
25974 tree type = TREE_TYPE (expression);
25976 if (dependent_type_p (type))
25977 return true;
25979 /* A functional cast has a list of operands. */
25980 expression = TREE_OPERAND (expression, 0);
25981 if (!expression)
25983 /* If there are no operands, it must be an expression such
25984 as "int()". This should not happen for aggregate types
25985 because it would form non-constant expressions. */
25986 gcc_assert (cxx_dialect >= cxx11
25987 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
25989 return false;
25992 if (TREE_CODE (expression) == TREE_LIST)
25993 return any_value_dependent_elements_p (expression);
25995 return value_dependent_expression_p (expression);
25998 case SIZEOF_EXPR:
25999 if (SIZEOF_EXPR_TYPE_P (expression))
26000 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
26001 /* FALLTHRU */
26002 case ALIGNOF_EXPR:
26003 case TYPEID_EXPR:
26004 /* A `sizeof' expression is value-dependent if the operand is
26005 type-dependent or is a pack expansion. */
26006 expression = TREE_OPERAND (expression, 0);
26007 if (PACK_EXPANSION_P (expression))
26008 return true;
26009 else if (TYPE_P (expression))
26010 return dependent_type_p (expression);
26011 return instantiation_dependent_uneval_expression_p (expression);
26013 case AT_ENCODE_EXPR:
26014 /* An 'encode' expression is value-dependent if the operand is
26015 type-dependent. */
26016 expression = TREE_OPERAND (expression, 0);
26017 return dependent_type_p (expression);
26019 case NOEXCEPT_EXPR:
26020 expression = TREE_OPERAND (expression, 0);
26021 return instantiation_dependent_uneval_expression_p (expression);
26023 case SCOPE_REF:
26024 /* All instantiation-dependent expressions should also be considered
26025 value-dependent. */
26026 return instantiation_dependent_scope_ref_p (expression);
26028 case COMPONENT_REF:
26029 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
26030 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
26032 case NONTYPE_ARGUMENT_PACK:
26033 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
26034 is value-dependent. */
26036 tree values = ARGUMENT_PACK_ARGS (expression);
26037 int i, len = TREE_VEC_LENGTH (values);
26039 for (i = 0; i < len; ++i)
26040 if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
26041 return true;
26043 return false;
26046 case TRAIT_EXPR:
26048 tree type2 = TRAIT_EXPR_TYPE2 (expression);
26050 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
26051 return true;
26053 if (!type2)
26054 return false;
26056 if (TREE_CODE (type2) != TREE_LIST)
26057 return dependent_type_p (type2);
26059 for (; type2; type2 = TREE_CHAIN (type2))
26060 if (dependent_type_p (TREE_VALUE (type2)))
26061 return true;
26063 return false;
26066 case MODOP_EXPR:
26067 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26068 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
26070 case ARRAY_REF:
26071 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26072 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
26074 case ADDR_EXPR:
26076 tree op = TREE_OPERAND (expression, 0);
26077 return (value_dependent_expression_p (op)
26078 || has_value_dependent_address (op));
26081 case REQUIRES_EXPR:
26082 /* Treat all requires-expressions as value-dependent so
26083 we don't try to fold them. */
26084 return true;
26086 case TYPE_REQ:
26087 return dependent_type_p (TREE_OPERAND (expression, 0));
26089 case CALL_EXPR:
26091 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
26092 return true;
26093 tree fn = get_callee_fndecl (expression);
26094 int i, nargs;
26095 nargs = call_expr_nargs (expression);
26096 for (i = 0; i < nargs; ++i)
26098 tree op = CALL_EXPR_ARG (expression, i);
26099 /* In a call to a constexpr member function, look through the
26100 implicit ADDR_EXPR on the object argument so that it doesn't
26101 cause the call to be considered value-dependent. We also
26102 look through it in potential_constant_expression. */
26103 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
26104 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26105 && TREE_CODE (op) == ADDR_EXPR)
26106 op = TREE_OPERAND (op, 0);
26107 if (value_dependent_expression_p (op))
26108 return true;
26110 return false;
26113 case TEMPLATE_ID_EXPR:
26114 return concept_definition_p (TREE_OPERAND (expression, 0));
26116 case CONSTRUCTOR:
26118 unsigned ix;
26119 tree val;
26120 if (dependent_type_p (TREE_TYPE (expression)))
26121 return true;
26122 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
26123 if (value_dependent_expression_p (val))
26124 return true;
26125 return false;
26128 case STMT_EXPR:
26129 /* Treat a GNU statement expression as dependent to avoid crashing
26130 under instantiate_non_dependent_expr; it can't be constant. */
26131 return true;
26133 default:
26134 /* A constant expression is value-dependent if any subexpression is
26135 value-dependent. */
26136 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
26138 case tcc_reference:
26139 case tcc_unary:
26140 case tcc_comparison:
26141 case tcc_binary:
26142 case tcc_expression:
26143 case tcc_vl_exp:
26145 int i, len = cp_tree_operand_length (expression);
26147 for (i = 0; i < len; i++)
26149 tree t = TREE_OPERAND (expression, i);
26151 /* In some cases, some of the operands may be missing.
26152 (For example, in the case of PREDECREMENT_EXPR, the
26153 amount to increment by may be missing.) That doesn't
26154 make the expression dependent. */
26155 if (t && value_dependent_expression_p (t))
26156 return true;
26159 break;
26160 default:
26161 break;
26163 break;
26166 /* The expression is not value-dependent. */
26167 return false;
26170 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
26171 [temp.dep.expr]. Note that an expression with no type is
26172 considered dependent. Other parts of the compiler arrange for an
26173 expression with type-dependent subexpressions to have no type, so
26174 this function doesn't have to be fully recursive. */
26176 bool
26177 type_dependent_expression_p (tree expression)
26179 if (!processing_template_decl)
26180 return false;
26182 if (expression == NULL_TREE || expression == error_mark_node)
26183 return false;
26185 STRIP_ANY_LOCATION_WRAPPER (expression);
26187 /* An unresolved name is always dependent. */
26188 if (identifier_p (expression)
26189 || TREE_CODE (expression) == USING_DECL
26190 || TREE_CODE (expression) == WILDCARD_DECL)
26191 return true;
26193 /* A lambda-expression in template context is dependent. dependent_type_p is
26194 true for a lambda in the scope of a class or function template, but that
26195 doesn't cover all template contexts, like a default template argument. */
26196 if (TREE_CODE (expression) == LAMBDA_EXPR)
26197 return true;
26199 /* A fold expression is type-dependent. */
26200 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
26201 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
26202 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
26203 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
26204 return true;
26206 /* Some expression forms are never type-dependent. */
26207 if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
26208 || TREE_CODE (expression) == SIZEOF_EXPR
26209 || TREE_CODE (expression) == ALIGNOF_EXPR
26210 || TREE_CODE (expression) == AT_ENCODE_EXPR
26211 || TREE_CODE (expression) == NOEXCEPT_EXPR
26212 || TREE_CODE (expression) == TRAIT_EXPR
26213 || TREE_CODE (expression) == TYPEID_EXPR
26214 || TREE_CODE (expression) == DELETE_EXPR
26215 || TREE_CODE (expression) == VEC_DELETE_EXPR
26216 || TREE_CODE (expression) == THROW_EXPR
26217 || TREE_CODE (expression) == REQUIRES_EXPR)
26218 return false;
26220 /* The types of these expressions depends only on the type to which
26221 the cast occurs. */
26222 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
26223 || TREE_CODE (expression) == STATIC_CAST_EXPR
26224 || TREE_CODE (expression) == CONST_CAST_EXPR
26225 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
26226 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
26227 || TREE_CODE (expression) == CAST_EXPR)
26228 return dependent_type_p (TREE_TYPE (expression));
26230 /* The types of these expressions depends only on the type created
26231 by the expression. */
26232 if (TREE_CODE (expression) == NEW_EXPR
26233 || TREE_CODE (expression) == VEC_NEW_EXPR)
26235 /* For NEW_EXPR tree nodes created inside a template, either
26236 the object type itself or a TREE_LIST may appear as the
26237 operand 1. */
26238 tree type = TREE_OPERAND (expression, 1);
26239 if (TREE_CODE (type) == TREE_LIST)
26240 /* This is an array type. We need to check array dimensions
26241 as well. */
26242 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
26243 || value_dependent_expression_p
26244 (TREE_OPERAND (TREE_VALUE (type), 1));
26245 else
26246 return dependent_type_p (type);
26249 if (TREE_CODE (expression) == SCOPE_REF)
26251 tree scope = TREE_OPERAND (expression, 0);
26252 tree name = TREE_OPERAND (expression, 1);
26254 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
26255 contains an identifier associated by name lookup with one or more
26256 declarations declared with a dependent type, or...a
26257 nested-name-specifier or qualified-id that names a member of an
26258 unknown specialization. */
26259 return (type_dependent_expression_p (name)
26260 || dependent_scope_p (scope));
26263 if (TREE_CODE (expression) == TEMPLATE_DECL
26264 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
26265 return uses_outer_template_parms (expression);
26267 if (TREE_CODE (expression) == STMT_EXPR)
26268 expression = stmt_expr_value_expr (expression);
26270 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
26272 tree elt;
26273 unsigned i;
26275 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
26277 if (type_dependent_expression_p (elt))
26278 return true;
26280 return false;
26283 /* A static data member of the current instantiation with incomplete
26284 array type is type-dependent, as the definition and specializations
26285 can have different bounds. */
26286 if (VAR_P (expression)
26287 && DECL_CLASS_SCOPE_P (expression)
26288 && dependent_type_p (DECL_CONTEXT (expression))
26289 && VAR_HAD_UNKNOWN_BOUND (expression))
26290 return true;
26292 /* An array of unknown bound depending on a variadic parameter, eg:
26294 template<typename... Args>
26295 void foo (Args... args)
26297 int arr[] = { args... };
26300 template<int... vals>
26301 void bar ()
26303 int arr[] = { vals... };
26306 If the array has no length and has an initializer, it must be that
26307 we couldn't determine its length in cp_complete_array_type because
26308 it is dependent. */
26309 if (VAR_P (expression)
26310 && TREE_TYPE (expression) != NULL_TREE
26311 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
26312 && !TYPE_DOMAIN (TREE_TYPE (expression))
26313 && DECL_INITIAL (expression))
26314 return true;
26316 /* A function or variable template-id is type-dependent if it has any
26317 dependent template arguments. */
26318 if (VAR_OR_FUNCTION_DECL_P (expression)
26319 && DECL_LANG_SPECIFIC (expression)
26320 && DECL_TEMPLATE_INFO (expression))
26322 /* Consider the innermost template arguments, since those are the ones
26323 that come from the template-id; the template arguments for the
26324 enclosing class do not make it type-dependent unless they are used in
26325 the type of the decl. */
26326 if (instantiates_primary_template_p (expression)
26327 && (any_dependent_template_arguments_p
26328 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
26329 return true;
26332 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
26333 type-dependent. Checking this is important for functions with auto return
26334 type, which looks like a dependent type. */
26335 if (TREE_CODE (expression) == FUNCTION_DECL
26336 && !(DECL_CLASS_SCOPE_P (expression)
26337 && dependent_type_p (DECL_CONTEXT (expression)))
26338 && !(DECL_LANG_SPECIFIC (expression)
26339 && DECL_FRIEND_P (expression)
26340 && (!DECL_FRIEND_CONTEXT (expression)
26341 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
26342 && !DECL_LOCAL_FUNCTION_P (expression))
26344 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
26345 || undeduced_auto_decl (expression));
26346 return false;
26349 /* Always dependent, on the number of arguments if nothing else. */
26350 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
26351 return true;
26353 if (TREE_TYPE (expression) == unknown_type_node)
26355 if (TREE_CODE (expression) == ADDR_EXPR)
26356 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
26357 if (TREE_CODE (expression) == COMPONENT_REF
26358 || TREE_CODE (expression) == OFFSET_REF)
26360 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
26361 return true;
26362 expression = TREE_OPERAND (expression, 1);
26363 if (identifier_p (expression))
26364 return false;
26366 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
26367 if (TREE_CODE (expression) == SCOPE_REF)
26368 return false;
26370 if (BASELINK_P (expression))
26372 if (BASELINK_OPTYPE (expression)
26373 && dependent_type_p (BASELINK_OPTYPE (expression)))
26374 return true;
26375 expression = BASELINK_FUNCTIONS (expression);
26378 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
26380 if (any_dependent_template_arguments_p
26381 (TREE_OPERAND (expression, 1)))
26382 return true;
26383 expression = TREE_OPERAND (expression, 0);
26384 if (identifier_p (expression))
26385 return true;
26388 gcc_assert (OVL_P (expression));
26390 for (lkp_iterator iter (expression); iter; ++iter)
26391 if (type_dependent_expression_p (*iter))
26392 return true;
26394 return false;
26397 /* The type of a non-type template parm declared with a placeholder type
26398 depends on the corresponding template argument, even though
26399 placeholders are not normally considered dependent. */
26400 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
26401 && is_auto (TREE_TYPE (expression)))
26402 return true;
26404 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
26406 /* Dependent type attributes might not have made it from the decl to
26407 the type yet. */
26408 if (DECL_P (expression)
26409 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
26410 return true;
26412 return (dependent_type_p (TREE_TYPE (expression)));
26415 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
26416 type-dependent if the expression refers to a member of the current
26417 instantiation and the type of the referenced member is dependent, or the
26418 class member access expression refers to a member of an unknown
26419 specialization.
26421 This function returns true if the OBJECT in such a class member access
26422 expression is of an unknown specialization. */
26424 bool
26425 type_dependent_object_expression_p (tree object)
26427 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
26428 dependent. */
26429 if (TREE_CODE (object) == IDENTIFIER_NODE)
26430 return true;
26431 tree scope = TREE_TYPE (object);
26432 return (!scope || dependent_scope_p (scope));
26435 /* walk_tree callback function for instantiation_dependent_expression_p,
26436 below. Returns non-zero if a dependent subexpression is found. */
26438 static tree
26439 instantiation_dependent_r (tree *tp, int *walk_subtrees,
26440 void * /*data*/)
26442 if (TYPE_P (*tp))
26444 /* We don't have to worry about decltype currently because decltype
26445 of an instantiation-dependent expr is a dependent type. This
26446 might change depending on the resolution of DR 1172. */
26447 *walk_subtrees = false;
26448 return NULL_TREE;
26450 enum tree_code code = TREE_CODE (*tp);
26451 switch (code)
26453 /* Don't treat an argument list as dependent just because it has no
26454 TREE_TYPE. */
26455 case TREE_LIST:
26456 case TREE_VEC:
26457 case NONTYPE_ARGUMENT_PACK:
26458 return NULL_TREE;
26460 case TEMPLATE_PARM_INDEX:
26461 if (dependent_type_p (TREE_TYPE (*tp)))
26462 return *tp;
26463 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
26464 return *tp;
26465 /* We'll check value-dependence separately. */
26466 return NULL_TREE;
26468 /* Handle expressions with type operands. */
26469 case SIZEOF_EXPR:
26470 case ALIGNOF_EXPR:
26471 case TYPEID_EXPR:
26472 case AT_ENCODE_EXPR:
26474 tree op = TREE_OPERAND (*tp, 0);
26475 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
26476 op = TREE_TYPE (op);
26477 if (TYPE_P (op))
26479 if (dependent_type_p (op))
26480 return *tp;
26481 else
26483 *walk_subtrees = false;
26484 return NULL_TREE;
26487 break;
26490 case COMPONENT_REF:
26491 if (identifier_p (TREE_OPERAND (*tp, 1)))
26492 /* In a template, finish_class_member_access_expr creates a
26493 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
26494 type-dependent, so that we can check access control at
26495 instantiation time (PR 42277). See also Core issue 1273. */
26496 return *tp;
26497 break;
26499 case SCOPE_REF:
26500 if (instantiation_dependent_scope_ref_p (*tp))
26501 return *tp;
26502 else
26503 break;
26505 /* Treat statement-expressions as dependent. */
26506 case BIND_EXPR:
26507 return *tp;
26509 /* Treat requires-expressions as dependent. */
26510 case REQUIRES_EXPR:
26511 return *tp;
26513 case CALL_EXPR:
26514 /* Treat concept checks as dependent. */
26515 if (concept_check_p (*tp))
26516 return *tp;
26517 break;
26519 case TEMPLATE_ID_EXPR:
26520 /* Treat concept checks as dependent. */
26521 if (concept_check_p (*tp))
26522 return *tp;
26523 break;
26525 case CONSTRUCTOR:
26526 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
26527 return *tp;
26528 break;
26530 default:
26531 break;
26534 if (type_dependent_expression_p (*tp))
26535 return *tp;
26536 else
26537 return NULL_TREE;
26540 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
26541 sense defined by the ABI:
26543 "An expression is instantiation-dependent if it is type-dependent
26544 or value-dependent, or it has a subexpression that is type-dependent
26545 or value-dependent."
26547 Except don't actually check value-dependence for unevaluated expressions,
26548 because in sizeof(i) we don't care about the value of i. Checking
26549 type-dependence will in turn check value-dependence of array bounds/template
26550 arguments as needed. */
26552 bool
26553 instantiation_dependent_uneval_expression_p (tree expression)
26555 tree result;
26557 if (!processing_template_decl)
26558 return false;
26560 if (expression == error_mark_node)
26561 return false;
26563 result = cp_walk_tree_without_duplicates (&expression,
26564 instantiation_dependent_r, NULL);
26565 return result != NULL_TREE;
26568 /* As above, but also check value-dependence of the expression as a whole. */
26570 bool
26571 instantiation_dependent_expression_p (tree expression)
26573 return (instantiation_dependent_uneval_expression_p (expression)
26574 || value_dependent_expression_p (expression));
26577 /* Like type_dependent_expression_p, but it also works while not processing
26578 a template definition, i.e. during substitution or mangling. */
26580 bool
26581 type_dependent_expression_p_push (tree expr)
26583 bool b;
26584 ++processing_template_decl;
26585 b = type_dependent_expression_p (expr);
26586 --processing_template_decl;
26587 return b;
26590 /* Returns TRUE if ARGS contains a type-dependent expression. */
26592 bool
26593 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
26595 unsigned int i;
26596 tree arg;
26598 FOR_EACH_VEC_SAFE_ELT (args, i, arg)
26600 if (type_dependent_expression_p (arg))
26601 return true;
26603 return false;
26606 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
26607 expressions) contains any type-dependent expressions. */
26609 bool
26610 any_type_dependent_elements_p (const_tree list)
26612 for (; list; list = TREE_CHAIN (list))
26613 if (type_dependent_expression_p (TREE_VALUE (list)))
26614 return true;
26616 return false;
26619 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
26620 expressions) contains any value-dependent expressions. */
26622 bool
26623 any_value_dependent_elements_p (const_tree list)
26625 for (; list; list = TREE_CHAIN (list))
26626 if (value_dependent_expression_p (TREE_VALUE (list)))
26627 return true;
26629 return false;
26632 /* Returns TRUE if the ARG (a template argument) is dependent. */
26634 bool
26635 dependent_template_arg_p (tree arg)
26637 if (!processing_template_decl)
26638 return false;
26640 /* Assume a template argument that was wrongly written by the user
26641 is dependent. This is consistent with what
26642 any_dependent_template_arguments_p [that calls this function]
26643 does. */
26644 if (!arg || arg == error_mark_node)
26645 return true;
26647 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
26648 arg = argument_pack_select_arg (arg);
26650 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
26651 return true;
26652 if (TREE_CODE (arg) == TEMPLATE_DECL)
26654 if (DECL_TEMPLATE_PARM_P (arg))
26655 return true;
26656 /* A member template of a dependent class is not necessarily
26657 type-dependent, but it is a dependent template argument because it
26658 will be a member of an unknown specialization to that template. */
26659 tree scope = CP_DECL_CONTEXT (arg);
26660 return TYPE_P (scope) && dependent_type_p (scope);
26662 else if (ARGUMENT_PACK_P (arg))
26664 tree args = ARGUMENT_PACK_ARGS (arg);
26665 int i, len = TREE_VEC_LENGTH (args);
26666 for (i = 0; i < len; ++i)
26668 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26669 return true;
26672 return false;
26674 else if (TYPE_P (arg))
26675 return dependent_type_p (arg);
26676 else
26677 return (type_dependent_expression_p (arg)
26678 || value_dependent_expression_p (arg));
26681 /* Returns true if ARGS (a collection of template arguments) contains
26682 any types that require structural equality testing. */
26684 bool
26685 any_template_arguments_need_structural_equality_p (tree args)
26687 int i;
26688 int j;
26690 if (!args)
26691 return false;
26692 if (args == error_mark_node)
26693 return true;
26695 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
26697 tree level = TMPL_ARGS_LEVEL (args, i + 1);
26698 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
26700 tree arg = TREE_VEC_ELT (level, j);
26701 tree packed_args = NULL_TREE;
26702 int k, len = 1;
26704 if (ARGUMENT_PACK_P (arg))
26706 /* Look inside the argument pack. */
26707 packed_args = ARGUMENT_PACK_ARGS (arg);
26708 len = TREE_VEC_LENGTH (packed_args);
26711 for (k = 0; k < len; ++k)
26713 if (packed_args)
26714 arg = TREE_VEC_ELT (packed_args, k);
26716 if (error_operand_p (arg))
26717 return true;
26718 else if (TREE_CODE (arg) == TEMPLATE_DECL)
26719 continue;
26720 else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
26721 return true;
26722 else if (!TYPE_P (arg) && TREE_TYPE (arg)
26723 && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
26724 return true;
26729 return false;
26732 /* Returns true if ARGS (a collection of template arguments) contains
26733 any dependent arguments. */
26735 bool
26736 any_dependent_template_arguments_p (const_tree args)
26738 int i;
26739 int j;
26741 if (!args)
26742 return false;
26743 if (args == error_mark_node)
26744 return true;
26746 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
26748 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
26749 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
26750 if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
26751 return true;
26754 return false;
26757 /* Returns true if ARGS contains any errors. */
26759 bool
26760 any_erroneous_template_args_p (const_tree args)
26762 int i;
26763 int j;
26765 if (args == error_mark_node)
26766 return true;
26768 if (args && TREE_CODE (args) != TREE_VEC)
26770 if (tree ti = get_template_info (args))
26771 args = TI_ARGS (ti);
26772 else
26773 args = NULL_TREE;
26776 if (!args)
26777 return false;
26779 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
26781 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
26782 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
26783 if (error_operand_p (TREE_VEC_ELT (level, j)))
26784 return true;
26787 return false;
26790 /* Returns TRUE if the template TMPL is type-dependent. */
26792 bool
26793 dependent_template_p (tree tmpl)
26795 if (TREE_CODE (tmpl) == OVERLOAD)
26797 for (lkp_iterator iter (tmpl); iter; ++iter)
26798 if (dependent_template_p (*iter))
26799 return true;
26800 return false;
26803 /* Template template parameters are dependent. */
26804 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
26805 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
26806 return true;
26807 /* So are names that have not been looked up. */
26808 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
26809 return true;
26810 return false;
26813 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
26815 bool
26816 dependent_template_id_p (tree tmpl, tree args)
26818 return (dependent_template_p (tmpl)
26819 || any_dependent_template_arguments_p (args));
26822 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
26823 are dependent. */
26825 bool
26826 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
26828 int i;
26830 if (!processing_template_decl)
26831 return false;
26833 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
26835 tree decl = TREE_VEC_ELT (declv, i);
26836 tree init = TREE_VEC_ELT (initv, i);
26837 tree cond = TREE_VEC_ELT (condv, i);
26838 tree incr = TREE_VEC_ELT (incrv, i);
26840 if (type_dependent_expression_p (decl)
26841 || TREE_CODE (decl) == SCOPE_REF)
26842 return true;
26844 if (init && type_dependent_expression_p (init))
26845 return true;
26847 if (cond == global_namespace)
26848 return true;
26850 if (type_dependent_expression_p (cond))
26851 return true;
26853 if (COMPARISON_CLASS_P (cond)
26854 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
26855 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
26856 return true;
26858 if (TREE_CODE (incr) == MODOP_EXPR)
26860 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
26861 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
26862 return true;
26864 else if (type_dependent_expression_p (incr))
26865 return true;
26866 else if (TREE_CODE (incr) == MODIFY_EXPR)
26868 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
26869 return true;
26870 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
26872 tree t = TREE_OPERAND (incr, 1);
26873 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
26874 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
26875 return true;
26877 /* If this loop has a class iterator with != comparison
26878 with increment other than i++/++i/i--/--i, make sure the
26879 increment is constant. */
26880 if (CLASS_TYPE_P (TREE_TYPE (decl))
26881 && TREE_CODE (cond) == NE_EXPR)
26883 if (TREE_OPERAND (t, 0) == decl)
26884 t = TREE_OPERAND (t, 1);
26885 else
26886 t = TREE_OPERAND (t, 0);
26887 if (TREE_CODE (t) != INTEGER_CST)
26888 return true;
26894 return false;
26897 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
26898 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
26899 no such TYPE can be found. Note that this function peers inside
26900 uninstantiated templates and therefore should be used only in
26901 extremely limited situations. ONLY_CURRENT_P restricts this
26902 peering to the currently open classes hierarchy (which is required
26903 when comparing types). */
26905 tree
26906 resolve_typename_type (tree type, bool only_current_p)
26908 tree scope;
26909 tree name;
26910 tree decl;
26911 int quals;
26912 tree pushed_scope;
26913 tree result;
26915 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
26917 scope = TYPE_CONTEXT (type);
26918 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
26919 gcc_checking_assert (uses_template_parms (scope));
26921 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
26922 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
26923 a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
26924 the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
26925 identifier of the TYPENAME_TYPE anymore.
26926 So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
26927 TYPENAME_TYPE instead, we avoid messing up with a possible
26928 typedef variant case. */
26929 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
26931 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
26932 it first before we can figure out what NAME refers to. */
26933 if (TREE_CODE (scope) == TYPENAME_TYPE)
26935 if (TYPENAME_IS_RESOLVING_P (scope))
26936 /* Given a class template A with a dependent base with nested type C,
26937 typedef typename A::C::C C will land us here, as trying to resolve
26938 the initial A::C leads to the local C typedef, which leads back to
26939 A::C::C. So we break the recursion now. */
26940 return type;
26941 else
26942 scope = resolve_typename_type (scope, only_current_p);
26944 /* If we don't know what SCOPE refers to, then we cannot resolve the
26945 TYPENAME_TYPE. */
26946 if (!CLASS_TYPE_P (scope))
26947 return type;
26948 /* If this is a typedef, we don't want to look inside (c++/11987). */
26949 if (typedef_variant_p (type))
26950 return type;
26951 /* If SCOPE isn't the template itself, it will not have a valid
26952 TYPE_FIELDS list. */
26953 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
26954 /* scope is either the template itself or a compatible instantiation
26955 like X<T>, so look up the name in the original template. */
26956 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
26957 /* If scope has no fields, it can't be a current instantiation. Check this
26958 before currently_open_class to avoid infinite recursion (71515). */
26959 if (!TYPE_FIELDS (scope))
26960 return type;
26961 /* If the SCOPE is not the current instantiation, there's no reason
26962 to look inside it. */
26963 if (only_current_p && !currently_open_class (scope))
26964 return type;
26965 /* Enter the SCOPE so that name lookup will be resolved as if we
26966 were in the class definition. In particular, SCOPE will no
26967 longer be considered a dependent type. */
26968 pushed_scope = push_scope (scope);
26969 /* Look up the declaration. */
26970 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
26971 tf_warning_or_error);
26973 result = NULL_TREE;
26975 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
26976 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
26977 tree fullname = TYPENAME_TYPE_FULLNAME (type);
26978 if (!decl)
26979 /*nop*/;
26980 else if (identifier_p (fullname)
26981 && TREE_CODE (decl) == TYPE_DECL)
26983 result = TREE_TYPE (decl);
26984 if (result == error_mark_node)
26985 result = NULL_TREE;
26987 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
26988 && DECL_CLASS_TEMPLATE_P (decl))
26990 /* Obtain the template and the arguments. */
26991 tree tmpl = TREE_OPERAND (fullname, 0);
26992 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
26994 /* We get here with a plain identifier because a previous tentative
26995 parse of the nested-name-specifier as part of a ptr-operator saw
26996 ::template X<A>. The use of ::template is necessary in a
26997 ptr-operator, but wrong in a declarator-id.
26999 [temp.names]: In a qualified-id of a declarator-id, the keyword
27000 template shall not appear at the top level. */
27001 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
27002 "keyword %<template%> not allowed in declarator-id");
27003 tmpl = decl;
27005 tree args = TREE_OPERAND (fullname, 1);
27006 /* Instantiate the template. */
27007 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
27008 /*entering_scope=*/true,
27009 tf_error | tf_user);
27010 if (result == error_mark_node)
27011 result = NULL_TREE;
27014 /* Leave the SCOPE. */
27015 if (pushed_scope)
27016 pop_scope (pushed_scope);
27018 /* If we failed to resolve it, return the original typename. */
27019 if (!result)
27020 return type;
27022 /* If lookup found a typename type, resolve that too. */
27023 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
27025 /* Ill-formed programs can cause infinite recursion here, so we
27026 must catch that. */
27027 TYPENAME_IS_RESOLVING_P (result) = 1;
27028 result = resolve_typename_type (result, only_current_p);
27029 TYPENAME_IS_RESOLVING_P (result) = 0;
27032 /* Qualify the resulting type. */
27033 quals = cp_type_quals (type);
27034 if (quals)
27035 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
27037 return result;
27040 /* EXPR is an expression which is not type-dependent. Return a proxy
27041 for EXPR that can be used to compute the types of larger
27042 expressions containing EXPR. */
27044 tree
27045 build_non_dependent_expr (tree expr)
27047 tree orig_expr = expr;
27048 tree inner_expr;
27050 /* When checking, try to get a constant value for all non-dependent
27051 expressions in order to expose bugs in *_dependent_expression_p
27052 and constexpr. This can affect code generation, see PR70704, so
27053 only do this for -fchecking=2. */
27054 if (flag_checking > 1
27055 && cxx_dialect >= cxx11
27056 /* Don't do this during nsdmi parsing as it can lead to
27057 unexpected recursive instantiations. */
27058 && !parsing_nsdmi ()
27059 /* Don't do this during concept processing either and for
27060 the same reason. */
27061 && !processing_constraint_expression_p ())
27062 fold_non_dependent_expr (expr);
27064 STRIP_ANY_LOCATION_WRAPPER (expr);
27066 /* Preserve OVERLOADs; the functions must be available to resolve
27067 types. */
27068 inner_expr = expr;
27069 if (TREE_CODE (inner_expr) == STMT_EXPR)
27070 inner_expr = stmt_expr_value_expr (inner_expr);
27071 if (TREE_CODE (inner_expr) == ADDR_EXPR)
27072 inner_expr = TREE_OPERAND (inner_expr, 0);
27073 if (TREE_CODE (inner_expr) == COMPONENT_REF)
27074 inner_expr = TREE_OPERAND (inner_expr, 1);
27075 if (is_overloaded_fn (inner_expr)
27076 || TREE_CODE (inner_expr) == OFFSET_REF)
27077 return orig_expr;
27078 /* There is no need to return a proxy for a variable or enumerator. */
27079 if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
27080 return orig_expr;
27081 /* Preserve string constants; conversions from string constants to
27082 "char *" are allowed, even though normally a "const char *"
27083 cannot be used to initialize a "char *". */
27084 if (TREE_CODE (expr) == STRING_CST)
27085 return orig_expr;
27086 /* Preserve void and arithmetic constants, as an optimization -- there is no
27087 reason to create a new node. */
27088 if (TREE_CODE (expr) == VOID_CST
27089 || TREE_CODE (expr) == INTEGER_CST
27090 || TREE_CODE (expr) == REAL_CST)
27091 return orig_expr;
27092 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
27093 There is at least one place where we want to know that a
27094 particular expression is a throw-expression: when checking a ?:
27095 expression, there are special rules if the second or third
27096 argument is a throw-expression. */
27097 if (TREE_CODE (expr) == THROW_EXPR)
27098 return orig_expr;
27100 /* Don't wrap an initializer list, we need to be able to look inside. */
27101 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
27102 return orig_expr;
27104 /* Don't wrap a dummy object, we need to be able to test for it. */
27105 if (is_dummy_object (expr))
27106 return orig_expr;
27108 if (TREE_CODE (expr) == COND_EXPR)
27109 return build3 (COND_EXPR,
27110 TREE_TYPE (expr),
27111 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
27112 (TREE_OPERAND (expr, 1)
27113 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
27114 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
27115 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
27116 if (TREE_CODE (expr) == COMPOUND_EXPR
27117 && !COMPOUND_EXPR_OVERLOADED (expr))
27118 return build2 (COMPOUND_EXPR,
27119 TREE_TYPE (expr),
27120 TREE_OPERAND (expr, 0),
27121 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
27123 /* If the type is unknown, it can't really be non-dependent */
27124 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
27126 /* Otherwise, build a NON_DEPENDENT_EXPR. */
27127 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
27128 TREE_TYPE (expr), expr);
27131 /* ARGS is a vector of expressions as arguments to a function call.
27132 Replace the arguments with equivalent non-dependent expressions.
27133 This modifies ARGS in place. */
27135 void
27136 make_args_non_dependent (vec<tree, va_gc> *args)
27138 unsigned int ix;
27139 tree arg;
27141 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
27143 tree newarg = build_non_dependent_expr (arg);
27144 if (newarg != arg)
27145 (*args)[ix] = newarg;
27149 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
27150 TEMPLATE_TYPE_PARM with a level one deeper than the actual template
27151 parms. If set_canonical is true, we set TYPE_CANONICAL on it. */
27153 static tree
27154 make_auto_1 (tree name, bool set_canonical)
27156 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
27157 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
27158 TYPE_STUB_DECL (au) = TYPE_NAME (au);
27159 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
27160 (0, processing_template_decl + 1, processing_template_decl + 1,
27161 TYPE_NAME (au), NULL_TREE);
27162 if (set_canonical)
27163 TYPE_CANONICAL (au) = canonical_type_parameter (au);
27164 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
27165 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
27167 return au;
27170 tree
27171 make_decltype_auto (void)
27173 return make_auto_1 (decltype_auto_identifier, true);
27176 tree
27177 make_auto (void)
27179 return make_auto_1 (auto_identifier, true);
27182 /* Return a C++17 deduction placeholder for class template TMPL. */
27184 tree
27185 make_template_placeholder (tree tmpl)
27187 tree t = make_auto_1 (auto_identifier, false);
27188 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
27189 /* Our canonical type depends on the placeholder. */
27190 TYPE_CANONICAL (t) = canonical_type_parameter (t);
27191 return t;
27194 /* True iff T is a C++17 class template deduction placeholder. */
27196 bool
27197 template_placeholder_p (tree t)
27199 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
27202 /* Make a "constrained auto" type-specifier. This is an auto or
27203 decltype(auto) type with constraints that must be associated after
27204 deduction. The constraint is formed from the given concept CON
27205 and its optional sequence of template arguments ARGS.
27207 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
27209 static tree
27210 make_constrained_placeholder_type (tree type, tree con, tree args)
27212 /* Build the constraint. */
27213 tree tmpl = DECL_TI_TEMPLATE (con);
27214 tree expr = tmpl;
27215 if (TREE_CODE (con) == FUNCTION_DECL)
27216 expr = ovl_make (tmpl);
27217 expr = build_concept_check (expr, type, args, tf_warning_or_error);
27219 PLACEHOLDER_TYPE_CONSTRAINTS (type) = expr;
27221 /* Our canonical type depends on the constraint. */
27222 TYPE_CANONICAL (type) = canonical_type_parameter (type);
27224 /* Attach the constraint to the type declaration. */
27225 return TYPE_NAME (type);
27228 /* Make a "constrained auto" type-specifier. */
27230 tree
27231 make_constrained_auto (tree con, tree args)
27233 tree type = make_auto_1 (auto_identifier, false);
27234 return make_constrained_placeholder_type (type, con, args);
27237 /* Make a "constrained decltype(auto)" type-specifier. */
27239 tree
27240 make_constrained_decltype_auto (tree con, tree args)
27242 tree type = make_auto_1 (decltype_auto_identifier, false);
27243 /* FIXME: I don't know why this isn't done in make_auto_1. */
27244 AUTO_IS_DECLTYPE (type) = true;
27245 return make_constrained_placeholder_type (type, con, args);
27248 /* Build and return a concept definition. Like other templates, the
27249 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
27250 the TEMPLATE_DECL. */
27252 tree
27253 finish_concept_definition (cp_expr id, tree init)
27255 gcc_assert (identifier_p (id));
27256 gcc_assert (processing_template_decl);
27258 location_t loc = id.get_location();
27260 /* A concept-definition shall not have associated constraints. */
27261 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
27263 error_at (loc, "a concept cannot be constrained");
27264 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
27267 /* A concept-definition shall appear in namespace scope. Templates
27268 aren't allowed in block scope, so we only need to check for class
27269 scope. */
27270 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
27272 error_at (loc, "concept %qE not in namespace scope", *id);
27273 return error_mark_node;
27276 /* Initially build the concept declaration; it's type is bool. */
27277 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
27278 DECL_CONTEXT (decl) = current_scope ();
27279 DECL_INITIAL (decl) = init;
27281 /* Push the enclosing template. */
27282 return push_template_decl (decl);
27285 /* Given type ARG, return std::initializer_list<ARG>. */
27287 static tree
27288 listify (tree arg)
27290 tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
27292 if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
27294 gcc_rich_location richloc (input_location);
27295 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
27296 error_at (&richloc,
27297 "deducing from brace-enclosed initializer list"
27298 " requires %<#include <initializer_list>%>");
27300 return error_mark_node;
27302 tree argvec = make_tree_vec (1);
27303 TREE_VEC_ELT (argvec, 0) = arg;
27305 return lookup_template_class (std_init_list, argvec, NULL_TREE,
27306 NULL_TREE, 0, tf_warning_or_error);
27309 /* Replace auto in TYPE with std::initializer_list<auto>. */
27311 static tree
27312 listify_autos (tree type, tree auto_node)
27314 tree init_auto = listify (strip_top_quals (auto_node));
27315 tree argvec = make_tree_vec (1);
27316 TREE_VEC_ELT (argvec, 0) = init_auto;
27317 if (processing_template_decl)
27318 argvec = add_to_template_args (current_template_args (), argvec);
27319 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
27322 /* Hash traits for hashing possibly constrained 'auto'
27323 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
27325 struct auto_hash : default_hash_traits<tree>
27327 static inline hashval_t hash (tree);
27328 static inline bool equal (tree, tree);
27331 /* Hash the 'auto' T. */
27333 inline hashval_t
27334 auto_hash::hash (tree t)
27336 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
27337 /* Matching constrained-type-specifiers denote the same template
27338 parameter, so hash the constraint. */
27339 return hash_placeholder_constraint (c);
27340 else
27341 /* But unconstrained autos are all separate, so just hash the pointer. */
27342 return iterative_hash_object (t, 0);
27345 /* Compare two 'auto's. */
27347 inline bool
27348 auto_hash::equal (tree t1, tree t2)
27350 if (t1 == t2)
27351 return true;
27353 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
27354 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
27356 /* Two unconstrained autos are distinct. */
27357 if (!c1 || !c2)
27358 return false;
27360 return equivalent_placeholder_constraints (c1, c2);
27363 /* for_each_template_parm callback for extract_autos: if t is a (possibly
27364 constrained) auto, add it to the vector. */
27366 static int
27367 extract_autos_r (tree t, void *data)
27369 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
27370 if (is_auto (t))
27372 /* All the autos were built with index 0; fix that up now. */
27373 tree *p = hash.find_slot (t, INSERT);
27374 unsigned idx;
27375 if (*p)
27376 /* If this is a repeated constrained-type-specifier, use the index we
27377 chose before. */
27378 idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
27379 else
27381 /* Otherwise this is new, so use the current count. */
27382 *p = t;
27383 idx = hash.elements () - 1;
27385 TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
27388 /* Always keep walking. */
27389 return 0;
27392 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
27393 says they can appear anywhere in the type. */
27395 static tree
27396 extract_autos (tree type)
27398 hash_set<tree> visited;
27399 hash_table<auto_hash> hash (2);
27401 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
27403 tree tree_vec = make_tree_vec (hash.elements());
27404 for (hash_table<auto_hash>::iterator iter = hash.begin();
27405 iter != hash.end(); ++iter)
27407 tree elt = *iter;
27408 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
27409 TREE_VEC_ELT (tree_vec, i)
27410 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
27413 return tree_vec;
27416 /* The stem for deduction guide names. */
27417 const char *const dguide_base = "__dguide_";
27419 /* Return the name for a deduction guide for class template TMPL. */
27421 tree
27422 dguide_name (tree tmpl)
27424 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
27425 tree tname = TYPE_IDENTIFIER (type);
27426 char *buf = (char *) alloca (1 + strlen (dguide_base)
27427 + IDENTIFIER_LENGTH (tname));
27428 memcpy (buf, dguide_base, strlen (dguide_base));
27429 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
27430 IDENTIFIER_LENGTH (tname) + 1);
27431 tree dname = get_identifier (buf);
27432 TREE_TYPE (dname) = type;
27433 return dname;
27436 /* True if NAME is the name of a deduction guide. */
27438 bool
27439 dguide_name_p (tree name)
27441 return (TREE_CODE (name) == IDENTIFIER_NODE
27442 && TREE_TYPE (name)
27443 && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
27444 strlen (dguide_base)));
27447 /* True if FN is a deduction guide. */
27449 bool
27450 deduction_guide_p (const_tree fn)
27452 if (DECL_P (fn))
27453 if (tree name = DECL_NAME (fn))
27454 return dguide_name_p (name);
27455 return false;
27458 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
27460 bool
27461 copy_guide_p (const_tree fn)
27463 gcc_assert (deduction_guide_p (fn));
27464 if (!DECL_ARTIFICIAL (fn))
27465 return false;
27466 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
27467 return (TREE_CHAIN (parms) == void_list_node
27468 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
27471 /* True if FN is a guide generated from a constructor template. */
27473 bool
27474 template_guide_p (const_tree fn)
27476 gcc_assert (deduction_guide_p (fn));
27477 if (!DECL_ARTIFICIAL (fn))
27478 return false;
27479 tree tmpl = DECL_TI_TEMPLATE (fn);
27480 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
27481 return PRIMARY_TEMPLATE_P (org);
27482 return false;
27485 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
27486 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
27487 template parameter types. Note that the handling of template template
27488 parameters relies on current_template_parms being set appropriately for the
27489 new template. */
27491 static tree
27492 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
27493 tree tsubst_args, tsubst_flags_t complain)
27495 if (olddecl == error_mark_node)
27496 return error_mark_node;
27498 tree oldidx = get_template_parm_index (olddecl);
27500 tree newtype;
27501 if (TREE_CODE (olddecl) == TYPE_DECL
27502 || TREE_CODE (olddecl) == TEMPLATE_DECL)
27504 tree oldtype = TREE_TYPE (olddecl);
27505 newtype = cxx_make_type (TREE_CODE (oldtype));
27506 TYPE_MAIN_VARIANT (newtype) = newtype;
27507 if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
27508 TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
27509 = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
27511 else
27513 newtype = TREE_TYPE (olddecl);
27514 if (type_uses_auto (newtype))
27516 // Substitute once to fix references to other template parameters.
27517 newtype = tsubst (newtype, tsubst_args,
27518 complain|tf_partial, NULL_TREE);
27519 // Now substitute again to reduce the level of the auto.
27520 newtype = tsubst (newtype, current_template_args (),
27521 complain, NULL_TREE);
27523 else
27524 newtype = tsubst (newtype, tsubst_args,
27525 complain, NULL_TREE);
27528 tree newdecl
27529 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
27530 DECL_NAME (olddecl), newtype);
27531 SET_DECL_TEMPLATE_PARM_P (newdecl);
27533 tree newidx;
27534 if (TREE_CODE (olddecl) == TYPE_DECL
27535 || TREE_CODE (olddecl) == TEMPLATE_DECL)
27537 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
27538 = build_template_parm_index (index, level, level,
27539 newdecl, newtype);
27540 TEMPLATE_PARM_PARAMETER_PACK (newidx)
27541 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
27542 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
27543 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
27545 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
27547 DECL_TEMPLATE_RESULT (newdecl)
27548 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
27549 DECL_NAME (olddecl), newtype);
27550 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
27551 // First create a copy (ttargs) of tsubst_args with an
27552 // additional level for the template template parameter's own
27553 // template parameters (ttparms).
27554 tree ttparms = (INNERMOST_TEMPLATE_PARMS
27555 (DECL_TEMPLATE_PARMS (olddecl)));
27556 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
27557 tree ttargs = make_tree_vec (depth + 1);
27558 for (int i = 0; i < depth; ++i)
27559 TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
27560 TREE_VEC_ELT (ttargs, depth)
27561 = template_parms_level_to_args (ttparms);
27562 // Substitute ttargs into ttparms to fix references to
27563 // other template parameters.
27564 ttparms = tsubst_template_parms_level (ttparms, ttargs,
27565 complain|tf_partial);
27566 // Now substitute again with args based on tparms, to reduce
27567 // the level of the ttparms.
27568 ttargs = current_template_args ();
27569 ttparms = tsubst_template_parms_level (ttparms, ttargs,
27570 complain);
27571 // Finally, tack the adjusted parms onto tparms.
27572 ttparms = tree_cons (size_int (depth), ttparms,
27573 current_template_parms);
27574 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
27577 else
27579 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
27580 tree newconst
27581 = build_decl (DECL_SOURCE_LOCATION (oldconst),
27582 TREE_CODE (oldconst),
27583 DECL_NAME (oldconst), newtype);
27584 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
27585 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
27586 SET_DECL_TEMPLATE_PARM_P (newconst);
27587 newidx = build_template_parm_index (index, level, level,
27588 newconst, newtype);
27589 TEMPLATE_PARM_PARAMETER_PACK (newidx)
27590 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
27591 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
27594 return newdecl;
27597 /* Returns a C++17 class deduction guide template based on the constructor
27598 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
27599 guide, or REFERENCE_TYPE for an implicit copy/move guide. */
27601 static tree
27602 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
27604 tree type, tparms, targs, fparms, fargs, ci;
27605 bool memtmpl = false;
27606 bool explicit_p;
27607 location_t loc;
27608 tree fn_tmpl = NULL_TREE;
27610 if (TYPE_P (ctor))
27612 type = ctor;
27613 bool copy_p = TYPE_REF_P (type);
27614 if (copy_p)
27616 type = TREE_TYPE (type);
27617 fparms = tree_cons (NULL_TREE, type, void_list_node);
27619 else
27620 fparms = void_list_node;
27622 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
27623 tparms = DECL_TEMPLATE_PARMS (ctmpl);
27624 targs = CLASSTYPE_TI_ARGS (type);
27625 ci = NULL_TREE;
27626 fargs = NULL_TREE;
27627 loc = DECL_SOURCE_LOCATION (ctmpl);
27628 explicit_p = false;
27630 else
27632 ++processing_template_decl;
27633 bool ok = true;
27635 fn_tmpl
27636 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
27637 : DECL_TI_TEMPLATE (ctor));
27638 if (outer_args)
27639 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
27640 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
27642 type = DECL_CONTEXT (ctor);
27644 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
27645 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
27646 fully specialized args for the enclosing class. Strip those off, as
27647 the deduction guide won't have those template parameters. */
27648 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
27649 TMPL_PARMS_DEPTH (tparms));
27650 /* Discard the 'this' parameter. */
27651 fparms = FUNCTION_ARG_CHAIN (ctor);
27652 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
27653 ci = get_constraints (ctor);
27654 loc = DECL_SOURCE_LOCATION (ctor);
27655 explicit_p = DECL_NONCONVERTING_P (ctor);
27657 if (PRIMARY_TEMPLATE_P (fn_tmpl))
27659 memtmpl = true;
27661 /* For a member template constructor, we need to flatten the two
27662 template parameter lists into one, and then adjust the function
27663 signature accordingly. This gets...complicated. */
27664 tree save_parms = current_template_parms;
27666 /* For a member template we should have two levels of parms/args, one
27667 for the class and one for the constructor. We stripped
27668 specialized args for further enclosing classes above. */
27669 const int depth = 2;
27670 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
27672 /* Template args for translating references to the two-level template
27673 parameters into references to the one-level template parameters we
27674 are creating. */
27675 tree tsubst_args = copy_node (targs);
27676 TMPL_ARGS_LEVEL (tsubst_args, depth)
27677 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
27679 /* Template parms for the constructor template. */
27680 tree ftparms = TREE_VALUE (tparms);
27681 unsigned flen = TREE_VEC_LENGTH (ftparms);
27682 /* Template parms for the class template. */
27683 tparms = TREE_CHAIN (tparms);
27684 tree ctparms = TREE_VALUE (tparms);
27685 unsigned clen = TREE_VEC_LENGTH (ctparms);
27686 /* Template parms for the deduction guide start as a copy of the
27687 template parms for the class. We set current_template_parms for
27688 lookup_template_class_1. */
27689 current_template_parms = tparms = copy_node (tparms);
27690 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
27691 for (unsigned i = 0; i < clen; ++i)
27692 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
27694 /* Now we need to rewrite the constructor parms to append them to the
27695 class parms. */
27696 for (unsigned i = 0; i < flen; ++i)
27698 unsigned index = i + clen;
27699 unsigned level = 1;
27700 tree oldelt = TREE_VEC_ELT (ftparms, i);
27701 tree olddecl = TREE_VALUE (oldelt);
27702 tree newdecl = rewrite_template_parm (olddecl, index, level,
27703 tsubst_args, complain);
27704 if (newdecl == error_mark_node)
27705 ok = false;
27706 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
27707 tsubst_args, complain, ctor);
27708 tree list = build_tree_list (newdef, newdecl);
27709 TEMPLATE_PARM_CONSTRAINTS (list)
27710 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
27711 tsubst_args, complain, ctor);
27712 TREE_VEC_ELT (new_vec, index) = list;
27713 TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
27716 /* Now we have a final set of template parms to substitute into the
27717 function signature. */
27718 targs = template_parms_to_args (tparms);
27719 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
27720 complain, ctor);
27721 if (fparms == error_mark_node)
27722 ok = false;
27723 fargs = tsubst (fargs, tsubst_args, complain, ctor);
27724 if (ci)
27725 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
27727 current_template_parms = save_parms;
27730 --processing_template_decl;
27731 if (!ok)
27732 return error_mark_node;
27735 if (!memtmpl)
27737 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
27738 tparms = copy_node (tparms);
27739 INNERMOST_TEMPLATE_PARMS (tparms)
27740 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
27743 tree fntype = build_function_type (type, fparms);
27744 tree ded_fn = build_lang_decl_loc (loc,
27745 FUNCTION_DECL,
27746 dguide_name (type), fntype);
27747 DECL_ARGUMENTS (ded_fn) = fargs;
27748 DECL_ARTIFICIAL (ded_fn) = true;
27749 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
27750 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
27751 DECL_ARTIFICIAL (ded_tmpl) = true;
27752 DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
27753 TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
27754 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
27755 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
27756 if (DECL_P (ctor))
27757 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
27758 if (ci)
27759 set_constraints (ded_tmpl, ci);
27761 return ded_tmpl;
27764 /* Deduce template arguments for the class template placeholder PTYPE for
27765 template TMPL based on the initializer INIT, and return the resulting
27766 type. */
27768 static tree
27769 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
27770 tsubst_flags_t complain)
27772 if (!DECL_CLASS_TEMPLATE_P (tmpl))
27774 /* We should have handled this in the caller. */
27775 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
27776 return ptype;
27777 if (complain & tf_error)
27778 error ("non-class template %qT used without template arguments", tmpl);
27779 return error_mark_node;
27781 if (init && TREE_TYPE (init) == ptype)
27782 /* Using the template parm as its own argument. */
27783 return ptype;
27785 tree type = TREE_TYPE (tmpl);
27787 bool try_list_ctor = false;
27789 releasing_vec rv_args = NULL;
27790 vec<tree,va_gc> *&args = *&rv_args;
27791 if (init == NULL_TREE
27792 || TREE_CODE (init) == TREE_LIST)
27793 args = make_tree_vector_from_list (init);
27794 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
27796 try_list_ctor = TYPE_HAS_LIST_CTOR (type);
27797 if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
27799 /* As an exception, the first phase in 16.3.1.7 (considering the
27800 initializer list as a single argument) is omitted if the
27801 initializer list consists of a single expression of type cv U,
27802 where U is a specialization of C or a class derived from a
27803 specialization of C. */
27804 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
27805 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
27807 tree etype = TREE_TYPE (elt);
27808 tree tparms = (INNERMOST_TEMPLATE_PARMS
27809 (DECL_TEMPLATE_PARMS (tmpl)));
27810 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
27811 int err = unify (tparms, targs, type, etype,
27812 UNIFY_ALLOW_DERIVED, /*explain*/false);
27813 if (err == 0)
27814 try_list_ctor = false;
27815 ggc_free (targs);
27818 if (try_list_ctor || is_std_init_list (type))
27819 args = make_tree_vector_single (init);
27820 else
27821 args = make_tree_vector_from_ctor (init);
27823 else
27824 args = make_tree_vector_single (init);
27826 tree dname = dguide_name (tmpl);
27827 tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
27828 /*type*/false, /*complain*/false,
27829 /*hidden*/false);
27830 bool elided = false;
27831 if (cands == error_mark_node)
27832 cands = NULL_TREE;
27834 /* Prune explicit deduction guides in copy-initialization context. */
27835 if (flags & LOOKUP_ONLYCONVERTING)
27837 for (lkp_iterator iter (cands); !elided && iter; ++iter)
27838 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
27839 elided = true;
27841 if (elided)
27843 /* Found a nonconverting guide, prune the candidates. */
27844 tree pruned = NULL_TREE;
27845 for (lkp_iterator iter (cands); iter; ++iter)
27846 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
27847 pruned = lookup_add (*iter, pruned);
27849 cands = pruned;
27853 tree outer_args = NULL_TREE;
27854 if (DECL_CLASS_SCOPE_P (tmpl)
27855 && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
27857 outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
27858 type = TREE_TYPE (most_general_template (tmpl));
27861 bool saw_ctor = false;
27862 // FIXME cache artificial deduction guides
27863 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
27865 /* Skip inherited constructors. */
27866 if (iter.using_p ())
27867 continue;
27869 tree guide = build_deduction_guide (*iter, outer_args, complain);
27870 if (guide == error_mark_node)
27871 return error_mark_node;
27872 if ((flags & LOOKUP_ONLYCONVERTING)
27873 && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
27874 elided = true;
27875 else
27876 cands = lookup_add (guide, cands);
27878 saw_ctor = true;
27881 tree call = error_mark_node;
27883 /* If this is list-initialization and the class has a list constructor, first
27884 try deducing from the list as a single argument, as [over.match.list]. */
27885 tree list_cands = NULL_TREE;
27886 if (try_list_ctor && cands)
27887 for (lkp_iterator iter (cands); iter; ++iter)
27889 tree dg = *iter;
27890 if (is_list_ctor (dg))
27891 list_cands = lookup_add (dg, list_cands);
27893 if (list_cands)
27895 ++cp_unevaluated_operand;
27896 call = build_new_function_call (list_cands, &args, tf_decltype);
27897 --cp_unevaluated_operand;
27899 if (call == error_mark_node)
27901 /* That didn't work, now try treating the list as a sequence of
27902 arguments. */
27903 release_tree_vector (args);
27904 args = make_tree_vector_from_ctor (init);
27908 /* Maybe generate an implicit deduction guide. */
27909 if (call == error_mark_node && args->length () < 2)
27911 tree gtype = NULL_TREE;
27913 if (args->length () == 1)
27914 /* Generate a copy guide. */
27915 gtype = build_reference_type (type);
27916 else if (!saw_ctor)
27917 /* Generate a default guide. */
27918 gtype = type;
27920 if (gtype)
27922 tree guide = build_deduction_guide (gtype, outer_args, complain);
27923 if (guide == error_mark_node)
27924 return error_mark_node;
27925 cands = lookup_add (guide, cands);
27929 if (elided && !cands)
27931 error ("cannot deduce template arguments for copy-initialization"
27932 " of %qT, as it has no non-explicit deduction guides or "
27933 "user-declared constructors", type);
27934 return error_mark_node;
27936 else if (!cands && call == error_mark_node)
27938 error ("cannot deduce template arguments of %qT, as it has no viable "
27939 "deduction guides", type);
27940 return error_mark_node;
27943 if (call == error_mark_node)
27945 ++cp_unevaluated_operand;
27946 call = build_new_function_call (cands, &args, tf_decltype);
27947 --cp_unevaluated_operand;
27950 if (call == error_mark_node && (complain & tf_warning_or_error))
27952 error ("class template argument deduction failed:");
27954 ++cp_unevaluated_operand;
27955 call = build_new_function_call (cands, &args, complain | tf_decltype);
27956 --cp_unevaluated_operand;
27958 if (elided)
27959 inform (input_location, "explicit deduction guides not considered "
27960 "for copy-initialization");
27963 return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
27966 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
27967 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
27968 The CONTEXT determines the context in which auto deduction is performed
27969 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
27970 OUTER_TARGS are used during template argument deduction
27971 (context == adc_unify) to properly substitute the result, and is ignored
27972 in other contexts.
27974 For partial-concept-ids, extra args may be appended to the list of deduced
27975 template arguments prior to determining constraint satisfaction. */
27977 tree
27978 do_auto_deduction (tree type, tree init, tree auto_node,
27979 tsubst_flags_t complain, auto_deduction_context context,
27980 tree outer_targs, int flags)
27982 tree targs;
27984 if (init == error_mark_node)
27985 return error_mark_node;
27987 if (init && type_dependent_expression_p (init)
27988 && context != adc_unify)
27989 /* Defining a subset of type-dependent expressions that we can deduce
27990 from ahead of time isn't worth the trouble. */
27991 return type;
27993 /* Similarly, we can't deduce from another undeduced decl. */
27994 if (init && undeduced_auto_decl (init))
27995 return type;
27997 /* We may be doing a partial substitution, but we still want to replace
27998 auto_node. */
27999 complain &= ~tf_partial;
28001 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
28002 /* C++17 class template argument deduction. */
28003 return do_class_deduction (type, tmpl, init, flags, complain);
28005 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
28006 /* Nothing we can do with this, even in deduction context. */
28007 return type;
28009 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
28010 with either a new invented type template parameter U or, if the
28011 initializer is a braced-init-list (8.5.4), with
28012 std::initializer_list<U>. */
28013 if (BRACE_ENCLOSED_INITIALIZER_P (init))
28015 if (!DIRECT_LIST_INIT_P (init))
28016 type = listify_autos (type, auto_node);
28017 else if (CONSTRUCTOR_NELTS (init) == 1)
28018 init = CONSTRUCTOR_ELT (init, 0)->value;
28019 else
28021 if (complain & tf_warning_or_error)
28023 if (permerror (input_location, "direct-list-initialization of "
28024 "%<auto%> requires exactly one element"))
28025 inform (input_location,
28026 "for deduction to %<std::initializer_list%>, use copy-"
28027 "list-initialization (i.e. add %<=%> before the %<{%>)");
28029 type = listify_autos (type, auto_node);
28033 if (type == error_mark_node)
28034 return error_mark_node;
28036 init = resolve_nondeduced_context (init, complain);
28038 if (context == adc_decomp_type
28039 && auto_node == type
28040 && init != error_mark_node
28041 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
28042 /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
28043 and initializer has array type, deduce cv-qualified array type. */
28044 return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
28045 complain);
28046 else if (AUTO_IS_DECLTYPE (auto_node))
28048 tree stripped_init = tree_strip_any_location_wrapper (init);
28049 bool id = (DECL_P (stripped_init)
28050 || ((TREE_CODE (init) == COMPONENT_REF
28051 || TREE_CODE (init) == SCOPE_REF)
28052 && !REF_PARENTHESIZED_P (init)));
28053 targs = make_tree_vec (1);
28054 TREE_VEC_ELT (targs, 0)
28055 = finish_decltype_type (init, id, tf_warning_or_error);
28056 if (type != auto_node)
28058 if (complain & tf_error)
28059 error ("%qT as type rather than plain %<decltype(auto)%>", type);
28060 return error_mark_node;
28063 else
28065 if (error_operand_p (init))
28066 return error_mark_node;
28068 tree parms = build_tree_list (NULL_TREE, type);
28069 tree tparms;
28071 if (flag_concepts)
28072 tparms = extract_autos (type);
28073 else
28075 tparms = make_tree_vec (1);
28076 TREE_VEC_ELT (tparms, 0)
28077 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
28080 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
28081 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
28082 DEDUCE_CALL,
28083 NULL, /*explain_p=*/false);
28084 if (val > 0)
28086 if (processing_template_decl)
28087 /* Try again at instantiation time. */
28088 return type;
28089 if (type && type != error_mark_node
28090 && (complain & tf_error))
28091 /* If type is error_mark_node a diagnostic must have been
28092 emitted by now. Also, having a mention to '<type error>'
28093 in the diagnostic is not really useful to the user. */
28095 if (cfun
28096 && FNDECL_USED_AUTO (current_function_decl)
28097 && (auto_node
28098 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
28099 && LAMBDA_FUNCTION_P (current_function_decl))
28100 error ("unable to deduce lambda return type from %qE", init);
28101 else
28102 error ("unable to deduce %qT from %qE", type, init);
28103 type_unification_real (tparms, targs, parms, &init, 1, 0,
28104 DEDUCE_CALL,
28105 NULL, /*explain_p=*/true);
28107 return error_mark_node;
28111 /* Check any placeholder constraints against the deduced type. */
28112 if (flag_concepts && !processing_template_decl)
28113 if (tree check = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
28115 /* Use the deduced type to check the associated constraints. If we
28116 have a partial-concept-id, rebuild the argument list so that
28117 we check using the extra arguments. */
28118 check = unpack_concept_check (check);
28119 gcc_assert (TREE_CODE (check) == TEMPLATE_ID_EXPR);
28120 tree cdecl = TREE_OPERAND (check, 0);
28121 if (OVL_P (cdecl))
28122 cdecl = OVL_FIRST (cdecl);
28123 tree cargs = TREE_OPERAND (check, 1);
28124 if (TREE_VEC_LENGTH (cargs) > 1)
28126 cargs = copy_node (cargs);
28127 TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
28129 else
28130 cargs = targs;
28132 /* Rebuild the check using the deduced arguments. */
28133 check = build_concept_check (cdecl, cargs, tf_none);
28135 if (!constraints_satisfied_p (check, cargs))
28137 if (complain & tf_warning_or_error)
28139 auto_diagnostic_group d;
28140 switch (context)
28142 case adc_unspecified:
28143 case adc_unify:
28144 error("placeholder constraints not satisfied");
28145 break;
28146 case adc_variable_type:
28147 case adc_decomp_type:
28148 error ("deduced initializer does not satisfy "
28149 "placeholder constraints");
28150 break;
28151 case adc_return_type:
28152 error ("deduced return type does not satisfy "
28153 "placeholder constraints");
28154 break;
28155 case adc_requirement:
28156 error ("deduced expression type does not satisfy "
28157 "placeholder constraints");
28158 break;
28160 diagnose_constraints (input_location, check, targs);
28162 return error_mark_node;
28166 if (processing_template_decl && context != adc_unify)
28167 outer_targs = current_template_args ();
28168 targs = add_to_template_args (outer_targs, targs);
28169 return tsubst (type, targs, complain, NULL_TREE);
28172 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
28173 result. */
28175 tree
28176 splice_late_return_type (tree type, tree late_return_type)
28178 if (is_auto (type))
28180 if (late_return_type)
28181 return late_return_type;
28183 tree idx = get_template_parm_index (type);
28184 if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
28185 /* In an abbreviated function template we didn't know we were dealing
28186 with a function template when we saw the auto return type, so update
28187 it to have the correct level. */
28188 return make_auto_1 (TYPE_IDENTIFIER (type), true);
28190 return type;
28193 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
28194 'decltype(auto)' or a deduced class template. */
28196 bool
28197 is_auto (const_tree type)
28199 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
28200 && (TYPE_IDENTIFIER (type) == auto_identifier
28201 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
28202 return true;
28203 else
28204 return false;
28207 /* for_each_template_parm callback for type_uses_auto. */
28210 is_auto_r (tree tp, void */*data*/)
28212 return is_auto (tp);
28215 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
28216 a use of `auto'. Returns NULL_TREE otherwise. */
28218 tree
28219 type_uses_auto (tree type)
28221 if (type == NULL_TREE)
28222 return NULL_TREE;
28223 else if (flag_concepts)
28225 /* The Concepts TS allows multiple autos in one type-specifier; just
28226 return the first one we find, do_auto_deduction will collect all of
28227 them. */
28228 if (uses_template_parms (type))
28229 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
28230 /*visited*/NULL, /*nondeduced*/false);
28231 else
28232 return NULL_TREE;
28234 else
28235 return find_type_usage (type, is_auto);
28238 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
28239 concepts are enabled, auto is acceptable in template arguments, but
28240 only when TEMPL identifies a template class. Return TRUE if any
28241 such errors were reported. */
28243 bool
28244 check_auto_in_tmpl_args (tree tmpl, tree args)
28246 /* If there were previous errors, nevermind. */
28247 if (!args || TREE_CODE (args) != TREE_VEC)
28248 return false;
28250 /* If TMPL is an identifier, we're parsing and we can't tell yet
28251 whether TMPL is supposed to be a type, a function or a variable.
28252 We'll only be able to tell during template substitution, so we
28253 expect to be called again then. If concepts are enabled and we
28254 know we have a type, we're ok. */
28255 if (flag_concepts
28256 && (identifier_p (tmpl)
28257 || (DECL_P (tmpl)
28258 && (DECL_TYPE_TEMPLATE_P (tmpl)
28259 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
28260 return false;
28262 /* Quickly search for any occurrences of auto; usually there won't
28263 be any, and then we'll avoid allocating the vector. */
28264 if (!type_uses_auto (args))
28265 return false;
28267 bool errors = false;
28269 tree vec = extract_autos (args);
28270 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
28272 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
28273 error_at (DECL_SOURCE_LOCATION (xauto),
28274 "invalid use of %qT in template argument", xauto);
28275 errors = true;
28278 return errors;
28281 /* For a given template T, return the vector of typedefs referenced
28282 in T for which access check is needed at T instantiation time.
28283 T is either a FUNCTION_DECL or a RECORD_TYPE.
28284 Those typedefs were added to T by the function
28285 append_type_to_template_for_access_check. */
28287 vec<qualified_typedef_usage_t, va_gc> *
28288 get_types_needing_access_check (tree t)
28290 tree ti;
28291 vec<qualified_typedef_usage_t, va_gc> *result = NULL;
28293 if (!t || t == error_mark_node)
28294 return NULL;
28296 if (!(ti = get_template_info (t)))
28297 return NULL;
28299 if (CLASS_TYPE_P (t)
28300 || TREE_CODE (t) == FUNCTION_DECL)
28302 if (!TI_TEMPLATE (ti))
28303 return NULL;
28305 result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
28308 return result;
28311 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
28312 tied to T. That list of typedefs will be access checked at
28313 T instantiation time.
28314 T is either a FUNCTION_DECL or a RECORD_TYPE.
28315 TYPE_DECL is a TYPE_DECL node representing a typedef.
28316 SCOPE is the scope through which TYPE_DECL is accessed.
28317 LOCATION is the location of the usage point of TYPE_DECL.
28319 This function is a subroutine of
28320 append_type_to_template_for_access_check. */
28322 static void
28323 append_type_to_template_for_access_check_1 (tree t,
28324 tree type_decl,
28325 tree scope,
28326 location_t location)
28328 qualified_typedef_usage_t typedef_usage;
28329 tree ti;
28331 if (!t || t == error_mark_node)
28332 return;
28334 gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
28335 || CLASS_TYPE_P (t))
28336 && type_decl
28337 && TREE_CODE (type_decl) == TYPE_DECL
28338 && scope);
28340 if (!(ti = get_template_info (t)))
28341 return;
28343 gcc_assert (TI_TEMPLATE (ti));
28345 typedef_usage.typedef_decl = type_decl;
28346 typedef_usage.context = scope;
28347 typedef_usage.locus = location;
28349 vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
28352 /* Append TYPE_DECL to the template TEMPL.
28353 TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
28354 At TEMPL instanciation time, TYPE_DECL will be checked to see
28355 if it can be accessed through SCOPE.
28356 LOCATION is the location of the usage point of TYPE_DECL.
28358 e.g. consider the following code snippet:
28360 class C
28362 typedef int myint;
28365 template<class U> struct S
28367 C::myint mi; // <-- usage point of the typedef C::myint
28370 S<char> s;
28372 At S<char> instantiation time, we need to check the access of C::myint
28373 In other words, we need to check the access of the myint typedef through
28374 the C scope. For that purpose, this function will add the myint typedef
28375 and the scope C through which its being accessed to a list of typedefs
28376 tied to the template S. That list will be walked at template instantiation
28377 time and access check performed on each typedefs it contains.
28378 Note that this particular code snippet should yield an error because
28379 myint is private to C. */
28381 void
28382 append_type_to_template_for_access_check (tree templ,
28383 tree type_decl,
28384 tree scope,
28385 location_t location)
28387 qualified_typedef_usage_t *iter;
28388 unsigned i;
28390 gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
28392 /* Make sure we don't append the type to the template twice. */
28393 FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
28394 if (iter->typedef_decl == type_decl && scope == iter->context)
28395 return;
28397 append_type_to_template_for_access_check_1 (templ, type_decl,
28398 scope, location);
28401 /* Recursively walk over && expressions searching for EXPR. Return a reference
28402 to that expression. */
28404 static tree *find_template_requirement (tree *t, tree key)
28406 if (*t == key)
28407 return t;
28408 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
28410 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
28411 return p;
28412 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
28413 return p;
28415 return 0;
28418 /* Convert the generic type parameters in PARM that match the types given in the
28419 range [START_IDX, END_IDX) from the current_template_parms into generic type
28420 packs. */
28422 tree
28423 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
28425 tree current = current_template_parms;
28426 int depth = TMPL_PARMS_DEPTH (current);
28427 current = INNERMOST_TEMPLATE_PARMS (current);
28428 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
28430 for (int i = 0; i < start_idx; ++i)
28431 TREE_VEC_ELT (replacement, i)
28432 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
28434 for (int i = start_idx; i < end_idx; ++i)
28436 /* Create a distinct parameter pack type from the current parm and add it
28437 to the replacement args to tsubst below into the generic function
28438 parameter. */
28439 tree node = TREE_VEC_ELT (current, i);
28440 tree o = TREE_TYPE (TREE_VALUE (node));
28441 tree t = copy_type (o);
28442 TEMPLATE_TYPE_PARM_INDEX (t)
28443 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
28444 o, 0, 0, tf_none);
28445 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
28446 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
28447 TYPE_MAIN_VARIANT (t) = t;
28448 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
28449 TYPE_CANONICAL (t) = canonical_type_parameter (t);
28450 TREE_VEC_ELT (replacement, i) = t;
28452 /* Replace the current template parameter with new pack. */
28453 TREE_VALUE (node) = TREE_CHAIN (t);
28455 /* Surgically adjust the associated constraint of adjusted parameter
28456 and it's corresponding contribution to the current template
28457 requirements. */
28458 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
28460 tree id = unpack_concept_check (constr);
28461 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = template_parm_to_arg (t);
28462 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
28463 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
28465 /* If there was a constraint, we also need to replace that in
28466 the template requirements, which we've already built. */
28467 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
28468 reqs = find_template_requirement (reqs, constr);
28469 *reqs = fold;
28473 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
28474 TREE_VEC_ELT (replacement, i)
28475 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
28477 /* If there are more levels then build up the replacement with the outer
28478 template parms. */
28479 if (depth > 1)
28480 replacement = add_to_template_args (template_parms_to_args
28481 (TREE_CHAIN (current_template_parms)),
28482 replacement);
28484 return tsubst (parm, replacement, tf_none, NULL_TREE);
28487 /* A mapping from declarations to constraint information. Note that
28488 both templates and their underlying declarations are mapped to the
28489 same constraint information.
28491 FIXME: This is defined in pt.c because garbage collection
28492 code is not being generated for constraint.cc. */
28494 static GTY ((cache)) tree_cache_map *decl_constraints;
28496 /* Returns the template constraints of declaration T. If T is not
28497 constrained, return NULL_TREE. Note that T must be non-null. */
28499 tree
28500 get_constraints (tree t)
28502 if (!flag_concepts)
28503 return NULL_TREE;
28504 if (!decl_constraints)
28505 return NULL_TREE;
28507 gcc_assert (DECL_P (t));
28508 if (TREE_CODE (t) == TEMPLATE_DECL)
28509 t = DECL_TEMPLATE_RESULT (t);
28510 tree* found = decl_constraints->get (t);
28511 if (found)
28512 return *found;
28513 else
28514 return NULL_TREE;
28517 /* Associate the given constraint information CI with the declaration
28518 T. If T is a template, then the constraints are associated with
28519 its underlying declaration. Don't build associations if CI is
28520 NULL_TREE. */
28522 void
28523 set_constraints (tree t, tree ci)
28525 if (!ci)
28526 return;
28527 gcc_assert (t && flag_concepts);
28528 if (TREE_CODE (t) == TEMPLATE_DECL)
28529 t = DECL_TEMPLATE_RESULT (t);
28530 bool found = hash_map_safe_put<hm_ggc> (decl_constraints, t, ci);
28531 gcc_assert (!found);
28534 /* Remove the associated constraints of the declaration T. */
28536 void
28537 remove_constraints (tree t)
28539 gcc_assert (DECL_P (t));
28540 if (TREE_CODE (t) == TEMPLATE_DECL)
28541 t = DECL_TEMPLATE_RESULT (t);
28543 if (decl_constraints)
28544 decl_constraints->remove (t);
28547 static hashval_t
28548 hash_subsumption_args (tree t1, tree t2)
28550 gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
28551 gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
28552 int val = 0;
28553 val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
28554 val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
28555 val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
28556 val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
28557 return val;
28560 /* Compare the constraints of two subsumption entries. The LEFT1 and
28561 LEFT2 arguments comprise the first subsumption pair and the RIGHT1
28562 and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
28564 static bool
28565 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
28567 if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
28568 if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
28569 if (comp_template_args (CHECK_CONSTR_ARGS (left1),
28570 CHECK_CONSTR_ARGS (right1)))
28571 return comp_template_args (CHECK_CONSTR_ARGS (left2),
28572 CHECK_CONSTR_ARGS (right2));
28573 return false;
28576 /* Key/value pair for learning and memoizing subsumption results. This
28577 associates a pair of check constraints (including arguments) with
28578 a boolean value indicating the result. */
28580 struct GTY((for_user)) subsumption_entry
28582 tree t1;
28583 tree t2;
28584 bool result;
28587 /* Hashing function and equality for constraint entries. */
28589 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
28591 static hashval_t hash (subsumption_entry *e)
28593 return hash_subsumption_args (e->t1, e->t2);
28596 static bool equal (subsumption_entry *e1, subsumption_entry *e2)
28598 ++comparing_specializations;
28599 bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
28600 --comparing_specializations;
28601 return eq;
28605 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
28607 /* Search for a previously cached subsumption result. */
28609 bool*
28610 lookup_subsumption_result (tree t1, tree t2)
28612 subsumption_entry elt = { t1, t2, false };
28613 subsumption_entry* found = subsumption_table->find (&elt);
28614 if (found)
28615 return &found->result;
28616 else
28617 return 0;
28620 /* Save a subsumption result. */
28622 bool
28623 save_subsumption_result (tree t1, tree t2, bool result)
28625 subsumption_entry elt = {t1, t2, result};
28626 subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
28627 subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
28628 *entry = elt;
28629 *slot = entry;
28630 return result;
28633 /* Set up the hash table for constraint association. */
28635 void
28636 init_constraint_processing (void)
28638 if (!flag_concepts)
28639 return;
28641 subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
28644 GTY(()) tree current_failed_constraint;
28646 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
28647 0..N-1. */
28649 void
28650 declare_integer_pack (void)
28652 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
28653 build_function_type_list (integer_type_node,
28654 integer_type_node,
28655 NULL_TREE),
28656 NULL_TREE, ECF_CONST);
28657 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
28658 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
28659 CP_BUILT_IN_INTEGER_PACK);
28662 /* Set up the hash tables for template instantiations. */
28664 void
28665 init_template_processing (void)
28667 /* FIXME: enable sanitization (PR87847) */
28668 decl_specializations = hash_table<spec_hasher>::create_ggc (37, false);
28669 type_specializations = hash_table<spec_hasher>::create_ggc (37, false);
28671 if (cxx_dialect >= cxx11)
28672 declare_integer_pack ();
28675 /* Print stats about the template hash tables for -fstats. */
28677 void
28678 print_template_statistics (void)
28680 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
28681 "%f collisions\n", (long) decl_specializations->size (),
28682 (long) decl_specializations->elements (),
28683 decl_specializations->collisions ());
28684 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
28685 "%f collisions\n", (long) type_specializations->size (),
28686 (long) type_specializations->elements (),
28687 type_specializations->collisions ());
28690 #if CHECKING_P
28692 namespace selftest {
28694 /* Verify that build_non_dependent_expr () works, for various expressions,
28695 and that location wrappers don't affect the results. */
28697 static void
28698 test_build_non_dependent_expr ()
28700 location_t loc = BUILTINS_LOCATION;
28702 /* Verify constants, without and with location wrappers. */
28703 tree int_cst = build_int_cst (integer_type_node, 42);
28704 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
28706 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
28707 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
28708 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
28710 tree string_lit = build_string (4, "foo");
28711 TREE_TYPE (string_lit) = char_array_type_node;
28712 string_lit = fix_string_type (string_lit);
28713 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
28715 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
28716 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
28717 ASSERT_EQ (wrapped_string_lit,
28718 build_non_dependent_expr (wrapped_string_lit));
28721 /* Verify that type_dependent_expression_p () works correctly, even
28722 in the presence of location wrapper nodes. */
28724 static void
28725 test_type_dependent_expression_p ()
28727 location_t loc = BUILTINS_LOCATION;
28729 tree name = get_identifier ("foo");
28731 /* If no templates are involved, nothing is type-dependent. */
28732 gcc_assert (!processing_template_decl);
28733 ASSERT_FALSE (type_dependent_expression_p (name));
28735 ++processing_template_decl;
28737 /* Within a template, an unresolved name is always type-dependent. */
28738 ASSERT_TRUE (type_dependent_expression_p (name));
28740 /* Ensure it copes with NULL_TREE and errors. */
28741 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
28742 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
28744 /* A USING_DECL in a template should be type-dependent, even if wrapped
28745 with a location wrapper (PR c++/83799). */
28746 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
28747 TREE_TYPE (using_decl) = integer_type_node;
28748 ASSERT_TRUE (type_dependent_expression_p (using_decl));
28749 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
28750 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
28751 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
28753 --processing_template_decl;
28756 /* Run all of the selftests within this file. */
28758 void
28759 cp_pt_c_tests ()
28761 test_build_non_dependent_expr ();
28762 test_type_dependent_expression_p ();
28765 } // namespace selftest
28767 #endif /* #if CHECKING_P */
28769 #include "gt-cp-pt.h"