[PR c++/84702] ICE with default tmpl arg of overload set
[official-gcc.git] / gcc / cp / pt.c
blob89024c10fe2ba5aa8e618c78bd987575072ff3c8
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2018 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 {
54 struct pending_template *next;
55 struct tinst_level *tinst;
58 static GTY(()) struct pending_template *pending_templates;
59 static GTY(()) struct pending_template *last_pending_template;
61 int processing_template_parmlist;
62 static int template_header_count;
64 static GTY(()) tree saved_trees;
65 static vec<int> inline_parm_levels;
67 static GTY(()) struct tinst_level *current_tinst_level;
69 static GTY(()) tree saved_access_scope;
71 /* Live only within one (recursive) call to tsubst_expr. We use
72 this to pass the statement expression node from the STMT_EXPR
73 to the EXPR_STMT that is its result. */
74 static tree cur_stmt_expr;
76 // -------------------------------------------------------------------------- //
77 // Local Specialization Stack
79 // Implementation of the RAII helper for creating new local
80 // specializations.
81 local_specialization_stack::local_specialization_stack (lss_policy policy)
82 : saved (local_specializations)
84 if (policy == lss_blank || !saved)
85 local_specializations = new hash_map<tree, tree>;
86 else
87 local_specializations = new hash_map<tree, tree>(*saved);
90 local_specialization_stack::~local_specialization_stack ()
92 delete local_specializations;
93 local_specializations = saved;
96 /* True if we've recursed into fn_type_unification too many times. */
97 static bool excessive_deduction_depth;
99 struct GTY((for_user)) spec_entry
101 tree tmpl;
102 tree args;
103 tree spec;
106 struct spec_hasher : ggc_ptr_hash<spec_entry>
108 static hashval_t hash (spec_entry *);
109 static bool equal (spec_entry *, spec_entry *);
112 static GTY (()) hash_table<spec_hasher> *decl_specializations;
114 static GTY (()) hash_table<spec_hasher> *type_specializations;
116 /* Contains canonical template parameter types. The vector is indexed by
117 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
118 TREE_LIST, whose TREE_VALUEs contain the canonical template
119 parameters of various types and levels. */
120 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
122 #define UNIFY_ALLOW_NONE 0
123 #define UNIFY_ALLOW_MORE_CV_QUAL 1
124 #define UNIFY_ALLOW_LESS_CV_QUAL 2
125 #define UNIFY_ALLOW_DERIVED 4
126 #define UNIFY_ALLOW_INTEGER 8
127 #define UNIFY_ALLOW_OUTER_LEVEL 16
128 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
129 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
131 enum template_base_result {
132 tbr_incomplete_type,
133 tbr_ambiguous_baseclass,
134 tbr_success
137 static void push_access_scope (tree);
138 static void pop_access_scope (tree);
139 static bool resolve_overloaded_unification (tree, tree, tree, tree,
140 unification_kind_t, int,
141 bool);
142 static int try_one_overload (tree, tree, tree, tree, tree,
143 unification_kind_t, int, bool, bool);
144 static int unify (tree, tree, tree, tree, int, bool);
145 static void add_pending_template (tree);
146 static tree reopen_tinst_level (struct tinst_level *);
147 static tree tsubst_initializer_list (tree, tree);
148 static tree get_partial_spec_bindings (tree, tree, tree);
149 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
150 bool, bool);
151 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
152 bool, bool);
153 static void tsubst_enum (tree, tree, tree);
154 static tree add_to_template_args (tree, tree);
155 static tree add_outermost_template_args (tree, tree);
156 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
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, int,
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 void template_parm_level_and_index (tree, int*, int*);
184 static int unify_pack_expansion (tree, tree, tree,
185 tree, unification_kind_t, bool, bool);
186 static tree copy_template_args (tree);
187 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
190 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
191 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
192 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
193 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
194 static bool check_specialization_scope (void);
195 static tree process_partial_specialization (tree);
196 static void set_current_access_from_decl (tree);
197 static enum template_base_result get_template_base (tree, tree, tree, tree,
198 bool , tree *);
199 static tree try_class_unification (tree, tree, tree, tree, bool);
200 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
201 tree, tree);
202 static bool template_template_parm_bindings_ok_p (tree, tree);
203 static void tsubst_default_arguments (tree, tsubst_flags_t);
204 static tree for_each_template_parm_r (tree *, int *, void *);
205 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
206 static void copy_default_args_to_explicit_spec (tree);
207 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
208 static bool dependent_template_arg_p (tree);
209 static bool any_template_arguments_need_structural_equality_p (tree);
210 static bool dependent_type_p_r (tree);
211 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
212 static tree tsubst_decl (tree, tree, tsubst_flags_t);
213 static void perform_typedefs_access_check (tree tmpl, tree targs);
214 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
215 location_t);
216 static tree listify (tree);
217 static tree listify_autos (tree, tree);
218 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
219 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
220 static bool complex_alias_template_p (const_tree tmpl);
221 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
222 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
223 static tree make_argument_pack (tree);
224 static void register_parameter_specializations (tree, tree);
225 static tree enclosing_instantiation_of (tree tctx);
227 /* Make the current scope suitable for access checking when we are
228 processing T. T can be FUNCTION_DECL for instantiated function
229 template, VAR_DECL for static member variable, or TYPE_DECL for
230 alias template (needed by instantiate_decl). */
232 static void
233 push_access_scope (tree t)
235 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
236 || TREE_CODE (t) == TYPE_DECL);
238 if (DECL_FRIEND_CONTEXT (t))
239 push_nested_class (DECL_FRIEND_CONTEXT (t));
240 else if (DECL_CLASS_SCOPE_P (t))
241 push_nested_class (DECL_CONTEXT (t));
242 else
243 push_to_top_level ();
245 if (TREE_CODE (t) == FUNCTION_DECL)
247 saved_access_scope = tree_cons
248 (NULL_TREE, current_function_decl, saved_access_scope);
249 current_function_decl = t;
253 /* Restore the scope set up by push_access_scope. T is the node we
254 are processing. */
256 static void
257 pop_access_scope (tree t)
259 if (TREE_CODE (t) == FUNCTION_DECL)
261 current_function_decl = TREE_VALUE (saved_access_scope);
262 saved_access_scope = TREE_CHAIN (saved_access_scope);
265 if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
266 pop_nested_class ();
267 else
268 pop_from_top_level ();
271 /* Do any processing required when DECL (a member template
272 declaration) is finished. Returns the TEMPLATE_DECL corresponding
273 to DECL, unless it is a specialization, in which case the DECL
274 itself is returned. */
276 tree
277 finish_member_template_decl (tree decl)
279 if (decl == error_mark_node)
280 return error_mark_node;
282 gcc_assert (DECL_P (decl));
284 if (TREE_CODE (decl) == TYPE_DECL)
286 tree type;
288 type = TREE_TYPE (decl);
289 if (type == error_mark_node)
290 return error_mark_node;
291 if (MAYBE_CLASS_TYPE_P (type)
292 && CLASSTYPE_TEMPLATE_INFO (type)
293 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
295 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
296 check_member_template (tmpl);
297 return tmpl;
299 return NULL_TREE;
301 else if (TREE_CODE (decl) == FIELD_DECL)
302 error ("data member %qD cannot be a member template", decl);
303 else if (DECL_TEMPLATE_INFO (decl))
305 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
307 check_member_template (DECL_TI_TEMPLATE (decl));
308 return DECL_TI_TEMPLATE (decl);
310 else
311 return decl;
313 else
314 error ("invalid member template declaration %qD", decl);
316 return error_mark_node;
319 /* Create a template info node. */
321 tree
322 build_template_info (tree template_decl, tree template_args)
324 tree result = make_node (TEMPLATE_INFO);
325 TI_TEMPLATE (result) = template_decl;
326 TI_ARGS (result) = template_args;
327 return result;
330 /* Return the template info node corresponding to T, whatever T is. */
332 tree
333 get_template_info (const_tree t)
335 tree tinfo = NULL_TREE;
337 if (!t || t == error_mark_node)
338 return NULL;
340 if (TREE_CODE (t) == NAMESPACE_DECL
341 || TREE_CODE (t) == PARM_DECL)
342 return NULL;
344 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
345 tinfo = DECL_TEMPLATE_INFO (t);
347 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
348 t = TREE_TYPE (t);
350 if (OVERLOAD_TYPE_P (t))
351 tinfo = TYPE_TEMPLATE_INFO (t);
352 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
353 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
355 return tinfo;
358 /* Returns the template nesting level of the indicated class TYPE.
360 For example, in:
361 template <class T>
362 struct A
364 template <class U>
365 struct B {};
368 A<T>::B<U> has depth two, while A<T> has depth one.
369 Both A<T>::B<int> and A<int>::B<U> have depth one, if
370 they are instantiations, not specializations.
372 This function is guaranteed to return 0 if passed NULL_TREE so
373 that, for example, `template_class_depth (current_class_type)' is
374 always safe. */
377 template_class_depth (tree type)
379 int depth;
381 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
383 tree tinfo = get_template_info (type);
385 if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
386 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
387 ++depth;
389 if (DECL_P (type))
390 type = CP_DECL_CONTEXT (type);
391 else if (LAMBDA_TYPE_P (type))
392 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
393 else
394 type = CP_TYPE_CONTEXT (type);
397 return depth;
400 /* Subroutine of maybe_begin_member_template_processing.
401 Returns true if processing DECL needs us to push template parms. */
403 static bool
404 inline_needs_template_parms (tree decl, bool nsdmi)
406 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
407 return false;
409 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
410 > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
413 /* Subroutine of maybe_begin_member_template_processing.
414 Push the template parms in PARMS, starting from LEVELS steps into the
415 chain, and ending at the beginning, since template parms are listed
416 innermost first. */
418 static void
419 push_inline_template_parms_recursive (tree parmlist, int levels)
421 tree parms = TREE_VALUE (parmlist);
422 int i;
424 if (levels > 1)
425 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
427 ++processing_template_decl;
428 current_template_parms
429 = tree_cons (size_int (processing_template_decl),
430 parms, current_template_parms);
431 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
433 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
434 NULL);
435 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
437 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
439 if (error_operand_p (parm))
440 continue;
442 gcc_assert (DECL_P (parm));
444 switch (TREE_CODE (parm))
446 case TYPE_DECL:
447 case TEMPLATE_DECL:
448 pushdecl (parm);
449 break;
451 case PARM_DECL:
452 /* Push the CONST_DECL. */
453 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
454 break;
456 default:
457 gcc_unreachable ();
462 /* Restore the template parameter context for a member template, a
463 friend template defined in a class definition, or a non-template
464 member of template class. */
466 void
467 maybe_begin_member_template_processing (tree decl)
469 tree parms;
470 int levels = 0;
471 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
473 if (nsdmi)
475 tree ctx = DECL_CONTEXT (decl);
476 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
477 /* Disregard full specializations (c++/60999). */
478 && uses_template_parms (ctx)
479 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
482 if (inline_needs_template_parms (decl, nsdmi))
484 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
485 levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
487 if (DECL_TEMPLATE_SPECIALIZATION (decl))
489 --levels;
490 parms = TREE_CHAIN (parms);
493 push_inline_template_parms_recursive (parms, levels);
496 /* Remember how many levels of template parameters we pushed so that
497 we can pop them later. */
498 inline_parm_levels.safe_push (levels);
501 /* Undo the effects of maybe_begin_member_template_processing. */
503 void
504 maybe_end_member_template_processing (void)
506 int i;
507 int last;
509 if (inline_parm_levels.length () == 0)
510 return;
512 last = inline_parm_levels.pop ();
513 for (i = 0; i < last; ++i)
515 --processing_template_decl;
516 current_template_parms = TREE_CHAIN (current_template_parms);
517 poplevel (0, 0, 0);
521 /* Return a new template argument vector which contains all of ARGS,
522 but has as its innermost set of arguments the EXTRA_ARGS. */
524 static tree
525 add_to_template_args (tree args, tree extra_args)
527 tree new_args;
528 int extra_depth;
529 int i;
530 int j;
532 if (args == NULL_TREE || extra_args == error_mark_node)
533 return extra_args;
535 extra_depth = TMPL_ARGS_DEPTH (extra_args);
536 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
538 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
539 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
541 for (j = 1; j <= extra_depth; ++j, ++i)
542 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
544 return new_args;
547 /* Like add_to_template_args, but only the outermost ARGS are added to
548 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
549 (EXTRA_ARGS) levels are added. This function is used to combine
550 the template arguments from a partial instantiation with the
551 template arguments used to attain the full instantiation from the
552 partial instantiation. */
554 static tree
555 add_outermost_template_args (tree args, tree extra_args)
557 tree new_args;
559 /* If there are more levels of EXTRA_ARGS than there are ARGS,
560 something very fishy is going on. */
561 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
563 /* If *all* the new arguments will be the EXTRA_ARGS, just return
564 them. */
565 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
566 return extra_args;
568 /* For the moment, we make ARGS look like it contains fewer levels. */
569 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
571 new_args = add_to_template_args (args, extra_args);
573 /* Now, we restore ARGS to its full dimensions. */
574 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
576 return new_args;
579 /* Return the N levels of innermost template arguments from the ARGS. */
581 tree
582 get_innermost_template_args (tree args, int n)
584 tree new_args;
585 int extra_levels;
586 int i;
588 gcc_assert (n >= 0);
590 /* If N is 1, just return the innermost set of template arguments. */
591 if (n == 1)
592 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
594 /* If we're not removing anything, just return the arguments we were
595 given. */
596 extra_levels = TMPL_ARGS_DEPTH (args) - n;
597 gcc_assert (extra_levels >= 0);
598 if (extra_levels == 0)
599 return args;
601 /* Make a new set of arguments, not containing the outer arguments. */
602 new_args = make_tree_vec (n);
603 for (i = 1; i <= n; ++i)
604 SET_TMPL_ARGS_LEVEL (new_args, i,
605 TMPL_ARGS_LEVEL (args, i + extra_levels));
607 return new_args;
610 /* The inverse of get_innermost_template_args: Return all but the innermost
611 EXTRA_LEVELS levels of template arguments from the ARGS. */
613 static tree
614 strip_innermost_template_args (tree args, int extra_levels)
616 tree new_args;
617 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
618 int i;
620 gcc_assert (n >= 0);
622 /* If N is 1, just return the outermost set of template arguments. */
623 if (n == 1)
624 return TMPL_ARGS_LEVEL (args, 1);
626 /* If we're not removing anything, just return the arguments we were
627 given. */
628 gcc_assert (extra_levels >= 0);
629 if (extra_levels == 0)
630 return args;
632 /* Make a new set of arguments, not containing the inner arguments. */
633 new_args = make_tree_vec (n);
634 for (i = 1; i <= n; ++i)
635 SET_TMPL_ARGS_LEVEL (new_args, i,
636 TMPL_ARGS_LEVEL (args, i));
638 return new_args;
641 /* We've got a template header coming up; push to a new level for storing
642 the parms. */
644 void
645 begin_template_parm_list (void)
647 /* We use a non-tag-transparent scope here, which causes pushtag to
648 put tags in this scope, rather than in the enclosing class or
649 namespace scope. This is the right thing, since we want
650 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
651 global template class, push_template_decl handles putting the
652 TEMPLATE_DECL into top-level scope. For a nested template class,
653 e.g.:
655 template <class T> struct S1 {
656 template <class T> struct S2 {};
659 pushtag contains special code to insert the TEMPLATE_DECL for S2
660 at the right scope. */
661 begin_scope (sk_template_parms, NULL);
662 ++processing_template_decl;
663 ++processing_template_parmlist;
664 note_template_header (0);
666 /* Add a dummy parameter level while we process the parameter list. */
667 current_template_parms
668 = tree_cons (size_int (processing_template_decl),
669 make_tree_vec (0),
670 current_template_parms);
673 /* This routine is called when a specialization is declared. If it is
674 invalid to declare a specialization here, an error is reported and
675 false is returned, otherwise this routine will return true. */
677 static bool
678 check_specialization_scope (void)
680 tree scope = current_scope ();
682 /* [temp.expl.spec]
684 An explicit specialization shall be declared in the namespace of
685 which the template is a member, or, for member templates, in the
686 namespace of which the enclosing class or enclosing class
687 template is a member. An explicit specialization of a member
688 function, member class or static data member of a class template
689 shall be declared in the namespace of which the class template
690 is a member. */
691 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
693 error ("explicit specialization in non-namespace scope %qD", scope);
694 return false;
697 /* [temp.expl.spec]
699 In an explicit specialization declaration for a member of a class
700 template or a member template that appears in namespace scope,
701 the member template and some of its enclosing class templates may
702 remain unspecialized, except that the declaration shall not
703 explicitly specialize a class member template if its enclosing
704 class templates are not explicitly specialized as well. */
705 if (current_template_parms)
707 error ("enclosing class templates are not explicitly specialized");
708 return false;
711 return true;
714 /* We've just seen template <>. */
716 bool
717 begin_specialization (void)
719 begin_scope (sk_template_spec, NULL);
720 note_template_header (1);
721 return check_specialization_scope ();
724 /* Called at then end of processing a declaration preceded by
725 template<>. */
727 void
728 end_specialization (void)
730 finish_scope ();
731 reset_specialization ();
734 /* Any template <>'s that we have seen thus far are not referring to a
735 function specialization. */
737 void
738 reset_specialization (void)
740 processing_specialization = 0;
741 template_header_count = 0;
744 /* We've just seen a template header. If SPECIALIZATION is nonzero,
745 it was of the form template <>. */
747 static void
748 note_template_header (int specialization)
750 processing_specialization = specialization;
751 template_header_count++;
754 /* We're beginning an explicit instantiation. */
756 void
757 begin_explicit_instantiation (void)
759 gcc_assert (!processing_explicit_instantiation);
760 processing_explicit_instantiation = true;
764 void
765 end_explicit_instantiation (void)
767 gcc_assert (processing_explicit_instantiation);
768 processing_explicit_instantiation = false;
771 /* An explicit specialization or partial specialization of TMPL is being
772 declared. Check that the namespace in which the specialization is
773 occurring is permissible. Returns false iff it is invalid to
774 specialize TMPL in the current namespace. */
776 static bool
777 check_specialization_namespace (tree tmpl)
779 tree tpl_ns = decl_namespace_context (tmpl);
781 /* [tmpl.expl.spec]
783 An explicit specialization shall be declared in a namespace enclosing the
784 specialized template. An explicit specialization whose declarator-id is
785 not qualified shall be declared in the nearest enclosing namespace of the
786 template, or, if the namespace is inline (7.3.1), any namespace from its
787 enclosing namespace set. */
788 if (current_scope() != DECL_CONTEXT (tmpl)
789 && !at_namespace_scope_p ())
791 error ("specialization of %qD must appear at namespace scope", tmpl);
792 return false;
795 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
796 /* Same or enclosing namespace. */
797 return true;
798 else
800 permerror (input_location,
801 "specialization of %qD in different namespace", tmpl);
802 inform (DECL_SOURCE_LOCATION (tmpl),
803 " from definition of %q#D", tmpl);
804 return false;
808 /* SPEC is an explicit instantiation. Check that it is valid to
809 perform this explicit instantiation in the current namespace. */
811 static void
812 check_explicit_instantiation_namespace (tree spec)
814 tree ns;
816 /* DR 275: An explicit instantiation shall appear in an enclosing
817 namespace of its template. */
818 ns = decl_namespace_context (spec);
819 if (!is_nested_namespace (current_namespace, ns))
820 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
821 "(which does not enclose namespace %qD)",
822 spec, current_namespace, ns);
825 // Returns the type of a template specialization only if that
826 // specialization needs to be defined. Otherwise (e.g., if the type has
827 // already been defined), the function returns NULL_TREE.
828 static tree
829 maybe_new_partial_specialization (tree type)
831 // An implicit instantiation of an incomplete type implies
832 // the definition of a new class template.
834 // template<typename T>
835 // struct S;
837 // template<typename T>
838 // struct S<T*>;
840 // Here, S<T*> is an implicit instantiation of S whose type
841 // is incomplete.
842 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
843 return type;
845 // It can also be the case that TYPE is a completed specialization.
846 // Continuing the previous example, suppose we also declare:
848 // template<typename T>
849 // requires Integral<T>
850 // struct S<T*>;
852 // Here, S<T*> refers to the specialization S<T*> defined
853 // above. However, we need to differentiate definitions because
854 // we intend to define a new partial specialization. In this case,
855 // we rely on the fact that the constraints are different for
856 // this declaration than that above.
858 // Note that we also get here for injected class names and
859 // late-parsed template definitions. We must ensure that we
860 // do not create new type declarations for those cases.
861 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
863 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
864 tree args = CLASSTYPE_TI_ARGS (type);
866 // If there are no template parameters, this cannot be a new
867 // partial template specializtion?
868 if (!current_template_parms)
869 return NULL_TREE;
871 // The injected-class-name is not a new partial specialization.
872 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
873 return NULL_TREE;
875 // If the constraints are not the same as those of the primary
876 // then, we can probably create a new specialization.
877 tree type_constr = current_template_constraints ();
879 if (type == TREE_TYPE (tmpl))
881 tree main_constr = get_constraints (tmpl);
882 if (equivalent_constraints (type_constr, main_constr))
883 return NULL_TREE;
886 // Also, if there's a pre-existing specialization with matching
887 // constraints, then this also isn't new.
888 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
889 while (specs)
891 tree spec_tmpl = TREE_VALUE (specs);
892 tree spec_args = TREE_PURPOSE (specs);
893 tree spec_constr = get_constraints (spec_tmpl);
894 if (comp_template_args (args, spec_args)
895 && equivalent_constraints (type_constr, spec_constr))
896 return NULL_TREE;
897 specs = TREE_CHAIN (specs);
900 // Create a new type node (and corresponding type decl)
901 // for the newly declared specialization.
902 tree t = make_class_type (TREE_CODE (type));
903 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
904 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
906 /* We only need a separate type node for storing the definition of this
907 partial specialization; uses of S<T*> are unconstrained, so all are
908 equivalent. So keep TYPE_CANONICAL the same. */
909 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
911 // Build the corresponding type decl.
912 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
913 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
914 DECL_SOURCE_LOCATION (d) = input_location;
916 return t;
919 return NULL_TREE;
922 /* The TYPE is being declared. If it is a template type, that means it
923 is a partial specialization. Do appropriate error-checking. */
925 tree
926 maybe_process_partial_specialization (tree type)
928 tree context;
930 if (type == error_mark_node)
931 return error_mark_node;
933 /* A lambda that appears in specialization context is not itself a
934 specialization. */
935 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
936 return type;
938 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
940 error ("name of class shadows template template parameter %qD",
941 TYPE_NAME (type));
942 return error_mark_node;
945 context = TYPE_CONTEXT (type);
947 if (TYPE_ALIAS_P (type))
949 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
951 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
952 error ("specialization of alias template %qD",
953 TI_TEMPLATE (tinfo));
954 else
955 error ("explicit specialization of non-template %qT", type);
956 return error_mark_node;
958 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
960 /* This is for ordinary explicit specialization and partial
961 specialization of a template class such as:
963 template <> class C<int>;
967 template <class T> class C<T*>;
969 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
971 if (tree t = maybe_new_partial_specialization (type))
973 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
974 && !at_namespace_scope_p ())
975 return error_mark_node;
976 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
977 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
978 if (processing_template_decl)
980 tree decl = push_template_decl (TYPE_MAIN_DECL (t));
981 if (decl == error_mark_node)
982 return error_mark_node;
983 return TREE_TYPE (decl);
986 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
987 error ("specialization of %qT after instantiation", type);
988 else if (errorcount && !processing_specialization
989 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
990 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
991 /* Trying to define a specialization either without a template<> header
992 or in an inappropriate place. We've already given an error, so just
993 bail now so we don't actually define the specialization. */
994 return error_mark_node;
996 else if (CLASS_TYPE_P (type)
997 && !CLASSTYPE_USE_TEMPLATE (type)
998 && CLASSTYPE_TEMPLATE_INFO (type)
999 && context && CLASS_TYPE_P (context)
1000 && CLASSTYPE_TEMPLATE_INFO (context))
1002 /* This is for an explicit specialization of member class
1003 template according to [temp.expl.spec/18]:
1005 template <> template <class U> class C<int>::D;
1007 The context `C<int>' must be an implicit instantiation.
1008 Otherwise this is just a member class template declared
1009 earlier like:
1011 template <> class C<int> { template <class U> class D; };
1012 template <> template <class U> class C<int>::D;
1014 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1015 while in the second case, `C<int>::D' is a primary template
1016 and `C<T>::D' may not exist. */
1018 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1019 && !COMPLETE_TYPE_P (type))
1021 tree t;
1022 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1024 if (current_namespace
1025 != decl_namespace_context (tmpl))
1027 permerror (input_location,
1028 "specializing %q#T in different namespace", type);
1029 permerror (DECL_SOURCE_LOCATION (tmpl),
1030 " from definition of %q#D", tmpl);
1033 /* Check for invalid specialization after instantiation:
1035 template <> template <> class C<int>::D<int>;
1036 template <> template <class U> class C<int>::D; */
1038 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1039 t; t = TREE_CHAIN (t))
1041 tree inst = TREE_VALUE (t);
1042 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1043 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1045 /* We already have a full specialization of this partial
1046 instantiation, or a full specialization has been
1047 looked up but not instantiated. Reassign it to the
1048 new member specialization template. */
1049 spec_entry elt;
1050 spec_entry *entry;
1052 elt.tmpl = most_general_template (tmpl);
1053 elt.args = CLASSTYPE_TI_ARGS (inst);
1054 elt.spec = inst;
1056 type_specializations->remove_elt (&elt);
1058 elt.tmpl = tmpl;
1059 elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1061 spec_entry **slot
1062 = type_specializations->find_slot (&elt, INSERT);
1063 entry = ggc_alloc<spec_entry> ();
1064 *entry = elt;
1065 *slot = entry;
1067 else
1068 /* But if we've had an implicit instantiation, that's a
1069 problem ([temp.expl.spec]/6). */
1070 error ("specialization %qT after instantiation %qT",
1071 type, inst);
1074 /* Mark TYPE as a specialization. And as a result, we only
1075 have one level of template argument for the innermost
1076 class template. */
1077 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1078 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1079 CLASSTYPE_TI_ARGS (type)
1080 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1083 else if (processing_specialization)
1085 /* Someday C++0x may allow for enum template specialization. */
1086 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1087 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1088 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1089 "of %qD not allowed by ISO C++", type);
1090 else
1092 error ("explicit specialization of non-template %qT", type);
1093 return error_mark_node;
1097 return type;
1100 /* Returns nonzero if we can optimize the retrieval of specializations
1101 for TMPL, a TEMPLATE_DECL. In particular, for such a template, we
1102 do not use DECL_TEMPLATE_SPECIALIZATIONS at all. */
1104 static inline bool
1105 optimize_specialization_lookup_p (tree tmpl)
1107 return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1108 && DECL_CLASS_SCOPE_P (tmpl)
1109 /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1110 parameter. */
1111 && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1112 /* The optimized lookup depends on the fact that the
1113 template arguments for the member function template apply
1114 purely to the containing class, which is not true if the
1115 containing class is an explicit or partial
1116 specialization. */
1117 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1118 && !DECL_MEMBER_TEMPLATE_P (tmpl)
1119 && !DECL_CONV_FN_P (tmpl)
1120 /* It is possible to have a template that is not a member
1121 template and is not a member of a template class:
1123 template <typename T>
1124 struct S { friend A::f(); };
1126 Here, the friend function is a template, but the context does
1127 not have template information. The optimized lookup relies
1128 on having ARGS be the template arguments for both the class
1129 and the function template. */
1130 && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1133 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1134 gone through coerce_template_parms by now. */
1136 static void
1137 verify_unstripped_args (tree args)
1139 ++processing_template_decl;
1140 if (!any_dependent_template_arguments_p (args))
1142 tree inner = INNERMOST_TEMPLATE_ARGS (args);
1143 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1145 tree arg = TREE_VEC_ELT (inner, i);
1146 if (TREE_CODE (arg) == TEMPLATE_DECL)
1147 /* OK */;
1148 else if (TYPE_P (arg))
1149 gcc_assert (strip_typedefs (arg, NULL) == arg);
1150 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1151 /* Allow typedefs on the type of a non-type argument, since a
1152 parameter can have them. */;
1153 else
1154 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1157 --processing_template_decl;
1160 /* Retrieve the specialization (in the sense of [temp.spec] - a
1161 specialization is either an instantiation or an explicit
1162 specialization) of TMPL for the given template ARGS. If there is
1163 no such specialization, return NULL_TREE. The ARGS are a vector of
1164 arguments, or a vector of vectors of arguments, in the case of
1165 templates with more than one level of parameters.
1167 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1168 then we search for a partial specialization matching ARGS. This
1169 parameter is ignored if TMPL is not a class template.
1171 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1172 result is a NONTYPE_ARGUMENT_PACK. */
1174 static tree
1175 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1177 if (tmpl == NULL_TREE)
1178 return NULL_TREE;
1180 if (args == error_mark_node)
1181 return NULL_TREE;
1183 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1184 || TREE_CODE (tmpl) == FIELD_DECL);
1186 /* There should be as many levels of arguments as there are
1187 levels of parameters. */
1188 gcc_assert (TMPL_ARGS_DEPTH (args)
1189 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1190 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1191 : template_class_depth (DECL_CONTEXT (tmpl))));
1193 if (flag_checking)
1194 verify_unstripped_args (args);
1196 /* Lambda functions in templates aren't instantiated normally, but through
1197 tsubst_lambda_expr. */
1198 if (lambda_fn_in_template_p (tmpl))
1199 return NULL_TREE;
1201 if (optimize_specialization_lookup_p (tmpl))
1203 /* The template arguments actually apply to the containing
1204 class. Find the class specialization with those
1205 arguments. */
1206 tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1207 tree class_specialization
1208 = retrieve_specialization (class_template, args, 0);
1209 if (!class_specialization)
1210 return NULL_TREE;
1212 /* Find the instance of TMPL. */
1213 tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1214 for (ovl_iterator iter (fns); iter; ++iter)
1216 tree fn = *iter;
1217 if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1218 /* using-declarations can add base methods to the method vec,
1219 and we don't want those here. */
1220 && DECL_CONTEXT (fn) == class_specialization)
1221 return fn;
1223 return NULL_TREE;
1225 else
1227 spec_entry *found;
1228 spec_entry elt;
1229 hash_table<spec_hasher> *specializations;
1231 elt.tmpl = tmpl;
1232 elt.args = args;
1233 elt.spec = NULL_TREE;
1235 if (DECL_CLASS_TEMPLATE_P (tmpl))
1236 specializations = type_specializations;
1237 else
1238 specializations = decl_specializations;
1240 if (hash == 0)
1241 hash = spec_hasher::hash (&elt);
1242 found = specializations->find_with_hash (&elt, hash);
1243 if (found)
1244 return found->spec;
1247 return NULL_TREE;
1250 /* Like retrieve_specialization, but for local declarations. */
1252 tree
1253 retrieve_local_specialization (tree tmpl)
1255 if (local_specializations == NULL)
1256 return NULL_TREE;
1258 tree *slot = local_specializations->get (tmpl);
1259 return slot ? *slot : NULL_TREE;
1262 /* Returns nonzero iff DECL is a specialization of TMPL. */
1265 is_specialization_of (tree decl, tree tmpl)
1267 tree t;
1269 if (TREE_CODE (decl) == FUNCTION_DECL)
1271 for (t = decl;
1272 t != NULL_TREE;
1273 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1274 if (t == tmpl)
1275 return 1;
1277 else
1279 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1281 for (t = TREE_TYPE (decl);
1282 t != NULL_TREE;
1283 t = CLASSTYPE_USE_TEMPLATE (t)
1284 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1285 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1286 return 1;
1289 return 0;
1292 /* Returns nonzero iff DECL is a specialization of friend declaration
1293 FRIEND_DECL according to [temp.friend]. */
1295 bool
1296 is_specialization_of_friend (tree decl, tree friend_decl)
1298 bool need_template = true;
1299 int template_depth;
1301 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1302 || TREE_CODE (decl) == TYPE_DECL);
1304 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1305 of a template class, we want to check if DECL is a specialization
1306 if this. */
1307 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1308 && DECL_TEMPLATE_INFO (friend_decl)
1309 && !DECL_USE_TEMPLATE (friend_decl))
1311 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1312 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1313 need_template = false;
1315 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1316 && !PRIMARY_TEMPLATE_P (friend_decl))
1317 need_template = false;
1319 /* There is nothing to do if this is not a template friend. */
1320 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1321 return false;
1323 if (is_specialization_of (decl, friend_decl))
1324 return true;
1326 /* [temp.friend/6]
1327 A member of a class template may be declared to be a friend of a
1328 non-template class. In this case, the corresponding member of
1329 every specialization of the class template is a friend of the
1330 class granting friendship.
1332 For example, given a template friend declaration
1334 template <class T> friend void A<T>::f();
1336 the member function below is considered a friend
1338 template <> struct A<int> {
1339 void f();
1342 For this type of template friend, TEMPLATE_DEPTH below will be
1343 nonzero. To determine if DECL is a friend of FRIEND, we first
1344 check if the enclosing class is a specialization of another. */
1346 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1347 if (template_depth
1348 && DECL_CLASS_SCOPE_P (decl)
1349 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1350 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1352 /* Next, we check the members themselves. In order to handle
1353 a few tricky cases, such as when FRIEND_DECL's are
1355 template <class T> friend void A<T>::g(T t);
1356 template <class T> template <T t> friend void A<T>::h();
1358 and DECL's are
1360 void A<int>::g(int);
1361 template <int> void A<int>::h();
1363 we need to figure out ARGS, the template arguments from
1364 the context of DECL. This is required for template substitution
1365 of `T' in the function parameter of `g' and template parameter
1366 of `h' in the above examples. Here ARGS corresponds to `int'. */
1368 tree context = DECL_CONTEXT (decl);
1369 tree args = NULL_TREE;
1370 int current_depth = 0;
1372 while (current_depth < template_depth)
1374 if (CLASSTYPE_TEMPLATE_INFO (context))
1376 if (current_depth == 0)
1377 args = TYPE_TI_ARGS (context);
1378 else
1379 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1380 current_depth++;
1382 context = TYPE_CONTEXT (context);
1385 if (TREE_CODE (decl) == FUNCTION_DECL)
1387 bool is_template;
1388 tree friend_type;
1389 tree decl_type;
1390 tree friend_args_type;
1391 tree decl_args_type;
1393 /* Make sure that both DECL and FRIEND_DECL are templates or
1394 non-templates. */
1395 is_template = DECL_TEMPLATE_INFO (decl)
1396 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1397 if (need_template ^ is_template)
1398 return false;
1399 else if (is_template)
1401 /* If both are templates, check template parameter list. */
1402 tree friend_parms
1403 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1404 args, tf_none);
1405 if (!comp_template_parms
1406 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1407 friend_parms))
1408 return false;
1410 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1412 else
1413 decl_type = TREE_TYPE (decl);
1415 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1416 tf_none, NULL_TREE);
1417 if (friend_type == error_mark_node)
1418 return false;
1420 /* Check if return types match. */
1421 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1422 return false;
1424 /* Check if function parameter types match, ignoring the
1425 `this' parameter. */
1426 friend_args_type = TYPE_ARG_TYPES (friend_type);
1427 decl_args_type = TYPE_ARG_TYPES (decl_type);
1428 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1429 friend_args_type = TREE_CHAIN (friend_args_type);
1430 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1431 decl_args_type = TREE_CHAIN (decl_args_type);
1433 return compparms (decl_args_type, friend_args_type);
1435 else
1437 /* DECL is a TYPE_DECL */
1438 bool is_template;
1439 tree decl_type = TREE_TYPE (decl);
1441 /* Make sure that both DECL and FRIEND_DECL are templates or
1442 non-templates. */
1443 is_template
1444 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1445 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1447 if (need_template ^ is_template)
1448 return false;
1449 else if (is_template)
1451 tree friend_parms;
1452 /* If both are templates, check the name of the two
1453 TEMPLATE_DECL's first because is_friend didn't. */
1454 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1455 != DECL_NAME (friend_decl))
1456 return false;
1458 /* Now check template parameter list. */
1459 friend_parms
1460 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1461 args, tf_none);
1462 return comp_template_parms
1463 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1464 friend_parms);
1466 else
1467 return (DECL_NAME (decl)
1468 == DECL_NAME (friend_decl));
1471 return false;
1474 /* Register the specialization SPEC as a specialization of TMPL with
1475 the indicated ARGS. IS_FRIEND indicates whether the specialization
1476 is actually just a friend declaration. ATTRLIST is the list of
1477 attributes that the specialization is declared with or NULL when
1478 it isn't. Returns SPEC, or an equivalent prior declaration, if
1479 available.
1481 We also store instantiations of field packs in the hash table, even
1482 though they are not themselves templates, to make lookup easier. */
1484 static tree
1485 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1486 hashval_t hash)
1488 tree fn;
1489 spec_entry **slot = NULL;
1490 spec_entry elt;
1492 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1493 || (TREE_CODE (tmpl) == FIELD_DECL
1494 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1496 if (TREE_CODE (spec) == FUNCTION_DECL
1497 && uses_template_parms (DECL_TI_ARGS (spec)))
1498 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1499 register it; we want the corresponding TEMPLATE_DECL instead.
1500 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1501 the more obvious `uses_template_parms (spec)' to avoid problems
1502 with default function arguments. In particular, given
1503 something like this:
1505 template <class T> void f(T t1, T t = T())
1507 the default argument expression is not substituted for in an
1508 instantiation unless and until it is actually needed. */
1509 return spec;
1511 if (optimize_specialization_lookup_p (tmpl))
1512 /* We don't put these specializations in the hash table, but we might
1513 want to give an error about a mismatch. */
1514 fn = retrieve_specialization (tmpl, args, 0);
1515 else
1517 elt.tmpl = tmpl;
1518 elt.args = args;
1519 elt.spec = spec;
1521 if (hash == 0)
1522 hash = spec_hasher::hash (&elt);
1524 slot =
1525 decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1526 if (*slot)
1527 fn = ((spec_entry *) *slot)->spec;
1528 else
1529 fn = NULL_TREE;
1532 /* We can sometimes try to re-register a specialization that we've
1533 already got. In particular, regenerate_decl_from_template calls
1534 duplicate_decls which will update the specialization list. But,
1535 we'll still get called again here anyhow. It's more convenient
1536 to simply allow this than to try to prevent it. */
1537 if (fn == spec)
1538 return spec;
1539 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1541 if (DECL_TEMPLATE_INSTANTIATION (fn))
1543 if (DECL_ODR_USED (fn)
1544 || DECL_EXPLICIT_INSTANTIATION (fn))
1546 error ("specialization of %qD after instantiation",
1547 fn);
1548 return error_mark_node;
1550 else
1552 tree clone;
1553 /* This situation should occur only if the first
1554 specialization is an implicit instantiation, the
1555 second is an explicit specialization, and the
1556 implicit instantiation has not yet been used. That
1557 situation can occur if we have implicitly
1558 instantiated a member function and then specialized
1559 it later.
1561 We can also wind up here if a friend declaration that
1562 looked like an instantiation turns out to be a
1563 specialization:
1565 template <class T> void foo(T);
1566 class S { friend void foo<>(int) };
1567 template <> void foo(int);
1569 We transform the existing DECL in place so that any
1570 pointers to it become pointers to the updated
1571 declaration.
1573 If there was a definition for the template, but not
1574 for the specialization, we want this to look as if
1575 there were no definition, and vice versa. */
1576 DECL_INITIAL (fn) = NULL_TREE;
1577 duplicate_decls (spec, fn, is_friend);
1578 /* The call to duplicate_decls will have applied
1579 [temp.expl.spec]:
1581 An explicit specialization of a function template
1582 is inline only if it is explicitly declared to be,
1583 and independently of whether its function template
1586 to the primary function; now copy the inline bits to
1587 the various clones. */
1588 FOR_EACH_CLONE (clone, fn)
1590 DECL_DECLARED_INLINE_P (clone)
1591 = DECL_DECLARED_INLINE_P (fn);
1592 DECL_SOURCE_LOCATION (clone)
1593 = DECL_SOURCE_LOCATION (fn);
1594 DECL_DELETED_FN (clone)
1595 = DECL_DELETED_FN (fn);
1597 check_specialization_namespace (tmpl);
1599 return fn;
1602 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1604 tree dd = duplicate_decls (spec, fn, is_friend);
1605 if (dd == error_mark_node)
1606 /* We've already complained in duplicate_decls. */
1607 return error_mark_node;
1609 if (dd == NULL_TREE && DECL_INITIAL (spec))
1610 /* Dup decl failed, but this is a new definition. Set the
1611 line number so any errors match this new
1612 definition. */
1613 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1615 return fn;
1618 else if (fn)
1619 return duplicate_decls (spec, fn, is_friend);
1621 /* A specialization must be declared in the same namespace as the
1622 template it is specializing. */
1623 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1624 && !check_specialization_namespace (tmpl))
1625 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1627 if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1629 spec_entry *entry = ggc_alloc<spec_entry> ();
1630 gcc_assert (tmpl && args && spec);
1631 *entry = elt;
1632 *slot = entry;
1633 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1634 && PRIMARY_TEMPLATE_P (tmpl)
1635 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1636 || variable_template_p (tmpl))
1637 /* If TMPL is a forward declaration of a template function, keep a list
1638 of all specializations in case we need to reassign them to a friend
1639 template later in tsubst_friend_function.
1641 Also keep a list of all variable template instantiations so that
1642 process_partial_specialization can check whether a later partial
1643 specialization would have used it. */
1644 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1645 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1648 return spec;
1651 /* Returns true iff two spec_entry nodes are equivalent. */
1653 int comparing_specializations;
1655 bool
1656 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1658 int equal;
1660 ++comparing_specializations;
1661 equal = (e1->tmpl == e2->tmpl
1662 && comp_template_args (e1->args, e2->args));
1663 if (equal && flag_concepts
1664 /* tmpl could be a FIELD_DECL for a capture pack. */
1665 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1666 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1667 && uses_template_parms (e1->args))
1669 /* Partial specializations of a variable template can be distinguished by
1670 constraints. */
1671 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1672 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1673 equal = equivalent_constraints (c1, c2);
1675 --comparing_specializations;
1677 return equal;
1680 /* Returns a hash for a template TMPL and template arguments ARGS. */
1682 static hashval_t
1683 hash_tmpl_and_args (tree tmpl, tree args)
1685 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1686 return iterative_hash_template_arg (args, val);
1689 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1690 ignoring SPEC. */
1692 hashval_t
1693 spec_hasher::hash (spec_entry *e)
1695 return hash_tmpl_and_args (e->tmpl, e->args);
1698 /* Recursively calculate a hash value for a template argument ARG, for use
1699 in the hash tables of template specializations. */
1701 hashval_t
1702 iterative_hash_template_arg (tree arg, hashval_t val)
1704 unsigned HOST_WIDE_INT i;
1705 enum tree_code code;
1706 char tclass;
1708 if (arg == NULL_TREE)
1709 return iterative_hash_object (arg, val);
1711 if (!TYPE_P (arg))
1712 STRIP_NOPS (arg);
1714 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1715 gcc_unreachable ();
1717 code = TREE_CODE (arg);
1718 tclass = TREE_CODE_CLASS (code);
1720 val = iterative_hash_object (code, val);
1722 switch (code)
1724 case ERROR_MARK:
1725 return val;
1727 case IDENTIFIER_NODE:
1728 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1730 case TREE_VEC:
1732 int i, len = TREE_VEC_LENGTH (arg);
1733 for (i = 0; i < len; ++i)
1734 val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1735 return val;
1738 case TYPE_PACK_EXPANSION:
1739 case EXPR_PACK_EXPANSION:
1740 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1741 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1743 case TYPE_ARGUMENT_PACK:
1744 case NONTYPE_ARGUMENT_PACK:
1745 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1747 case TREE_LIST:
1748 for (; arg; arg = TREE_CHAIN (arg))
1749 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1750 return val;
1752 case OVERLOAD:
1753 for (lkp_iterator iter (arg); iter; ++iter)
1754 val = iterative_hash_template_arg (*iter, val);
1755 return val;
1757 case CONSTRUCTOR:
1759 tree field, value;
1760 iterative_hash_template_arg (TREE_TYPE (arg), val);
1761 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1763 val = iterative_hash_template_arg (field, val);
1764 val = iterative_hash_template_arg (value, val);
1766 return val;
1769 case PARM_DECL:
1770 if (!DECL_ARTIFICIAL (arg))
1772 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1773 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1775 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1777 case TARGET_EXPR:
1778 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1780 case PTRMEM_CST:
1781 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1782 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1784 case TEMPLATE_PARM_INDEX:
1785 val = iterative_hash_template_arg
1786 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1787 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1788 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1790 case TRAIT_EXPR:
1791 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1792 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1793 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1795 case BASELINK:
1796 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1797 val);
1798 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1799 val);
1801 case MODOP_EXPR:
1802 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1803 code = TREE_CODE (TREE_OPERAND (arg, 1));
1804 val = iterative_hash_object (code, val);
1805 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1807 case LAMBDA_EXPR:
1808 /* A lambda can't appear in a template arg, but don't crash on
1809 erroneous input. */
1810 gcc_assert (seen_error ());
1811 return val;
1813 case CAST_EXPR:
1814 case IMPLICIT_CONV_EXPR:
1815 case STATIC_CAST_EXPR:
1816 case REINTERPRET_CAST_EXPR:
1817 case CONST_CAST_EXPR:
1818 case DYNAMIC_CAST_EXPR:
1819 case NEW_EXPR:
1820 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1821 /* Now hash operands as usual. */
1822 break;
1824 default:
1825 break;
1828 switch (tclass)
1830 case tcc_type:
1831 if (alias_template_specialization_p (arg))
1833 // We want an alias specialization that survived strip_typedefs
1834 // to hash differently from its TYPE_CANONICAL, to avoid hash
1835 // collisions that compare as different in template_args_equal.
1836 // These could be dependent specializations that strip_typedefs
1837 // left alone, or untouched specializations because
1838 // coerce_template_parms returns the unconverted template
1839 // arguments if it sees incomplete argument packs.
1840 tree ti = TYPE_ALIAS_TEMPLATE_INFO (arg);
1841 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1843 if (TYPE_CANONICAL (arg))
1844 return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1845 val);
1846 else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1847 return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1848 /* Otherwise just compare the types during lookup. */
1849 return val;
1851 case tcc_declaration:
1852 case tcc_constant:
1853 return iterative_hash_expr (arg, val);
1855 default:
1856 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1858 unsigned n = cp_tree_operand_length (arg);
1859 for (i = 0; i < n; ++i)
1860 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1861 return val;
1864 gcc_unreachable ();
1865 return 0;
1868 /* Unregister the specialization SPEC as a specialization of TMPL.
1869 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1870 if the SPEC was listed as a specialization of TMPL.
1872 Note that SPEC has been ggc_freed, so we can't look inside it. */
1874 bool
1875 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1877 spec_entry *entry;
1878 spec_entry elt;
1880 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1881 elt.args = TI_ARGS (tinfo);
1882 elt.spec = NULL_TREE;
1884 entry = decl_specializations->find (&elt);
1885 if (entry != NULL)
1887 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1888 gcc_assert (new_spec != NULL_TREE);
1889 entry->spec = new_spec;
1890 return 1;
1893 return 0;
1896 /* Like register_specialization, but for local declarations. We are
1897 registering SPEC, an instantiation of TMPL. */
1899 void
1900 register_local_specialization (tree spec, tree tmpl)
1902 gcc_assert (tmpl != spec);
1903 local_specializations->put (tmpl, spec);
1906 /* TYPE is a class type. Returns true if TYPE is an explicitly
1907 specialized class. */
1909 bool
1910 explicit_class_specialization_p (tree type)
1912 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1913 return false;
1914 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1917 /* Print the list of functions at FNS, going through all the overloads
1918 for each element of the list. Alternatively, FNS can not be a
1919 TREE_LIST, in which case it will be printed together with all the
1920 overloads.
1922 MORE and *STR should respectively be FALSE and NULL when the function
1923 is called from the outside. They are used internally on recursive
1924 calls. print_candidates manages the two parameters and leaves NULL
1925 in *STR when it ends. */
1927 static void
1928 print_candidates_1 (tree fns, char **str, bool more = false)
1930 if (TREE_CODE (fns) == TREE_LIST)
1931 for (; fns; fns = TREE_CHAIN (fns))
1932 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1933 else
1934 for (lkp_iterator iter (fns); iter;)
1936 tree cand = *iter;
1937 ++iter;
1939 const char *pfx = *str;
1940 if (!pfx)
1942 if (more || iter)
1943 pfx = _("candidates are:");
1944 else
1945 pfx = _("candidate is:");
1946 *str = get_spaces (pfx);
1948 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
1952 /* Print the list of candidate FNS in an error message. FNS can also
1953 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
1955 void
1956 print_candidates (tree fns)
1958 char *str = NULL;
1959 print_candidates_1 (fns, &str);
1960 free (str);
1963 /* Get a (possibly) constrained template declaration for the
1964 purpose of ordering candidates. */
1965 static tree
1966 get_template_for_ordering (tree list)
1968 gcc_assert (TREE_CODE (list) == TREE_LIST);
1969 tree f = TREE_VALUE (list);
1970 if (tree ti = DECL_TEMPLATE_INFO (f))
1971 return TI_TEMPLATE (ti);
1972 return f;
1975 /* Among candidates having the same signature, return the
1976 most constrained or NULL_TREE if there is no best candidate.
1977 If the signatures of candidates vary (e.g., template
1978 specialization vs. member function), then there can be no
1979 most constrained.
1981 Note that we don't compare constraints on the functions
1982 themselves, but rather those of their templates. */
1983 static tree
1984 most_constrained_function (tree candidates)
1986 // Try to find the best candidate in a first pass.
1987 tree champ = candidates;
1988 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
1990 int winner = more_constrained (get_template_for_ordering (champ),
1991 get_template_for_ordering (c));
1992 if (winner == -1)
1993 champ = c; // The candidate is more constrained
1994 else if (winner == 0)
1995 return NULL_TREE; // Neither is more constrained
1998 // Verify that the champ is better than previous candidates.
1999 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2000 if (!more_constrained (get_template_for_ordering (champ),
2001 get_template_for_ordering (c)))
2002 return NULL_TREE;
2005 return champ;
2009 /* Returns the template (one of the functions given by TEMPLATE_ID)
2010 which can be specialized to match the indicated DECL with the
2011 explicit template args given in TEMPLATE_ID. The DECL may be
2012 NULL_TREE if none is available. In that case, the functions in
2013 TEMPLATE_ID are non-members.
2015 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2016 specialization of a member template.
2018 The TEMPLATE_COUNT is the number of references to qualifying
2019 template classes that appeared in the name of the function. See
2020 check_explicit_specialization for a more accurate description.
2022 TSK indicates what kind of template declaration (if any) is being
2023 declared. TSK_TEMPLATE indicates that the declaration given by
2024 DECL, though a FUNCTION_DECL, has template parameters, and is
2025 therefore a template function.
2027 The template args (those explicitly specified and those deduced)
2028 are output in a newly created vector *TARGS_OUT.
2030 If it is impossible to determine the result, an error message is
2031 issued. The error_mark_node is returned to indicate failure. */
2033 static tree
2034 determine_specialization (tree template_id,
2035 tree decl,
2036 tree* targs_out,
2037 int need_member_template,
2038 int template_count,
2039 tmpl_spec_kind tsk)
2041 tree fns;
2042 tree targs;
2043 tree explicit_targs;
2044 tree candidates = NULL_TREE;
2046 /* A TREE_LIST of templates of which DECL may be a specialization.
2047 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2048 corresponding TREE_PURPOSE is the set of template arguments that,
2049 when used to instantiate the template, would produce a function
2050 with the signature of DECL. */
2051 tree templates = NULL_TREE;
2052 int header_count;
2053 cp_binding_level *b;
2055 *targs_out = NULL_TREE;
2057 if (template_id == error_mark_node || decl == error_mark_node)
2058 return error_mark_node;
2060 /* We shouldn't be specializing a member template of an
2061 unspecialized class template; we already gave an error in
2062 check_specialization_scope, now avoid crashing. */
2063 if (!VAR_P (decl)
2064 && template_count && DECL_CLASS_SCOPE_P (decl)
2065 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2067 gcc_assert (errorcount);
2068 return error_mark_node;
2071 fns = TREE_OPERAND (template_id, 0);
2072 explicit_targs = TREE_OPERAND (template_id, 1);
2074 if (fns == error_mark_node)
2075 return error_mark_node;
2077 /* Check for baselinks. */
2078 if (BASELINK_P (fns))
2079 fns = BASELINK_FUNCTIONS (fns);
2081 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2083 error ("%qD is not a function template", fns);
2084 return error_mark_node;
2086 else if (VAR_P (decl) && !variable_template_p (fns))
2088 error ("%qD is not a variable template", fns);
2089 return error_mark_node;
2092 /* Count the number of template headers specified for this
2093 specialization. */
2094 header_count = 0;
2095 for (b = current_binding_level;
2096 b->kind == sk_template_parms;
2097 b = b->level_chain)
2098 ++header_count;
2100 tree orig_fns = fns;
2102 if (variable_template_p (fns))
2104 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2105 targs = coerce_template_parms (parms, explicit_targs, fns,
2106 tf_warning_or_error,
2107 /*req_all*/true, /*use_defarg*/true);
2108 if (targs != error_mark_node)
2109 templates = tree_cons (targs, fns, templates);
2111 else for (lkp_iterator iter (fns); iter; ++iter)
2113 tree fn = *iter;
2115 if (TREE_CODE (fn) == TEMPLATE_DECL)
2117 tree decl_arg_types;
2118 tree fn_arg_types;
2119 tree insttype;
2121 /* In case of explicit specialization, we need to check if
2122 the number of template headers appearing in the specialization
2123 is correct. This is usually done in check_explicit_specialization,
2124 but the check done there cannot be exhaustive when specializing
2125 member functions. Consider the following code:
2127 template <> void A<int>::f(int);
2128 template <> template <> void A<int>::f(int);
2130 Assuming that A<int> is not itself an explicit specialization
2131 already, the first line specializes "f" which is a non-template
2132 member function, whilst the second line specializes "f" which
2133 is a template member function. So both lines are syntactically
2134 correct, and check_explicit_specialization does not reject
2135 them.
2137 Here, we can do better, as we are matching the specialization
2138 against the declarations. We count the number of template
2139 headers, and we check if they match TEMPLATE_COUNT + 1
2140 (TEMPLATE_COUNT is the number of qualifying template classes,
2141 plus there must be another header for the member template
2142 itself).
2144 Notice that if header_count is zero, this is not a
2145 specialization but rather a template instantiation, so there
2146 is no check we can perform here. */
2147 if (header_count && header_count != template_count + 1)
2148 continue;
2150 /* Check that the number of template arguments at the
2151 innermost level for DECL is the same as for FN. */
2152 if (current_binding_level->kind == sk_template_parms
2153 && !current_binding_level->explicit_spec_p
2154 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2155 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2156 (current_template_parms))))
2157 continue;
2159 /* DECL might be a specialization of FN. */
2160 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2161 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2163 /* For a non-static member function, we need to make sure
2164 that the const qualification is the same. Since
2165 get_bindings does not try to merge the "this" parameter,
2166 we must do the comparison explicitly. */
2167 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2169 if (!same_type_p (TREE_VALUE (fn_arg_types),
2170 TREE_VALUE (decl_arg_types)))
2171 continue;
2173 /* And the ref-qualification. */
2174 if (type_memfn_rqual (TREE_TYPE (decl))
2175 != type_memfn_rqual (TREE_TYPE (fn)))
2176 continue;
2179 /* Skip the "this" parameter and, for constructors of
2180 classes with virtual bases, the VTT parameter. A
2181 full specialization of a constructor will have a VTT
2182 parameter, but a template never will. */
2183 decl_arg_types
2184 = skip_artificial_parms_for (decl, decl_arg_types);
2185 fn_arg_types
2186 = skip_artificial_parms_for (fn, fn_arg_types);
2188 /* Function templates cannot be specializations; there are
2189 no partial specializations of functions. Therefore, if
2190 the type of DECL does not match FN, there is no
2191 match.
2193 Note that it should never be the case that we have both
2194 candidates added here, and for regular member functions
2195 below. */
2196 if (tsk == tsk_template)
2198 if (compparms (fn_arg_types, decl_arg_types))
2199 candidates = tree_cons (NULL_TREE, fn, candidates);
2200 continue;
2203 /* See whether this function might be a specialization of this
2204 template. Suppress access control because we might be trying
2205 to make this specialization a friend, and we have already done
2206 access control for the declaration of the specialization. */
2207 push_deferring_access_checks (dk_no_check);
2208 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2209 pop_deferring_access_checks ();
2211 if (!targs)
2212 /* We cannot deduce template arguments that when used to
2213 specialize TMPL will produce DECL. */
2214 continue;
2216 if (uses_template_parms (targs))
2217 /* We deduced something involving 'auto', which isn't a valid
2218 template argument. */
2219 continue;
2221 /* Remove, from the set of candidates, all those functions
2222 whose constraints are not satisfied. */
2223 if (flag_concepts && !constraints_satisfied_p (fn, targs))
2224 continue;
2226 // Then, try to form the new function type.
2227 insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2228 if (insttype == error_mark_node)
2229 continue;
2230 fn_arg_types
2231 = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2232 if (!compparms (fn_arg_types, decl_arg_types))
2233 continue;
2235 /* Save this template, and the arguments deduced. */
2236 templates = tree_cons (targs, fn, templates);
2238 else if (need_member_template)
2239 /* FN is an ordinary member function, and we need a
2240 specialization of a member template. */
2242 else if (TREE_CODE (fn) != FUNCTION_DECL)
2243 /* We can get IDENTIFIER_NODEs here in certain erroneous
2244 cases. */
2246 else if (!DECL_FUNCTION_MEMBER_P (fn))
2247 /* This is just an ordinary non-member function. Nothing can
2248 be a specialization of that. */
2250 else if (DECL_ARTIFICIAL (fn))
2251 /* Cannot specialize functions that are created implicitly. */
2253 else
2255 tree decl_arg_types;
2257 /* This is an ordinary member function. However, since
2258 we're here, we can assume its enclosing class is a
2259 template class. For example,
2261 template <typename T> struct S { void f(); };
2262 template <> void S<int>::f() {}
2264 Here, S<int>::f is a non-template, but S<int> is a
2265 template class. If FN has the same type as DECL, we
2266 might be in business. */
2268 if (!DECL_TEMPLATE_INFO (fn))
2269 /* Its enclosing class is an explicit specialization
2270 of a template class. This is not a candidate. */
2271 continue;
2273 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2274 TREE_TYPE (TREE_TYPE (fn))))
2275 /* The return types differ. */
2276 continue;
2278 /* Adjust the type of DECL in case FN is a static member. */
2279 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2280 if (DECL_STATIC_FUNCTION_P (fn)
2281 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2282 decl_arg_types = TREE_CHAIN (decl_arg_types);
2284 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2285 decl_arg_types))
2286 continue;
2288 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2289 && (type_memfn_rqual (TREE_TYPE (decl))
2290 != type_memfn_rqual (TREE_TYPE (fn))))
2291 continue;
2293 // If the deduced arguments do not satisfy the constraints,
2294 // this is not a candidate.
2295 if (flag_concepts && !constraints_satisfied_p (fn))
2296 continue;
2298 // Add the candidate.
2299 candidates = tree_cons (NULL_TREE, fn, candidates);
2303 if (templates && TREE_CHAIN (templates))
2305 /* We have:
2307 [temp.expl.spec]
2309 It is possible for a specialization with a given function
2310 signature to be instantiated from more than one function
2311 template. In such cases, explicit specification of the
2312 template arguments must be used to uniquely identify the
2313 function template specialization being specialized.
2315 Note that here, there's no suggestion that we're supposed to
2316 determine which of the candidate templates is most
2317 specialized. However, we, also have:
2319 [temp.func.order]
2321 Partial ordering of overloaded function template
2322 declarations is used in the following contexts to select
2323 the function template to which a function template
2324 specialization refers:
2326 -- when an explicit specialization refers to a function
2327 template.
2329 So, we do use the partial ordering rules, at least for now.
2330 This extension can only serve to make invalid programs valid,
2331 so it's safe. And, there is strong anecdotal evidence that
2332 the committee intended the partial ordering rules to apply;
2333 the EDG front end has that behavior, and John Spicer claims
2334 that the committee simply forgot to delete the wording in
2335 [temp.expl.spec]. */
2336 tree tmpl = most_specialized_instantiation (templates);
2337 if (tmpl != error_mark_node)
2339 templates = tmpl;
2340 TREE_CHAIN (templates) = NULL_TREE;
2344 // Concepts allows multiple declarations of member functions
2345 // with the same signature. Like above, we need to rely on
2346 // on the partial ordering of those candidates to determine which
2347 // is the best.
2348 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2350 if (tree cand = most_constrained_function (candidates))
2352 candidates = cand;
2353 TREE_CHAIN (cand) = NULL_TREE;
2357 if (templates == NULL_TREE && candidates == NULL_TREE)
2359 error ("template-id %qD for %q+D does not match any template "
2360 "declaration", template_id, decl);
2361 if (header_count && header_count != template_count + 1)
2362 inform (input_location, "saw %d %<template<>%>, need %d for "
2363 "specializing a member function template",
2364 header_count, template_count + 1);
2365 else
2366 print_candidates (orig_fns);
2367 return error_mark_node;
2369 else if ((templates && TREE_CHAIN (templates))
2370 || (candidates && TREE_CHAIN (candidates))
2371 || (templates && candidates))
2373 error ("ambiguous template specialization %qD for %q+D",
2374 template_id, decl);
2375 candidates = chainon (candidates, templates);
2376 print_candidates (candidates);
2377 return error_mark_node;
2380 /* We have one, and exactly one, match. */
2381 if (candidates)
2383 tree fn = TREE_VALUE (candidates);
2384 *targs_out = copy_node (DECL_TI_ARGS (fn));
2386 // Propagate the candidate's constraints to the declaration.
2387 set_constraints (decl, get_constraints (fn));
2389 /* DECL is a re-declaration or partial instantiation of a template
2390 function. */
2391 if (TREE_CODE (fn) == TEMPLATE_DECL)
2392 return fn;
2393 /* It was a specialization of an ordinary member function in a
2394 template class. */
2395 return DECL_TI_TEMPLATE (fn);
2398 /* It was a specialization of a template. */
2399 targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2400 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2402 *targs_out = copy_node (targs);
2403 SET_TMPL_ARGS_LEVEL (*targs_out,
2404 TMPL_ARGS_DEPTH (*targs_out),
2405 TREE_PURPOSE (templates));
2407 else
2408 *targs_out = TREE_PURPOSE (templates);
2409 return TREE_VALUE (templates);
2412 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2413 but with the default argument values filled in from those in the
2414 TMPL_TYPES. */
2416 static tree
2417 copy_default_args_to_explicit_spec_1 (tree spec_types,
2418 tree tmpl_types)
2420 tree new_spec_types;
2422 if (!spec_types)
2423 return NULL_TREE;
2425 if (spec_types == void_list_node)
2426 return void_list_node;
2428 /* Substitute into the rest of the list. */
2429 new_spec_types =
2430 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2431 TREE_CHAIN (tmpl_types));
2433 /* Add the default argument for this parameter. */
2434 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2435 TREE_VALUE (spec_types),
2436 new_spec_types);
2439 /* DECL is an explicit specialization. Replicate default arguments
2440 from the template it specializes. (That way, code like:
2442 template <class T> void f(T = 3);
2443 template <> void f(double);
2444 void g () { f (); }
2446 works, as required.) An alternative approach would be to look up
2447 the correct default arguments at the call-site, but this approach
2448 is consistent with how implicit instantiations are handled. */
2450 static void
2451 copy_default_args_to_explicit_spec (tree decl)
2453 tree tmpl;
2454 tree spec_types;
2455 tree tmpl_types;
2456 tree new_spec_types;
2457 tree old_type;
2458 tree new_type;
2459 tree t;
2460 tree object_type = NULL_TREE;
2461 tree in_charge = NULL_TREE;
2462 tree vtt = NULL_TREE;
2464 /* See if there's anything we need to do. */
2465 tmpl = DECL_TI_TEMPLATE (decl);
2466 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2467 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2468 if (TREE_PURPOSE (t))
2469 break;
2470 if (!t)
2471 return;
2473 old_type = TREE_TYPE (decl);
2474 spec_types = TYPE_ARG_TYPES (old_type);
2476 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2478 /* Remove the this pointer, but remember the object's type for
2479 CV quals. */
2480 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2481 spec_types = TREE_CHAIN (spec_types);
2482 tmpl_types = TREE_CHAIN (tmpl_types);
2484 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2486 /* DECL may contain more parameters than TMPL due to the extra
2487 in-charge parameter in constructors and destructors. */
2488 in_charge = spec_types;
2489 spec_types = TREE_CHAIN (spec_types);
2491 if (DECL_HAS_VTT_PARM_P (decl))
2493 vtt = spec_types;
2494 spec_types = TREE_CHAIN (spec_types);
2498 /* Compute the merged default arguments. */
2499 new_spec_types =
2500 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2502 /* Compute the new FUNCTION_TYPE. */
2503 if (object_type)
2505 if (vtt)
2506 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2507 TREE_VALUE (vtt),
2508 new_spec_types);
2510 if (in_charge)
2511 /* Put the in-charge parameter back. */
2512 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2513 TREE_VALUE (in_charge),
2514 new_spec_types);
2516 new_type = build_method_type_directly (object_type,
2517 TREE_TYPE (old_type),
2518 new_spec_types);
2520 else
2521 new_type = build_function_type (TREE_TYPE (old_type),
2522 new_spec_types);
2523 new_type = cp_build_type_attribute_variant (new_type,
2524 TYPE_ATTRIBUTES (old_type));
2525 new_type = build_exception_variant (new_type,
2526 TYPE_RAISES_EXCEPTIONS (old_type));
2528 if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2529 TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2531 TREE_TYPE (decl) = new_type;
2534 /* Return the number of template headers we expect to see for a definition
2535 or specialization of CTYPE or one of its non-template members. */
2538 num_template_headers_for_class (tree ctype)
2540 int num_templates = 0;
2542 while (ctype && CLASS_TYPE_P (ctype))
2544 /* You're supposed to have one `template <...>' for every
2545 template class, but you don't need one for a full
2546 specialization. For example:
2548 template <class T> struct S{};
2549 template <> struct S<int> { void f(); };
2550 void S<int>::f () {}
2552 is correct; there shouldn't be a `template <>' for the
2553 definition of `S<int>::f'. */
2554 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2555 /* If CTYPE does not have template information of any
2556 kind, then it is not a template, nor is it nested
2557 within a template. */
2558 break;
2559 if (explicit_class_specialization_p (ctype))
2560 break;
2561 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2562 ++num_templates;
2564 ctype = TYPE_CONTEXT (ctype);
2567 return num_templates;
2570 /* Do a simple sanity check on the template headers that precede the
2571 variable declaration DECL. */
2573 void
2574 check_template_variable (tree decl)
2576 tree ctx = CP_DECL_CONTEXT (decl);
2577 int wanted = num_template_headers_for_class (ctx);
2578 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2579 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2581 if (cxx_dialect < cxx14)
2582 pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2583 "variable templates only available with "
2584 "-std=c++14 or -std=gnu++14");
2586 // Namespace-scope variable templates should have a template header.
2587 ++wanted;
2589 if (template_header_count > wanted)
2591 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2592 "too many template headers for %qD "
2593 "(should be %d)",
2594 decl, wanted);
2595 if (warned && CLASS_TYPE_P (ctx)
2596 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2597 inform (DECL_SOURCE_LOCATION (decl),
2598 "members of an explicitly specialized class are defined "
2599 "without a template header");
2603 /* An explicit specialization whose declarator-id or class-head-name is not
2604 qualified shall be declared in the nearest enclosing namespace of the
2605 template, or, if the namespace is inline (7.3.1), any namespace from its
2606 enclosing namespace set.
2608 If the name declared in the explicit instantiation is an unqualified name,
2609 the explicit instantiation shall appear in the namespace where its template
2610 is declared or, if that namespace is inline (7.3.1), any namespace from its
2611 enclosing namespace set. */
2613 void
2614 check_unqualified_spec_or_inst (tree t, location_t loc)
2616 tree tmpl = most_general_template (t);
2617 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2618 && !is_nested_namespace (current_namespace,
2619 CP_DECL_CONTEXT (tmpl), true))
2621 if (processing_specialization)
2622 permerror (loc, "explicit specialization of %qD outside its "
2623 "namespace must use a nested-name-specifier", tmpl);
2624 else if (processing_explicit_instantiation
2625 && cxx_dialect >= cxx11)
2626 /* This was allowed in C++98, so only pedwarn. */
2627 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2628 "outside its namespace must use a nested-name-"
2629 "specifier", tmpl);
2633 /* Warn for a template specialization SPEC that is missing some of a set
2634 of function or type attributes that the template TEMPL is declared with.
2635 ATTRLIST is a list of additional attributes that SPEC should be taken
2636 to ultimately be declared with. */
2638 static void
2639 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2641 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2642 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2644 if (TREE_CODE (tmpl) != FUNCTION_DECL)
2645 return;
2647 /* Avoid warning if either declaration or its type is deprecated. */
2648 if (TREE_DEPRECATED (tmpl)
2649 || TREE_DEPRECATED (spec))
2650 return;
2652 tree tmpl_type = TREE_TYPE (tmpl);
2653 tree spec_type = TREE_TYPE (spec);
2655 if (TREE_DEPRECATED (tmpl_type)
2656 || TREE_DEPRECATED (spec_type)
2657 || TREE_DEPRECATED (TREE_TYPE (tmpl_type))
2658 || TREE_DEPRECATED (TREE_TYPE (spec_type)))
2659 return;
2661 tree tmpl_attrs[] = { DECL_ATTRIBUTES (tmpl), TYPE_ATTRIBUTES (tmpl_type) };
2662 tree spec_attrs[] = { DECL_ATTRIBUTES (spec), TYPE_ATTRIBUTES (spec_type) };
2664 if (!spec_attrs[0])
2665 spec_attrs[0] = attrlist;
2666 else if (!spec_attrs[1])
2667 spec_attrs[1] = attrlist;
2669 /* Avoid warning if the primary has no attributes. */
2670 if (!tmpl_attrs[0] && !tmpl_attrs[1])
2671 return;
2673 /* Avoid warning if either declaration contains an attribute on
2674 the white list below. */
2675 const char* const whitelist[] = {
2676 "error", "warning"
2679 for (unsigned i = 0; i != 2; ++i)
2680 for (unsigned j = 0; j != sizeof whitelist / sizeof *whitelist; ++j)
2681 if (lookup_attribute (whitelist[j], tmpl_attrs[i])
2682 || lookup_attribute (whitelist[j], spec_attrs[i]))
2683 return;
2685 /* Avoid warning if the difference between the primary and
2686 the specialization is not in one of the attributes below. */
2687 const char* const blacklist[] = {
2688 "alloc_align", "alloc_size", "assume_aligned", "format",
2689 "format_arg", "malloc", "nonnull"
2692 /* Put together a list of the black listed attributes that the primary
2693 template is declared with that the specialization is not, in case
2694 it's not apparent from the most recent declaration of the primary. */
2695 unsigned nattrs = 0;
2696 pretty_printer str;
2698 for (unsigned i = 0; i != sizeof blacklist / sizeof *blacklist; ++i)
2700 for (unsigned j = 0; j != 2; ++j)
2702 if (!lookup_attribute (blacklist[i], tmpl_attrs[j]))
2703 continue;
2705 for (unsigned k = 0; k != 1 + !!spec_attrs[1]; ++k)
2707 if (lookup_attribute (blacklist[i], spec_attrs[k]))
2708 break;
2710 if (nattrs)
2711 pp_string (&str, ", ");
2712 pp_begin_quote (&str, pp_show_color (global_dc->printer));
2713 pp_string (&str, blacklist[i]);
2714 pp_end_quote (&str, pp_show_color (global_dc->printer));
2715 ++nattrs;
2720 if (!nattrs)
2721 return;
2723 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2724 "explicit specialization %q#D may be missing attributes",
2725 spec))
2726 inform (DECL_SOURCE_LOCATION (tmpl),
2727 nattrs > 1
2728 ? G_("missing primary template attributes %s")
2729 : G_("missing primary template attribute %s"),
2730 pp_formatted_text (&str));
2733 /* Check to see if the function just declared, as indicated in
2734 DECLARATOR, and in DECL, is a specialization of a function
2735 template. We may also discover that the declaration is an explicit
2736 instantiation at this point.
2738 Returns DECL, or an equivalent declaration that should be used
2739 instead if all goes well. Issues an error message if something is
2740 amiss. Returns error_mark_node if the error is not easily
2741 recoverable.
2743 FLAGS is a bitmask consisting of the following flags:
2745 2: The function has a definition.
2746 4: The function is a friend.
2748 The TEMPLATE_COUNT is the number of references to qualifying
2749 template classes that appeared in the name of the function. For
2750 example, in
2752 template <class T> struct S { void f(); };
2753 void S<int>::f();
2755 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2756 classes are not counted in the TEMPLATE_COUNT, so that in
2758 template <class T> struct S {};
2759 template <> struct S<int> { void f(); }
2760 template <> void S<int>::f();
2762 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2763 invalid; there should be no template <>.)
2765 If the function is a specialization, it is marked as such via
2766 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2767 is set up correctly, and it is added to the list of specializations
2768 for that template. */
2770 tree
2771 check_explicit_specialization (tree declarator,
2772 tree decl,
2773 int template_count,
2774 int flags,
2775 tree attrlist)
2777 int have_def = flags & 2;
2778 int is_friend = flags & 4;
2779 bool is_concept = flags & 8;
2780 int specialization = 0;
2781 int explicit_instantiation = 0;
2782 int member_specialization = 0;
2783 tree ctype = DECL_CLASS_CONTEXT (decl);
2784 tree dname = DECL_NAME (decl);
2785 tmpl_spec_kind tsk;
2787 if (is_friend)
2789 if (!processing_specialization)
2790 tsk = tsk_none;
2791 else
2792 tsk = tsk_excessive_parms;
2794 else
2795 tsk = current_tmpl_spec_kind (template_count);
2797 switch (tsk)
2799 case tsk_none:
2800 if (processing_specialization && !VAR_P (decl))
2802 specialization = 1;
2803 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2805 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2807 if (is_friend)
2808 /* This could be something like:
2810 template <class T> void f(T);
2811 class S { friend void f<>(int); } */
2812 specialization = 1;
2813 else
2815 /* This case handles bogus declarations like template <>
2816 template <class T> void f<int>(); */
2818 error ("template-id %qD in declaration of primary template",
2819 declarator);
2820 return decl;
2823 break;
2825 case tsk_invalid_member_spec:
2826 /* The error has already been reported in
2827 check_specialization_scope. */
2828 return error_mark_node;
2830 case tsk_invalid_expl_inst:
2831 error ("template parameter list used in explicit instantiation");
2833 /* Fall through. */
2835 case tsk_expl_inst:
2836 if (have_def)
2837 error ("definition provided for explicit instantiation");
2839 explicit_instantiation = 1;
2840 break;
2842 case tsk_excessive_parms:
2843 case tsk_insufficient_parms:
2844 if (tsk == tsk_excessive_parms)
2845 error ("too many template parameter lists in declaration of %qD",
2846 decl);
2847 else if (template_header_count)
2848 error("too few template parameter lists in declaration of %qD", decl);
2849 else
2850 error("explicit specialization of %qD must be introduced by "
2851 "%<template <>%>", decl);
2853 /* Fall through. */
2854 case tsk_expl_spec:
2855 if (is_concept)
2856 error ("explicit specialization declared %<concept%>");
2858 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2859 /* In cases like template<> constexpr bool v = true;
2860 We'll give an error in check_template_variable. */
2861 break;
2863 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2864 if (ctype)
2865 member_specialization = 1;
2866 else
2867 specialization = 1;
2868 break;
2870 case tsk_template:
2871 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2873 /* This case handles bogus declarations like template <>
2874 template <class T> void f<int>(); */
2876 if (!uses_template_parms (declarator))
2877 error ("template-id %qD in declaration of primary template",
2878 declarator);
2879 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2881 /* Partial specialization of variable template. */
2882 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2883 specialization = 1;
2884 goto ok;
2886 else if (cxx_dialect < cxx14)
2887 error ("non-type partial specialization %qD "
2888 "is not allowed", declarator);
2889 else
2890 error ("non-class, non-variable partial specialization %qD "
2891 "is not allowed", declarator);
2892 return decl;
2893 ok:;
2896 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2897 /* This is a specialization of a member template, without
2898 specialization the containing class. Something like:
2900 template <class T> struct S {
2901 template <class U> void f (U);
2903 template <> template <class U> void S<int>::f(U) {}
2905 That's a specialization -- but of the entire template. */
2906 specialization = 1;
2907 break;
2909 default:
2910 gcc_unreachable ();
2913 if ((specialization || member_specialization)
2914 /* This doesn't apply to variable templates. */
2915 && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2916 || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2918 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2919 for (; t; t = TREE_CHAIN (t))
2920 if (TREE_PURPOSE (t))
2922 permerror (input_location,
2923 "default argument specified in explicit specialization");
2924 break;
2928 if (specialization || member_specialization || explicit_instantiation)
2930 tree tmpl = NULL_TREE;
2931 tree targs = NULL_TREE;
2932 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2934 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2935 if (!was_template_id)
2937 tree fns;
2939 gcc_assert (identifier_p (declarator));
2940 if (ctype)
2941 fns = dname;
2942 else
2944 /* If there is no class context, the explicit instantiation
2945 must be at namespace scope. */
2946 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2948 /* Find the namespace binding, using the declaration
2949 context. */
2950 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2951 false, true);
2952 if (fns == error_mark_node)
2953 /* If lookup fails, look for a friend declaration so we can
2954 give a better diagnostic. */
2955 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2956 /*type*/false, /*complain*/true,
2957 /*hidden*/true);
2959 if (fns == error_mark_node || !is_overloaded_fn (fns))
2961 error ("%qD is not a template function", dname);
2962 fns = error_mark_node;
2966 declarator = lookup_template_function (fns, NULL_TREE);
2969 if (declarator == error_mark_node)
2970 return error_mark_node;
2972 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2974 if (!explicit_instantiation)
2975 /* A specialization in class scope. This is invalid,
2976 but the error will already have been flagged by
2977 check_specialization_scope. */
2978 return error_mark_node;
2979 else
2981 /* It's not valid to write an explicit instantiation in
2982 class scope, e.g.:
2984 class C { template void f(); }
2986 This case is caught by the parser. However, on
2987 something like:
2989 template class C { void f(); };
2991 (which is invalid) we can get here. The error will be
2992 issued later. */
2996 return decl;
2998 else if (ctype != NULL_TREE
2999 && (identifier_p (TREE_OPERAND (declarator, 0))))
3001 // We'll match variable templates in start_decl.
3002 if (VAR_P (decl))
3003 return decl;
3005 /* Find the list of functions in ctype that have the same
3006 name as the declared function. */
3007 tree name = TREE_OPERAND (declarator, 0);
3009 if (constructor_name_p (name, ctype))
3011 if (DECL_CONSTRUCTOR_P (decl)
3012 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3013 : !CLASSTYPE_DESTRUCTOR (ctype))
3015 /* From [temp.expl.spec]:
3017 If such an explicit specialization for the member
3018 of a class template names an implicitly-declared
3019 special member function (clause _special_), the
3020 program is ill-formed.
3022 Similar language is found in [temp.explicit]. */
3023 error ("specialization of implicitly-declared special member function");
3024 return error_mark_node;
3027 name = DECL_NAME (decl);
3030 /* For a type-conversion operator, We might be looking for
3031 `operator int' which will be a specialization of
3032 `operator T'. Grab all the conversion operators, and
3033 then select from them. */
3034 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3035 ? conv_op_identifier : name);
3037 if (fns == NULL_TREE)
3039 error ("no member function %qD declared in %qT", name, ctype);
3040 return error_mark_node;
3042 else
3043 TREE_OPERAND (declarator, 0) = fns;
3046 /* Figure out what exactly is being specialized at this point.
3047 Note that for an explicit instantiation, even one for a
3048 member function, we cannot tell a priori whether the
3049 instantiation is for a member template, or just a member
3050 function of a template class. Even if a member template is
3051 being instantiated, the member template arguments may be
3052 elided if they can be deduced from the rest of the
3053 declaration. */
3054 tmpl = determine_specialization (declarator, decl,
3055 &targs,
3056 member_specialization,
3057 template_count,
3058 tsk);
3060 if (!tmpl || tmpl == error_mark_node)
3061 /* We couldn't figure out what this declaration was
3062 specializing. */
3063 return error_mark_node;
3064 else
3066 if (TREE_CODE (decl) == FUNCTION_DECL
3067 && DECL_HIDDEN_FRIEND_P (tmpl))
3069 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3070 "friend declaration %qD is not visible to "
3071 "explicit specialization", tmpl))
3072 inform (DECL_SOURCE_LOCATION (tmpl),
3073 "friend declaration here");
3075 else if (!ctype && !is_friend
3076 && CP_DECL_CONTEXT (decl) == current_namespace)
3077 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3079 tree gen_tmpl = most_general_template (tmpl);
3081 if (explicit_instantiation)
3083 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3084 is done by do_decl_instantiation later. */
3086 int arg_depth = TMPL_ARGS_DEPTH (targs);
3087 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3089 if (arg_depth > parm_depth)
3091 /* If TMPL is not the most general template (for
3092 example, if TMPL is a friend template that is
3093 injected into namespace scope), then there will
3094 be too many levels of TARGS. Remove some of them
3095 here. */
3096 int i;
3097 tree new_targs;
3099 new_targs = make_tree_vec (parm_depth);
3100 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3101 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3102 = TREE_VEC_ELT (targs, i);
3103 targs = new_targs;
3106 return instantiate_template (tmpl, targs, tf_error);
3109 /* If we thought that the DECL was a member function, but it
3110 turns out to be specializing a static member function,
3111 make DECL a static member function as well. */
3112 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3113 && DECL_STATIC_FUNCTION_P (tmpl)
3114 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3115 revert_static_member_fn (decl);
3117 /* If this is a specialization of a member template of a
3118 template class, we want to return the TEMPLATE_DECL, not
3119 the specialization of it. */
3120 if (tsk == tsk_template && !was_template_id)
3122 tree result = DECL_TEMPLATE_RESULT (tmpl);
3123 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3124 DECL_INITIAL (result) = NULL_TREE;
3125 if (have_def)
3127 tree parm;
3128 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3129 DECL_SOURCE_LOCATION (result)
3130 = DECL_SOURCE_LOCATION (decl);
3131 /* We want to use the argument list specified in the
3132 definition, not in the original declaration. */
3133 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3134 for (parm = DECL_ARGUMENTS (result); parm;
3135 parm = DECL_CHAIN (parm))
3136 DECL_CONTEXT (parm) = result;
3138 return register_specialization (tmpl, gen_tmpl, targs,
3139 is_friend, 0);
3142 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3143 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3145 if (was_template_id)
3146 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3148 /* Inherit default function arguments from the template
3149 DECL is specializing. */
3150 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3151 copy_default_args_to_explicit_spec (decl);
3153 /* This specialization has the same protection as the
3154 template it specializes. */
3155 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3156 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3158 /* 7.1.1-1 [dcl.stc]
3160 A storage-class-specifier shall not be specified in an
3161 explicit specialization...
3163 The parser rejects these, so unless action is taken here,
3164 explicit function specializations will always appear with
3165 global linkage.
3167 The action recommended by the C++ CWG in response to C++
3168 defect report 605 is to make the storage class and linkage
3169 of the explicit specialization match the templated function:
3171 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3173 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3175 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3176 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3178 /* A concept cannot be specialized. */
3179 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3181 error ("explicit specialization of function concept %qD",
3182 gen_tmpl);
3183 return error_mark_node;
3186 /* This specialization has the same linkage and visibility as
3187 the function template it specializes. */
3188 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3189 if (! TREE_PUBLIC (decl))
3191 DECL_INTERFACE_KNOWN (decl) = 1;
3192 DECL_NOT_REALLY_EXTERN (decl) = 1;
3194 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3195 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3197 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3198 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3202 /* If DECL is a friend declaration, declared using an
3203 unqualified name, the namespace associated with DECL may
3204 have been set incorrectly. For example, in:
3206 template <typename T> void f(T);
3207 namespace N {
3208 struct S { friend void f<int>(int); }
3211 we will have set the DECL_CONTEXT for the friend
3212 declaration to N, rather than to the global namespace. */
3213 if (DECL_NAMESPACE_SCOPE_P (decl))
3214 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3216 if (is_friend && !have_def)
3217 /* This is not really a declaration of a specialization.
3218 It's just the name of an instantiation. But, it's not
3219 a request for an instantiation, either. */
3220 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3221 else if (TREE_CODE (decl) == FUNCTION_DECL)
3222 /* A specialization is not necessarily COMDAT. */
3223 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3224 && DECL_DECLARED_INLINE_P (decl));
3225 else if (VAR_P (decl))
3226 DECL_COMDAT (decl) = false;
3228 /* If this is a full specialization, register it so that we can find
3229 it again. Partial specializations will be registered in
3230 process_partial_specialization. */
3231 if (!processing_template_decl)
3233 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3235 decl = register_specialization (decl, gen_tmpl, targs,
3236 is_friend, 0);
3240 /* A 'structor should already have clones. */
3241 gcc_assert (decl == error_mark_node
3242 || variable_template_p (tmpl)
3243 || !(DECL_CONSTRUCTOR_P (decl)
3244 || DECL_DESTRUCTOR_P (decl))
3245 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3249 return decl;
3252 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3253 parameters. These are represented in the same format used for
3254 DECL_TEMPLATE_PARMS. */
3257 comp_template_parms (const_tree parms1, const_tree parms2)
3259 const_tree p1;
3260 const_tree p2;
3262 if (parms1 == parms2)
3263 return 1;
3265 for (p1 = parms1, p2 = parms2;
3266 p1 != NULL_TREE && p2 != NULL_TREE;
3267 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3269 tree t1 = TREE_VALUE (p1);
3270 tree t2 = TREE_VALUE (p2);
3271 int i;
3273 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3274 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3276 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3277 return 0;
3279 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3281 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3282 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3284 /* If either of the template parameters are invalid, assume
3285 they match for the sake of error recovery. */
3286 if (error_operand_p (parm1) || error_operand_p (parm2))
3287 return 1;
3289 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3290 return 0;
3292 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3293 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3294 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3295 continue;
3296 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3297 return 0;
3301 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3302 /* One set of parameters has more parameters lists than the
3303 other. */
3304 return 0;
3306 return 1;
3309 /* Determine whether PARM is a parameter pack. */
3311 bool
3312 template_parameter_pack_p (const_tree parm)
3314 /* Determine if we have a non-type template parameter pack. */
3315 if (TREE_CODE (parm) == PARM_DECL)
3316 return (DECL_TEMPLATE_PARM_P (parm)
3317 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3318 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3319 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3321 /* If this is a list of template parameters, we could get a
3322 TYPE_DECL or a TEMPLATE_DECL. */
3323 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3324 parm = TREE_TYPE (parm);
3326 /* Otherwise it must be a type template parameter. */
3327 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3328 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3329 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3332 /* Determine if T is a function parameter pack. */
3334 bool
3335 function_parameter_pack_p (const_tree t)
3337 if (t && TREE_CODE (t) == PARM_DECL)
3338 return DECL_PACK_P (t);
3339 return false;
3342 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3343 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3345 tree
3346 get_function_template_decl (const_tree primary_func_tmpl_inst)
3348 if (! primary_func_tmpl_inst
3349 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3350 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3351 return NULL;
3353 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3356 /* Return true iff the function parameter PARAM_DECL was expanded
3357 from the function parameter pack PACK. */
3359 bool
3360 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3362 if (DECL_ARTIFICIAL (param_decl)
3363 || !function_parameter_pack_p (pack))
3364 return false;
3366 /* The parameter pack and its pack arguments have the same
3367 DECL_PARM_INDEX. */
3368 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3371 /* Determine whether ARGS describes a variadic template args list,
3372 i.e., one that is terminated by a template argument pack. */
3374 static bool
3375 template_args_variadic_p (tree args)
3377 int nargs;
3378 tree last_parm;
3380 if (args == NULL_TREE)
3381 return false;
3383 args = INNERMOST_TEMPLATE_ARGS (args);
3384 nargs = TREE_VEC_LENGTH (args);
3386 if (nargs == 0)
3387 return false;
3389 last_parm = TREE_VEC_ELT (args, nargs - 1);
3391 return ARGUMENT_PACK_P (last_parm);
3394 /* Generate a new name for the parameter pack name NAME (an
3395 IDENTIFIER_NODE) that incorporates its */
3397 static tree
3398 make_ith_pack_parameter_name (tree name, int i)
3400 /* Munge the name to include the parameter index. */
3401 #define NUMBUF_LEN 128
3402 char numbuf[NUMBUF_LEN];
3403 char* newname;
3404 int newname_len;
3406 if (name == NULL_TREE)
3407 return name;
3408 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3409 newname_len = IDENTIFIER_LENGTH (name)
3410 + strlen (numbuf) + 2;
3411 newname = (char*)alloca (newname_len);
3412 snprintf (newname, newname_len,
3413 "%s#%i", IDENTIFIER_POINTER (name), i);
3414 return get_identifier (newname);
3417 /* Return true if T is a primary function, class or alias template
3418 specialization, not including the template pattern. */
3420 bool
3421 primary_template_specialization_p (const_tree t)
3423 if (!t)
3424 return false;
3426 if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3427 return (DECL_LANG_SPECIFIC (t)
3428 && DECL_USE_TEMPLATE (t)
3429 && DECL_TEMPLATE_INFO (t)
3430 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3431 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3432 return (CLASSTYPE_TEMPLATE_INFO (t)
3433 && CLASSTYPE_USE_TEMPLATE (t)
3434 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3435 else if (alias_template_specialization_p (t))
3436 return true;
3437 return false;
3440 /* Return true if PARM is a template template parameter. */
3442 bool
3443 template_template_parameter_p (const_tree parm)
3445 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3448 /* Return true iff PARM is a DECL representing a type template
3449 parameter. */
3451 bool
3452 template_type_parameter_p (const_tree parm)
3454 return (parm
3455 && (TREE_CODE (parm) == TYPE_DECL
3456 || TREE_CODE (parm) == TEMPLATE_DECL)
3457 && DECL_TEMPLATE_PARM_P (parm));
3460 /* Return the template parameters of T if T is a
3461 primary template instantiation, NULL otherwise. */
3463 tree
3464 get_primary_template_innermost_parameters (const_tree t)
3466 tree parms = NULL, template_info = NULL;
3468 if ((template_info = get_template_info (t))
3469 && primary_template_specialization_p (t))
3470 parms = INNERMOST_TEMPLATE_PARMS
3471 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3473 return parms;
3476 /* Return the template parameters of the LEVELth level from the full list
3477 of template parameters PARMS. */
3479 tree
3480 get_template_parms_at_level (tree parms, int level)
3482 tree p;
3483 if (!parms
3484 || TREE_CODE (parms) != TREE_LIST
3485 || level > TMPL_PARMS_DEPTH (parms))
3486 return NULL_TREE;
3488 for (p = parms; p; p = TREE_CHAIN (p))
3489 if (TMPL_PARMS_DEPTH (p) == level)
3490 return p;
3492 return NULL_TREE;
3495 /* Returns the template arguments of T if T is a template instantiation,
3496 NULL otherwise. */
3498 tree
3499 get_template_innermost_arguments (const_tree t)
3501 tree args = NULL, template_info = NULL;
3503 if ((template_info = get_template_info (t))
3504 && TI_ARGS (template_info))
3505 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3507 return args;
3510 /* Return the argument pack elements of T if T is a template argument pack,
3511 NULL otherwise. */
3513 tree
3514 get_template_argument_pack_elems (const_tree t)
3516 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3517 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3518 return NULL;
3520 return ARGUMENT_PACK_ARGS (t);
3523 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3524 ARGUMENT_PACK_SELECT represents. */
3526 static tree
3527 argument_pack_select_arg (tree t)
3529 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3530 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3532 /* If the selected argument is an expansion E, that most likely means we were
3533 called from gen_elem_of_pack_expansion_instantiation during the
3534 substituting of an argument pack (of which the Ith element is a pack
3535 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3536 In this case, the Ith element resulting from this substituting is going to
3537 be a pack expansion, which pattern is the pattern of E. Let's return the
3538 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3539 resulting pack expansion from it. */
3540 if (PACK_EXPANSION_P (arg))
3542 /* Make sure we aren't throwing away arg info. */
3543 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3544 arg = PACK_EXPANSION_PATTERN (arg);
3547 return arg;
3551 /* True iff FN is a function representing a built-in variadic parameter
3552 pack. */
3554 bool
3555 builtin_pack_fn_p (tree fn)
3557 if (!fn
3558 || TREE_CODE (fn) != FUNCTION_DECL
3559 || !DECL_IS_BUILTIN (fn))
3560 return false;
3562 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3563 return true;
3565 return false;
3568 /* True iff CALL is a call to a function representing a built-in variadic
3569 parameter pack. */
3571 static bool
3572 builtin_pack_call_p (tree call)
3574 if (TREE_CODE (call) != CALL_EXPR)
3575 return false;
3576 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3579 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3581 static tree
3582 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3583 tree in_decl)
3585 tree ohi = CALL_EXPR_ARG (call, 0);
3586 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3587 false/*fn*/, true/*int_cst*/);
3589 if (value_dependent_expression_p (hi))
3591 if (hi != ohi)
3593 call = copy_node (call);
3594 CALL_EXPR_ARG (call, 0) = hi;
3596 tree ex = make_pack_expansion (call, complain);
3597 tree vec = make_tree_vec (1);
3598 TREE_VEC_ELT (vec, 0) = ex;
3599 return vec;
3601 else
3603 hi = cxx_constant_value (hi);
3604 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3606 /* Calculate the largest value of len that won't make the size of the vec
3607 overflow an int. The compiler will exceed resource limits long before
3608 this, but it seems a decent place to diagnose. */
3609 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3611 if (len < 0 || len > max)
3613 if ((complain & tf_error)
3614 && hi != error_mark_node)
3615 error ("argument to __integer_pack must be between 0 and %d", max);
3616 return error_mark_node;
3619 tree vec = make_tree_vec (len);
3621 for (int i = 0; i < len; ++i)
3622 TREE_VEC_ELT (vec, i) = size_int (i);
3624 return vec;
3628 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3629 CALL. */
3631 static tree
3632 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3633 tree in_decl)
3635 if (!builtin_pack_call_p (call))
3636 return NULL_TREE;
3638 tree fn = CALL_EXPR_FN (call);
3640 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3641 return expand_integer_pack (call, args, complain, in_decl);
3643 return NULL_TREE;
3646 /* Structure used to track the progress of find_parameter_packs_r. */
3647 struct find_parameter_pack_data
3649 /* TREE_LIST that will contain all of the parameter packs found by
3650 the traversal. */
3651 tree* parameter_packs;
3653 /* Set of AST nodes that have been visited by the traversal. */
3654 hash_set<tree> *visited;
3656 /* True iff we're making a type pack expansion. */
3657 bool type_pack_expansion_p;
3660 /* Identifies all of the argument packs that occur in a template
3661 argument and appends them to the TREE_LIST inside DATA, which is a
3662 find_parameter_pack_data structure. This is a subroutine of
3663 make_pack_expansion and uses_parameter_packs. */
3664 static tree
3665 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3667 tree t = *tp;
3668 struct find_parameter_pack_data* ppd =
3669 (struct find_parameter_pack_data*)data;
3670 bool parameter_pack_p = false;
3672 /* Handle type aliases/typedefs. */
3673 if (TYPE_ALIAS_P (t))
3675 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3676 cp_walk_tree (&TI_ARGS (tinfo),
3677 &find_parameter_packs_r,
3678 ppd, ppd->visited);
3679 *walk_subtrees = 0;
3680 return NULL_TREE;
3683 /* Identify whether this is a parameter pack or not. */
3684 switch (TREE_CODE (t))
3686 case TEMPLATE_PARM_INDEX:
3687 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3688 parameter_pack_p = true;
3689 break;
3691 case TEMPLATE_TYPE_PARM:
3692 t = TYPE_MAIN_VARIANT (t);
3693 /* FALLTHRU */
3694 case TEMPLATE_TEMPLATE_PARM:
3695 /* If the placeholder appears in the decl-specifier-seq of a function
3696 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3697 is a pack expansion, the invented template parameter is a template
3698 parameter pack. */
3699 if (ppd->type_pack_expansion_p && is_auto (t))
3700 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3701 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3702 parameter_pack_p = true;
3703 break;
3705 case FIELD_DECL:
3706 case PARM_DECL:
3707 if (DECL_PACK_P (t))
3709 /* We don't want to walk into the type of a PARM_DECL,
3710 because we don't want to see the type parameter pack. */
3711 *walk_subtrees = 0;
3712 parameter_pack_p = true;
3714 break;
3716 case VAR_DECL:
3717 if (DECL_PACK_P (t))
3719 /* We don't want to walk into the type of a variadic capture proxy,
3720 because we don't want to see the type parameter pack. */
3721 *walk_subtrees = 0;
3722 parameter_pack_p = true;
3724 else if (variable_template_specialization_p (t))
3726 cp_walk_tree (&DECL_TI_ARGS (t),
3727 find_parameter_packs_r,
3728 ppd, ppd->visited);
3729 *walk_subtrees = 0;
3731 break;
3733 case CALL_EXPR:
3734 if (builtin_pack_call_p (t))
3735 parameter_pack_p = true;
3736 break;
3738 case BASES:
3739 parameter_pack_p = true;
3740 break;
3741 default:
3742 /* Not a parameter pack. */
3743 break;
3746 if (parameter_pack_p)
3748 /* Add this parameter pack to the list. */
3749 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3752 if (TYPE_P (t))
3753 cp_walk_tree (&TYPE_CONTEXT (t),
3754 &find_parameter_packs_r, ppd, ppd->visited);
3756 /* This switch statement will return immediately if we don't find a
3757 parameter pack. */
3758 switch (TREE_CODE (t))
3760 case TEMPLATE_PARM_INDEX:
3761 return NULL_TREE;
3763 case BOUND_TEMPLATE_TEMPLATE_PARM:
3764 /* Check the template itself. */
3765 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3766 &find_parameter_packs_r, ppd, ppd->visited);
3767 /* Check the template arguments. */
3768 cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3769 ppd->visited);
3770 *walk_subtrees = 0;
3771 return NULL_TREE;
3773 case TEMPLATE_TYPE_PARM:
3774 case TEMPLATE_TEMPLATE_PARM:
3775 return NULL_TREE;
3777 case PARM_DECL:
3778 return NULL_TREE;
3780 case DECL_EXPR:
3781 /* Ignore the declaration of a capture proxy for a parameter pack. */
3782 if (is_capture_proxy (DECL_EXPR_DECL (t)))
3783 *walk_subtrees = 0;
3784 return NULL_TREE;
3786 case RECORD_TYPE:
3787 if (TYPE_PTRMEMFUNC_P (t))
3788 return NULL_TREE;
3789 /* Fall through. */
3791 case UNION_TYPE:
3792 case ENUMERAL_TYPE:
3793 if (TYPE_TEMPLATE_INFO (t))
3794 cp_walk_tree (&TYPE_TI_ARGS (t),
3795 &find_parameter_packs_r, ppd, ppd->visited);
3797 *walk_subtrees = 0;
3798 return NULL_TREE;
3800 case TEMPLATE_DECL:
3801 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3802 return NULL_TREE;
3803 gcc_fallthrough();
3805 case CONSTRUCTOR:
3806 cp_walk_tree (&TREE_TYPE (t),
3807 &find_parameter_packs_r, ppd, ppd->visited);
3808 return NULL_TREE;
3810 case TYPENAME_TYPE:
3811 cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3812 ppd, ppd->visited);
3813 *walk_subtrees = 0;
3814 return NULL_TREE;
3816 case TYPE_PACK_EXPANSION:
3817 case EXPR_PACK_EXPANSION:
3818 *walk_subtrees = 0;
3819 return NULL_TREE;
3821 case INTEGER_TYPE:
3822 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3823 ppd, ppd->visited);
3824 *walk_subtrees = 0;
3825 return NULL_TREE;
3827 case IDENTIFIER_NODE:
3828 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3829 ppd->visited);
3830 *walk_subtrees = 0;
3831 return NULL_TREE;
3833 case LAMBDA_EXPR:
3835 /* Look at explicit captures. */
3836 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3837 cap; cap = TREE_CHAIN (cap))
3838 cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3839 ppd->visited);
3840 /* Since we defer implicit capture, look in the body as well. */
3841 tree fn = lambda_function (t);
3842 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3843 ppd->visited);
3844 *walk_subtrees = 0;
3845 return NULL_TREE;
3848 case DECLTYPE_TYPE:
3850 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3851 type_pack_expansion_p to false so that any placeholders
3852 within the expression don't get marked as parameter packs. */
3853 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3854 ppd->type_pack_expansion_p = false;
3855 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3856 ppd, ppd->visited);
3857 ppd->type_pack_expansion_p = type_pack_expansion_p;
3858 *walk_subtrees = 0;
3859 return NULL_TREE;
3862 default:
3863 return NULL_TREE;
3866 return NULL_TREE;
3869 /* Determines if the expression or type T uses any parameter packs. */
3870 bool
3871 uses_parameter_packs (tree t)
3873 tree parameter_packs = NULL_TREE;
3874 struct find_parameter_pack_data ppd;
3875 ppd.parameter_packs = &parameter_packs;
3876 ppd.visited = new hash_set<tree>;
3877 ppd.type_pack_expansion_p = false;
3878 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3879 delete ppd.visited;
3880 return parameter_packs != NULL_TREE;
3883 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3884 representation a base-class initializer into a parameter pack
3885 expansion. If all goes well, the resulting node will be an
3886 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3887 respectively. */
3888 tree
3889 make_pack_expansion (tree arg, tsubst_flags_t complain)
3891 tree result;
3892 tree parameter_packs = NULL_TREE;
3893 bool for_types = false;
3894 struct find_parameter_pack_data ppd;
3896 if (!arg || arg == error_mark_node)
3897 return arg;
3899 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3901 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3902 class initializer. In this case, the TREE_PURPOSE will be a
3903 _TYPE node (representing the base class expansion we're
3904 initializing) and the TREE_VALUE will be a TREE_LIST
3905 containing the initialization arguments.
3907 The resulting expansion looks somewhat different from most
3908 expansions. Rather than returning just one _EXPANSION, we
3909 return a TREE_LIST whose TREE_PURPOSE is a
3910 TYPE_PACK_EXPANSION containing the bases that will be
3911 initialized. The TREE_VALUE will be identical to the
3912 original TREE_VALUE, which is a list of arguments that will
3913 be passed to each base. We do not introduce any new pack
3914 expansion nodes into the TREE_VALUE (although it is possible
3915 that some already exist), because the TREE_PURPOSE and
3916 TREE_VALUE all need to be expanded together with the same
3917 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
3918 resulting TREE_PURPOSE will mention the parameter packs in
3919 both the bases and the arguments to the bases. */
3920 tree purpose;
3921 tree value;
3922 tree parameter_packs = NULL_TREE;
3924 /* Determine which parameter packs will be used by the base
3925 class expansion. */
3926 ppd.visited = new hash_set<tree>;
3927 ppd.parameter_packs = &parameter_packs;
3928 ppd.type_pack_expansion_p = true;
3929 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3930 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3931 &ppd, ppd.visited);
3933 if (parameter_packs == NULL_TREE)
3935 if (complain & tf_error)
3936 error ("base initializer expansion %qT contains no parameter packs",
3937 arg);
3938 delete ppd.visited;
3939 return error_mark_node;
3942 if (TREE_VALUE (arg) != void_type_node)
3944 /* Collect the sets of parameter packs used in each of the
3945 initialization arguments. */
3946 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3948 /* Determine which parameter packs will be expanded in this
3949 argument. */
3950 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3951 &ppd, ppd.visited);
3955 delete ppd.visited;
3957 /* Create the pack expansion type for the base type. */
3958 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3959 SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3960 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3961 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
3963 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3964 they will rarely be compared to anything. */
3965 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3967 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3970 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3971 for_types = true;
3973 /* Build the PACK_EXPANSION_* node. */
3974 result = for_types
3975 ? cxx_make_type (TYPE_PACK_EXPANSION)
3976 : make_node (EXPR_PACK_EXPANSION);
3977 SET_PACK_EXPANSION_PATTERN (result, arg);
3978 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3980 /* Propagate type and const-expression information. */
3981 TREE_TYPE (result) = TREE_TYPE (arg);
3982 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3983 /* Mark this read now, since the expansion might be length 0. */
3984 mark_exp_read (arg);
3986 else
3987 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3988 they will rarely be compared to anything. */
3989 SET_TYPE_STRUCTURAL_EQUALITY (result);
3991 /* Determine which parameter packs will be expanded. */
3992 ppd.parameter_packs = &parameter_packs;
3993 ppd.visited = new hash_set<tree>;
3994 ppd.type_pack_expansion_p = TYPE_P (arg);
3995 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3996 delete ppd.visited;
3998 /* Make sure we found some parameter packs. */
3999 if (parameter_packs == NULL_TREE)
4001 if (complain & tf_error)
4003 if (TYPE_P (arg))
4004 error ("expansion pattern %qT contains no argument packs", arg);
4005 else
4006 error ("expansion pattern %qE contains no argument packs", arg);
4008 return error_mark_node;
4010 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4012 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4014 return result;
4017 /* Checks T for any "bare" parameter packs, which have not yet been
4018 expanded, and issues an error if any are found. This operation can
4019 only be done on full expressions or types (e.g., an expression
4020 statement, "if" condition, etc.), because we could have expressions like:
4022 foo(f(g(h(args)))...)
4024 where "args" is a parameter pack. check_for_bare_parameter_packs
4025 should not be called for the subexpressions args, h(args),
4026 g(h(args)), or f(g(h(args))), because we would produce erroneous
4027 error messages.
4029 Returns TRUE and emits an error if there were bare parameter packs,
4030 returns FALSE otherwise. */
4031 bool
4032 check_for_bare_parameter_packs (tree t)
4034 tree parameter_packs = NULL_TREE;
4035 struct find_parameter_pack_data ppd;
4037 if (!processing_template_decl || !t || t == error_mark_node)
4038 return false;
4040 /* A lambda might use a parameter pack from the containing context. */
4041 if (current_class_type && LAMBDA_TYPE_P (current_class_type))
4042 return false;
4044 if (TREE_CODE (t) == TYPE_DECL)
4045 t = TREE_TYPE (t);
4047 ppd.parameter_packs = &parameter_packs;
4048 ppd.visited = new hash_set<tree>;
4049 ppd.type_pack_expansion_p = false;
4050 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4051 delete ppd.visited;
4053 if (parameter_packs)
4055 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
4056 error_at (loc, "parameter packs not expanded with %<...%>:");
4057 while (parameter_packs)
4059 tree pack = TREE_VALUE (parameter_packs);
4060 tree name = NULL_TREE;
4062 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4063 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4064 name = TYPE_NAME (pack);
4065 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4066 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4067 else if (TREE_CODE (pack) == CALL_EXPR)
4068 name = DECL_NAME (CALL_EXPR_FN (pack));
4069 else
4070 name = DECL_NAME (pack);
4072 if (name)
4073 inform (loc, " %qD", name);
4074 else
4075 inform (loc, " <anonymous>");
4077 parameter_packs = TREE_CHAIN (parameter_packs);
4080 return true;
4083 return false;
4086 /* Expand any parameter packs that occur in the template arguments in
4087 ARGS. */
4088 tree
4089 expand_template_argument_pack (tree args)
4091 if (args == error_mark_node)
4092 return error_mark_node;
4094 tree result_args = NULL_TREE;
4095 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4096 int num_result_args = -1;
4097 int non_default_args_count = -1;
4099 /* First, determine if we need to expand anything, and the number of
4100 slots we'll need. */
4101 for (in_arg = 0; in_arg < nargs; ++in_arg)
4103 tree arg = TREE_VEC_ELT (args, in_arg);
4104 if (arg == NULL_TREE)
4105 return args;
4106 if (ARGUMENT_PACK_P (arg))
4108 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4109 if (num_result_args < 0)
4110 num_result_args = in_arg + num_packed;
4111 else
4112 num_result_args += num_packed;
4114 else
4116 if (num_result_args >= 0)
4117 num_result_args++;
4121 /* If no expansion is necessary, we're done. */
4122 if (num_result_args < 0)
4123 return args;
4125 /* Expand arguments. */
4126 result_args = make_tree_vec (num_result_args);
4127 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4128 non_default_args_count =
4129 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4130 for (in_arg = 0; in_arg < nargs; ++in_arg)
4132 tree arg = TREE_VEC_ELT (args, in_arg);
4133 if (ARGUMENT_PACK_P (arg))
4135 tree packed = ARGUMENT_PACK_ARGS (arg);
4136 int i, num_packed = TREE_VEC_LENGTH (packed);
4137 for (i = 0; i < num_packed; ++i, ++out_arg)
4138 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4139 if (non_default_args_count > 0)
4140 non_default_args_count += num_packed - 1;
4142 else
4144 TREE_VEC_ELT (result_args, out_arg) = arg;
4145 ++out_arg;
4148 if (non_default_args_count >= 0)
4149 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4150 return result_args;
4153 /* Checks if DECL shadows a template parameter.
4155 [temp.local]: A template-parameter shall not be redeclared within its
4156 scope (including nested scopes).
4158 Emits an error and returns TRUE if the DECL shadows a parameter,
4159 returns FALSE otherwise. */
4161 bool
4162 check_template_shadow (tree decl)
4164 tree olddecl;
4166 /* If we're not in a template, we can't possibly shadow a template
4167 parameter. */
4168 if (!current_template_parms)
4169 return true;
4171 /* Figure out what we're shadowing. */
4172 decl = OVL_FIRST (decl);
4173 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4175 /* If there's no previous binding for this name, we're not shadowing
4176 anything, let alone a template parameter. */
4177 if (!olddecl)
4178 return true;
4180 /* If we're not shadowing a template parameter, we're done. Note
4181 that OLDDECL might be an OVERLOAD (or perhaps even an
4182 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4183 node. */
4184 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4185 return true;
4187 /* We check for decl != olddecl to avoid bogus errors for using a
4188 name inside a class. We check TPFI to avoid duplicate errors for
4189 inline member templates. */
4190 if (decl == olddecl
4191 || (DECL_TEMPLATE_PARM_P (decl)
4192 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4193 return true;
4195 /* Don't complain about the injected class name, as we've already
4196 complained about the class itself. */
4197 if (DECL_SELF_REFERENCE_P (decl))
4198 return false;
4200 if (DECL_TEMPLATE_PARM_P (decl))
4201 error ("declaration of template parameter %q+D shadows "
4202 "template parameter", decl);
4203 else
4204 error ("declaration of %q+#D shadows template parameter", decl);
4205 inform (DECL_SOURCE_LOCATION (olddecl),
4206 "template parameter %qD declared here", olddecl);
4207 return false;
4210 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4211 ORIG_LEVEL, DECL, and TYPE. */
4213 static tree
4214 build_template_parm_index (int index,
4215 int level,
4216 int orig_level,
4217 tree decl,
4218 tree type)
4220 tree t = make_node (TEMPLATE_PARM_INDEX);
4221 TEMPLATE_PARM_IDX (t) = index;
4222 TEMPLATE_PARM_LEVEL (t) = level;
4223 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4224 TEMPLATE_PARM_DECL (t) = decl;
4225 TREE_TYPE (t) = type;
4226 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4227 TREE_READONLY (t) = TREE_READONLY (decl);
4229 return t;
4232 /* Find the canonical type parameter for the given template type
4233 parameter. Returns the canonical type parameter, which may be TYPE
4234 if no such parameter existed. */
4236 static tree
4237 canonical_type_parameter (tree type)
4239 tree list;
4240 int idx = TEMPLATE_TYPE_IDX (type);
4241 if (!canonical_template_parms)
4242 vec_alloc (canonical_template_parms, idx + 1);
4244 if (canonical_template_parms->length () <= (unsigned) idx)
4245 vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4247 list = (*canonical_template_parms)[idx];
4248 while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4249 list = TREE_CHAIN (list);
4251 if (list)
4252 return TREE_VALUE (list);
4253 else
4255 (*canonical_template_parms)[idx]
4256 = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4257 return type;
4261 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4262 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4263 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4264 new one is created. */
4266 static tree
4267 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4268 tsubst_flags_t complain)
4270 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4271 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4272 != TEMPLATE_PARM_LEVEL (index) - levels)
4273 || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4275 tree orig_decl = TEMPLATE_PARM_DECL (index);
4276 tree decl, t;
4278 decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4279 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4280 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4281 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4282 DECL_ARTIFICIAL (decl) = 1;
4283 SET_DECL_TEMPLATE_PARM_P (decl);
4285 t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4286 TEMPLATE_PARM_LEVEL (index) - levels,
4287 TEMPLATE_PARM_ORIG_LEVEL (index),
4288 decl, type);
4289 TEMPLATE_PARM_DESCENDANTS (index) = t;
4290 TEMPLATE_PARM_PARAMETER_PACK (t)
4291 = TEMPLATE_PARM_PARAMETER_PACK (index);
4293 /* Template template parameters need this. */
4294 if (TREE_CODE (decl) == TEMPLATE_DECL)
4296 DECL_TEMPLATE_RESULT (decl)
4297 = build_decl (DECL_SOURCE_LOCATION (decl),
4298 TYPE_DECL, DECL_NAME (decl), type);
4299 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4300 DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4301 (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4305 return TEMPLATE_PARM_DESCENDANTS (index);
4308 /* Process information from new template parameter PARM and append it
4309 to the LIST being built. This new parameter is a non-type
4310 parameter iff IS_NON_TYPE is true. This new parameter is a
4311 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4312 is in PARM_LOC. */
4314 tree
4315 process_template_parm (tree list, location_t parm_loc, tree parm,
4316 bool is_non_type, bool is_parameter_pack)
4318 tree decl = 0;
4319 int idx = 0;
4321 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4322 tree defval = TREE_PURPOSE (parm);
4323 tree constr = TREE_TYPE (parm);
4325 if (list)
4327 tree p = tree_last (list);
4329 if (p && TREE_VALUE (p) != error_mark_node)
4331 p = TREE_VALUE (p);
4332 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4333 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4334 else
4335 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4338 ++idx;
4341 if (is_non_type)
4343 parm = TREE_VALUE (parm);
4345 SET_DECL_TEMPLATE_PARM_P (parm);
4347 if (TREE_TYPE (parm) != error_mark_node)
4349 /* [temp.param]
4351 The top-level cv-qualifiers on the template-parameter are
4352 ignored when determining its type. */
4353 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4354 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4355 TREE_TYPE (parm) = error_mark_node;
4356 else if (uses_parameter_packs (TREE_TYPE (parm))
4357 && !is_parameter_pack
4358 /* If we're in a nested template parameter list, the template
4359 template parameter could be a parameter pack. */
4360 && processing_template_parmlist == 1)
4362 /* This template parameter is not a parameter pack, but it
4363 should be. Complain about "bare" parameter packs. */
4364 check_for_bare_parameter_packs (TREE_TYPE (parm));
4366 /* Recover by calling this a parameter pack. */
4367 is_parameter_pack = true;
4371 /* A template parameter is not modifiable. */
4372 TREE_CONSTANT (parm) = 1;
4373 TREE_READONLY (parm) = 1;
4374 decl = build_decl (parm_loc,
4375 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4376 TREE_CONSTANT (decl) = 1;
4377 TREE_READONLY (decl) = 1;
4378 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4379 = build_template_parm_index (idx, processing_template_decl,
4380 processing_template_decl,
4381 decl, TREE_TYPE (parm));
4383 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4384 = is_parameter_pack;
4386 else
4388 tree t;
4389 parm = TREE_VALUE (TREE_VALUE (parm));
4391 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4393 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4394 /* This is for distinguishing between real templates and template
4395 template parameters */
4396 TREE_TYPE (parm) = t;
4397 TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4398 decl = parm;
4400 else
4402 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4403 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4404 decl = build_decl (parm_loc,
4405 TYPE_DECL, parm, t);
4408 TYPE_NAME (t) = decl;
4409 TYPE_STUB_DECL (t) = decl;
4410 parm = decl;
4411 TEMPLATE_TYPE_PARM_INDEX (t)
4412 = build_template_parm_index (idx, processing_template_decl,
4413 processing_template_decl,
4414 decl, TREE_TYPE (parm));
4415 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4416 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4418 DECL_ARTIFICIAL (decl) = 1;
4419 SET_DECL_TEMPLATE_PARM_P (decl);
4421 /* Build requirements for the type/template parameter.
4422 This must be done after SET_DECL_TEMPLATE_PARM_P or
4423 process_template_parm could fail. */
4424 tree reqs = finish_shorthand_constraint (parm, constr);
4426 pushdecl (decl);
4428 if (defval && TREE_CODE (defval) == OVERLOAD)
4429 lookup_keep (defval, true);
4431 /* Build the parameter node linking the parameter declaration,
4432 its default argument (if any), and its constraints (if any). */
4433 parm = build_tree_list (defval, parm);
4434 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4436 return chainon (list, parm);
4439 /* The end of a template parameter list has been reached. Process the
4440 tree list into a parameter vector, converting each parameter into a more
4441 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4442 as PARM_DECLs. */
4444 tree
4445 end_template_parm_list (tree parms)
4447 int nparms;
4448 tree parm, next;
4449 tree saved_parmlist = make_tree_vec (list_length (parms));
4451 /* Pop the dummy parameter level and add the real one. */
4452 current_template_parms = TREE_CHAIN (current_template_parms);
4454 current_template_parms
4455 = tree_cons (size_int (processing_template_decl),
4456 saved_parmlist, current_template_parms);
4458 for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4460 next = TREE_CHAIN (parm);
4461 TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4462 TREE_CHAIN (parm) = NULL_TREE;
4465 --processing_template_parmlist;
4467 return saved_parmlist;
4470 // Explicitly indicate the end of the template parameter list. We assume
4471 // that the current template parameters have been constructed and/or
4472 // managed explicitly, as when creating new template template parameters
4473 // from a shorthand constraint.
4474 void
4475 end_template_parm_list ()
4477 --processing_template_parmlist;
4480 /* end_template_decl is called after a template declaration is seen. */
4482 void
4483 end_template_decl (void)
4485 reset_specialization ();
4487 if (! processing_template_decl)
4488 return;
4490 /* This matches the pushlevel in begin_template_parm_list. */
4491 finish_scope ();
4493 --processing_template_decl;
4494 current_template_parms = TREE_CHAIN (current_template_parms);
4497 /* Takes a TREE_LIST representing a template parameter and convert it
4498 into an argument suitable to be passed to the type substitution
4499 functions. Note that If the TREE_LIST contains an error_mark
4500 node, the returned argument is error_mark_node. */
4502 tree
4503 template_parm_to_arg (tree t)
4506 if (t == NULL_TREE
4507 || TREE_CODE (t) != TREE_LIST)
4508 return t;
4510 if (error_operand_p (TREE_VALUE (t)))
4511 return error_mark_node;
4513 t = TREE_VALUE (t);
4515 if (TREE_CODE (t) == TYPE_DECL
4516 || TREE_CODE (t) == TEMPLATE_DECL)
4518 t = TREE_TYPE (t);
4520 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4522 /* Turn this argument into a TYPE_ARGUMENT_PACK
4523 with a single element, which expands T. */
4524 tree vec = make_tree_vec (1);
4525 if (CHECKING_P)
4526 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4528 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4530 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4531 SET_ARGUMENT_PACK_ARGS (t, vec);
4534 else
4536 t = DECL_INITIAL (t);
4538 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4540 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4541 with a single element, which expands T. */
4542 tree vec = make_tree_vec (1);
4543 if (CHECKING_P)
4544 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4546 t = convert_from_reference (t);
4547 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4549 t = make_node (NONTYPE_ARGUMENT_PACK);
4550 SET_ARGUMENT_PACK_ARGS (t, vec);
4552 else
4553 t = convert_from_reference (t);
4555 return t;
4558 /* Given a single level of template parameters (a TREE_VEC), return it
4559 as a set of template arguments. */
4561 static tree
4562 template_parms_level_to_args (tree parms)
4564 tree a = copy_node (parms);
4565 TREE_TYPE (a) = NULL_TREE;
4566 for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4567 TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4569 if (CHECKING_P)
4570 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4572 return a;
4575 /* Given a set of template parameters, return them as a set of template
4576 arguments. The template parameters are represented as a TREE_VEC, in
4577 the form documented in cp-tree.h for template arguments. */
4579 static tree
4580 template_parms_to_args (tree parms)
4582 tree header;
4583 tree args = NULL_TREE;
4584 int length = TMPL_PARMS_DEPTH (parms);
4585 int l = length;
4587 /* If there is only one level of template parameters, we do not
4588 create a TREE_VEC of TREE_VECs. Instead, we return a single
4589 TREE_VEC containing the arguments. */
4590 if (length > 1)
4591 args = make_tree_vec (length);
4593 for (header = parms; header; header = TREE_CHAIN (header))
4595 tree a = template_parms_level_to_args (TREE_VALUE (header));
4597 if (length > 1)
4598 TREE_VEC_ELT (args, --l) = a;
4599 else
4600 args = a;
4603 return args;
4606 /* Within the declaration of a template, return the currently active
4607 template parameters as an argument TREE_VEC. */
4609 static tree
4610 current_template_args (void)
4612 return template_parms_to_args (current_template_parms);
4615 /* Update the declared TYPE by doing any lookups which were thought to be
4616 dependent, but are not now that we know the SCOPE of the declarator. */
4618 tree
4619 maybe_update_decl_type (tree orig_type, tree scope)
4621 tree type = orig_type;
4623 if (type == NULL_TREE)
4624 return type;
4626 if (TREE_CODE (orig_type) == TYPE_DECL)
4627 type = TREE_TYPE (type);
4629 if (scope && TYPE_P (scope) && dependent_type_p (scope)
4630 && dependent_type_p (type)
4631 /* Don't bother building up the args in this case. */
4632 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4634 /* tsubst in the args corresponding to the template parameters,
4635 including auto if present. Most things will be unchanged, but
4636 make_typename_type and tsubst_qualified_id will resolve
4637 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
4638 tree args = current_template_args ();
4639 tree auto_node = type_uses_auto (type);
4640 tree pushed;
4641 if (auto_node)
4643 tree auto_vec = make_tree_vec (1);
4644 TREE_VEC_ELT (auto_vec, 0) = auto_node;
4645 args = add_to_template_args (args, auto_vec);
4647 pushed = push_scope (scope);
4648 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4649 if (pushed)
4650 pop_scope (scope);
4653 if (type == error_mark_node)
4654 return orig_type;
4656 if (TREE_CODE (orig_type) == TYPE_DECL)
4658 if (same_type_p (type, TREE_TYPE (orig_type)))
4659 type = orig_type;
4660 else
4661 type = TYPE_NAME (type);
4663 return type;
4666 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4667 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
4668 the new template is a member template. */
4670 tree
4671 build_template_decl (tree decl, tree parms, bool member_template_p)
4673 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4674 DECL_TEMPLATE_PARMS (tmpl) = parms;
4675 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4676 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4677 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4679 return tmpl;
4682 struct template_parm_data
4684 /* The level of the template parameters we are currently
4685 processing. */
4686 int level;
4688 /* The index of the specialization argument we are currently
4689 processing. */
4690 int current_arg;
4692 /* An array whose size is the number of template parameters. The
4693 elements are nonzero if the parameter has been used in any one
4694 of the arguments processed so far. */
4695 int* parms;
4697 /* An array whose size is the number of template arguments. The
4698 elements are nonzero if the argument makes use of template
4699 parameters of this level. */
4700 int* arg_uses_template_parms;
4703 /* Subroutine of push_template_decl used to see if each template
4704 parameter in a partial specialization is used in the explicit
4705 argument list. If T is of the LEVEL given in DATA (which is
4706 treated as a template_parm_data*), then DATA->PARMS is marked
4707 appropriately. */
4709 static int
4710 mark_template_parm (tree t, void* data)
4712 int level;
4713 int idx;
4714 struct template_parm_data* tpd = (struct template_parm_data*) data;
4716 template_parm_level_and_index (t, &level, &idx);
4718 if (level == tpd->level)
4720 tpd->parms[idx] = 1;
4721 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4724 /* In C++17 the type of a non-type argument is a deduced context. */
4725 if (cxx_dialect >= cxx17
4726 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4727 for_each_template_parm (TREE_TYPE (t),
4728 &mark_template_parm,
4729 data,
4730 NULL,
4731 /*include_nondeduced_p=*/false);
4733 /* Return zero so that for_each_template_parm will continue the
4734 traversal of the tree; we want to mark *every* template parm. */
4735 return 0;
4738 /* Process the partial specialization DECL. */
4740 static tree
4741 process_partial_specialization (tree decl)
4743 tree type = TREE_TYPE (decl);
4744 tree tinfo = get_template_info (decl);
4745 tree maintmpl = TI_TEMPLATE (tinfo);
4746 tree specargs = TI_ARGS (tinfo);
4747 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4748 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4749 tree inner_parms;
4750 tree inst;
4751 int nargs = TREE_VEC_LENGTH (inner_args);
4752 int ntparms;
4753 int i;
4754 bool did_error_intro = false;
4755 struct template_parm_data tpd;
4756 struct template_parm_data tpd2;
4758 gcc_assert (current_template_parms);
4760 /* A concept cannot be specialized. */
4761 if (flag_concepts && variable_concept_p (maintmpl))
4763 error ("specialization of variable concept %q#D", maintmpl);
4764 return error_mark_node;
4767 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4768 ntparms = TREE_VEC_LENGTH (inner_parms);
4770 /* We check that each of the template parameters given in the
4771 partial specialization is used in the argument list to the
4772 specialization. For example:
4774 template <class T> struct S;
4775 template <class T> struct S<T*>;
4777 The second declaration is OK because `T*' uses the template
4778 parameter T, whereas
4780 template <class T> struct S<int>;
4782 is no good. Even trickier is:
4784 template <class T>
4785 struct S1
4787 template <class U>
4788 struct S2;
4789 template <class U>
4790 struct S2<T>;
4793 The S2<T> declaration is actually invalid; it is a
4794 full-specialization. Of course,
4796 template <class U>
4797 struct S2<T (*)(U)>;
4799 or some such would have been OK. */
4800 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4801 tpd.parms = XALLOCAVEC (int, ntparms);
4802 memset (tpd.parms, 0, sizeof (int) * ntparms);
4804 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4805 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4806 for (i = 0; i < nargs; ++i)
4808 tpd.current_arg = i;
4809 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4810 &mark_template_parm,
4811 &tpd,
4812 NULL,
4813 /*include_nondeduced_p=*/false);
4815 for (i = 0; i < ntparms; ++i)
4816 if (tpd.parms[i] == 0)
4818 /* One of the template parms was not used in a deduced context in the
4819 specialization. */
4820 if (!did_error_intro)
4822 error ("template parameters not deducible in "
4823 "partial specialization:");
4824 did_error_intro = true;
4827 inform (input_location, " %qD",
4828 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4831 if (did_error_intro)
4832 return error_mark_node;
4834 /* [temp.class.spec]
4836 The argument list of the specialization shall not be identical to
4837 the implicit argument list of the primary template. */
4838 tree main_args
4839 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4840 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4841 && (!flag_concepts
4842 || !strictly_subsumes (current_template_constraints (),
4843 get_constraints (maintmpl))))
4845 if (!flag_concepts)
4846 error ("partial specialization %q+D does not specialize "
4847 "any template arguments; to define the primary template, "
4848 "remove the template argument list", decl);
4849 else
4850 error ("partial specialization %q+D does not specialize any "
4851 "template arguments and is not more constrained than "
4852 "the primary template; to define the primary template, "
4853 "remove the template argument list", decl);
4854 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4857 /* A partial specialization that replaces multiple parameters of the
4858 primary template with a pack expansion is less specialized for those
4859 parameters. */
4860 if (nargs < DECL_NTPARMS (maintmpl))
4862 error ("partial specialization is not more specialized than the "
4863 "primary template because it replaces multiple parameters "
4864 "with a pack expansion");
4865 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4866 /* Avoid crash in process_partial_specialization. */
4867 return decl;
4870 /* If we aren't in a dependent class, we can actually try deduction. */
4871 else if (tpd.level == 1
4872 /* FIXME we should be able to handle a partial specialization of a
4873 partial instantiation, but currently we can't (c++/41727). */
4874 && TMPL_ARGS_DEPTH (specargs) == 1
4875 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
4877 if (permerror (input_location, "partial specialization %qD is not "
4878 "more specialized than", decl))
4879 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
4880 maintmpl);
4883 /* [temp.class.spec]
4885 A partially specialized non-type argument expression shall not
4886 involve template parameters of the partial specialization except
4887 when the argument expression is a simple identifier.
4889 The type of a template parameter corresponding to a specialized
4890 non-type argument shall not be dependent on a parameter of the
4891 specialization.
4893 Also, we verify that pack expansions only occur at the
4894 end of the argument list. */
4895 gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4896 tpd2.parms = 0;
4897 for (i = 0; i < nargs; ++i)
4899 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4900 tree arg = TREE_VEC_ELT (inner_args, i);
4901 tree packed_args = NULL_TREE;
4902 int j, len = 1;
4904 if (ARGUMENT_PACK_P (arg))
4906 /* Extract the arguments from the argument pack. We'll be
4907 iterating over these in the following loop. */
4908 packed_args = ARGUMENT_PACK_ARGS (arg);
4909 len = TREE_VEC_LENGTH (packed_args);
4912 for (j = 0; j < len; j++)
4914 if (packed_args)
4915 /* Get the Jth argument in the parameter pack. */
4916 arg = TREE_VEC_ELT (packed_args, j);
4918 if (PACK_EXPANSION_P (arg))
4920 /* Pack expansions must come at the end of the
4921 argument list. */
4922 if ((packed_args && j < len - 1)
4923 || (!packed_args && i < nargs - 1))
4925 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4926 error ("parameter pack argument %qE must be at the "
4927 "end of the template argument list", arg);
4928 else
4929 error ("parameter pack argument %qT must be at the "
4930 "end of the template argument list", arg);
4934 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4935 /* We only care about the pattern. */
4936 arg = PACK_EXPANSION_PATTERN (arg);
4938 if (/* These first two lines are the `non-type' bit. */
4939 !TYPE_P (arg)
4940 && TREE_CODE (arg) != TEMPLATE_DECL
4941 /* This next two lines are the `argument expression is not just a
4942 simple identifier' condition and also the `specialized
4943 non-type argument' bit. */
4944 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4945 && !(REFERENCE_REF_P (arg)
4946 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4948 if ((!packed_args && tpd.arg_uses_template_parms[i])
4949 || (packed_args && uses_template_parms (arg)))
4950 error ("template argument %qE involves template parameter(s)",
4951 arg);
4952 else
4954 /* Look at the corresponding template parameter,
4955 marking which template parameters its type depends
4956 upon. */
4957 tree type = TREE_TYPE (parm);
4959 if (!tpd2.parms)
4961 /* We haven't yet initialized TPD2. Do so now. */
4962 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4963 /* The number of parameters here is the number in the
4964 main template, which, as checked in the assertion
4965 above, is NARGS. */
4966 tpd2.parms = XALLOCAVEC (int, nargs);
4967 tpd2.level =
4968 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4971 /* Mark the template parameters. But this time, we're
4972 looking for the template parameters of the main
4973 template, not in the specialization. */
4974 tpd2.current_arg = i;
4975 tpd2.arg_uses_template_parms[i] = 0;
4976 memset (tpd2.parms, 0, sizeof (int) * nargs);
4977 for_each_template_parm (type,
4978 &mark_template_parm,
4979 &tpd2,
4980 NULL,
4981 /*include_nondeduced_p=*/false);
4983 if (tpd2.arg_uses_template_parms [i])
4985 /* The type depended on some template parameters.
4986 If they are fully specialized in the
4987 specialization, that's OK. */
4988 int j;
4989 int count = 0;
4990 for (j = 0; j < nargs; ++j)
4991 if (tpd2.parms[j] != 0
4992 && tpd.arg_uses_template_parms [j])
4993 ++count;
4994 if (count != 0)
4995 error_n (input_location, count,
4996 "type %qT of template argument %qE depends "
4997 "on a template parameter",
4998 "type %qT of template argument %qE depends "
4999 "on template parameters",
5000 type,
5001 arg);
5008 /* We should only get here once. */
5009 if (TREE_CODE (decl) == TYPE_DECL)
5010 gcc_assert (!COMPLETE_TYPE_P (type));
5012 // Build the template decl.
5013 tree tmpl = build_template_decl (decl, current_template_parms,
5014 DECL_MEMBER_TEMPLATE_P (maintmpl));
5015 TREE_TYPE (tmpl) = type;
5016 DECL_TEMPLATE_RESULT (tmpl) = decl;
5017 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5018 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5019 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5021 /* Give template template parms a DECL_CONTEXT of the template
5022 for which they are a parameter. */
5023 for (i = 0; i < ntparms; ++i)
5025 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5026 if (TREE_CODE (parm) == TEMPLATE_DECL)
5027 DECL_CONTEXT (parm) = tmpl;
5030 if (VAR_P (decl))
5031 /* We didn't register this in check_explicit_specialization so we could
5032 wait until the constraints were set. */
5033 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5034 else
5035 associate_classtype_constraints (type);
5037 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5038 = tree_cons (specargs, tmpl,
5039 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5040 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5042 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5043 inst = TREE_CHAIN (inst))
5045 tree instance = TREE_VALUE (inst);
5046 if (TYPE_P (instance)
5047 ? (COMPLETE_TYPE_P (instance)
5048 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5049 : DECL_TEMPLATE_INSTANTIATION (instance))
5051 tree spec = most_specialized_partial_spec (instance, tf_none);
5052 tree inst_decl = (DECL_P (instance)
5053 ? instance : TYPE_NAME (instance));
5054 if (!spec)
5055 /* OK */;
5056 else if (spec == error_mark_node)
5057 permerror (input_location,
5058 "declaration of %qD ambiguates earlier template "
5059 "instantiation for %qD", decl, inst_decl);
5060 else if (TREE_VALUE (spec) == tmpl)
5061 permerror (input_location,
5062 "partial specialization of %qD after instantiation "
5063 "of %qD", decl, inst_decl);
5067 return decl;
5070 /* PARM is a template parameter of some form; return the corresponding
5071 TEMPLATE_PARM_INDEX. */
5073 static tree
5074 get_template_parm_index (tree parm)
5076 if (TREE_CODE (parm) == PARM_DECL
5077 || TREE_CODE (parm) == CONST_DECL)
5078 parm = DECL_INITIAL (parm);
5079 else if (TREE_CODE (parm) == TYPE_DECL
5080 || TREE_CODE (parm) == TEMPLATE_DECL)
5081 parm = TREE_TYPE (parm);
5082 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5083 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5084 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5085 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5086 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5087 return parm;
5090 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5091 parameter packs used by the template parameter PARM. */
5093 static void
5094 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5096 /* A type parm can't refer to another parm. */
5097 if (TREE_CODE (parm) == TYPE_DECL)
5098 return;
5099 else if (TREE_CODE (parm) == PARM_DECL)
5101 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5102 ppd, ppd->visited);
5103 return;
5106 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5108 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5109 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5110 fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
5113 /* PARM is a template parameter pack. Return any parameter packs used in
5114 its type or the type of any of its template parameters. If there are
5115 any such packs, it will be instantiated into a fixed template parameter
5116 list by partial instantiation rather than be fully deduced. */
5118 tree
5119 fixed_parameter_pack_p (tree parm)
5121 /* This can only be true in a member template. */
5122 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5123 return NULL_TREE;
5124 /* This can only be true for a parameter pack. */
5125 if (!template_parameter_pack_p (parm))
5126 return NULL_TREE;
5127 /* A type parm can't refer to another parm. */
5128 if (TREE_CODE (parm) == TYPE_DECL)
5129 return NULL_TREE;
5131 tree parameter_packs = NULL_TREE;
5132 struct find_parameter_pack_data ppd;
5133 ppd.parameter_packs = &parameter_packs;
5134 ppd.visited = new hash_set<tree>;
5135 ppd.type_pack_expansion_p = false;
5137 fixed_parameter_pack_p_1 (parm, &ppd);
5139 delete ppd.visited;
5140 return parameter_packs;
5143 /* Check that a template declaration's use of default arguments and
5144 parameter packs is not invalid. Here, PARMS are the template
5145 parameters. IS_PRIMARY is true if DECL is the thing declared by
5146 a primary template. IS_PARTIAL is true if DECL is a partial
5147 specialization.
5149 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5150 function template declaration or a friend class template
5151 declaration. In the function case, 1 indicates a declaration, 2
5152 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5153 emitted for extraneous default arguments.
5155 Returns TRUE if there were no errors found, FALSE otherwise. */
5157 bool
5158 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5159 bool is_partial, int is_friend_decl)
5161 const char *msg;
5162 int last_level_to_check;
5163 tree parm_level;
5164 bool no_errors = true;
5166 /* [temp.param]
5168 A default template-argument shall not be specified in a
5169 function template declaration or a function template definition, nor
5170 in the template-parameter-list of the definition of a member of a
5171 class template. */
5173 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5174 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5175 /* You can't have a function template declaration in a local
5176 scope, nor you can you define a member of a class template in a
5177 local scope. */
5178 return true;
5180 if ((TREE_CODE (decl) == TYPE_DECL
5181 && TREE_TYPE (decl)
5182 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5183 || (TREE_CODE (decl) == FUNCTION_DECL
5184 && LAMBDA_FUNCTION_P (decl)))
5185 /* A lambda doesn't have an explicit declaration; don't complain
5186 about the parms of the enclosing class. */
5187 return true;
5189 if (current_class_type
5190 && !TYPE_BEING_DEFINED (current_class_type)
5191 && DECL_LANG_SPECIFIC (decl)
5192 && DECL_DECLARES_FUNCTION_P (decl)
5193 /* If this is either a friend defined in the scope of the class
5194 or a member function. */
5195 && (DECL_FUNCTION_MEMBER_P (decl)
5196 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5197 : DECL_FRIEND_CONTEXT (decl)
5198 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5199 : false)
5200 /* And, if it was a member function, it really was defined in
5201 the scope of the class. */
5202 && (!DECL_FUNCTION_MEMBER_P (decl)
5203 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5204 /* We already checked these parameters when the template was
5205 declared, so there's no need to do it again now. This function
5206 was defined in class scope, but we're processing its body now
5207 that the class is complete. */
5208 return true;
5210 /* Core issue 226 (C++0x only): the following only applies to class
5211 templates. */
5212 if (is_primary
5213 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5215 /* [temp.param]
5217 If a template-parameter has a default template-argument, all
5218 subsequent template-parameters shall have a default
5219 template-argument supplied. */
5220 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5222 tree inner_parms = TREE_VALUE (parm_level);
5223 int ntparms = TREE_VEC_LENGTH (inner_parms);
5224 int seen_def_arg_p = 0;
5225 int i;
5227 for (i = 0; i < ntparms; ++i)
5229 tree parm = TREE_VEC_ELT (inner_parms, i);
5231 if (parm == error_mark_node)
5232 continue;
5234 if (TREE_PURPOSE (parm))
5235 seen_def_arg_p = 1;
5236 else if (seen_def_arg_p
5237 && !template_parameter_pack_p (TREE_VALUE (parm)))
5239 error ("no default argument for %qD", TREE_VALUE (parm));
5240 /* For better subsequent error-recovery, we indicate that
5241 there should have been a default argument. */
5242 TREE_PURPOSE (parm) = error_mark_node;
5243 no_errors = false;
5245 else if (!is_partial
5246 && !is_friend_decl
5247 /* Don't complain about an enclosing partial
5248 specialization. */
5249 && parm_level == parms
5250 && TREE_CODE (decl) == TYPE_DECL
5251 && i < ntparms - 1
5252 && template_parameter_pack_p (TREE_VALUE (parm))
5253 /* A fixed parameter pack will be partially
5254 instantiated into a fixed length list. */
5255 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5257 /* A primary class template can only have one
5258 parameter pack, at the end of the template
5259 parameter list. */
5261 error ("parameter pack %q+D must be at the end of the"
5262 " template parameter list", TREE_VALUE (parm));
5264 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5265 = error_mark_node;
5266 no_errors = false;
5272 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5273 || is_partial
5274 || !is_primary
5275 || is_friend_decl)
5276 /* For an ordinary class template, default template arguments are
5277 allowed at the innermost level, e.g.:
5278 template <class T = int>
5279 struct S {};
5280 but, in a partial specialization, they're not allowed even
5281 there, as we have in [temp.class.spec]:
5283 The template parameter list of a specialization shall not
5284 contain default template argument values.
5286 So, for a partial specialization, or for a function template
5287 (in C++98/C++03), we look at all of them. */
5289 else
5290 /* But, for a primary class template that is not a partial
5291 specialization we look at all template parameters except the
5292 innermost ones. */
5293 parms = TREE_CHAIN (parms);
5295 /* Figure out what error message to issue. */
5296 if (is_friend_decl == 2)
5297 msg = G_("default template arguments may not be used in function template "
5298 "friend re-declaration");
5299 else if (is_friend_decl)
5300 msg = G_("default template arguments may not be used in template "
5301 "friend declarations");
5302 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5303 msg = G_("default template arguments may not be used in function templates "
5304 "without -std=c++11 or -std=gnu++11");
5305 else if (is_partial)
5306 msg = G_("default template arguments may not be used in "
5307 "partial specializations");
5308 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5309 msg = G_("default argument for template parameter for class enclosing %qD");
5310 else
5311 /* Per [temp.param]/9, "A default template-argument shall not be
5312 specified in the template-parameter-lists of the definition of
5313 a member of a class template that appears outside of the member's
5314 class.", thus if we aren't handling a member of a class template
5315 there is no need to examine the parameters. */
5316 return true;
5318 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5319 /* If we're inside a class definition, there's no need to
5320 examine the parameters to the class itself. On the one
5321 hand, they will be checked when the class is defined, and,
5322 on the other, default arguments are valid in things like:
5323 template <class T = double>
5324 struct S { template <class U> void f(U); };
5325 Here the default argument for `S' has no bearing on the
5326 declaration of `f'. */
5327 last_level_to_check = template_class_depth (current_class_type) + 1;
5328 else
5329 /* Check everything. */
5330 last_level_to_check = 0;
5332 for (parm_level = parms;
5333 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5334 parm_level = TREE_CHAIN (parm_level))
5336 tree inner_parms = TREE_VALUE (parm_level);
5337 int i;
5338 int ntparms;
5340 ntparms = TREE_VEC_LENGTH (inner_parms);
5341 for (i = 0; i < ntparms; ++i)
5343 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5344 continue;
5346 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5348 if (msg)
5350 no_errors = false;
5351 if (is_friend_decl == 2)
5352 return no_errors;
5354 error (msg, decl);
5355 msg = 0;
5358 /* Clear out the default argument so that we are not
5359 confused later. */
5360 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5364 /* At this point, if we're still interested in issuing messages,
5365 they must apply to classes surrounding the object declared. */
5366 if (msg)
5367 msg = G_("default argument for template parameter for class "
5368 "enclosing %qD");
5371 return no_errors;
5374 /* Worker for push_template_decl_real, called via
5375 for_each_template_parm. DATA is really an int, indicating the
5376 level of the parameters we are interested in. If T is a template
5377 parameter of that level, return nonzero. */
5379 static int
5380 template_parm_this_level_p (tree t, void* data)
5382 int this_level = *(int *)data;
5383 int level;
5385 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5386 level = TEMPLATE_PARM_LEVEL (t);
5387 else
5388 level = TEMPLATE_TYPE_LEVEL (t);
5389 return level == this_level;
5392 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5393 DATA is really an int, indicating the innermost outer level of parameters.
5394 If T is a template parameter of that level or further out, return
5395 nonzero. */
5397 static int
5398 template_parm_outer_level (tree t, void *data)
5400 int this_level = *(int *)data;
5401 int level;
5403 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5404 level = TEMPLATE_PARM_LEVEL (t);
5405 else
5406 level = TEMPLATE_TYPE_LEVEL (t);
5407 return level <= this_level;
5410 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5411 parameters given by current_template_args, or reuses a
5412 previously existing one, if appropriate. Returns the DECL, or an
5413 equivalent one, if it is replaced via a call to duplicate_decls.
5415 If IS_FRIEND is true, DECL is a friend declaration. */
5417 tree
5418 push_template_decl_real (tree decl, bool is_friend)
5420 tree tmpl;
5421 tree args;
5422 tree info;
5423 tree ctx;
5424 bool is_primary;
5425 bool is_partial;
5426 int new_template_p = 0;
5427 /* True if the template is a member template, in the sense of
5428 [temp.mem]. */
5429 bool member_template_p = false;
5431 if (decl == error_mark_node || !current_template_parms)
5432 return error_mark_node;
5434 /* See if this is a partial specialization. */
5435 is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5436 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5437 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5438 || (VAR_P (decl)
5439 && DECL_LANG_SPECIFIC (decl)
5440 && DECL_TEMPLATE_SPECIALIZATION (decl)
5441 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5443 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5444 is_friend = true;
5446 if (is_friend)
5447 /* For a friend, we want the context of the friend, not
5448 the type of which it is a friend. */
5449 ctx = CP_DECL_CONTEXT (decl);
5450 else if (CP_DECL_CONTEXT (decl)
5451 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5452 /* In the case of a virtual function, we want the class in which
5453 it is defined. */
5454 ctx = CP_DECL_CONTEXT (decl);
5455 else
5456 /* Otherwise, if we're currently defining some class, the DECL
5457 is assumed to be a member of the class. */
5458 ctx = current_scope ();
5460 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5461 ctx = NULL_TREE;
5463 if (!DECL_CONTEXT (decl))
5464 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5466 /* See if this is a primary template. */
5467 if (is_friend && ctx
5468 && uses_template_parms_level (ctx, processing_template_decl))
5469 /* A friend template that specifies a class context, i.e.
5470 template <typename T> friend void A<T>::f();
5471 is not primary. */
5472 is_primary = false;
5473 else if (TREE_CODE (decl) == TYPE_DECL
5474 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5475 is_primary = false;
5476 else
5477 is_primary = template_parm_scope_p ();
5479 if (is_primary)
5481 warning (OPT_Wtemplates, "template %qD declared", decl);
5483 if (DECL_CLASS_SCOPE_P (decl))
5484 member_template_p = true;
5485 if (TREE_CODE (decl) == TYPE_DECL
5486 && anon_aggrname_p (DECL_NAME (decl)))
5488 error ("template class without a name");
5489 return error_mark_node;
5491 else if (TREE_CODE (decl) == FUNCTION_DECL)
5493 if (member_template_p)
5495 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5496 error ("member template %qD may not have virt-specifiers", decl);
5498 if (DECL_DESTRUCTOR_P (decl))
5500 /* [temp.mem]
5502 A destructor shall not be a member template. */
5503 error ("destructor %qD declared as member template", decl);
5504 return error_mark_node;
5506 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5507 && (!prototype_p (TREE_TYPE (decl))
5508 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5509 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5510 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5511 == void_list_node)))
5513 /* [basic.stc.dynamic.allocation]
5515 An allocation function can be a function
5516 template. ... Template allocation functions shall
5517 have two or more parameters. */
5518 error ("invalid template declaration of %qD", decl);
5519 return error_mark_node;
5522 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5523 && CLASS_TYPE_P (TREE_TYPE (decl)))
5525 /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS. */
5526 tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5527 for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5529 tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5530 if (TREE_CODE (t) == TYPE_DECL)
5531 t = TREE_TYPE (t);
5532 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5533 TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5536 else if (TREE_CODE (decl) == TYPE_DECL
5537 && TYPE_DECL_ALIAS_P (decl))
5538 /* alias-declaration */
5539 gcc_assert (!DECL_ARTIFICIAL (decl));
5540 else if (VAR_P (decl))
5541 /* C++14 variable template. */;
5542 else
5544 error ("template declaration of %q#D", decl);
5545 return error_mark_node;
5549 /* Check to see that the rules regarding the use of default
5550 arguments are not being violated. We check args for a friend
5551 functions when we know whether it's a definition, introducing
5552 declaration or re-declaration. */
5553 if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5554 check_default_tmpl_args (decl, current_template_parms,
5555 is_primary, is_partial, is_friend);
5557 /* Ensure that there are no parameter packs in the type of this
5558 declaration that have not been expanded. */
5559 if (TREE_CODE (decl) == FUNCTION_DECL)
5561 /* Check each of the arguments individually to see if there are
5562 any bare parameter packs. */
5563 tree type = TREE_TYPE (decl);
5564 tree arg = DECL_ARGUMENTS (decl);
5565 tree argtype = TYPE_ARG_TYPES (type);
5567 while (arg && argtype)
5569 if (!DECL_PACK_P (arg)
5570 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5572 /* This is a PARM_DECL that contains unexpanded parameter
5573 packs. We have already complained about this in the
5574 check_for_bare_parameter_packs call, so just replace
5575 these types with ERROR_MARK_NODE. */
5576 TREE_TYPE (arg) = error_mark_node;
5577 TREE_VALUE (argtype) = error_mark_node;
5580 arg = DECL_CHAIN (arg);
5581 argtype = TREE_CHAIN (argtype);
5584 /* Check for bare parameter packs in the return type and the
5585 exception specifiers. */
5586 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5587 /* Errors were already issued, set return type to int
5588 as the frontend doesn't expect error_mark_node as
5589 the return type. */
5590 TREE_TYPE (type) = integer_type_node;
5591 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5592 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5594 else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5595 && TYPE_DECL_ALIAS_P (decl))
5596 ? DECL_ORIGINAL_TYPE (decl)
5597 : TREE_TYPE (decl)))
5599 TREE_TYPE (decl) = error_mark_node;
5600 return error_mark_node;
5603 if (is_partial)
5604 return process_partial_specialization (decl);
5606 args = current_template_args ();
5608 if (!ctx
5609 || TREE_CODE (ctx) == FUNCTION_DECL
5610 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5611 || (TREE_CODE (decl) == TYPE_DECL
5612 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5613 || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5615 if (DECL_LANG_SPECIFIC (decl)
5616 && DECL_TEMPLATE_INFO (decl)
5617 && DECL_TI_TEMPLATE (decl))
5618 tmpl = DECL_TI_TEMPLATE (decl);
5619 /* If DECL is a TYPE_DECL for a class-template, then there won't
5620 be DECL_LANG_SPECIFIC. The information equivalent to
5621 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
5622 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5623 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5624 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5626 /* Since a template declaration already existed for this
5627 class-type, we must be redeclaring it here. Make sure
5628 that the redeclaration is valid. */
5629 redeclare_class_template (TREE_TYPE (decl),
5630 current_template_parms,
5631 current_template_constraints ());
5632 /* We don't need to create a new TEMPLATE_DECL; just use the
5633 one we already had. */
5634 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5636 else
5638 tmpl = build_template_decl (decl, current_template_parms,
5639 member_template_p);
5640 new_template_p = 1;
5642 if (DECL_LANG_SPECIFIC (decl)
5643 && DECL_TEMPLATE_SPECIALIZATION (decl))
5645 /* A specialization of a member template of a template
5646 class. */
5647 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5648 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5649 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5653 else
5655 tree a, t, current, parms;
5656 int i;
5657 tree tinfo = get_template_info (decl);
5659 if (!tinfo)
5661 error ("template definition of non-template %q#D", decl);
5662 return error_mark_node;
5665 tmpl = TI_TEMPLATE (tinfo);
5667 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5668 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5669 && DECL_TEMPLATE_SPECIALIZATION (decl)
5670 && DECL_MEMBER_TEMPLATE_P (tmpl))
5672 tree new_tmpl;
5674 /* The declaration is a specialization of a member
5675 template, declared outside the class. Therefore, the
5676 innermost template arguments will be NULL, so we
5677 replace them with the arguments determined by the
5678 earlier call to check_explicit_specialization. */
5679 args = DECL_TI_ARGS (decl);
5681 new_tmpl
5682 = build_template_decl (decl, current_template_parms,
5683 member_template_p);
5684 DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5685 TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5686 DECL_TI_TEMPLATE (decl) = new_tmpl;
5687 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5688 DECL_TEMPLATE_INFO (new_tmpl)
5689 = build_template_info (tmpl, args);
5691 register_specialization (new_tmpl,
5692 most_general_template (tmpl),
5693 args,
5694 is_friend, 0);
5695 return decl;
5698 /* Make sure the template headers we got make sense. */
5700 parms = DECL_TEMPLATE_PARMS (tmpl);
5701 i = TMPL_PARMS_DEPTH (parms);
5702 if (TMPL_ARGS_DEPTH (args) != i)
5704 error ("expected %d levels of template parms for %q#D, got %d",
5705 i, decl, TMPL_ARGS_DEPTH (args));
5706 DECL_INTERFACE_KNOWN (decl) = 1;
5707 return error_mark_node;
5709 else
5710 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5712 a = TMPL_ARGS_LEVEL (args, i);
5713 t = INNERMOST_TEMPLATE_PARMS (parms);
5715 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5717 if (current == decl)
5718 error ("got %d template parameters for %q#D",
5719 TREE_VEC_LENGTH (a), decl);
5720 else
5721 error ("got %d template parameters for %q#T",
5722 TREE_VEC_LENGTH (a), current);
5723 error (" but %d required", TREE_VEC_LENGTH (t));
5724 /* Avoid crash in import_export_decl. */
5725 DECL_INTERFACE_KNOWN (decl) = 1;
5726 return error_mark_node;
5729 if (current == decl)
5730 current = ctx;
5731 else if (current == NULL_TREE)
5732 /* Can happen in erroneous input. */
5733 break;
5734 else
5735 current = get_containing_scope (current);
5738 /* Check that the parms are used in the appropriate qualifying scopes
5739 in the declarator. */
5740 if (!comp_template_args
5741 (TI_ARGS (tinfo),
5742 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5744 error ("template arguments to %qD do not match original "
5745 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5746 if (!uses_template_parms (TI_ARGS (tinfo)))
5747 inform (input_location, "use %<template<>%> for"
5748 " an explicit specialization");
5749 /* Avoid crash in import_export_decl. */
5750 DECL_INTERFACE_KNOWN (decl) = 1;
5751 return error_mark_node;
5755 DECL_TEMPLATE_RESULT (tmpl) = decl;
5756 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5758 /* Push template declarations for global functions and types. Note
5759 that we do not try to push a global template friend declared in a
5760 template class; such a thing may well depend on the template
5761 parameters of the class. */
5762 if (new_template_p && !ctx
5763 && !(is_friend && template_class_depth (current_class_type) > 0))
5765 tmpl = pushdecl_namespace_level (tmpl, is_friend);
5766 if (tmpl == error_mark_node)
5767 return error_mark_node;
5769 /* Hide template friend classes that haven't been declared yet. */
5770 if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5772 DECL_ANTICIPATED (tmpl) = 1;
5773 DECL_FRIEND_P (tmpl) = 1;
5777 if (is_primary)
5779 tree parms = DECL_TEMPLATE_PARMS (tmpl);
5781 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5783 /* Give template template parms a DECL_CONTEXT of the template
5784 for which they are a parameter. */
5785 parms = INNERMOST_TEMPLATE_PARMS (parms);
5786 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5788 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5789 if (TREE_CODE (parm) == TEMPLATE_DECL)
5790 DECL_CONTEXT (parm) = tmpl;
5793 if (TREE_CODE (decl) == TYPE_DECL
5794 && TYPE_DECL_ALIAS_P (decl)
5795 && complex_alias_template_p (tmpl))
5796 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5799 /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5800 back to its most general template. If TMPL is a specialization,
5801 ARGS may only have the innermost set of arguments. Add the missing
5802 argument levels if necessary. */
5803 if (DECL_TEMPLATE_INFO (tmpl))
5804 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5806 info = build_template_info (tmpl, args);
5808 if (DECL_IMPLICIT_TYPEDEF_P (decl))
5809 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5810 else
5812 if (is_primary)
5813 retrofit_lang_decl (decl);
5814 if (DECL_LANG_SPECIFIC (decl))
5815 DECL_TEMPLATE_INFO (decl) = info;
5818 if (flag_implicit_templates
5819 && !is_friend
5820 && TREE_PUBLIC (decl)
5821 && VAR_OR_FUNCTION_DECL_P (decl))
5822 /* Set DECL_COMDAT on template instantiations; if we force
5823 them to be emitted by explicit instantiation or -frepo,
5824 mark_needed will tell cgraph to do the right thing. */
5825 DECL_COMDAT (decl) = true;
5827 return DECL_TEMPLATE_RESULT (tmpl);
5830 tree
5831 push_template_decl (tree decl)
5833 return push_template_decl_real (decl, false);
5836 /* FN is an inheriting constructor that inherits from the constructor
5837 template INHERITED; turn FN into a constructor template with a matching
5838 template header. */
5840 tree
5841 add_inherited_template_parms (tree fn, tree inherited)
5843 tree inner_parms
5844 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5845 inner_parms = copy_node (inner_parms);
5846 tree parms
5847 = tree_cons (size_int (processing_template_decl + 1),
5848 inner_parms, current_template_parms);
5849 tree tmpl = build_template_decl (fn, parms, /*member*/true);
5850 tree args = template_parms_to_args (parms);
5851 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5852 TREE_TYPE (tmpl) = TREE_TYPE (fn);
5853 DECL_TEMPLATE_RESULT (tmpl) = fn;
5854 DECL_ARTIFICIAL (tmpl) = true;
5855 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5856 return tmpl;
5859 /* Called when a class template TYPE is redeclared with the indicated
5860 template PARMS, e.g.:
5862 template <class T> struct S;
5863 template <class T> struct S {}; */
5865 bool
5866 redeclare_class_template (tree type, tree parms, tree cons)
5868 tree tmpl;
5869 tree tmpl_parms;
5870 int i;
5872 if (!TYPE_TEMPLATE_INFO (type))
5874 error ("%qT is not a template type", type);
5875 return false;
5878 tmpl = TYPE_TI_TEMPLATE (type);
5879 if (!PRIMARY_TEMPLATE_P (tmpl))
5880 /* The type is nested in some template class. Nothing to worry
5881 about here; there are no new template parameters for the nested
5882 type. */
5883 return true;
5885 if (!parms)
5887 error ("template specifiers not specified in declaration of %qD",
5888 tmpl);
5889 return false;
5892 parms = INNERMOST_TEMPLATE_PARMS (parms);
5893 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5895 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5897 error_n (input_location, TREE_VEC_LENGTH (parms),
5898 "redeclared with %d template parameter",
5899 "redeclared with %d template parameters",
5900 TREE_VEC_LENGTH (parms));
5901 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5902 "previous declaration %qD used %d template parameter",
5903 "previous declaration %qD used %d template parameters",
5904 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5905 return false;
5908 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5910 tree tmpl_parm;
5911 tree parm;
5912 tree tmpl_default;
5913 tree parm_default;
5915 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5916 || TREE_VEC_ELT (parms, i) == error_mark_node)
5917 continue;
5919 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5920 if (error_operand_p (tmpl_parm))
5921 return false;
5923 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5924 tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5925 parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5927 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5928 TEMPLATE_DECL. */
5929 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5930 || (TREE_CODE (tmpl_parm) != TYPE_DECL
5931 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5932 || (TREE_CODE (tmpl_parm) != PARM_DECL
5933 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5934 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5935 || (TREE_CODE (tmpl_parm) == PARM_DECL
5936 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5937 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5939 error ("template parameter %q+#D", tmpl_parm);
5940 error ("redeclared here as %q#D", parm);
5941 return false;
5944 if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5946 /* We have in [temp.param]:
5948 A template-parameter may not be given default arguments
5949 by two different declarations in the same scope. */
5950 error_at (input_location, "redefinition of default argument for %q#D", parm);
5951 inform (DECL_SOURCE_LOCATION (tmpl_parm),
5952 "original definition appeared here");
5953 return false;
5956 if (parm_default != NULL_TREE)
5957 /* Update the previous template parameters (which are the ones
5958 that will really count) with the new default value. */
5959 TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5960 else if (tmpl_default != NULL_TREE)
5961 /* Update the new parameters, too; they'll be used as the
5962 parameters for any members. */
5963 TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5965 /* Give each template template parm in this redeclaration a
5966 DECL_CONTEXT of the template for which they are a parameter. */
5967 if (TREE_CODE (parm) == TEMPLATE_DECL)
5969 gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
5970 DECL_CONTEXT (parm) = tmpl;
5973 if (TREE_CODE (parm) == TYPE_DECL)
5974 TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
5977 // Cannot redeclare a class template with a different set of constraints.
5978 if (!equivalent_constraints (get_constraints (tmpl), cons))
5980 error_at (input_location, "redeclaration %q#D with different "
5981 "constraints", tmpl);
5982 inform (DECL_SOURCE_LOCATION (tmpl),
5983 "original declaration appeared here");
5986 return true;
5989 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
5990 to be used when the caller has already checked
5991 (processing_template_decl
5992 && !instantiation_dependent_expression_p (expr)
5993 && potential_constant_expression (expr))
5994 and cleared processing_template_decl. */
5996 tree
5997 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
5999 return tsubst_copy_and_build (expr,
6000 /*args=*/NULL_TREE,
6001 complain,
6002 /*in_decl=*/NULL_TREE,
6003 /*function_p=*/false,
6004 /*integral_constant_expression_p=*/true);
6007 /* Simplify EXPR if it is a non-dependent expression. Returns the
6008 (possibly simplified) expression. */
6010 tree
6011 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6013 if (expr == NULL_TREE)
6014 return NULL_TREE;
6016 /* If we're in a template, but EXPR isn't value dependent, simplify
6017 it. We're supposed to treat:
6019 template <typename T> void f(T[1 + 1]);
6020 template <typename T> void f(T[2]);
6022 as two declarations of the same function, for example. */
6023 if (processing_template_decl
6024 && is_nondependent_constant_expression (expr))
6026 processing_template_decl_sentinel s;
6027 expr = instantiate_non_dependent_expr_internal (expr, complain);
6029 return expr;
6032 tree
6033 instantiate_non_dependent_expr (tree expr)
6035 return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6038 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6039 an uninstantiated expression. */
6041 tree
6042 instantiate_non_dependent_or_null (tree expr)
6044 if (expr == NULL_TREE)
6045 return NULL_TREE;
6046 if (processing_template_decl)
6048 if (!is_nondependent_constant_expression (expr))
6049 expr = NULL_TREE;
6050 else
6052 processing_template_decl_sentinel s;
6053 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6056 return expr;
6059 /* True iff T is a specialization of a variable template. */
6061 bool
6062 variable_template_specialization_p (tree t)
6064 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6065 return false;
6066 tree tmpl = DECL_TI_TEMPLATE (t);
6067 return variable_template_p (tmpl);
6070 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6071 template declaration, or a TYPE_DECL for an alias declaration. */
6073 bool
6074 alias_type_or_template_p (tree t)
6076 if (t == NULL_TREE)
6077 return false;
6078 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6079 || (TYPE_P (t)
6080 && TYPE_NAME (t)
6081 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6082 || DECL_ALIAS_TEMPLATE_P (t));
6085 /* Return TRUE iff T is a specialization of an alias template. */
6087 bool
6088 alias_template_specialization_p (const_tree t)
6090 /* It's an alias template specialization if it's an alias and its
6091 TYPE_NAME is a specialization of a primary template. */
6092 if (TYPE_ALIAS_P (t))
6093 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6094 return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6096 return false;
6099 /* An alias template is complex from a SFINAE perspective if a template-id
6100 using that alias can be ill-formed when the expansion is not, as with
6101 the void_t template. We determine this by checking whether the
6102 expansion for the alias template uses all its template parameters. */
6104 struct uses_all_template_parms_data
6106 int level;
6107 bool *seen;
6110 static int
6111 uses_all_template_parms_r (tree t, void *data_)
6113 struct uses_all_template_parms_data &data
6114 = *(struct uses_all_template_parms_data*)data_;
6115 tree idx = get_template_parm_index (t);
6117 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6118 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6119 return 0;
6122 static bool
6123 complex_alias_template_p (const_tree tmpl)
6125 struct uses_all_template_parms_data data;
6126 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6127 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6128 data.level = TMPL_PARMS_DEPTH (parms);
6129 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6130 data.seen = XALLOCAVEC (bool, len);
6131 for (int i = 0; i < len; ++i)
6132 data.seen[i] = false;
6134 for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
6135 for (int i = 0; i < len; ++i)
6136 if (!data.seen[i])
6137 return true;
6138 return false;
6141 /* Return TRUE iff T is a specialization of a complex alias template with
6142 dependent template-arguments. */
6144 bool
6145 dependent_alias_template_spec_p (const_tree t)
6147 if (!alias_template_specialization_p (t))
6148 return false;
6150 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6151 if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6152 return false;
6154 tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6155 if (!any_dependent_template_arguments_p (args))
6156 return false;
6158 return true;
6161 /* Return the number of innermost template parameters in TMPL. */
6163 static int
6164 num_innermost_template_parms (tree tmpl)
6166 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6167 return TREE_VEC_LENGTH (parms);
6170 /* Return either TMPL or another template that it is equivalent to under DR
6171 1286: An alias that just changes the name of a template is equivalent to
6172 the other template. */
6174 static tree
6175 get_underlying_template (tree tmpl)
6177 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6178 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6180 /* Determine if the alias is equivalent to an underlying template. */
6181 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6182 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6183 if (!tinfo)
6184 break;
6186 tree underlying = TI_TEMPLATE (tinfo);
6187 if (!PRIMARY_TEMPLATE_P (underlying)
6188 || (num_innermost_template_parms (tmpl)
6189 != num_innermost_template_parms (underlying)))
6190 break;
6192 tree alias_args = INNERMOST_TEMPLATE_ARGS
6193 (template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
6194 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6195 break;
6197 /* Alias is equivalent. Strip it and repeat. */
6198 tmpl = underlying;
6201 return tmpl;
6204 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6205 must be a reference-to-function or a pointer-to-function type, as specified
6206 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6207 and check that the resulting function has external linkage. */
6209 static tree
6210 convert_nontype_argument_function (tree type, tree expr,
6211 tsubst_flags_t complain)
6213 tree fns = expr;
6214 tree fn, fn_no_ptr;
6215 linkage_kind linkage;
6217 fn = instantiate_type (type, fns, tf_none);
6218 if (fn == error_mark_node)
6219 return error_mark_node;
6221 if (value_dependent_expression_p (fn))
6222 goto accept;
6224 fn_no_ptr = strip_fnptr_conv (fn);
6225 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6226 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6227 if (BASELINK_P (fn_no_ptr))
6228 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6230 /* [temp.arg.nontype]/1
6232 A template-argument for a non-type, non-template template-parameter
6233 shall be one of:
6234 [...]
6235 -- the address of an object or function with external [C++11: or
6236 internal] linkage. */
6238 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6240 if (complain & tf_error)
6242 error ("%qE is not a valid template argument for type %qT",
6243 expr, type);
6244 if (TYPE_PTR_P (type))
6245 inform (input_location, "it must be the address of a function "
6246 "with external linkage");
6247 else
6248 inform (input_location, "it must be the name of a function with "
6249 "external linkage");
6251 return NULL_TREE;
6254 linkage = decl_linkage (fn_no_ptr);
6255 if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6257 if (complain & tf_error)
6259 if (cxx_dialect >= cxx11)
6260 error ("%qE is not a valid template argument for type %qT "
6261 "because %qD has no linkage",
6262 expr, type, fn_no_ptr);
6263 else
6264 error ("%qE is not a valid template argument for type %qT "
6265 "because %qD does not have external linkage",
6266 expr, type, fn_no_ptr);
6268 return NULL_TREE;
6271 accept:
6272 if (TREE_CODE (type) == REFERENCE_TYPE)
6274 if (REFERENCE_REF_P (fn))
6275 fn = TREE_OPERAND (fn, 0);
6276 else
6277 fn = build_address (fn);
6279 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6280 fn = build_nop (type, fn);
6282 return fn;
6285 /* Subroutine of convert_nontype_argument.
6286 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6287 Emit an error otherwise. */
6289 static bool
6290 check_valid_ptrmem_cst_expr (tree type, tree expr,
6291 tsubst_flags_t complain)
6293 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6294 tree orig_expr = expr;
6295 STRIP_NOPS (expr);
6296 if (null_ptr_cst_p (expr))
6297 return true;
6298 if (TREE_CODE (expr) == PTRMEM_CST
6299 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6300 PTRMEM_CST_CLASS (expr)))
6301 return true;
6302 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6303 return true;
6304 if (processing_template_decl
6305 && TREE_CODE (expr) == ADDR_EXPR
6306 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6307 return true;
6308 if (complain & tf_error)
6310 error_at (loc, "%qE is not a valid template argument for type %qT",
6311 orig_expr, type);
6312 if (TREE_CODE (expr) != PTRMEM_CST)
6313 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6314 else
6315 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6317 return false;
6320 /* Returns TRUE iff the address of OP is value-dependent.
6322 14.6.2.4 [temp.dep.temp]:
6323 A non-integral non-type template-argument is dependent if its type is
6324 dependent or it has either of the following forms
6325 qualified-id
6326 & qualified-id
6327 and contains a nested-name-specifier which specifies a class-name that
6328 names a dependent type.
6330 We generalize this to just say that the address of a member of a
6331 dependent class is value-dependent; the above doesn't cover the
6332 address of a static data member named with an unqualified-id. */
6334 static bool
6335 has_value_dependent_address (tree op)
6337 /* We could use get_inner_reference here, but there's no need;
6338 this is only relevant for template non-type arguments, which
6339 can only be expressed as &id-expression. */
6340 if (DECL_P (op))
6342 tree ctx = CP_DECL_CONTEXT (op);
6343 if (TYPE_P (ctx) && dependent_type_p (ctx))
6344 return true;
6347 return false;
6350 /* The next set of functions are used for providing helpful explanatory
6351 diagnostics for failed overload resolution. Their messages should be
6352 indented by two spaces for consistency with the messages in
6353 call.c */
6355 static int
6356 unify_success (bool /*explain_p*/)
6358 return 0;
6361 /* Other failure functions should call this one, to provide a single function
6362 for setting a breakpoint on. */
6364 static int
6365 unify_invalid (bool /*explain_p*/)
6367 return 1;
6370 static int
6371 unify_parameter_deduction_failure (bool explain_p, tree parm)
6373 if (explain_p)
6374 inform (input_location,
6375 " couldn't deduce template parameter %qD", parm);
6376 return unify_invalid (explain_p);
6379 static int
6380 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6382 if (explain_p)
6383 inform (input_location,
6384 " types %qT and %qT have incompatible cv-qualifiers",
6385 parm, arg);
6386 return unify_invalid (explain_p);
6389 static int
6390 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6392 if (explain_p)
6393 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6394 return unify_invalid (explain_p);
6397 static int
6398 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6400 if (explain_p)
6401 inform (input_location,
6402 " template parameter %qD is not a parameter pack, but "
6403 "argument %qD is",
6404 parm, arg);
6405 return unify_invalid (explain_p);
6408 static int
6409 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6411 if (explain_p)
6412 inform (input_location,
6413 " template argument %qE does not match "
6414 "pointer-to-member constant %qE",
6415 arg, parm);
6416 return unify_invalid (explain_p);
6419 static int
6420 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6422 if (explain_p)
6423 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6424 return unify_invalid (explain_p);
6427 static int
6428 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6430 if (explain_p)
6431 inform (input_location,
6432 " inconsistent parameter pack deduction with %qT and %qT",
6433 old_arg, new_arg);
6434 return unify_invalid (explain_p);
6437 static int
6438 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6440 if (explain_p)
6442 if (TYPE_P (parm))
6443 inform (input_location,
6444 " deduced conflicting types for parameter %qT (%qT and %qT)",
6445 parm, first, second);
6446 else
6447 inform (input_location,
6448 " deduced conflicting values for non-type parameter "
6449 "%qE (%qE and %qE)", parm, first, second);
6451 return unify_invalid (explain_p);
6454 static int
6455 unify_vla_arg (bool explain_p, tree arg)
6457 if (explain_p)
6458 inform (input_location,
6459 " variable-sized array type %qT is not "
6460 "a valid template argument",
6461 arg);
6462 return unify_invalid (explain_p);
6465 static int
6466 unify_method_type_error (bool explain_p, tree arg)
6468 if (explain_p)
6469 inform (input_location,
6470 " member function type %qT is not a valid template argument",
6471 arg);
6472 return unify_invalid (explain_p);
6475 static int
6476 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6478 if (explain_p)
6480 if (least_p)
6481 inform_n (input_location, wanted,
6482 " candidate expects at least %d argument, %d provided",
6483 " candidate expects at least %d arguments, %d provided",
6484 wanted, have);
6485 else
6486 inform_n (input_location, wanted,
6487 " candidate expects %d argument, %d provided",
6488 " candidate expects %d arguments, %d provided",
6489 wanted, have);
6491 return unify_invalid (explain_p);
6494 static int
6495 unify_too_many_arguments (bool explain_p, int have, int wanted)
6497 return unify_arity (explain_p, have, wanted);
6500 static int
6501 unify_too_few_arguments (bool explain_p, int have, int wanted,
6502 bool least_p = false)
6504 return unify_arity (explain_p, have, wanted, least_p);
6507 static int
6508 unify_arg_conversion (bool explain_p, tree to_type,
6509 tree from_type, tree arg)
6511 if (explain_p)
6512 inform (EXPR_LOC_OR_LOC (arg, input_location),
6513 " cannot convert %qE (type %qT) to type %qT",
6514 arg, from_type, to_type);
6515 return unify_invalid (explain_p);
6518 static int
6519 unify_no_common_base (bool explain_p, enum template_base_result r,
6520 tree parm, tree arg)
6522 if (explain_p)
6523 switch (r)
6525 case tbr_ambiguous_baseclass:
6526 inform (input_location, " %qT is an ambiguous base class of %qT",
6527 parm, arg);
6528 break;
6529 default:
6530 inform (input_location, " %qT is not derived from %qT", arg, parm);
6531 break;
6533 return unify_invalid (explain_p);
6536 static int
6537 unify_inconsistent_template_template_parameters (bool explain_p)
6539 if (explain_p)
6540 inform (input_location,
6541 " template parameters of a template template argument are "
6542 "inconsistent with other deduced template arguments");
6543 return unify_invalid (explain_p);
6546 static int
6547 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6549 if (explain_p)
6550 inform (input_location,
6551 " can't deduce a template for %qT from non-template type %qT",
6552 parm, arg);
6553 return unify_invalid (explain_p);
6556 static int
6557 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6559 if (explain_p)
6560 inform (input_location,
6561 " template argument %qE does not match %qE", arg, parm);
6562 return unify_invalid (explain_p);
6565 /* Attempt to convert the non-type template parameter EXPR to the
6566 indicated TYPE. If the conversion is successful, return the
6567 converted value. If the conversion is unsuccessful, return
6568 NULL_TREE if we issued an error message, or error_mark_node if we
6569 did not. We issue error messages for out-and-out bad template
6570 parameters, but not simply because the conversion failed, since we
6571 might be just trying to do argument deduction. Both TYPE and EXPR
6572 must be non-dependent.
6574 The conversion follows the special rules described in
6575 [temp.arg.nontype], and it is much more strict than an implicit
6576 conversion.
6578 This function is called twice for each template argument (see
6579 lookup_template_class for a more accurate description of this
6580 problem). This means that we need to handle expressions which
6581 are not valid in a C++ source, but can be created from the
6582 first call (for instance, casts to perform conversions). These
6583 hacks can go away after we fix the double coercion problem. */
6585 static tree
6586 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6588 tree expr_type;
6589 location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6590 tree orig_expr = expr;
6592 /* Detect immediately string literals as invalid non-type argument.
6593 This special-case is not needed for correctness (we would easily
6594 catch this later), but only to provide better diagnostic for this
6595 common user mistake. As suggested by DR 100, we do not mention
6596 linkage issues in the diagnostic as this is not the point. */
6597 /* FIXME we're making this OK. */
6598 if (TREE_CODE (expr) == STRING_CST)
6600 if (complain & tf_error)
6601 error ("%qE is not a valid template argument for type %qT "
6602 "because string literals can never be used in this context",
6603 expr, type);
6604 return NULL_TREE;
6607 /* Add the ADDR_EXPR now for the benefit of
6608 value_dependent_expression_p. */
6609 if (TYPE_PTROBV_P (type)
6610 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6612 expr = decay_conversion (expr, complain);
6613 if (expr == error_mark_node)
6614 return error_mark_node;
6617 /* If we are in a template, EXPR may be non-dependent, but still
6618 have a syntactic, rather than semantic, form. For example, EXPR
6619 might be a SCOPE_REF, rather than the VAR_DECL to which the
6620 SCOPE_REF refers. Preserving the qualifying scope is necessary
6621 so that access checking can be performed when the template is
6622 instantiated -- but here we need the resolved form so that we can
6623 convert the argument. */
6624 bool non_dep = false;
6625 if (TYPE_REF_OBJ_P (type)
6626 && has_value_dependent_address (expr))
6627 /* If we want the address and it's value-dependent, don't fold. */;
6628 else if (processing_template_decl
6629 && is_nondependent_constant_expression (expr))
6630 non_dep = true;
6631 if (error_operand_p (expr))
6632 return error_mark_node;
6633 expr_type = TREE_TYPE (expr);
6635 /* If the argument is non-dependent, perform any conversions in
6636 non-dependent context as well. */
6637 processing_template_decl_sentinel s (non_dep);
6638 if (non_dep)
6639 expr = instantiate_non_dependent_expr_internal (expr, complain);
6641 if (value_dependent_expression_p (expr))
6642 expr = canonicalize_expr_argument (expr, complain);
6644 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6645 to a non-type argument of "nullptr". */
6646 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
6647 expr = fold_simple (convert (type, expr));
6649 /* In C++11, integral or enumeration non-type template arguments can be
6650 arbitrary constant expressions. Pointer and pointer to
6651 member arguments can be general constant expressions that evaluate
6652 to a null value, but otherwise still need to be of a specific form. */
6653 if (cxx_dialect >= cxx11)
6655 if (TREE_CODE (expr) == PTRMEM_CST)
6656 /* A PTRMEM_CST is already constant, and a valid template
6657 argument for a parameter of pointer to member type, we just want
6658 to leave it in that form rather than lower it to a
6659 CONSTRUCTOR. */;
6660 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6661 || cxx_dialect >= cxx17)
6663 /* C++17: A template-argument for a non-type template-parameter shall
6664 be a converted constant expression (8.20) of the type of the
6665 template-parameter. */
6666 expr = build_converted_constant_expr (type, expr, complain);
6667 if (expr == error_mark_node)
6668 return error_mark_node;
6669 expr = maybe_constant_value (expr);
6670 expr = convert_from_reference (expr);
6672 else if (TYPE_PTR_OR_PTRMEM_P (type))
6674 tree folded = maybe_constant_value (expr);
6675 if (TYPE_PTR_P (type) ? integer_zerop (folded)
6676 : null_member_pointer_value_p (folded))
6677 expr = folded;
6681 if (TREE_CODE (type) == REFERENCE_TYPE)
6682 expr = mark_lvalue_use (expr);
6683 else
6684 expr = mark_rvalue_use (expr);
6686 /* HACK: Due to double coercion, we can get a
6687 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6688 which is the tree that we built on the first call (see
6689 below when coercing to reference to object or to reference to
6690 function). We just strip everything and get to the arg.
6691 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6692 for examples. */
6693 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6695 tree probe_type, probe = expr;
6696 if (REFERENCE_REF_P (probe))
6697 probe = TREE_OPERAND (probe, 0);
6698 probe_type = TREE_TYPE (probe);
6699 if (TREE_CODE (probe) == NOP_EXPR)
6701 /* ??? Maybe we could use convert_from_reference here, but we
6702 would need to relax its constraints because the NOP_EXPR
6703 could actually change the type to something more cv-qualified,
6704 and this is not folded by convert_from_reference. */
6705 tree addr = TREE_OPERAND (probe, 0);
6706 if (TREE_CODE (probe_type) == REFERENCE_TYPE
6707 && TREE_CODE (addr) == ADDR_EXPR
6708 && TYPE_PTR_P (TREE_TYPE (addr))
6709 && (same_type_ignoring_top_level_qualifiers_p
6710 (TREE_TYPE (probe_type),
6711 TREE_TYPE (TREE_TYPE (addr)))))
6713 expr = TREE_OPERAND (addr, 0);
6714 expr_type = TREE_TYPE (probe_type);
6719 /* [temp.arg.nontype]/5, bullet 1
6721 For a non-type template-parameter of integral or enumeration type,
6722 integral promotions (_conv.prom_) and integral conversions
6723 (_conv.integral_) are applied. */
6724 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6726 if (cxx_dialect < cxx11)
6728 tree t = build_converted_constant_expr (type, expr, complain);
6729 t = maybe_constant_value (t);
6730 if (t != error_mark_node)
6731 expr = t;
6734 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6735 return error_mark_node;
6737 /* Notice that there are constant expressions like '4 % 0' which
6738 do not fold into integer constants. */
6739 if (TREE_CODE (expr) != INTEGER_CST
6740 && !value_dependent_expression_p (expr))
6742 if (complain & tf_error)
6744 int errs = errorcount, warns = warningcount + werrorcount;
6745 if (!require_potential_constant_expression (expr))
6746 expr = error_mark_node;
6747 else
6748 expr = cxx_constant_value (expr);
6749 if (errorcount > errs || warningcount + werrorcount > warns)
6750 inform (loc, "in template argument for type %qT ", type);
6751 if (expr == error_mark_node)
6752 return NULL_TREE;
6753 /* else cxx_constant_value complained but gave us
6754 a real constant, so go ahead. */
6755 if (TREE_CODE (expr) != INTEGER_CST)
6757 /* Some assemble time constant expressions like
6758 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
6759 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
6760 as we can emit them into .rodata initializers of
6761 variables, yet they can't fold into an INTEGER_CST at
6762 compile time. Refuse them here. */
6763 gcc_checking_assert (reduced_constant_expression_p (expr));
6764 error_at (loc, "template argument %qE for type %qT not "
6765 "a constant integer", expr, type);
6766 return NULL_TREE;
6769 else
6770 return NULL_TREE;
6773 /* Avoid typedef problems. */
6774 if (TREE_TYPE (expr) != type)
6775 expr = fold_convert (type, expr);
6777 /* [temp.arg.nontype]/5, bullet 2
6779 For a non-type template-parameter of type pointer to object,
6780 qualification conversions (_conv.qual_) and the array-to-pointer
6781 conversion (_conv.array_) are applied. */
6782 else if (TYPE_PTROBV_P (type))
6784 tree decayed = expr;
6786 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
6787 decay_conversion or an explicit cast. If it's a problematic cast,
6788 we'll complain about it below. */
6789 if (TREE_CODE (expr) == NOP_EXPR)
6791 tree probe = expr;
6792 STRIP_NOPS (probe);
6793 if (TREE_CODE (probe) == ADDR_EXPR
6794 && TYPE_PTR_P (TREE_TYPE (probe)))
6796 expr = probe;
6797 expr_type = TREE_TYPE (expr);
6801 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
6803 A template-argument for a non-type, non-template template-parameter
6804 shall be one of: [...]
6806 -- the name of a non-type template-parameter;
6807 -- the address of an object or function with external linkage, [...]
6808 expressed as "& id-expression" where the & is optional if the name
6809 refers to a function or array, or if the corresponding
6810 template-parameter is a reference.
6812 Here, we do not care about functions, as they are invalid anyway
6813 for a parameter of type pointer-to-object. */
6815 if (value_dependent_expression_p (expr))
6816 /* Non-type template parameters are OK. */
6818 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6819 /* Null pointer values are OK in C++11. */;
6820 else if (TREE_CODE (expr) != ADDR_EXPR)
6822 if (VAR_P (expr))
6824 if (complain & tf_error)
6825 error ("%qD is not a valid template argument "
6826 "because %qD is a variable, not the address of "
6827 "a variable", orig_expr, expr);
6828 return NULL_TREE;
6830 if (POINTER_TYPE_P (expr_type))
6832 if (complain & tf_error)
6833 error ("%qE is not a valid template argument for %qT "
6834 "because it is not the address of a variable",
6835 orig_expr, type);
6836 return NULL_TREE;
6838 /* Other values, like integer constants, might be valid
6839 non-type arguments of some other type. */
6840 return error_mark_node;
6842 else
6844 tree decl = TREE_OPERAND (expr, 0);
6846 if (!VAR_P (decl))
6848 if (complain & tf_error)
6849 error ("%qE is not a valid template argument of type %qT "
6850 "because %qE is not a variable", orig_expr, type, decl);
6851 return NULL_TREE;
6853 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6855 if (complain & tf_error)
6856 error ("%qE is not a valid template argument of type %qT "
6857 "because %qD does not have external linkage",
6858 orig_expr, type, decl);
6859 return NULL_TREE;
6861 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6862 && decl_linkage (decl) == lk_none)
6864 if (complain & tf_error)
6865 error ("%qE is not a valid template argument of type %qT "
6866 "because %qD has no linkage", orig_expr, type, decl);
6867 return NULL_TREE;
6869 /* C++17: For a non-type template-parameter of reference or pointer
6870 type, the value of the constant expression shall not refer to (or
6871 for a pointer type, shall not be the address of):
6872 * a subobject (4.5),
6873 * a temporary object (15.2),
6874 * a string literal (5.13.5),
6875 * the result of a typeid expression (8.2.8), or
6876 * a predefined __func__ variable (11.4.1). */
6877 else if (DECL_ARTIFICIAL (decl))
6879 if (complain & tf_error)
6880 error ("the address of %qD is not a valid template argument",
6881 decl);
6882 return NULL_TREE;
6884 else if (!same_type_ignoring_top_level_qualifiers_p
6885 (strip_array_types (TREE_TYPE (type)),
6886 strip_array_types (TREE_TYPE (decl))))
6888 if (complain & tf_error)
6889 error ("the address of the %qT subobject of %qD is not a "
6890 "valid template argument", TREE_TYPE (type), decl);
6891 return NULL_TREE;
6893 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6895 if (complain & tf_error)
6896 error ("the address of %qD is not a valid template argument "
6897 "because it does not have static storage duration",
6898 decl);
6899 return NULL_TREE;
6903 expr = decayed;
6905 expr = perform_qualification_conversions (type, expr);
6906 if (expr == error_mark_node)
6907 return error_mark_node;
6909 /* [temp.arg.nontype]/5, bullet 3
6911 For a non-type template-parameter of type reference to object, no
6912 conversions apply. The type referred to by the reference may be more
6913 cv-qualified than the (otherwise identical) type of the
6914 template-argument. The template-parameter is bound directly to the
6915 template-argument, which must be an lvalue. */
6916 else if (TYPE_REF_OBJ_P (type))
6918 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6919 expr_type))
6920 return error_mark_node;
6922 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6924 if (complain & tf_error)
6925 error ("%qE is not a valid template argument for type %qT "
6926 "because of conflicts in cv-qualification", expr, type);
6927 return NULL_TREE;
6930 if (!lvalue_p (expr))
6932 if (complain & tf_error)
6933 error ("%qE is not a valid template argument for type %qT "
6934 "because it is not an lvalue", expr, type);
6935 return NULL_TREE;
6938 /* [temp.arg.nontype]/1
6940 A template-argument for a non-type, non-template template-parameter
6941 shall be one of: [...]
6943 -- the address of an object or function with external linkage. */
6944 if (INDIRECT_REF_P (expr)
6945 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6947 expr = TREE_OPERAND (expr, 0);
6948 if (DECL_P (expr))
6950 if (complain & tf_error)
6951 error ("%q#D is not a valid template argument for type %qT "
6952 "because a reference variable does not have a constant "
6953 "address", expr, type);
6954 return NULL_TREE;
6958 if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
6959 && value_dependent_expression_p (expr))
6960 /* OK, dependent reference. We don't want to ask whether a DECL is
6961 itself value-dependent, since what we want here is its address. */;
6962 else
6964 if (!DECL_P (expr))
6966 if (complain & tf_error)
6967 error ("%qE is not a valid template argument for type %qT "
6968 "because it is not an object with linkage",
6969 expr, type);
6970 return NULL_TREE;
6973 /* DR 1155 allows internal linkage in C++11 and up. */
6974 linkage_kind linkage = decl_linkage (expr);
6975 if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
6977 if (complain & tf_error)
6978 error ("%qE is not a valid template argument for type %qT "
6979 "because object %qD does not have linkage",
6980 expr, type, expr);
6981 return NULL_TREE;
6984 expr = build_address (expr);
6987 if (!same_type_p (type, TREE_TYPE (expr)))
6988 expr = build_nop (type, expr);
6990 /* [temp.arg.nontype]/5, bullet 4
6992 For a non-type template-parameter of type pointer to function, only
6993 the function-to-pointer conversion (_conv.func_) is applied. If the
6994 template-argument represents a set of overloaded functions (or a
6995 pointer to such), the matching function is selected from the set
6996 (_over.over_). */
6997 else if (TYPE_PTRFN_P (type))
6999 /* If the argument is a template-id, we might not have enough
7000 context information to decay the pointer. */
7001 if (!type_unknown_p (expr_type))
7003 expr = decay_conversion (expr, complain);
7004 if (expr == error_mark_node)
7005 return error_mark_node;
7008 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7009 /* Null pointer values are OK in C++11. */
7010 return perform_qualification_conversions (type, expr);
7012 expr = convert_nontype_argument_function (type, expr, complain);
7013 if (!expr || expr == error_mark_node)
7014 return expr;
7016 /* [temp.arg.nontype]/5, bullet 5
7018 For a non-type template-parameter of type reference to function, no
7019 conversions apply. If the template-argument represents a set of
7020 overloaded functions, the matching function is selected from the set
7021 (_over.over_). */
7022 else if (TYPE_REFFN_P (type))
7024 if (TREE_CODE (expr) == ADDR_EXPR)
7026 if (complain & tf_error)
7028 error ("%qE is not a valid template argument for type %qT "
7029 "because it is a pointer", expr, type);
7030 inform (input_location, "try using %qE instead",
7031 TREE_OPERAND (expr, 0));
7033 return NULL_TREE;
7036 expr = convert_nontype_argument_function (type, expr, complain);
7037 if (!expr || expr == error_mark_node)
7038 return expr;
7040 /* [temp.arg.nontype]/5, bullet 6
7042 For a non-type template-parameter of type pointer to member function,
7043 no conversions apply. If the template-argument represents a set of
7044 overloaded member functions, the matching member function is selected
7045 from the set (_over.over_). */
7046 else if (TYPE_PTRMEMFUNC_P (type))
7048 expr = instantiate_type (type, expr, tf_none);
7049 if (expr == error_mark_node)
7050 return error_mark_node;
7052 /* [temp.arg.nontype] bullet 1 says the pointer to member
7053 expression must be a pointer-to-member constant. */
7054 if (!value_dependent_expression_p (expr)
7055 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7056 return NULL_TREE;
7058 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7059 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7060 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7061 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7063 /* [temp.arg.nontype]/5, bullet 7
7065 For a non-type template-parameter of type pointer to data member,
7066 qualification conversions (_conv.qual_) are applied. */
7067 else if (TYPE_PTRDATAMEM_P (type))
7069 /* [temp.arg.nontype] bullet 1 says the pointer to member
7070 expression must be a pointer-to-member constant. */
7071 if (!value_dependent_expression_p (expr)
7072 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7073 return NULL_TREE;
7075 expr = perform_qualification_conversions (type, expr);
7076 if (expr == error_mark_node)
7077 return expr;
7079 else if (NULLPTR_TYPE_P (type))
7081 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7083 if (complain & tf_error)
7084 error ("%qE is not a valid template argument for type %qT "
7085 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7086 return NULL_TREE;
7088 return expr;
7090 /* A template non-type parameter must be one of the above. */
7091 else
7092 gcc_unreachable ();
7094 /* Sanity check: did we actually convert the argument to the
7095 right type? */
7096 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7097 (type, TREE_TYPE (expr)));
7098 return convert_from_reference (expr);
7101 /* Subroutine of coerce_template_template_parms, which returns 1 if
7102 PARM_PARM and ARG_PARM match using the rule for the template
7103 parameters of template template parameters. Both PARM and ARG are
7104 template parameters; the rest of the arguments are the same as for
7105 coerce_template_template_parms.
7107 static int
7108 coerce_template_template_parm (tree parm,
7109 tree arg,
7110 tsubst_flags_t complain,
7111 tree in_decl,
7112 tree outer_args)
7114 if (arg == NULL_TREE || error_operand_p (arg)
7115 || parm == NULL_TREE || error_operand_p (parm))
7116 return 0;
7118 if (TREE_CODE (arg) != TREE_CODE (parm))
7119 return 0;
7121 switch (TREE_CODE (parm))
7123 case TEMPLATE_DECL:
7124 /* We encounter instantiations of templates like
7125 template <template <template <class> class> class TT>
7126 class C; */
7128 tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7129 tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7131 if (!coerce_template_template_parms
7132 (parmparm, argparm, complain, in_decl, outer_args))
7133 return 0;
7135 /* Fall through. */
7137 case TYPE_DECL:
7138 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7139 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7140 /* Argument is a parameter pack but parameter is not. */
7141 return 0;
7142 break;
7144 case PARM_DECL:
7145 /* The tsubst call is used to handle cases such as
7147 template <int> class C {};
7148 template <class T, template <T> class TT> class D {};
7149 D<int, C> d;
7151 i.e. the parameter list of TT depends on earlier parameters. */
7152 if (!uses_template_parms (TREE_TYPE (arg)))
7154 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7155 if (!uses_template_parms (t)
7156 && !same_type_p (t, TREE_TYPE (arg)))
7157 return 0;
7160 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7161 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7162 /* Argument is a parameter pack but parameter is not. */
7163 return 0;
7165 break;
7167 default:
7168 gcc_unreachable ();
7171 return 1;
7174 /* Coerce template argument list ARGLIST for use with template
7175 template-parameter TEMPL. */
7177 static tree
7178 coerce_template_args_for_ttp (tree templ, tree arglist,
7179 tsubst_flags_t complain)
7181 /* Consider an example where a template template parameter declared as
7183 template <class T, class U = std::allocator<T> > class TT
7185 The template parameter level of T and U are one level larger than
7186 of TT. To proper process the default argument of U, say when an
7187 instantiation `TT<int>' is seen, we need to build the full
7188 arguments containing {int} as the innermost level. Outer levels,
7189 available when not appearing as default template argument, can be
7190 obtained from the arguments of the enclosing template.
7192 Suppose that TT is later substituted with std::vector. The above
7193 instantiation is `TT<int, std::allocator<T> >' with TT at
7194 level 1, and T at level 2, while the template arguments at level 1
7195 becomes {std::vector} and the inner level 2 is {int}. */
7197 tree outer = DECL_CONTEXT (templ);
7198 if (outer)
7200 if (DECL_TEMPLATE_SPECIALIZATION (outer))
7201 /* We want arguments for the partial specialization, not arguments for
7202 the primary template. */
7203 outer = template_parms_to_args (DECL_TEMPLATE_PARMS (outer));
7204 else
7205 outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7207 else if (current_template_parms)
7209 /* This is an argument of the current template, so we haven't set
7210 DECL_CONTEXT yet. */
7211 tree relevant_template_parms;
7213 /* Parameter levels that are greater than the level of the given
7214 template template parm are irrelevant. */
7215 relevant_template_parms = current_template_parms;
7216 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7217 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7218 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7220 outer = template_parms_to_args (relevant_template_parms);
7223 if (outer)
7224 arglist = add_to_template_args (outer, arglist);
7226 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7227 return coerce_template_parms (parmlist, arglist, templ,
7228 complain,
7229 /*require_all_args=*/true,
7230 /*use_default_args=*/true);
7233 /* A cache of template template parameters with match-all default
7234 arguments. */
7235 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7236 static void
7237 store_defaulted_ttp (tree v, tree t)
7239 if (!defaulted_ttp_cache)
7240 defaulted_ttp_cache = hash_map<tree,tree>::create_ggc (13);
7241 defaulted_ttp_cache->put (v, t);
7243 static tree
7244 lookup_defaulted_ttp (tree v)
7246 if (defaulted_ttp_cache)
7247 if (tree *p = defaulted_ttp_cache->get (v))
7248 return *p;
7249 return NULL_TREE;
7252 /* T is a bound template template-parameter. Copy its arguments into default
7253 arguments of the template template-parameter's template parameters. */
7255 static tree
7256 add_defaults_to_ttp (tree otmpl)
7258 if (tree c = lookup_defaulted_ttp (otmpl))
7259 return c;
7261 tree ntmpl = copy_node (otmpl);
7263 tree ntype = copy_node (TREE_TYPE (otmpl));
7264 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7265 TYPE_MAIN_VARIANT (ntype) = ntype;
7266 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7267 TYPE_NAME (ntype) = ntmpl;
7268 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7270 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7271 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7272 TEMPLATE_PARM_DECL (idx) = ntmpl;
7273 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7275 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7276 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7277 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7278 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7279 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7281 tree o = TREE_VEC_ELT (vec, i);
7282 if (!template_parameter_pack_p (TREE_VALUE (o)))
7284 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7285 TREE_PURPOSE (n) = any_targ_node;
7289 store_defaulted_ttp (otmpl, ntmpl);
7290 return ntmpl;
7293 /* ARG is a bound potential template template-argument, and PARGS is a list
7294 of arguments for the corresponding template template-parameter. Adjust
7295 PARGS as appropriate for application to ARG's template, and if ARG is a
7296 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7297 arguments to the template template parameter. */
7299 static tree
7300 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7302 ++processing_template_decl;
7303 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7304 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7306 /* When comparing two template template-parameters in partial ordering,
7307 rewrite the one currently being used as an argument to have default
7308 arguments for all parameters. */
7309 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7310 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7311 if (pargs != error_mark_node)
7312 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7313 TYPE_TI_ARGS (arg));
7315 else
7317 tree aparms
7318 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7319 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7320 /*require_all*/true,
7321 /*use_default*/true);
7323 --processing_template_decl;
7324 return pargs;
7327 /* Subroutine of unify for the case when PARM is a
7328 BOUND_TEMPLATE_TEMPLATE_PARM. */
7330 static int
7331 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7332 bool explain_p)
7334 tree parmvec = TYPE_TI_ARGS (parm);
7335 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7337 /* The template template parm might be variadic and the argument
7338 not, so flatten both argument lists. */
7339 parmvec = expand_template_argument_pack (parmvec);
7340 argvec = expand_template_argument_pack (argvec);
7342 if (flag_new_ttp)
7344 /* In keeping with P0522R0, adjust P's template arguments
7345 to apply to A's template; then flatten it again. */
7346 tree nparmvec = parmvec;
7347 nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7348 nparmvec = expand_template_argument_pack (nparmvec);
7350 if (unify (tparms, targs, nparmvec, argvec,
7351 UNIFY_ALLOW_NONE, explain_p))
7352 return 1;
7354 /* If the P0522 adjustment eliminated a pack expansion, deduce
7355 empty packs. */
7356 if (flag_new_ttp
7357 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7358 && unify_pack_expansion (tparms, targs, parmvec, argvec,
7359 DEDUCE_EXACT, /*sub*/true, explain_p))
7360 return 1;
7362 else
7364 /* Deduce arguments T, i from TT<T> or TT<i>.
7365 We check each element of PARMVEC and ARGVEC individually
7366 rather than the whole TREE_VEC since they can have
7367 different number of elements, which is allowed under N2555. */
7369 int len = TREE_VEC_LENGTH (parmvec);
7371 /* Check if the parameters end in a pack, making them
7372 variadic. */
7373 int parm_variadic_p = 0;
7374 if (len > 0
7375 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7376 parm_variadic_p = 1;
7378 for (int i = 0; i < len - parm_variadic_p; ++i)
7379 /* If the template argument list of P contains a pack
7380 expansion that is not the last template argument, the
7381 entire template argument list is a non-deduced
7382 context. */
7383 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7384 return unify_success (explain_p);
7386 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7387 return unify_too_few_arguments (explain_p,
7388 TREE_VEC_LENGTH (argvec), len);
7390 for (int i = 0; i < len - parm_variadic_p; ++i)
7391 if (unify (tparms, targs,
7392 TREE_VEC_ELT (parmvec, i),
7393 TREE_VEC_ELT (argvec, i),
7394 UNIFY_ALLOW_NONE, explain_p))
7395 return 1;
7397 if (parm_variadic_p
7398 && unify_pack_expansion (tparms, targs,
7399 parmvec, argvec,
7400 DEDUCE_EXACT,
7401 /*subr=*/true, explain_p))
7402 return 1;
7405 return 0;
7408 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7409 template template parameters. Both PARM_PARMS and ARG_PARMS are
7410 vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7411 or PARM_DECL.
7413 Consider the example:
7414 template <class T> class A;
7415 template<template <class U> class TT> class B;
7417 For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7418 the parameters to A, and OUTER_ARGS contains A. */
7420 static int
7421 coerce_template_template_parms (tree parm_parms,
7422 tree arg_parms,
7423 tsubst_flags_t complain,
7424 tree in_decl,
7425 tree outer_args)
7427 int nparms, nargs, i;
7428 tree parm, arg;
7429 int variadic_p = 0;
7431 gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7432 gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7434 nparms = TREE_VEC_LENGTH (parm_parms);
7435 nargs = TREE_VEC_LENGTH (arg_parms);
7437 if (flag_new_ttp)
7439 /* P0522R0: A template template-parameter P is at least as specialized as
7440 a template template-argument A if, given the following rewrite to two
7441 function templates, the function template corresponding to P is at
7442 least as specialized as the function template corresponding to A
7443 according to the partial ordering rules for function templates
7444 ([temp.func.order]). Given an invented class template X with the
7445 template parameter list of A (including default arguments):
7447 * Each of the two function templates has the same template parameters,
7448 respectively, as P or A.
7450 * Each function template has a single function parameter whose type is
7451 a specialization of X with template arguments corresponding to the
7452 template parameters from the respective function template where, for
7453 each template parameter PP in the template parameter list of the
7454 function template, a corresponding template argument AA is formed. If
7455 PP declares a parameter pack, then AA is the pack expansion
7456 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7458 If the rewrite produces an invalid type, then P is not at least as
7459 specialized as A. */
7461 /* So coerce P's args to apply to A's parms, and then deduce between A's
7462 args and the converted args. If that succeeds, A is at least as
7463 specialized as P, so they match.*/
7464 tree pargs = template_parms_level_to_args (parm_parms);
7465 ++processing_template_decl;
7466 pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7467 /*require_all*/true, /*use_default*/true);
7468 --processing_template_decl;
7469 if (pargs != error_mark_node)
7471 tree targs = make_tree_vec (nargs);
7472 tree aargs = template_parms_level_to_args (arg_parms);
7473 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7474 /*explain*/false))
7475 return 1;
7479 /* Determine whether we have a parameter pack at the end of the
7480 template template parameter's template parameter list. */
7481 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7483 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7485 if (error_operand_p (parm))
7486 return 0;
7488 switch (TREE_CODE (parm))
7490 case TEMPLATE_DECL:
7491 case TYPE_DECL:
7492 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7493 variadic_p = 1;
7494 break;
7496 case PARM_DECL:
7497 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7498 variadic_p = 1;
7499 break;
7501 default:
7502 gcc_unreachable ();
7506 if (nargs != nparms
7507 && !(variadic_p && nargs >= nparms - 1))
7508 return 0;
7510 /* Check all of the template parameters except the parameter pack at
7511 the end (if any). */
7512 for (i = 0; i < nparms - variadic_p; ++i)
7514 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7515 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7516 continue;
7518 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7519 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7521 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7522 outer_args))
7523 return 0;
7527 if (variadic_p)
7529 /* Check each of the template parameters in the template
7530 argument against the template parameter pack at the end of
7531 the template template parameter. */
7532 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7533 return 0;
7535 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7537 for (; i < nargs; ++i)
7539 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7540 continue;
7542 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7544 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7545 outer_args))
7546 return 0;
7550 return 1;
7553 /* Verifies that the deduced template arguments (in TARGS) for the
7554 template template parameters (in TPARMS) represent valid bindings,
7555 by comparing the template parameter list of each template argument
7556 to the template parameter list of its corresponding template
7557 template parameter, in accordance with DR150. This
7558 routine can only be called after all template arguments have been
7559 deduced. It will return TRUE if all of the template template
7560 parameter bindings are okay, FALSE otherwise. */
7561 bool
7562 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7564 int i, ntparms = TREE_VEC_LENGTH (tparms);
7565 bool ret = true;
7567 /* We're dealing with template parms in this process. */
7568 ++processing_template_decl;
7570 targs = INNERMOST_TEMPLATE_ARGS (targs);
7572 for (i = 0; i < ntparms; ++i)
7574 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7575 tree targ = TREE_VEC_ELT (targs, i);
7577 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7579 tree packed_args = NULL_TREE;
7580 int idx, len = 1;
7582 if (ARGUMENT_PACK_P (targ))
7584 /* Look inside the argument pack. */
7585 packed_args = ARGUMENT_PACK_ARGS (targ);
7586 len = TREE_VEC_LENGTH (packed_args);
7589 for (idx = 0; idx < len; ++idx)
7591 tree targ_parms = NULL_TREE;
7593 if (packed_args)
7594 /* Extract the next argument from the argument
7595 pack. */
7596 targ = TREE_VEC_ELT (packed_args, idx);
7598 if (PACK_EXPANSION_P (targ))
7599 /* Look at the pattern of the pack expansion. */
7600 targ = PACK_EXPANSION_PATTERN (targ);
7602 /* Extract the template parameters from the template
7603 argument. */
7604 if (TREE_CODE (targ) == TEMPLATE_DECL)
7605 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7606 else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7607 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7609 /* Verify that we can coerce the template template
7610 parameters from the template argument to the template
7611 parameter. This requires an exact match. */
7612 if (targ_parms
7613 && !coerce_template_template_parms
7614 (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7615 targ_parms,
7616 tf_none,
7617 tparm,
7618 targs))
7620 ret = false;
7621 goto out;
7627 out:
7629 --processing_template_decl;
7630 return ret;
7633 /* Since type attributes aren't mangled, we need to strip them from
7634 template type arguments. */
7636 static tree
7637 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7639 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7640 return arg;
7641 bool removed_attributes = false;
7642 tree canon = strip_typedefs (arg, &removed_attributes);
7643 if (removed_attributes
7644 && (complain & tf_warning))
7645 warning (OPT_Wignored_attributes,
7646 "ignoring attributes on template argument %qT", arg);
7647 return canon;
7650 /* And from inside dependent non-type arguments like sizeof(Type). */
7652 static tree
7653 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7655 if (!arg || arg == error_mark_node)
7656 return arg;
7657 bool removed_attributes = false;
7658 tree canon = strip_typedefs_expr (arg, &removed_attributes);
7659 if (removed_attributes
7660 && (complain & tf_warning))
7661 warning (OPT_Wignored_attributes,
7662 "ignoring attributes in template argument %qE", arg);
7663 return canon;
7666 // A template declaration can be substituted for a constrained
7667 // template template parameter only when the argument is more
7668 // constrained than the parameter.
7669 static bool
7670 is_compatible_template_arg (tree parm, tree arg)
7672 tree parm_cons = get_constraints (parm);
7674 /* For now, allow constrained template template arguments
7675 and unconstrained template template parameters. */
7676 if (parm_cons == NULL_TREE)
7677 return true;
7679 tree arg_cons = get_constraints (arg);
7681 // If the template parameter is constrained, we need to rewrite its
7682 // constraints in terms of the ARG's template parameters. This ensures
7683 // that all of the template parameter types will have the same depth.
7685 // Note that this is only valid when coerce_template_template_parm is
7686 // true for the innermost template parameters of PARM and ARG. In other
7687 // words, because coercion is successful, this conversion will be valid.
7688 if (parm_cons)
7690 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7691 parm_cons = tsubst_constraint_info (parm_cons,
7692 INNERMOST_TEMPLATE_ARGS (args),
7693 tf_none, NULL_TREE);
7694 if (parm_cons == error_mark_node)
7695 return false;
7698 return subsumes (parm_cons, arg_cons);
7701 // Convert a placeholder argument into a binding to the original
7702 // parameter. The original parameter is saved as the TREE_TYPE of
7703 // ARG.
7704 static inline tree
7705 convert_wildcard_argument (tree parm, tree arg)
7707 TREE_TYPE (arg) = parm;
7708 return arg;
7711 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7712 because one of them is dependent. But we need to represent the
7713 conversion for the benefit of cp_tree_equal. */
7715 static tree
7716 maybe_convert_nontype_argument (tree type, tree arg)
7718 /* Auto parms get no conversion. */
7719 if (type_uses_auto (type))
7720 return arg;
7721 /* We don't need or want to add this conversion now if we're going to use the
7722 argument for deduction. */
7723 if (value_dependent_expression_p (arg))
7724 return arg;
7726 type = cv_unqualified (type);
7727 tree argtype = TREE_TYPE (arg);
7728 if (same_type_p (type, argtype))
7729 return arg;
7731 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
7732 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
7733 return arg;
7736 /* Convert the indicated template ARG as necessary to match the
7737 indicated template PARM. Returns the converted ARG, or
7738 error_mark_node if the conversion was unsuccessful. Error and
7739 warning messages are issued under control of COMPLAIN. This
7740 conversion is for the Ith parameter in the parameter list. ARGS is
7741 the full set of template arguments deduced so far. */
7743 static tree
7744 convert_template_argument (tree parm,
7745 tree arg,
7746 tree args,
7747 tsubst_flags_t complain,
7748 int i,
7749 tree in_decl)
7751 tree orig_arg;
7752 tree val;
7753 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7755 if (parm == error_mark_node)
7756 return error_mark_node;
7758 /* Trivially convert placeholders. */
7759 if (TREE_CODE (arg) == WILDCARD_DECL)
7760 return convert_wildcard_argument (parm, arg);
7762 if (arg == any_targ_node)
7763 return arg;
7765 if (TREE_CODE (arg) == TREE_LIST
7766 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7768 /* The template argument was the name of some
7769 member function. That's usually
7770 invalid, but static members are OK. In any
7771 case, grab the underlying fields/functions
7772 and issue an error later if required. */
7773 orig_arg = TREE_VALUE (arg);
7774 TREE_TYPE (arg) = unknown_type_node;
7777 orig_arg = arg;
7779 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7780 requires_type = (TREE_CODE (parm) == TYPE_DECL
7781 || requires_tmpl_type);
7783 /* When determining whether an argument pack expansion is a template,
7784 look at the pattern. */
7785 if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7786 arg = PACK_EXPANSION_PATTERN (arg);
7788 /* Deal with an injected-class-name used as a template template arg. */
7789 if (requires_tmpl_type && CLASS_TYPE_P (arg))
7791 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7792 if (TREE_CODE (t) == TEMPLATE_DECL)
7794 if (cxx_dialect >= cxx11)
7795 /* OK under DR 1004. */;
7796 else if (complain & tf_warning_or_error)
7797 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7798 " used as template template argument", TYPE_NAME (arg));
7799 else if (flag_pedantic_errors)
7800 t = arg;
7802 arg = t;
7806 is_tmpl_type =
7807 ((TREE_CODE (arg) == TEMPLATE_DECL
7808 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7809 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7810 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7811 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7813 if (is_tmpl_type
7814 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7815 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7816 arg = TYPE_STUB_DECL (arg);
7818 is_type = TYPE_P (arg) || is_tmpl_type;
7820 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7821 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7823 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7825 if (complain & tf_error)
7826 error ("invalid use of destructor %qE as a type", orig_arg);
7827 return error_mark_node;
7830 permerror (input_location,
7831 "to refer to a type member of a template parameter, "
7832 "use %<typename %E%>", orig_arg);
7834 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7835 TREE_OPERAND (arg, 1),
7836 typename_type,
7837 complain);
7838 arg = orig_arg;
7839 is_type = 1;
7841 if (is_type != requires_type)
7843 if (in_decl)
7845 if (complain & tf_error)
7847 error ("type/value mismatch at argument %d in template "
7848 "parameter list for %qD",
7849 i + 1, in_decl);
7850 if (is_type)
7851 inform (input_location,
7852 " expected a constant of type %qT, got %qT",
7853 TREE_TYPE (parm),
7854 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7855 else if (requires_tmpl_type)
7856 inform (input_location,
7857 " expected a class template, got %qE", orig_arg);
7858 else
7859 inform (input_location,
7860 " expected a type, got %qE", orig_arg);
7863 return error_mark_node;
7865 if (is_tmpl_type ^ requires_tmpl_type)
7867 if (in_decl && (complain & tf_error))
7869 error ("type/value mismatch at argument %d in template "
7870 "parameter list for %qD",
7871 i + 1, in_decl);
7872 if (is_tmpl_type)
7873 inform (input_location,
7874 " expected a type, got %qT", DECL_NAME (arg));
7875 else
7876 inform (input_location,
7877 " expected a class template, got %qT", orig_arg);
7879 return error_mark_node;
7882 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7883 /* We already did the appropriate conversion when packing args. */
7884 val = orig_arg;
7885 else if (is_type)
7887 if (requires_tmpl_type)
7889 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7890 /* The number of argument required is not known yet.
7891 Just accept it for now. */
7892 val = orig_arg;
7893 else
7895 tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7896 tree argparm;
7898 /* Strip alias templates that are equivalent to another
7899 template. */
7900 arg = get_underlying_template (arg);
7901 argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7903 if (coerce_template_template_parms (parmparm, argparm,
7904 complain, in_decl,
7905 args))
7907 val = arg;
7909 /* TEMPLATE_TEMPLATE_PARM node is preferred over
7910 TEMPLATE_DECL. */
7911 if (val != error_mark_node)
7913 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
7914 val = TREE_TYPE (val);
7915 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
7916 val = make_pack_expansion (val, complain);
7919 else
7921 if (in_decl && (complain & tf_error))
7923 error ("type/value mismatch at argument %d in "
7924 "template parameter list for %qD",
7925 i + 1, in_decl);
7926 inform (input_location,
7927 " expected a template of type %qD, got %qT",
7928 parm, orig_arg);
7931 val = error_mark_node;
7934 // Check that the constraints are compatible before allowing the
7935 // substitution.
7936 if (val != error_mark_node)
7937 if (!is_compatible_template_arg (parm, arg))
7939 if (in_decl && (complain & tf_error))
7941 error ("constraint mismatch at argument %d in "
7942 "template parameter list for %qD",
7943 i + 1, in_decl);
7944 inform (input_location, " expected %qD but got %qD",
7945 parm, arg);
7947 val = error_mark_node;
7951 else
7952 val = orig_arg;
7953 /* We only form one instance of each template specialization.
7954 Therefore, if we use a non-canonical variant (i.e., a
7955 typedef), any future messages referring to the type will use
7956 the typedef, which is confusing if those future uses do not
7957 themselves also use the typedef. */
7958 if (TYPE_P (val))
7959 val = canonicalize_type_argument (val, complain);
7961 else
7963 tree t = TREE_TYPE (parm);
7965 if (tree a = type_uses_auto (t))
7967 t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
7968 if (t == error_mark_node)
7969 return error_mark_node;
7971 else
7972 t = tsubst (t, args, complain, in_decl);
7974 if (invalid_nontype_parm_type_p (t, complain))
7975 return error_mark_node;
7977 if (!type_dependent_expression_p (orig_arg)
7978 && !uses_template_parms (t))
7979 /* We used to call digest_init here. However, digest_init
7980 will report errors, which we don't want when complain
7981 is zero. More importantly, digest_init will try too
7982 hard to convert things: for example, `0' should not be
7983 converted to pointer type at this point according to
7984 the standard. Accepting this is not merely an
7985 extension, since deciding whether or not these
7986 conversions can occur is part of determining which
7987 function template to call, or whether a given explicit
7988 argument specification is valid. */
7989 val = convert_nontype_argument (t, orig_arg, complain);
7990 else
7992 val = canonicalize_expr_argument (orig_arg, complain);
7993 val = maybe_convert_nontype_argument (t, val);
7997 if (val == NULL_TREE)
7998 val = error_mark_node;
7999 else if (val == error_mark_node && (complain & tf_error))
8000 error ("could not convert template argument %qE from %qT to %qT",
8001 orig_arg, TREE_TYPE (orig_arg), t);
8003 if (INDIRECT_REF_P (val))
8005 /* Reject template arguments that are references to built-in
8006 functions with no library fallbacks. */
8007 const_tree inner = TREE_OPERAND (val, 0);
8008 const_tree innertype = TREE_TYPE (inner);
8009 if (innertype
8010 && TREE_CODE (innertype) == REFERENCE_TYPE
8011 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8012 && TREE_OPERAND_LENGTH (inner) > 0
8013 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8014 return error_mark_node;
8017 if (TREE_CODE (val) == SCOPE_REF)
8019 /* Strip typedefs from the SCOPE_REF. */
8020 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8021 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8022 complain);
8023 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8024 QUALIFIED_NAME_IS_TEMPLATE (val));
8028 return val;
8031 /* Coerces the remaining template arguments in INNER_ARGS (from
8032 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8033 Returns the coerced argument pack. PARM_IDX is the position of this
8034 parameter in the template parameter list. ARGS is the original
8035 template argument list. */
8036 static tree
8037 coerce_template_parameter_pack (tree parms,
8038 int parm_idx,
8039 tree args,
8040 tree inner_args,
8041 int arg_idx,
8042 tree new_args,
8043 int* lost,
8044 tree in_decl,
8045 tsubst_flags_t complain)
8047 tree parm = TREE_VEC_ELT (parms, parm_idx);
8048 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8049 tree packed_args;
8050 tree argument_pack;
8051 tree packed_parms = NULL_TREE;
8053 if (arg_idx > nargs)
8054 arg_idx = nargs;
8056 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8058 /* When the template parameter is a non-type template parameter pack
8059 or template template parameter pack whose type or template
8060 parameters use parameter packs, we know exactly how many arguments
8061 we are looking for. Build a vector of the instantiated decls for
8062 these template parameters in PACKED_PARMS. */
8063 /* We can't use make_pack_expansion here because it would interpret a
8064 _DECL as a use rather than a declaration. */
8065 tree decl = TREE_VALUE (parm);
8066 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8067 SET_PACK_EXPANSION_PATTERN (exp, decl);
8068 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8069 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8071 TREE_VEC_LENGTH (args)--;
8072 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8073 TREE_VEC_LENGTH (args)++;
8075 if (packed_parms == error_mark_node)
8076 return error_mark_node;
8078 /* If we're doing a partial instantiation of a member template,
8079 verify that all of the types used for the non-type
8080 template parameter pack are, in fact, valid for non-type
8081 template parameters. */
8082 if (arg_idx < nargs
8083 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8085 int j, len = TREE_VEC_LENGTH (packed_parms);
8086 for (j = 0; j < len; ++j)
8088 tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
8089 if (invalid_nontype_parm_type_p (t, complain))
8090 return error_mark_node;
8092 /* We don't know how many args we have yet, just
8093 use the unconverted ones for now. */
8094 return NULL_TREE;
8097 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8099 /* Check if we have a placeholder pack, which indicates we're
8100 in the context of a introduction list. In that case we want
8101 to match this pack to the single placeholder. */
8102 else if (arg_idx < nargs
8103 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8104 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8106 nargs = arg_idx + 1;
8107 packed_args = make_tree_vec (1);
8109 else
8110 packed_args = make_tree_vec (nargs - arg_idx);
8112 /* Convert the remaining arguments, which will be a part of the
8113 parameter pack "parm". */
8114 int first_pack_arg = arg_idx;
8115 for (; arg_idx < nargs; ++arg_idx)
8117 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8118 tree actual_parm = TREE_VALUE (parm);
8119 int pack_idx = arg_idx - first_pack_arg;
8121 if (packed_parms)
8123 /* Once we've packed as many args as we have types, stop. */
8124 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8125 break;
8126 else if (PACK_EXPANSION_P (arg))
8127 /* We don't know how many args we have yet, just
8128 use the unconverted ones for now. */
8129 return NULL_TREE;
8130 else
8131 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8134 if (arg == error_mark_node)
8136 if (complain & tf_error)
8137 error ("template argument %d is invalid", arg_idx + 1);
8139 else
8140 arg = convert_template_argument (actual_parm,
8141 arg, new_args, complain, parm_idx,
8142 in_decl);
8143 if (arg == error_mark_node)
8144 (*lost)++;
8145 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8148 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8149 && TREE_VEC_LENGTH (packed_args) > 0)
8151 if (complain & tf_error)
8152 error ("wrong number of template arguments (%d, should be %d)",
8153 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8154 return error_mark_node;
8157 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8158 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8159 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8160 else
8162 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8163 TREE_CONSTANT (argument_pack) = 1;
8166 SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8167 if (CHECKING_P)
8168 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8169 TREE_VEC_LENGTH (packed_args));
8170 return argument_pack;
8173 /* Returns the number of pack expansions in the template argument vector
8174 ARGS. */
8176 static int
8177 pack_expansion_args_count (tree args)
8179 int i;
8180 int count = 0;
8181 if (args)
8182 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8184 tree elt = TREE_VEC_ELT (args, i);
8185 if (elt && PACK_EXPANSION_P (elt))
8186 ++count;
8188 return count;
8191 /* Convert all template arguments to their appropriate types, and
8192 return a vector containing the innermost resulting template
8193 arguments. If any error occurs, return error_mark_node. Error and
8194 warning messages are issued under control of COMPLAIN.
8196 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8197 for arguments not specified in ARGS. Otherwise, if
8198 USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8199 unspecified arguments. If REQUIRE_ALL_ARGS is true, but
8200 USE_DEFAULT_ARGS is false, then all arguments must be specified in
8201 ARGS. */
8203 static tree
8204 coerce_template_parms (tree parms,
8205 tree args,
8206 tree in_decl,
8207 tsubst_flags_t complain,
8208 bool require_all_args,
8209 bool use_default_args)
8211 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8212 tree orig_inner_args;
8213 tree inner_args;
8214 tree new_args;
8215 tree new_inner_args;
8216 int saved_unevaluated_operand;
8217 int saved_inhibit_evaluation_warnings;
8219 /* When used as a boolean value, indicates whether this is a
8220 variadic template parameter list. Since it's an int, we can also
8221 subtract it from nparms to get the number of non-variadic
8222 parameters. */
8223 int variadic_p = 0;
8224 int variadic_args_p = 0;
8225 int post_variadic_parms = 0;
8227 /* Likewise for parameters with default arguments. */
8228 int default_p = 0;
8230 if (args == error_mark_node)
8231 return error_mark_node;
8233 nparms = TREE_VEC_LENGTH (parms);
8235 /* Determine if there are any parameter packs or default arguments. */
8236 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8238 tree parm = TREE_VEC_ELT (parms, parm_idx);
8239 if (variadic_p)
8240 ++post_variadic_parms;
8241 if (template_parameter_pack_p (TREE_VALUE (parm)))
8242 ++variadic_p;
8243 if (TREE_PURPOSE (parm))
8244 ++default_p;
8247 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8248 /* If there are no parameters that follow a parameter pack, we need to
8249 expand any argument packs so that we can deduce a parameter pack from
8250 some non-packed args followed by an argument pack, as in variadic85.C.
8251 If there are such parameters, we need to leave argument packs intact
8252 so the arguments are assigned properly. This can happen when dealing
8253 with a nested class inside a partial specialization of a class
8254 template, as in variadic92.C, or when deducing a template parameter pack
8255 from a sub-declarator, as in variadic114.C. */
8256 if (!post_variadic_parms)
8257 inner_args = expand_template_argument_pack (inner_args);
8259 /* Count any pack expansion args. */
8260 variadic_args_p = pack_expansion_args_count (inner_args);
8262 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8263 if ((nargs - variadic_args_p > nparms && !variadic_p)
8264 || (nargs < nparms - variadic_p
8265 && require_all_args
8266 && !variadic_args_p
8267 && (!use_default_args
8268 || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8269 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8271 if (complain & tf_error)
8273 if (variadic_p || default_p)
8275 nparms -= variadic_p + default_p;
8276 error ("wrong number of template arguments "
8277 "(%d, should be at least %d)", nargs, nparms);
8279 else
8280 error ("wrong number of template arguments "
8281 "(%d, should be %d)", nargs, nparms);
8283 if (in_decl)
8284 inform (DECL_SOURCE_LOCATION (in_decl),
8285 "provided for %qD", in_decl);
8288 return error_mark_node;
8290 /* We can't pass a pack expansion to a non-pack parameter of an alias
8291 template (DR 1430). */
8292 else if (in_decl
8293 && (DECL_ALIAS_TEMPLATE_P (in_decl)
8294 || concept_template_p (in_decl))
8295 && variadic_args_p
8296 && nargs - variadic_args_p < nparms - variadic_p)
8298 if (complain & tf_error)
8300 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8302 tree arg = TREE_VEC_ELT (inner_args, i);
8303 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8305 if (PACK_EXPANSION_P (arg)
8306 && !template_parameter_pack_p (parm))
8308 if (DECL_ALIAS_TEMPLATE_P (in_decl))
8309 error_at (location_of (arg),
8310 "pack expansion argument for non-pack parameter "
8311 "%qD of alias template %qD", parm, in_decl);
8312 else
8313 error_at (location_of (arg),
8314 "pack expansion argument for non-pack parameter "
8315 "%qD of concept %qD", parm, in_decl);
8316 inform (DECL_SOURCE_LOCATION (parm), "declared here");
8317 goto found;
8320 gcc_unreachable ();
8321 found:;
8323 return error_mark_node;
8326 /* We need to evaluate the template arguments, even though this
8327 template-id may be nested within a "sizeof". */
8328 saved_unevaluated_operand = cp_unevaluated_operand;
8329 cp_unevaluated_operand = 0;
8330 saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8331 c_inhibit_evaluation_warnings = 0;
8332 new_inner_args = make_tree_vec (nparms);
8333 new_args = add_outermost_template_args (args, new_inner_args);
8334 int pack_adjust = 0;
8335 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8337 tree arg;
8338 tree parm;
8340 /* Get the Ith template parameter. */
8341 parm = TREE_VEC_ELT (parms, parm_idx);
8343 if (parm == error_mark_node)
8345 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8346 continue;
8349 /* Calculate the next argument. */
8350 if (arg_idx < nargs)
8351 arg = TREE_VEC_ELT (inner_args, arg_idx);
8352 else
8353 arg = NULL_TREE;
8355 if (template_parameter_pack_p (TREE_VALUE (parm))
8356 && !(arg && ARGUMENT_PACK_P (arg)))
8358 /* Some arguments will be placed in the
8359 template parameter pack PARM. */
8360 arg = coerce_template_parameter_pack (parms, parm_idx, args,
8361 inner_args, arg_idx,
8362 new_args, &lost,
8363 in_decl, complain);
8365 if (arg == NULL_TREE)
8367 /* We don't know how many args we have yet, just use the
8368 unconverted (and still packed) ones for now. */
8369 new_inner_args = orig_inner_args;
8370 arg_idx = nargs;
8371 break;
8374 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8376 /* Store this argument. */
8377 if (arg == error_mark_node)
8379 lost++;
8380 /* We are done with all of the arguments. */
8381 arg_idx = nargs;
8383 else
8385 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8386 arg_idx += pack_adjust;
8389 continue;
8391 else if (arg)
8393 if (PACK_EXPANSION_P (arg))
8395 /* "If every valid specialization of a variadic template
8396 requires an empty template parameter pack, the template is
8397 ill-formed, no diagnostic required." So check that the
8398 pattern works with this parameter. */
8399 tree pattern = PACK_EXPANSION_PATTERN (arg);
8400 tree conv = convert_template_argument (TREE_VALUE (parm),
8401 pattern, new_args,
8402 complain, parm_idx,
8403 in_decl);
8404 if (conv == error_mark_node)
8406 if (complain & tf_error)
8407 inform (input_location, "so any instantiation with a "
8408 "non-empty parameter pack would be ill-formed");
8409 ++lost;
8411 else if (TYPE_P (conv) && !TYPE_P (pattern))
8412 /* Recover from missing typename. */
8413 TREE_VEC_ELT (inner_args, arg_idx)
8414 = make_pack_expansion (conv, complain);
8416 /* We don't know how many args we have yet, just
8417 use the unconverted ones for now. */
8418 new_inner_args = inner_args;
8419 arg_idx = nargs;
8420 break;
8423 else if (require_all_args)
8425 /* There must be a default arg in this case. */
8426 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8427 complain, in_decl);
8428 /* The position of the first default template argument,
8429 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8430 Record that. */
8431 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8432 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8433 arg_idx - pack_adjust);
8435 else
8436 break;
8438 if (arg == error_mark_node)
8440 if (complain & tf_error)
8441 error ("template argument %d is invalid", arg_idx + 1);
8443 else if (!arg)
8444 /* This only occurs if there was an error in the template
8445 parameter list itself (which we would already have
8446 reported) that we are trying to recover from, e.g., a class
8447 template with a parameter list such as
8448 template<typename..., typename>. */
8449 ++lost;
8450 else
8451 arg = convert_template_argument (TREE_VALUE (parm),
8452 arg, new_args, complain,
8453 parm_idx, in_decl);
8455 if (arg == error_mark_node)
8456 lost++;
8457 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8459 cp_unevaluated_operand = saved_unevaluated_operand;
8460 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8462 if (variadic_p && arg_idx < nargs)
8464 if (complain & tf_error)
8466 error ("wrong number of template arguments "
8467 "(%d, should be %d)", nargs, arg_idx);
8468 if (in_decl)
8469 error ("provided for %q+D", in_decl);
8471 return error_mark_node;
8474 if (lost)
8475 return error_mark_node;
8477 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8478 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8479 TREE_VEC_LENGTH (new_inner_args));
8481 return new_inner_args;
8484 /* Convert all template arguments to their appropriate types, and
8485 return a vector containing the innermost resulting template
8486 arguments. If any error occurs, return error_mark_node. Error and
8487 warning messages are not issued.
8489 Note that no function argument deduction is performed, and default
8490 arguments are used to fill in unspecified arguments. */
8491 tree
8492 coerce_template_parms (tree parms, tree args, tree in_decl)
8494 return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8497 /* Convert all template arguments to their appropriate type, and
8498 instantiate default arguments as needed. This returns a vector
8499 containing the innermost resulting template arguments, or
8500 error_mark_node if unsuccessful. */
8501 tree
8502 coerce_template_parms (tree parms, tree args, tree in_decl,
8503 tsubst_flags_t complain)
8505 return coerce_template_parms (parms, args, in_decl, complain, true, true);
8508 /* Like coerce_template_parms. If PARMS represents all template
8509 parameters levels, this function returns a vector of vectors
8510 representing all the resulting argument levels. Note that in this
8511 case, only the innermost arguments are coerced because the
8512 outermost ones are supposed to have been coerced already.
8514 Otherwise, if PARMS represents only (the innermost) vector of
8515 parameters, this function returns a vector containing just the
8516 innermost resulting arguments. */
8518 static tree
8519 coerce_innermost_template_parms (tree parms,
8520 tree args,
8521 tree in_decl,
8522 tsubst_flags_t complain,
8523 bool require_all_args,
8524 bool use_default_args)
8526 int parms_depth = TMPL_PARMS_DEPTH (parms);
8527 int args_depth = TMPL_ARGS_DEPTH (args);
8528 tree coerced_args;
8530 if (parms_depth > 1)
8532 coerced_args = make_tree_vec (parms_depth);
8533 tree level;
8534 int cur_depth;
8536 for (level = parms, cur_depth = parms_depth;
8537 parms_depth > 0 && level != NULL_TREE;
8538 level = TREE_CHAIN (level), --cur_depth)
8540 tree l;
8541 if (cur_depth == args_depth)
8542 l = coerce_template_parms (TREE_VALUE (level),
8543 args, in_decl, complain,
8544 require_all_args,
8545 use_default_args);
8546 else
8547 l = TMPL_ARGS_LEVEL (args, cur_depth);
8549 if (l == error_mark_node)
8550 return error_mark_node;
8552 SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8555 else
8556 coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8557 args, in_decl, complain,
8558 require_all_args,
8559 use_default_args);
8560 return coerced_args;
8563 /* Returns 1 if template args OT and NT are equivalent. */
8566 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8568 if (nt == ot)
8569 return 1;
8570 if (nt == NULL_TREE || ot == NULL_TREE)
8571 return false;
8572 if (nt == any_targ_node || ot == any_targ_node)
8573 return true;
8575 if (TREE_CODE (nt) == TREE_VEC)
8576 /* For member templates */
8577 return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8578 else if (PACK_EXPANSION_P (ot))
8579 return (PACK_EXPANSION_P (nt)
8580 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8581 PACK_EXPANSION_PATTERN (nt))
8582 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8583 PACK_EXPANSION_EXTRA_ARGS (nt)));
8584 else if (ARGUMENT_PACK_P (ot))
8586 int i, len;
8587 tree opack, npack;
8589 if (!ARGUMENT_PACK_P (nt))
8590 return 0;
8592 opack = ARGUMENT_PACK_ARGS (ot);
8593 npack = ARGUMENT_PACK_ARGS (nt);
8594 len = TREE_VEC_LENGTH (opack);
8595 if (TREE_VEC_LENGTH (npack) != len)
8596 return 0;
8597 for (i = 0; i < len; ++i)
8598 if (!template_args_equal (TREE_VEC_ELT (opack, i),
8599 TREE_VEC_ELT (npack, i)))
8600 return 0;
8601 return 1;
8603 else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8604 gcc_unreachable ();
8605 else if (TYPE_P (nt))
8607 if (!TYPE_P (ot))
8608 return false;
8609 /* Don't treat an alias template specialization with dependent
8610 arguments as equivalent to its underlying type when used as a
8611 template argument; we need them to be distinct so that we
8612 substitute into the specialization arguments at instantiation
8613 time. And aliases can't be equivalent without being ==, so
8614 we don't need to look any deeper.
8616 During partial ordering, however, we need to treat them normally so
8617 that we can order uses of the same alias with different
8618 cv-qualification (79960). */
8619 if (!partial_order
8620 && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8621 return false;
8622 else
8623 return same_type_p (ot, nt);
8625 else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8626 return 0;
8627 else
8629 /* Try to treat a template non-type argument that has been converted
8630 to the parameter type as equivalent to one that hasn't yet. */
8631 for (enum tree_code code1 = TREE_CODE (ot);
8632 CONVERT_EXPR_CODE_P (code1)
8633 || code1 == NON_LVALUE_EXPR;
8634 code1 = TREE_CODE (ot))
8635 ot = TREE_OPERAND (ot, 0);
8636 for (enum tree_code code2 = TREE_CODE (nt);
8637 CONVERT_EXPR_CODE_P (code2)
8638 || code2 == NON_LVALUE_EXPR;
8639 code2 = TREE_CODE (nt))
8640 nt = TREE_OPERAND (nt, 0);
8642 return cp_tree_equal (ot, nt);
8646 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
8647 template arguments. Returns 0 otherwise, and updates OLDARG_PTR and
8648 NEWARG_PTR with the offending arguments if they are non-NULL. */
8651 comp_template_args (tree oldargs, tree newargs,
8652 tree *oldarg_ptr, tree *newarg_ptr,
8653 bool partial_order)
8655 int i;
8657 if (oldargs == newargs)
8658 return 1;
8660 if (!oldargs || !newargs)
8661 return 0;
8663 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
8664 return 0;
8666 for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
8668 tree nt = TREE_VEC_ELT (newargs, i);
8669 tree ot = TREE_VEC_ELT (oldargs, i);
8671 if (! template_args_equal (ot, nt, partial_order))
8673 if (oldarg_ptr != NULL)
8674 *oldarg_ptr = ot;
8675 if (newarg_ptr != NULL)
8676 *newarg_ptr = nt;
8677 return 0;
8680 return 1;
8683 inline bool
8684 comp_template_args_porder (tree oargs, tree nargs)
8686 return comp_template_args (oargs, nargs, NULL, NULL, true);
8689 static void
8690 add_pending_template (tree d)
8692 tree ti = (TYPE_P (d)
8693 ? CLASSTYPE_TEMPLATE_INFO (d)
8694 : DECL_TEMPLATE_INFO (d));
8695 struct pending_template *pt;
8696 int level;
8698 if (TI_PENDING_TEMPLATE_FLAG (ti))
8699 return;
8701 /* We are called both from instantiate_decl, where we've already had a
8702 tinst_level pushed, and instantiate_template, where we haven't.
8703 Compensate. */
8704 level = !current_tinst_level || current_tinst_level->decl != d;
8706 if (level)
8707 push_tinst_level (d);
8709 pt = ggc_alloc<pending_template> ();
8710 pt->next = NULL;
8711 pt->tinst = current_tinst_level;
8712 if (last_pending_template)
8713 last_pending_template->next = pt;
8714 else
8715 pending_templates = pt;
8717 last_pending_template = pt;
8719 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
8721 if (level)
8722 pop_tinst_level ();
8726 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
8727 ARGLIST. Valid choices for FNS are given in the cp-tree.def
8728 documentation for TEMPLATE_ID_EXPR. */
8730 tree
8731 lookup_template_function (tree fns, tree arglist)
8733 tree type;
8735 if (fns == error_mark_node || arglist == error_mark_node)
8736 return error_mark_node;
8738 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
8740 if (!is_overloaded_fn (fns) && !identifier_p (fns))
8742 error ("%q#D is not a function template", fns);
8743 return error_mark_node;
8746 if (BASELINK_P (fns))
8748 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
8749 unknown_type_node,
8750 BASELINK_FUNCTIONS (fns),
8751 arglist);
8752 return fns;
8755 type = TREE_TYPE (fns);
8756 if (TREE_CODE (fns) == OVERLOAD || !type)
8757 type = unknown_type_node;
8759 return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
8762 /* Within the scope of a template class S<T>, the name S gets bound
8763 (in build_self_reference) to a TYPE_DECL for the class, not a
8764 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
8765 or one of its enclosing classes, and that type is a template,
8766 return the associated TEMPLATE_DECL. Otherwise, the original
8767 DECL is returned.
8769 Also handle the case when DECL is a TREE_LIST of ambiguous
8770 injected-class-names from different bases. */
8772 tree
8773 maybe_get_template_decl_from_type_decl (tree decl)
8775 if (decl == NULL_TREE)
8776 return decl;
8778 /* DR 176: A lookup that finds an injected-class-name (10.2
8779 [class.member.lookup]) can result in an ambiguity in certain cases
8780 (for example, if it is found in more than one base class). If all of
8781 the injected-class-names that are found refer to specializations of
8782 the same class template, and if the name is followed by a
8783 template-argument-list, the reference refers to the class template
8784 itself and not a specialization thereof, and is not ambiguous. */
8785 if (TREE_CODE (decl) == TREE_LIST)
8787 tree t, tmpl = NULL_TREE;
8788 for (t = decl; t; t = TREE_CHAIN (t))
8790 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
8791 if (!tmpl)
8792 tmpl = elt;
8793 else if (tmpl != elt)
8794 break;
8796 if (tmpl && t == NULL_TREE)
8797 return tmpl;
8798 else
8799 return decl;
8802 return (decl != NULL_TREE
8803 && DECL_SELF_REFERENCE_P (decl)
8804 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
8805 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
8808 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
8809 parameters, find the desired type.
8811 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
8813 IN_DECL, if non-NULL, is the template declaration we are trying to
8814 instantiate.
8816 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
8817 the class we are looking up.
8819 Issue error and warning messages under control of COMPLAIN.
8821 If the template class is really a local class in a template
8822 function, then the FUNCTION_CONTEXT is the function in which it is
8823 being instantiated.
8825 ??? Note that this function is currently called *twice* for each
8826 template-id: the first time from the parser, while creating the
8827 incomplete type (finish_template_type), and the second type during the
8828 real instantiation (instantiate_template_class). This is surely something
8829 that we want to avoid. It also causes some problems with argument
8830 coercion (see convert_nontype_argument for more information on this). */
8832 static tree
8833 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
8834 int entering_scope, tsubst_flags_t complain)
8836 tree templ = NULL_TREE, parmlist;
8837 tree t;
8838 spec_entry **slot;
8839 spec_entry *entry;
8840 spec_entry elt;
8841 hashval_t hash;
8843 if (identifier_p (d1))
8845 tree value = innermost_non_namespace_value (d1);
8846 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
8847 templ = value;
8848 else
8850 if (context)
8851 push_decl_namespace (context);
8852 templ = lookup_name (d1);
8853 templ = maybe_get_template_decl_from_type_decl (templ);
8854 if (context)
8855 pop_decl_namespace ();
8857 if (templ)
8858 context = DECL_CONTEXT (templ);
8860 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
8862 tree type = TREE_TYPE (d1);
8864 /* If we are declaring a constructor, say A<T>::A<T>, we will get
8865 an implicit typename for the second A. Deal with it. */
8866 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
8867 type = TREE_TYPE (type);
8869 if (CLASSTYPE_TEMPLATE_INFO (type))
8871 templ = CLASSTYPE_TI_TEMPLATE (type);
8872 d1 = DECL_NAME (templ);
8875 else if (TREE_CODE (d1) == ENUMERAL_TYPE
8876 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
8878 templ = TYPE_TI_TEMPLATE (d1);
8879 d1 = DECL_NAME (templ);
8881 else if (DECL_TYPE_TEMPLATE_P (d1))
8883 templ = d1;
8884 d1 = DECL_NAME (templ);
8885 context = DECL_CONTEXT (templ);
8887 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
8889 templ = d1;
8890 d1 = DECL_NAME (templ);
8893 /* Issue an error message if we didn't find a template. */
8894 if (! templ)
8896 if (complain & tf_error)
8897 error ("%qT is not a template", d1);
8898 return error_mark_node;
8901 if (TREE_CODE (templ) != TEMPLATE_DECL
8902 /* Make sure it's a user visible template, if it was named by
8903 the user. */
8904 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
8905 && !PRIMARY_TEMPLATE_P (templ)))
8907 if (complain & tf_error)
8909 error ("non-template type %qT used as a template", d1);
8910 if (in_decl)
8911 error ("for template declaration %q+D", in_decl);
8913 return error_mark_node;
8916 complain &= ~tf_user;
8918 /* An alias that just changes the name of a template is equivalent to the
8919 other template, so if any of the arguments are pack expansions, strip
8920 the alias to avoid problems with a pack expansion passed to a non-pack
8921 alias template parameter (DR 1430). */
8922 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
8923 templ = get_underlying_template (templ);
8925 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
8927 tree parm;
8928 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
8929 if (arglist2 == error_mark_node
8930 || (!uses_template_parms (arglist2)
8931 && check_instantiated_args (templ, arglist2, complain)))
8932 return error_mark_node;
8934 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
8935 return parm;
8937 else
8939 tree template_type = TREE_TYPE (templ);
8940 tree gen_tmpl;
8941 tree type_decl;
8942 tree found = NULL_TREE;
8943 int arg_depth;
8944 int parm_depth;
8945 int is_dependent_type;
8946 int use_partial_inst_tmpl = false;
8948 if (template_type == error_mark_node)
8949 /* An error occurred while building the template TEMPL, and a
8950 diagnostic has most certainly been emitted for that
8951 already. Let's propagate that error. */
8952 return error_mark_node;
8954 gen_tmpl = most_general_template (templ);
8955 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
8956 parm_depth = TMPL_PARMS_DEPTH (parmlist);
8957 arg_depth = TMPL_ARGS_DEPTH (arglist);
8959 if (arg_depth == 1 && parm_depth > 1)
8961 /* We've been given an incomplete set of template arguments.
8962 For example, given:
8964 template <class T> struct S1 {
8965 template <class U> struct S2 {};
8966 template <class U> struct S2<U*> {};
8969 we will be called with an ARGLIST of `U*', but the
8970 TEMPLATE will be `template <class T> template
8971 <class U> struct S1<T>::S2'. We must fill in the missing
8972 arguments. */
8973 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
8974 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
8975 arg_depth = TMPL_ARGS_DEPTH (arglist);
8978 /* Now we should have enough arguments. */
8979 gcc_assert (parm_depth == arg_depth);
8981 /* From here on, we're only interested in the most general
8982 template. */
8984 /* Calculate the BOUND_ARGS. These will be the args that are
8985 actually tsubst'd into the definition to create the
8986 instantiation. */
8987 arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
8988 complain,
8989 /*require_all_args=*/true,
8990 /*use_default_args=*/true);
8992 if (arglist == error_mark_node)
8993 /* We were unable to bind the arguments. */
8994 return error_mark_node;
8996 /* In the scope of a template class, explicit references to the
8997 template class refer to the type of the template, not any
8998 instantiation of it. For example, in:
9000 template <class T> class C { void f(C<T>); }
9002 the `C<T>' is just the same as `C'. Outside of the
9003 class, however, such a reference is an instantiation. */
9004 if (entering_scope
9005 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9006 || currently_open_class (template_type))
9008 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9010 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9011 return template_type;
9014 /* If we already have this specialization, return it. */
9015 elt.tmpl = gen_tmpl;
9016 elt.args = arglist;
9017 elt.spec = NULL_TREE;
9018 hash = spec_hasher::hash (&elt);
9019 entry = type_specializations->find_with_hash (&elt, hash);
9021 if (entry)
9022 return entry->spec;
9024 /* If the the template's constraints are not satisfied,
9025 then we cannot form a valid type.
9027 Note that the check is deferred until after the hash
9028 lookup. This prevents redundant checks on previously
9029 instantiated specializations. */
9030 if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9032 if (complain & tf_error)
9034 error ("template constraint failure");
9035 diagnose_constraints (input_location, gen_tmpl, arglist);
9037 return error_mark_node;
9040 is_dependent_type = uses_template_parms (arglist);
9042 /* If the deduced arguments are invalid, then the binding
9043 failed. */
9044 if (!is_dependent_type
9045 && check_instantiated_args (gen_tmpl,
9046 INNERMOST_TEMPLATE_ARGS (arglist),
9047 complain))
9048 return error_mark_node;
9050 if (!is_dependent_type
9051 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9052 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9053 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9055 found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9056 DECL_NAME (gen_tmpl),
9057 /*tag_scope=*/ts_global);
9058 return found;
9061 context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
9062 complain, in_decl);
9063 if (context == error_mark_node)
9064 return error_mark_node;
9066 if (!context)
9067 context = global_namespace;
9069 /* Create the type. */
9070 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9072 /* The user referred to a specialization of an alias
9073 template represented by GEN_TMPL.
9075 [temp.alias]/2 says:
9077 When a template-id refers to the specialization of an
9078 alias template, it is equivalent to the associated
9079 type obtained by substitution of its
9080 template-arguments for the template-parameters in the
9081 type-id of the alias template. */
9083 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9084 /* Note that the call above (by indirectly calling
9085 register_specialization in tsubst_decl) registers the
9086 TYPE_DECL representing the specialization of the alias
9087 template. So next time someone substitutes ARGLIST for
9088 the template parms into the alias template (GEN_TMPL),
9089 she'll get that TYPE_DECL back. */
9091 if (t == error_mark_node)
9092 return t;
9094 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9096 if (!is_dependent_type)
9098 set_current_access_from_decl (TYPE_NAME (template_type));
9099 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9100 tsubst (ENUM_UNDERLYING_TYPE (template_type),
9101 arglist, complain, in_decl),
9102 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9103 arglist, complain, in_decl),
9104 SCOPED_ENUM_P (template_type), NULL);
9106 if (t == error_mark_node)
9107 return t;
9109 else
9111 /* We don't want to call start_enum for this type, since
9112 the values for the enumeration constants may involve
9113 template parameters. And, no one should be interested
9114 in the enumeration constants for such a type. */
9115 t = cxx_make_type (ENUMERAL_TYPE);
9116 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9118 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9119 ENUM_FIXED_UNDERLYING_TYPE_P (t)
9120 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9122 else if (CLASS_TYPE_P (template_type))
9124 /* Lambda closures are regenerated in tsubst_lambda_expr, not
9125 instantiated here. */
9126 gcc_assert (!LAMBDA_TYPE_P (template_type));
9128 t = make_class_type (TREE_CODE (template_type));
9129 CLASSTYPE_DECLARED_CLASS (t)
9130 = CLASSTYPE_DECLARED_CLASS (template_type);
9131 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9133 /* A local class. Make sure the decl gets registered properly. */
9134 if (context == current_function_decl)
9135 pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
9137 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9138 /* This instantiation is another name for the primary
9139 template type. Set the TYPE_CANONICAL field
9140 appropriately. */
9141 TYPE_CANONICAL (t) = template_type;
9142 else if (any_template_arguments_need_structural_equality_p (arglist))
9143 /* Some of the template arguments require structural
9144 equality testing, so this template class requires
9145 structural equality testing. */
9146 SET_TYPE_STRUCTURAL_EQUALITY (t);
9148 else
9149 gcc_unreachable ();
9151 /* If we called start_enum or pushtag above, this information
9152 will already be set up. */
9153 if (!TYPE_NAME (t))
9155 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9157 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9158 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9159 DECL_SOURCE_LOCATION (type_decl)
9160 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9162 else
9163 type_decl = TYPE_NAME (t);
9165 if (CLASS_TYPE_P (template_type))
9167 TREE_PRIVATE (type_decl)
9168 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9169 TREE_PROTECTED (type_decl)
9170 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9171 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9173 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9174 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9178 if (OVERLOAD_TYPE_P (t)
9179 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9181 static const char *tags[] = {"abi_tag", "may_alias"};
9183 for (unsigned ix = 0; ix != 2; ix++)
9185 tree attributes
9186 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9188 if (attributes)
9189 TYPE_ATTRIBUTES (t)
9190 = tree_cons (TREE_PURPOSE (attributes),
9191 TREE_VALUE (attributes),
9192 TYPE_ATTRIBUTES (t));
9196 /* Let's consider the explicit specialization of a member
9197 of a class template specialization that is implicitly instantiated,
9198 e.g.:
9199 template<class T>
9200 struct S
9202 template<class U> struct M {}; //#0
9205 template<>
9206 template<>
9207 struct S<int>::M<char> //#1
9209 int i;
9211 [temp.expl.spec]/4 says this is valid.
9213 In this case, when we write:
9214 S<int>::M<char> m;
9216 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9217 the one of #0.
9219 When we encounter #1, we want to store the partial instantiation
9220 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9222 For all cases other than this "explicit specialization of member of a
9223 class template", we just want to store the most general template into
9224 the CLASSTYPE_TI_TEMPLATE of M.
9226 This case of "explicit specialization of member of a class template"
9227 only happens when:
9228 1/ the enclosing class is an instantiation of, and therefore not
9229 the same as, the context of the most general template, and
9230 2/ we aren't looking at the partial instantiation itself, i.e.
9231 the innermost arguments are not the same as the innermost parms of
9232 the most general template.
9234 So it's only when 1/ and 2/ happens that we want to use the partial
9235 instantiation of the member template in lieu of its most general
9236 template. */
9238 if (PRIMARY_TEMPLATE_P (gen_tmpl)
9239 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9240 /* the enclosing class must be an instantiation... */
9241 && CLASS_TYPE_P (context)
9242 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9244 TREE_VEC_LENGTH (arglist)--;
9245 ++processing_template_decl;
9246 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9247 tree partial_inst_args =
9248 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9249 arglist, complain, NULL_TREE);
9250 --processing_template_decl;
9251 TREE_VEC_LENGTH (arglist)++;
9252 if (partial_inst_args == error_mark_node)
9253 return error_mark_node;
9254 use_partial_inst_tmpl =
9255 /*...and we must not be looking at the partial instantiation
9256 itself. */
9257 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9258 partial_inst_args);
9261 if (!use_partial_inst_tmpl)
9262 /* This case is easy; there are no member templates involved. */
9263 found = gen_tmpl;
9264 else
9266 /* This is a full instantiation of a member template. Find
9267 the partial instantiation of which this is an instance. */
9269 /* Temporarily reduce by one the number of levels in the ARGLIST
9270 so as to avoid comparing the last set of arguments. */
9271 TREE_VEC_LENGTH (arglist)--;
9272 found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9273 TREE_VEC_LENGTH (arglist)++;
9274 /* FOUND is either a proper class type, or an alias
9275 template specialization. In the later case, it's a
9276 TYPE_DECL, resulting from the substituting of arguments
9277 for parameters in the TYPE_DECL of the alias template
9278 done earlier. So be careful while getting the template
9279 of FOUND. */
9280 found = (TREE_CODE (found) == TEMPLATE_DECL
9281 ? found
9282 : (TREE_CODE (found) == TYPE_DECL
9283 ? DECL_TI_TEMPLATE (found)
9284 : CLASSTYPE_TI_TEMPLATE (found)));
9287 // Build template info for the new specialization.
9288 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9290 elt.spec = t;
9291 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9292 entry = ggc_alloc<spec_entry> ();
9293 *entry = elt;
9294 *slot = entry;
9296 /* Note this use of the partial instantiation so we can check it
9297 later in maybe_process_partial_specialization. */
9298 DECL_TEMPLATE_INSTANTIATIONS (found)
9299 = tree_cons (arglist, t,
9300 DECL_TEMPLATE_INSTANTIATIONS (found));
9302 if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9303 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9304 /* Now that the type has been registered on the instantiations
9305 list, we set up the enumerators. Because the enumeration
9306 constants may involve the enumeration type itself, we make
9307 sure to register the type first, and then create the
9308 constants. That way, doing tsubst_expr for the enumeration
9309 constants won't result in recursive calls here; we'll find
9310 the instantiation and exit above. */
9311 tsubst_enum (template_type, t, arglist);
9313 if (CLASS_TYPE_P (template_type) && is_dependent_type)
9314 /* If the type makes use of template parameters, the
9315 code that generates debugging information will crash. */
9316 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9318 /* Possibly limit visibility based on template args. */
9319 TREE_PUBLIC (type_decl) = 1;
9320 determine_visibility (type_decl);
9322 inherit_targ_abi_tags (t);
9324 return t;
9328 /* Wrapper for lookup_template_class_1. */
9330 tree
9331 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9332 int entering_scope, tsubst_flags_t complain)
9334 tree ret;
9335 timevar_push (TV_TEMPLATE_INST);
9336 ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9337 entering_scope, complain);
9338 timevar_pop (TV_TEMPLATE_INST);
9339 return ret;
9342 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
9344 tree
9345 lookup_template_variable (tree templ, tree arglist)
9347 /* The type of the expression is NULL_TREE since the template-id could refer
9348 to an explicit or partial specialization. */
9349 tree type = NULL_TREE;
9350 if (flag_concepts && variable_concept_p (templ))
9351 /* Except that concepts are always bool. */
9352 type = boolean_type_node;
9353 return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
9356 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9358 tree
9359 finish_template_variable (tree var, tsubst_flags_t complain)
9361 tree templ = TREE_OPERAND (var, 0);
9362 tree arglist = TREE_OPERAND (var, 1);
9364 /* We never want to return a VAR_DECL for a variable concept, since they
9365 aren't instantiated. In a template, leave the TEMPLATE_ID_EXPR alone. */
9366 bool concept_p = flag_concepts && variable_concept_p (templ);
9367 if (concept_p && processing_template_decl)
9368 return var;
9370 tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
9371 arglist = add_outermost_template_args (tmpl_args, arglist);
9373 templ = most_general_template (templ);
9374 tree parms = DECL_TEMPLATE_PARMS (templ);
9375 arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
9376 /*req_all*/true,
9377 /*use_default*/true);
9379 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
9381 if (complain & tf_error)
9383 error ("use of invalid variable template %qE", var);
9384 diagnose_constraints (location_of (var), templ, arglist);
9386 return error_mark_node;
9389 /* If a template-id refers to a specialization of a variable
9390 concept, then the expression is true if and only if the
9391 concept's constraints are satisfied by the given template
9392 arguments.
9394 NOTE: This is an extension of Concepts Lite TS that
9395 allows constraints to be used in expressions. */
9396 if (concept_p)
9398 tree decl = DECL_TEMPLATE_RESULT (templ);
9399 return evaluate_variable_concept (decl, arglist);
9402 return instantiate_template (templ, arglist, complain);
9405 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
9406 TARGS template args, and instantiate it if it's not dependent. */
9408 tree
9409 lookup_and_finish_template_variable (tree templ, tree targs,
9410 tsubst_flags_t complain)
9412 templ = lookup_template_variable (templ, targs);
9413 if (!any_dependent_template_arguments_p (targs))
9415 templ = finish_template_variable (templ, complain);
9416 mark_used (templ);
9419 return convert_from_reference (templ);
9423 struct pair_fn_data
9425 tree_fn_t fn;
9426 tree_fn_t any_fn;
9427 void *data;
9428 /* True when we should also visit template parameters that occur in
9429 non-deduced contexts. */
9430 bool include_nondeduced_p;
9431 hash_set<tree> *visited;
9434 /* Called from for_each_template_parm via walk_tree. */
9436 static tree
9437 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
9439 tree t = *tp;
9440 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
9441 tree_fn_t fn = pfd->fn;
9442 void *data = pfd->data;
9443 tree result = NULL_TREE;
9445 #define WALK_SUBTREE(NODE) \
9446 do \
9448 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
9449 pfd->include_nondeduced_p, \
9450 pfd->any_fn); \
9451 if (result) goto out; \
9453 while (0)
9455 if (pfd->any_fn && (*pfd->any_fn)(t, data))
9456 return t;
9458 if (TYPE_P (t)
9459 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
9460 WALK_SUBTREE (TYPE_CONTEXT (t));
9462 switch (TREE_CODE (t))
9464 case RECORD_TYPE:
9465 if (TYPE_PTRMEMFUNC_P (t))
9466 break;
9467 /* Fall through. */
9469 case UNION_TYPE:
9470 case ENUMERAL_TYPE:
9471 if (!TYPE_TEMPLATE_INFO (t))
9472 *walk_subtrees = 0;
9473 else
9474 WALK_SUBTREE (TYPE_TI_ARGS (t));
9475 break;
9477 case INTEGER_TYPE:
9478 WALK_SUBTREE (TYPE_MIN_VALUE (t));
9479 WALK_SUBTREE (TYPE_MAX_VALUE (t));
9480 break;
9482 case METHOD_TYPE:
9483 /* Since we're not going to walk subtrees, we have to do this
9484 explicitly here. */
9485 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
9486 /* Fall through. */
9488 case FUNCTION_TYPE:
9489 /* Check the return type. */
9490 WALK_SUBTREE (TREE_TYPE (t));
9492 /* Check the parameter types. Since default arguments are not
9493 instantiated until they are needed, the TYPE_ARG_TYPES may
9494 contain expressions that involve template parameters. But,
9495 no-one should be looking at them yet. And, once they're
9496 instantiated, they don't contain template parameters, so
9497 there's no point in looking at them then, either. */
9499 tree parm;
9501 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
9502 WALK_SUBTREE (TREE_VALUE (parm));
9504 /* Since we've already handled the TYPE_ARG_TYPES, we don't
9505 want walk_tree walking into them itself. */
9506 *walk_subtrees = 0;
9509 if (flag_noexcept_type)
9511 tree spec = TYPE_RAISES_EXCEPTIONS (t);
9512 if (spec)
9513 WALK_SUBTREE (TREE_PURPOSE (spec));
9515 break;
9517 case TYPEOF_TYPE:
9518 case UNDERLYING_TYPE:
9519 if (pfd->include_nondeduced_p
9520 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
9521 pfd->visited,
9522 pfd->include_nondeduced_p,
9523 pfd->any_fn))
9524 return error_mark_node;
9525 break;
9527 case FUNCTION_DECL:
9528 case VAR_DECL:
9529 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9530 WALK_SUBTREE (DECL_TI_ARGS (t));
9531 /* Fall through. */
9533 case PARM_DECL:
9534 case CONST_DECL:
9535 if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
9536 WALK_SUBTREE (DECL_INITIAL (t));
9537 if (DECL_CONTEXT (t)
9538 && pfd->include_nondeduced_p)
9539 WALK_SUBTREE (DECL_CONTEXT (t));
9540 break;
9542 case BOUND_TEMPLATE_TEMPLATE_PARM:
9543 /* Record template parameters such as `T' inside `TT<T>'. */
9544 WALK_SUBTREE (TYPE_TI_ARGS (t));
9545 /* Fall through. */
9547 case TEMPLATE_TEMPLATE_PARM:
9548 case TEMPLATE_TYPE_PARM:
9549 case TEMPLATE_PARM_INDEX:
9550 if (fn && (*fn)(t, data))
9551 return t;
9552 else if (!fn)
9553 return t;
9554 break;
9556 case TEMPLATE_DECL:
9557 /* A template template parameter is encountered. */
9558 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9559 WALK_SUBTREE (TREE_TYPE (t));
9561 /* Already substituted template template parameter */
9562 *walk_subtrees = 0;
9563 break;
9565 case TYPENAME_TYPE:
9566 /* A template-id in a TYPENAME_TYPE might be a deduced context after
9567 partial instantiation. */
9568 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
9569 break;
9571 case CONSTRUCTOR:
9572 if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
9573 && pfd->include_nondeduced_p)
9574 WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
9575 break;
9577 case INDIRECT_REF:
9578 case COMPONENT_REF:
9579 /* If there's no type, then this thing must be some expression
9580 involving template parameters. */
9581 if (!fn && !TREE_TYPE (t))
9582 return error_mark_node;
9583 break;
9585 case MODOP_EXPR:
9586 case CAST_EXPR:
9587 case IMPLICIT_CONV_EXPR:
9588 case REINTERPRET_CAST_EXPR:
9589 case CONST_CAST_EXPR:
9590 case STATIC_CAST_EXPR:
9591 case DYNAMIC_CAST_EXPR:
9592 case ARROW_EXPR:
9593 case DOTSTAR_EXPR:
9594 case TYPEID_EXPR:
9595 case PSEUDO_DTOR_EXPR:
9596 if (!fn)
9597 return error_mark_node;
9598 break;
9600 default:
9601 break;
9604 #undef WALK_SUBTREE
9606 /* We didn't find any template parameters we liked. */
9607 out:
9608 return result;
9611 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
9612 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
9613 call FN with the parameter and the DATA.
9614 If FN returns nonzero, the iteration is terminated, and
9615 for_each_template_parm returns 1. Otherwise, the iteration
9616 continues. If FN never returns a nonzero value, the value
9617 returned by for_each_template_parm is 0. If FN is NULL, it is
9618 considered to be the function which always returns 1.
9620 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
9621 parameters that occur in non-deduced contexts. When false, only
9622 visits those template parameters that can be deduced. */
9624 static tree
9625 for_each_template_parm (tree t, tree_fn_t fn, void* data,
9626 hash_set<tree> *visited,
9627 bool include_nondeduced_p,
9628 tree_fn_t any_fn)
9630 struct pair_fn_data pfd;
9631 tree result;
9633 /* Set up. */
9634 pfd.fn = fn;
9635 pfd.any_fn = any_fn;
9636 pfd.data = data;
9637 pfd.include_nondeduced_p = include_nondeduced_p;
9639 /* Walk the tree. (Conceptually, we would like to walk without
9640 duplicates, but for_each_template_parm_r recursively calls
9641 for_each_template_parm, so we would need to reorganize a fair
9642 bit to use walk_tree_without_duplicates, so we keep our own
9643 visited list.) */
9644 if (visited)
9645 pfd.visited = visited;
9646 else
9647 pfd.visited = new hash_set<tree>;
9648 result = cp_walk_tree (&t,
9649 for_each_template_parm_r,
9650 &pfd,
9651 pfd.visited);
9653 /* Clean up. */
9654 if (!visited)
9656 delete pfd.visited;
9657 pfd.visited = 0;
9660 return result;
9663 /* Returns true if T depends on any template parameter. */
9666 uses_template_parms (tree t)
9668 if (t == NULL_TREE)
9669 return false;
9671 bool dependent_p;
9672 int saved_processing_template_decl;
9674 saved_processing_template_decl = processing_template_decl;
9675 if (!saved_processing_template_decl)
9676 processing_template_decl = 1;
9677 if (TYPE_P (t))
9678 dependent_p = dependent_type_p (t);
9679 else if (TREE_CODE (t) == TREE_VEC)
9680 dependent_p = any_dependent_template_arguments_p (t);
9681 else if (TREE_CODE (t) == TREE_LIST)
9682 dependent_p = (uses_template_parms (TREE_VALUE (t))
9683 || uses_template_parms (TREE_CHAIN (t)));
9684 else if (TREE_CODE (t) == TYPE_DECL)
9685 dependent_p = dependent_type_p (TREE_TYPE (t));
9686 else if (DECL_P (t)
9687 || EXPR_P (t)
9688 || TREE_CODE (t) == TEMPLATE_PARM_INDEX
9689 || TREE_CODE (t) == OVERLOAD
9690 || BASELINK_P (t)
9691 || identifier_p (t)
9692 || TREE_CODE (t) == TRAIT_EXPR
9693 || TREE_CODE (t) == CONSTRUCTOR
9694 || CONSTANT_CLASS_P (t))
9695 dependent_p = (type_dependent_expression_p (t)
9696 || value_dependent_expression_p (t));
9697 else
9699 gcc_assert (t == error_mark_node);
9700 dependent_p = false;
9703 processing_template_decl = saved_processing_template_decl;
9705 return dependent_p;
9708 /* Returns true iff current_function_decl is an incompletely instantiated
9709 template. Useful instead of processing_template_decl because the latter
9710 is set to 0 during instantiate_non_dependent_expr. */
9712 bool
9713 in_template_function (void)
9715 tree fn = current_function_decl;
9716 bool ret;
9717 ++processing_template_decl;
9718 ret = (fn && DECL_LANG_SPECIFIC (fn)
9719 && DECL_TEMPLATE_INFO (fn)
9720 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
9721 --processing_template_decl;
9722 return ret;
9725 /* Returns true if T depends on any template parameter with level LEVEL. */
9727 bool
9728 uses_template_parms_level (tree t, int level)
9730 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
9731 /*include_nondeduced_p=*/true);
9734 /* Returns true if the signature of DECL depends on any template parameter from
9735 its enclosing class. */
9737 bool
9738 uses_outer_template_parms (tree decl)
9740 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
9741 if (depth == 0)
9742 return false;
9743 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
9744 &depth, NULL, /*include_nondeduced_p=*/true))
9745 return true;
9746 if (PRIMARY_TEMPLATE_P (decl)
9747 && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
9748 (DECL_TEMPLATE_PARMS (decl)),
9749 template_parm_outer_level,
9750 &depth, NULL, /*include_nondeduced_p=*/true))
9751 return true;
9752 tree ci = get_constraints (decl);
9753 if (ci)
9754 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
9755 if (ci && for_each_template_parm (ci, template_parm_outer_level,
9756 &depth, NULL, /*nondeduced*/true))
9757 return true;
9758 return false;
9761 /* Returns TRUE iff INST is an instantiation we don't need to do in an
9762 ill-formed translation unit, i.e. a variable or function that isn't
9763 usable in a constant expression. */
9765 static inline bool
9766 neglectable_inst_p (tree d)
9768 return (DECL_P (d)
9769 && !undeduced_auto_decl (d)
9770 && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
9771 : decl_maybe_constant_var_p (d)));
9774 /* Returns TRUE iff we should refuse to instantiate DECL because it's
9775 neglectable and instantiated from within an erroneous instantiation. */
9777 static bool
9778 limit_bad_template_recursion (tree decl)
9780 struct tinst_level *lev = current_tinst_level;
9781 int errs = errorcount + sorrycount;
9782 if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
9783 return false;
9785 for (; lev; lev = lev->next)
9786 if (neglectable_inst_p (lev->decl))
9787 break;
9789 return (lev && errs > lev->errors);
9792 static int tinst_depth;
9793 extern int max_tinst_depth;
9794 int depth_reached;
9796 static GTY(()) struct tinst_level *last_error_tinst_level;
9798 /* We're starting to instantiate D; record the template instantiation context
9799 for diagnostics and to restore it later. */
9801 bool
9802 push_tinst_level (tree d)
9804 return push_tinst_level_loc (d, input_location);
9807 /* We're starting to instantiate D; record the template instantiation context
9808 at LOC for diagnostics and to restore it later. */
9810 bool
9811 push_tinst_level_loc (tree d, location_t loc)
9813 struct tinst_level *new_level;
9815 if (tinst_depth >= max_tinst_depth)
9817 /* Tell error.c not to try to instantiate any templates. */
9818 at_eof = 2;
9819 fatal_error (input_location,
9820 "template instantiation depth exceeds maximum of %d"
9821 " (use -ftemplate-depth= to increase the maximum)",
9822 max_tinst_depth);
9823 return false;
9826 /* If the current instantiation caused problems, don't let it instantiate
9827 anything else. Do allow deduction substitution and decls usable in
9828 constant expressions. */
9829 if (limit_bad_template_recursion (d))
9830 return false;
9832 /* When not -quiet, dump template instantiations other than functions, since
9833 announce_function will take care of those. */
9834 if (!quiet_flag
9835 && TREE_CODE (d) != TREE_LIST
9836 && TREE_CODE (d) != FUNCTION_DECL)
9837 fprintf (stderr, " %s", decl_as_string (d, TFF_DECL_SPECIFIERS));
9839 new_level = ggc_alloc<tinst_level> ();
9840 new_level->decl = d;
9841 new_level->locus = loc;
9842 new_level->errors = errorcount+sorrycount;
9843 new_level->in_system_header_p = in_system_header_at (input_location);
9844 new_level->next = current_tinst_level;
9845 current_tinst_level = new_level;
9847 ++tinst_depth;
9848 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
9849 depth_reached = tinst_depth;
9851 return true;
9854 /* We're done instantiating this template; return to the instantiation
9855 context. */
9857 void
9858 pop_tinst_level (void)
9860 /* Restore the filename and line number stashed away when we started
9861 this instantiation. */
9862 input_location = current_tinst_level->locus;
9863 current_tinst_level = current_tinst_level->next;
9864 --tinst_depth;
9867 /* We're instantiating a deferred template; restore the template
9868 instantiation context in which the instantiation was requested, which
9869 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
9871 static tree
9872 reopen_tinst_level (struct tinst_level *level)
9874 struct tinst_level *t;
9876 tinst_depth = 0;
9877 for (t = level; t; t = t->next)
9878 ++tinst_depth;
9880 current_tinst_level = level;
9881 pop_tinst_level ();
9882 if (current_tinst_level)
9883 current_tinst_level->errors = errorcount+sorrycount;
9884 return level->decl;
9887 /* Returns the TINST_LEVEL which gives the original instantiation
9888 context. */
9890 struct tinst_level *
9891 outermost_tinst_level (void)
9893 struct tinst_level *level = current_tinst_level;
9894 if (level)
9895 while (level->next)
9896 level = level->next;
9897 return level;
9900 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
9901 vector of template arguments, as for tsubst.
9903 Returns an appropriate tsubst'd friend declaration. */
9905 static tree
9906 tsubst_friend_function (tree decl, tree args)
9908 tree new_friend;
9910 if (TREE_CODE (decl) == FUNCTION_DECL
9911 && DECL_TEMPLATE_INSTANTIATION (decl)
9912 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
9913 /* This was a friend declared with an explicit template
9914 argument list, e.g.:
9916 friend void f<>(T);
9918 to indicate that f was a template instantiation, not a new
9919 function declaration. Now, we have to figure out what
9920 instantiation of what template. */
9922 tree template_id, arglist, fns;
9923 tree new_args;
9924 tree tmpl;
9925 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
9927 /* Friend functions are looked up in the containing namespace scope.
9928 We must enter that scope, to avoid finding member functions of the
9929 current class with same name. */
9930 push_nested_namespace (ns);
9931 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
9932 tf_warning_or_error, NULL_TREE,
9933 /*integral_constant_expression_p=*/false);
9934 pop_nested_namespace (ns);
9935 arglist = tsubst (DECL_TI_ARGS (decl), args,
9936 tf_warning_or_error, NULL_TREE);
9937 template_id = lookup_template_function (fns, arglist);
9939 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
9940 tmpl = determine_specialization (template_id, new_friend,
9941 &new_args,
9942 /*need_member_template=*/0,
9943 TREE_VEC_LENGTH (args),
9944 tsk_none);
9945 return instantiate_template (tmpl, new_args, tf_error);
9948 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
9950 /* The NEW_FRIEND will look like an instantiation, to the
9951 compiler, but is not an instantiation from the point of view of
9952 the language. For example, we might have had:
9954 template <class T> struct S {
9955 template <class U> friend void f(T, U);
9958 Then, in S<int>, template <class U> void f(int, U) is not an
9959 instantiation of anything. */
9960 if (new_friend == error_mark_node)
9961 return error_mark_node;
9963 DECL_USE_TEMPLATE (new_friend) = 0;
9964 if (TREE_CODE (decl) == TEMPLATE_DECL)
9966 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
9967 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
9968 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
9971 /* The mangled name for the NEW_FRIEND is incorrect. The function
9972 is not a template instantiation and should not be mangled like
9973 one. Therefore, we forget the mangling here; we'll recompute it
9974 later if we need it. */
9975 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
9977 SET_DECL_RTL (new_friend, NULL);
9978 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
9981 if (DECL_NAMESPACE_SCOPE_P (new_friend))
9983 tree old_decl;
9984 tree new_friend_template_info;
9985 tree new_friend_result_template_info;
9986 tree ns;
9987 int new_friend_is_defn;
9989 /* We must save some information from NEW_FRIEND before calling
9990 duplicate decls since that function will free NEW_FRIEND if
9991 possible. */
9992 new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
9993 new_friend_is_defn =
9994 (DECL_INITIAL (DECL_TEMPLATE_RESULT
9995 (template_for_substitution (new_friend)))
9996 != NULL_TREE);
9997 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
9999 /* This declaration is a `primary' template. */
10000 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10002 new_friend_result_template_info
10003 = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10005 else
10006 new_friend_result_template_info = NULL_TREE;
10008 /* Inside pushdecl_namespace_level, we will push into the
10009 current namespace. However, the friend function should go
10010 into the namespace of the template. */
10011 ns = decl_namespace_context (new_friend);
10012 push_nested_namespace (ns);
10013 old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10014 pop_nested_namespace (ns);
10016 if (old_decl == error_mark_node)
10017 return error_mark_node;
10019 if (old_decl != new_friend)
10021 /* This new friend declaration matched an existing
10022 declaration. For example, given:
10024 template <class T> void f(T);
10025 template <class U> class C {
10026 template <class T> friend void f(T) {}
10029 the friend declaration actually provides the definition
10030 of `f', once C has been instantiated for some type. So,
10031 old_decl will be the out-of-class template declaration,
10032 while new_friend is the in-class definition.
10034 But, if `f' was called before this point, the
10035 instantiation of `f' will have DECL_TI_ARGS corresponding
10036 to `T' but not to `U', references to which might appear
10037 in the definition of `f'. Previously, the most general
10038 template for an instantiation of `f' was the out-of-class
10039 version; now it is the in-class version. Therefore, we
10040 run through all specialization of `f', adding to their
10041 DECL_TI_ARGS appropriately. In particular, they need a
10042 new set of outer arguments, corresponding to the
10043 arguments for this class instantiation.
10045 The same situation can arise with something like this:
10047 friend void f(int);
10048 template <class T> class C {
10049 friend void f(T) {}
10052 when `C<int>' is instantiated. Now, `f(int)' is defined
10053 in the class. */
10055 if (!new_friend_is_defn)
10056 /* On the other hand, if the in-class declaration does
10057 *not* provide a definition, then we don't want to alter
10058 existing definitions. We can just leave everything
10059 alone. */
10061 else
10063 tree new_template = TI_TEMPLATE (new_friend_template_info);
10064 tree new_args = TI_ARGS (new_friend_template_info);
10066 /* Overwrite whatever template info was there before, if
10067 any, with the new template information pertaining to
10068 the declaration. */
10069 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10071 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10073 /* We should have called reregister_specialization in
10074 duplicate_decls. */
10075 gcc_assert (retrieve_specialization (new_template,
10076 new_args, 0)
10077 == old_decl);
10079 /* Instantiate it if the global has already been used. */
10080 if (DECL_ODR_USED (old_decl))
10081 instantiate_decl (old_decl, /*defer_ok=*/true,
10082 /*expl_inst_class_mem_p=*/false);
10084 else
10086 tree t;
10088 /* Indicate that the old function template is a partial
10089 instantiation. */
10090 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10091 = new_friend_result_template_info;
10093 gcc_assert (new_template
10094 == most_general_template (new_template));
10095 gcc_assert (new_template != old_decl);
10097 /* Reassign any specializations already in the hash table
10098 to the new more general template, and add the
10099 additional template args. */
10100 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10101 t != NULL_TREE;
10102 t = TREE_CHAIN (t))
10104 tree spec = TREE_VALUE (t);
10105 spec_entry elt;
10107 elt.tmpl = old_decl;
10108 elt.args = DECL_TI_ARGS (spec);
10109 elt.spec = NULL_TREE;
10111 decl_specializations->remove_elt (&elt);
10113 DECL_TI_ARGS (spec)
10114 = add_outermost_template_args (new_args,
10115 DECL_TI_ARGS (spec));
10117 register_specialization
10118 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
10121 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10125 /* The information from NEW_FRIEND has been merged into OLD_DECL
10126 by duplicate_decls. */
10127 new_friend = old_decl;
10130 else
10132 tree context = DECL_CONTEXT (new_friend);
10133 bool dependent_p;
10135 /* In the code
10136 template <class T> class C {
10137 template <class U> friend void C1<U>::f (); // case 1
10138 friend void C2<T>::f (); // case 2
10140 we only need to make sure CONTEXT is a complete type for
10141 case 2. To distinguish between the two cases, we note that
10142 CONTEXT of case 1 remains dependent type after tsubst while
10143 this isn't true for case 2. */
10144 ++processing_template_decl;
10145 dependent_p = dependent_type_p (context);
10146 --processing_template_decl;
10148 if (!dependent_p
10149 && !complete_type_or_else (context, NULL_TREE))
10150 return error_mark_node;
10152 if (COMPLETE_TYPE_P (context))
10154 tree fn = new_friend;
10155 /* do_friend adds the TEMPLATE_DECL for any member friend
10156 template even if it isn't a member template, i.e.
10157 template <class T> friend A<T>::f();
10158 Look through it in that case. */
10159 if (TREE_CODE (fn) == TEMPLATE_DECL
10160 && !PRIMARY_TEMPLATE_P (fn))
10161 fn = DECL_TEMPLATE_RESULT (fn);
10162 /* Check to see that the declaration is really present, and,
10163 possibly obtain an improved declaration. */
10164 fn = check_classfn (context, fn, NULL_TREE);
10166 if (fn)
10167 new_friend = fn;
10171 return new_friend;
10174 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
10175 template arguments, as for tsubst.
10177 Returns an appropriate tsubst'd friend type or error_mark_node on
10178 failure. */
10180 static tree
10181 tsubst_friend_class (tree friend_tmpl, tree args)
10183 tree tmpl;
10185 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10187 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10188 return TREE_TYPE (tmpl);
10191 tree context = CP_DECL_CONTEXT (friend_tmpl);
10192 if (TREE_CODE (context) == NAMESPACE_DECL)
10193 push_nested_namespace (context);
10194 else
10195 push_nested_class (context);
10197 tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
10198 /*non_class=*/false, /*block_p=*/false,
10199 /*namespaces_only=*/false, LOOKUP_HIDDEN);
10201 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
10203 /* The friend template has already been declared. Just
10204 check to see that the declarations match, and install any new
10205 default parameters. We must tsubst the default parameters,
10206 of course. We only need the innermost template parameters
10207 because that is all that redeclare_class_template will look
10208 at. */
10209 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
10210 > TMPL_ARGS_DEPTH (args))
10212 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
10213 args, tf_warning_or_error);
10214 location_t saved_input_location = input_location;
10215 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
10216 tree cons = get_constraints (tmpl);
10217 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
10218 input_location = saved_input_location;
10221 else
10223 /* The friend template has not already been declared. In this
10224 case, the instantiation of the template class will cause the
10225 injection of this template into the namespace scope. */
10226 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
10228 if (tmpl != error_mark_node)
10230 /* The new TMPL is not an instantiation of anything, so we
10231 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
10232 for the new type because that is supposed to be the
10233 corresponding template decl, i.e., TMPL. */
10234 DECL_USE_TEMPLATE (tmpl) = 0;
10235 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
10236 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
10237 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
10238 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
10240 /* It is hidden. */
10241 retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
10242 DECL_ANTICIPATED (tmpl)
10243 = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
10245 /* Inject this template into the enclosing namspace scope. */
10246 tmpl = pushdecl_namespace_level (tmpl, true);
10250 if (TREE_CODE (context) == NAMESPACE_DECL)
10251 pop_nested_namespace (context);
10252 else
10253 pop_nested_class ();
10255 return TREE_TYPE (tmpl);
10258 /* Returns zero if TYPE cannot be completed later due to circularity.
10259 Otherwise returns one. */
10261 static int
10262 can_complete_type_without_circularity (tree type)
10264 if (type == NULL_TREE || type == error_mark_node)
10265 return 0;
10266 else if (COMPLETE_TYPE_P (type))
10267 return 1;
10268 else if (TREE_CODE (type) == ARRAY_TYPE)
10269 return can_complete_type_without_circularity (TREE_TYPE (type));
10270 else if (CLASS_TYPE_P (type)
10271 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
10272 return 0;
10273 else
10274 return 1;
10277 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
10278 tsubst_flags_t, tree);
10280 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
10281 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
10283 static tree
10284 tsubst_attribute (tree t, tree *decl_p, tree args,
10285 tsubst_flags_t complain, tree in_decl)
10287 gcc_assert (ATTR_IS_DEPENDENT (t));
10289 tree val = TREE_VALUE (t);
10290 if (val == NULL_TREE)
10291 /* Nothing to do. */;
10292 else if ((flag_openmp || flag_openmp_simd)
10293 && is_attribute_p ("omp declare simd",
10294 get_attribute_name (t)))
10296 tree clauses = TREE_VALUE (val);
10297 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
10298 complain, in_decl);
10299 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
10300 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
10301 tree parms = DECL_ARGUMENTS (*decl_p);
10302 clauses
10303 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
10304 if (clauses)
10305 val = build_tree_list (NULL_TREE, clauses);
10306 else
10307 val = NULL_TREE;
10309 /* If the first attribute argument is an identifier, don't
10310 pass it through tsubst. Attributes like mode, format,
10311 cleanup and several target specific attributes expect it
10312 unmodified. */
10313 else if (attribute_takes_identifier_p (get_attribute_name (t)))
10315 tree chain
10316 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
10317 /*integral_constant_expression_p=*/false);
10318 if (chain != TREE_CHAIN (val))
10319 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
10321 else if (PACK_EXPANSION_P (val))
10323 /* An attribute pack expansion. */
10324 tree purp = TREE_PURPOSE (t);
10325 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
10326 if (pack == error_mark_node)
10327 return error_mark_node;
10328 int len = TREE_VEC_LENGTH (pack);
10329 tree list = NULL_TREE;
10330 tree *q = &list;
10331 for (int i = 0; i < len; ++i)
10333 tree elt = TREE_VEC_ELT (pack, i);
10334 *q = build_tree_list (purp, elt);
10335 q = &TREE_CHAIN (*q);
10337 return list;
10339 else
10340 val = tsubst_expr (val, args, complain, in_decl,
10341 /*integral_constant_expression_p=*/false);
10343 if (val != TREE_VALUE (t))
10344 return build_tree_list (TREE_PURPOSE (t), val);
10345 return t;
10348 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
10349 unchanged or a new TREE_LIST chain. */
10351 static tree
10352 tsubst_attributes (tree attributes, tree args,
10353 tsubst_flags_t complain, tree in_decl)
10355 tree last_dep = NULL_TREE;
10357 for (tree t = attributes; t; t = TREE_CHAIN (t))
10358 if (ATTR_IS_DEPENDENT (t))
10360 last_dep = t;
10361 attributes = copy_list (attributes);
10362 break;
10365 if (last_dep)
10366 for (tree *p = &attributes; *p; )
10368 tree t = *p;
10369 if (ATTR_IS_DEPENDENT (t))
10371 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
10372 if (subst != t)
10374 *p = subst;
10375 while (*p)
10376 p = &TREE_CHAIN (*p);
10377 *p = TREE_CHAIN (t);
10378 continue;
10381 p = &TREE_CHAIN (*p);
10384 return attributes;
10387 /* Apply any attributes which had to be deferred until instantiation
10388 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
10389 ARGS, COMPLAIN, IN_DECL are as tsubst. */
10391 static void
10392 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
10393 tree args, tsubst_flags_t complain, tree in_decl)
10395 tree last_dep = NULL_TREE;
10396 tree t;
10397 tree *p;
10399 if (attributes == NULL_TREE)
10400 return;
10402 if (DECL_P (*decl_p))
10404 if (TREE_TYPE (*decl_p) == error_mark_node)
10405 return;
10406 p = &DECL_ATTRIBUTES (*decl_p);
10407 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
10408 to our attributes parameter. */
10409 gcc_assert (*p == attributes);
10411 else
10413 p = &TYPE_ATTRIBUTES (*decl_p);
10414 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
10415 lookup_template_class_1, and should be preserved. */
10416 gcc_assert (*p != attributes);
10417 while (*p)
10418 p = &TREE_CHAIN (*p);
10421 for (t = attributes; t; t = TREE_CHAIN (t))
10422 if (ATTR_IS_DEPENDENT (t))
10424 last_dep = t;
10425 attributes = copy_list (attributes);
10426 break;
10429 *p = attributes;
10430 if (last_dep)
10432 tree late_attrs = NULL_TREE;
10433 tree *q = &late_attrs;
10435 for (; *p; )
10437 t = *p;
10438 if (ATTR_IS_DEPENDENT (t))
10440 *p = TREE_CHAIN (t);
10441 TREE_CHAIN (t) = NULL_TREE;
10442 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
10443 while (*q)
10444 q = &TREE_CHAIN (*q);
10446 else
10447 p = &TREE_CHAIN (t);
10450 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
10454 /* Perform (or defer) access check for typedefs that were referenced
10455 from within the template TMPL code.
10456 This is a subroutine of instantiate_decl and instantiate_class_template.
10457 TMPL is the template to consider and TARGS is the list of arguments of
10458 that template. */
10460 static void
10461 perform_typedefs_access_check (tree tmpl, tree targs)
10463 location_t saved_location;
10464 unsigned i;
10465 qualified_typedef_usage_t *iter;
10467 if (!tmpl
10468 || (!CLASS_TYPE_P (tmpl)
10469 && TREE_CODE (tmpl) != FUNCTION_DECL))
10470 return;
10472 saved_location = input_location;
10473 FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
10475 tree type_decl = iter->typedef_decl;
10476 tree type_scope = iter->context;
10478 if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
10479 continue;
10481 if (uses_template_parms (type_decl))
10482 type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
10483 if (uses_template_parms (type_scope))
10484 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
10486 /* Make access check error messages point to the location
10487 of the use of the typedef. */
10488 input_location = iter->locus;
10489 perform_or_defer_access_check (TYPE_BINFO (type_scope),
10490 type_decl, type_decl,
10491 tf_warning_or_error);
10493 input_location = saved_location;
10496 static tree
10497 instantiate_class_template_1 (tree type)
10499 tree templ, args, pattern, t, member;
10500 tree typedecl;
10501 tree pbinfo;
10502 tree base_list;
10503 unsigned int saved_maximum_field_alignment;
10504 tree fn_context;
10506 if (type == error_mark_node)
10507 return error_mark_node;
10509 if (COMPLETE_OR_OPEN_TYPE_P (type)
10510 || uses_template_parms (type))
10511 return type;
10513 /* Figure out which template is being instantiated. */
10514 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
10515 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
10517 /* Mark the type as in the process of being defined. */
10518 TYPE_BEING_DEFINED (type) = 1;
10520 /* Determine what specialization of the original template to
10521 instantiate. */
10522 t = most_specialized_partial_spec (type, tf_warning_or_error);
10523 if (t == error_mark_node)
10524 return error_mark_node;
10525 else if (t)
10527 /* This TYPE is actually an instantiation of a partial
10528 specialization. We replace the innermost set of ARGS with
10529 the arguments appropriate for substitution. For example,
10530 given:
10532 template <class T> struct S {};
10533 template <class T> struct S<T*> {};
10535 and supposing that we are instantiating S<int*>, ARGS will
10536 presently be {int*} -- but we need {int}. */
10537 pattern = TREE_TYPE (t);
10538 args = TREE_PURPOSE (t);
10540 else
10542 pattern = TREE_TYPE (templ);
10543 args = CLASSTYPE_TI_ARGS (type);
10546 /* If the template we're instantiating is incomplete, then clearly
10547 there's nothing we can do. */
10548 if (!COMPLETE_TYPE_P (pattern))
10550 /* We can try again later. */
10551 TYPE_BEING_DEFINED (type) = 0;
10552 return type;
10555 /* If we've recursively instantiated too many templates, stop. */
10556 if (! push_tinst_level (type))
10557 return type;
10559 /* We may be in the middle of deferred access check. Disable
10560 it now. */
10561 push_deferring_access_checks (dk_no_deferred);
10563 int saved_unevaluated_operand = cp_unevaluated_operand;
10564 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
10566 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
10567 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
10568 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
10569 fn_context = error_mark_node;
10570 if (!fn_context)
10571 push_to_top_level ();
10572 else
10574 cp_unevaluated_operand = 0;
10575 c_inhibit_evaluation_warnings = 0;
10577 /* Use #pragma pack from the template context. */
10578 saved_maximum_field_alignment = maximum_field_alignment;
10579 maximum_field_alignment = TYPE_PRECISION (pattern);
10581 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
10583 /* Set the input location to the most specialized template definition.
10584 This is needed if tsubsting causes an error. */
10585 typedecl = TYPE_MAIN_DECL (pattern);
10586 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
10587 DECL_SOURCE_LOCATION (typedecl);
10589 TYPE_PACKED (type) = TYPE_PACKED (pattern);
10590 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
10591 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
10592 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
10593 if (ANON_AGGR_TYPE_P (pattern))
10594 SET_ANON_AGGR_TYPE_P (type);
10595 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
10597 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
10598 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
10599 /* Adjust visibility for template arguments. */
10600 determine_visibility (TYPE_MAIN_DECL (type));
10602 if (CLASS_TYPE_P (type))
10603 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
10605 pbinfo = TYPE_BINFO (pattern);
10607 /* We should never instantiate a nested class before its enclosing
10608 class; we need to look up the nested class by name before we can
10609 instantiate it, and that lookup should instantiate the enclosing
10610 class. */
10611 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
10612 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
10614 base_list = NULL_TREE;
10615 if (BINFO_N_BASE_BINFOS (pbinfo))
10617 tree pbase_binfo;
10618 tree pushed_scope;
10619 int i;
10621 /* We must enter the scope containing the type, as that is where
10622 the accessibility of types named in dependent bases are
10623 looked up from. */
10624 pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
10626 /* Substitute into each of the bases to determine the actual
10627 basetypes. */
10628 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
10630 tree base;
10631 tree access = BINFO_BASE_ACCESS (pbinfo, i);
10632 tree expanded_bases = NULL_TREE;
10633 int idx, len = 1;
10635 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
10637 expanded_bases =
10638 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
10639 args, tf_error, NULL_TREE);
10640 if (expanded_bases == error_mark_node)
10641 continue;
10643 len = TREE_VEC_LENGTH (expanded_bases);
10646 for (idx = 0; idx < len; idx++)
10648 if (expanded_bases)
10649 /* Extract the already-expanded base class. */
10650 base = TREE_VEC_ELT (expanded_bases, idx);
10651 else
10652 /* Substitute to figure out the base class. */
10653 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
10654 NULL_TREE);
10656 if (base == error_mark_node)
10657 continue;
10659 base_list = tree_cons (access, base, base_list);
10660 if (BINFO_VIRTUAL_P (pbase_binfo))
10661 TREE_TYPE (base_list) = integer_type_node;
10665 /* The list is now in reverse order; correct that. */
10666 base_list = nreverse (base_list);
10668 if (pushed_scope)
10669 pop_scope (pushed_scope);
10671 /* Now call xref_basetypes to set up all the base-class
10672 information. */
10673 xref_basetypes (type, base_list);
10675 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
10676 (int) ATTR_FLAG_TYPE_IN_PLACE,
10677 args, tf_error, NULL_TREE);
10678 fixup_attribute_variants (type);
10680 /* Now that our base classes are set up, enter the scope of the
10681 class, so that name lookups into base classes, etc. will work
10682 correctly. This is precisely analogous to what we do in
10683 begin_class_definition when defining an ordinary non-template
10684 class, except we also need to push the enclosing classes. */
10685 push_nested_class (type);
10687 /* Now members are processed in the order of declaration. */
10688 for (member = CLASSTYPE_DECL_LIST (pattern);
10689 member; member = TREE_CHAIN (member))
10691 tree t = TREE_VALUE (member);
10693 if (TREE_PURPOSE (member))
10695 if (TYPE_P (t))
10697 if (LAMBDA_TYPE_P (t))
10698 /* A closure type for a lambda in an NSDMI or default argument.
10699 Ignore it; it will be regenerated when needed. */
10700 continue;
10702 /* Build new CLASSTYPE_NESTED_UTDS. */
10704 tree newtag;
10705 bool class_template_p;
10707 class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
10708 && TYPE_LANG_SPECIFIC (t)
10709 && CLASSTYPE_IS_TEMPLATE (t));
10710 /* If the member is a class template, then -- even after
10711 substitution -- there may be dependent types in the
10712 template argument list for the class. We increment
10713 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
10714 that function will assume that no types are dependent
10715 when outside of a template. */
10716 if (class_template_p)
10717 ++processing_template_decl;
10718 newtag = tsubst (t, args, tf_error, NULL_TREE);
10719 if (class_template_p)
10720 --processing_template_decl;
10721 if (newtag == error_mark_node)
10722 continue;
10724 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
10726 tree name = TYPE_IDENTIFIER (t);
10728 if (class_template_p)
10729 /* Unfortunately, lookup_template_class sets
10730 CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
10731 instantiation (i.e., for the type of a member
10732 template class nested within a template class.)
10733 This behavior is required for
10734 maybe_process_partial_specialization to work
10735 correctly, but is not accurate in this case;
10736 the TAG is not an instantiation of anything.
10737 (The corresponding TEMPLATE_DECL is an
10738 instantiation, but the TYPE is not.) */
10739 CLASSTYPE_USE_TEMPLATE (newtag) = 0;
10741 /* Now, we call pushtag to put this NEWTAG into the scope of
10742 TYPE. We first set up the IDENTIFIER_TYPE_VALUE to avoid
10743 pushtag calling push_template_decl. We don't have to do
10744 this for enums because it will already have been done in
10745 tsubst_enum. */
10746 if (name)
10747 SET_IDENTIFIER_TYPE_VALUE (name, newtag);
10748 pushtag (name, newtag, /*tag_scope=*/ts_current);
10751 else if (DECL_DECLARES_FUNCTION_P (t))
10753 tree r;
10755 if (TREE_CODE (t) == TEMPLATE_DECL)
10756 ++processing_template_decl;
10757 r = tsubst (t, args, tf_error, NULL_TREE);
10758 if (TREE_CODE (t) == TEMPLATE_DECL)
10759 --processing_template_decl;
10760 set_current_access_from_decl (r);
10761 finish_member_declaration (r);
10762 /* Instantiate members marked with attribute used. */
10763 if (r != error_mark_node && DECL_PRESERVE_P (r))
10764 mark_used (r);
10765 if (TREE_CODE (r) == FUNCTION_DECL
10766 && DECL_OMP_DECLARE_REDUCTION_P (r))
10767 cp_check_omp_declare_reduction (r);
10769 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
10770 && LAMBDA_TYPE_P (TREE_TYPE (t)))
10771 /* A closure type for a lambda in an NSDMI or default argument.
10772 Ignore it; it will be regenerated when needed. */;
10773 else
10775 /* Build new TYPE_FIELDS. */
10776 if (TREE_CODE (t) == STATIC_ASSERT)
10778 tree condition;
10780 ++c_inhibit_evaluation_warnings;
10781 condition =
10782 tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
10783 tf_warning_or_error, NULL_TREE,
10784 /*integral_constant_expression_p=*/true);
10785 --c_inhibit_evaluation_warnings;
10787 finish_static_assert (condition,
10788 STATIC_ASSERT_MESSAGE (t),
10789 STATIC_ASSERT_SOURCE_LOCATION (t),
10790 /*member_p=*/true);
10792 else if (TREE_CODE (t) != CONST_DECL)
10794 tree r;
10795 tree vec = NULL_TREE;
10796 int len = 1;
10798 /* The file and line for this declaration, to
10799 assist in error message reporting. Since we
10800 called push_tinst_level above, we don't need to
10801 restore these. */
10802 input_location = DECL_SOURCE_LOCATION (t);
10804 if (TREE_CODE (t) == TEMPLATE_DECL)
10805 ++processing_template_decl;
10806 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
10807 if (TREE_CODE (t) == TEMPLATE_DECL)
10808 --processing_template_decl;
10810 if (TREE_CODE (r) == TREE_VEC)
10812 /* A capture pack became multiple fields. */
10813 vec = r;
10814 len = TREE_VEC_LENGTH (vec);
10817 for (int i = 0; i < len; ++i)
10819 if (vec)
10820 r = TREE_VEC_ELT (vec, i);
10821 if (VAR_P (r))
10823 /* In [temp.inst]:
10825 [t]he initialization (and any associated
10826 side-effects) of a static data member does
10827 not occur unless the static data member is
10828 itself used in a way that requires the
10829 definition of the static data member to
10830 exist.
10832 Therefore, we do not substitute into the
10833 initialized for the static data member here. */
10834 finish_static_data_member_decl
10836 /*init=*/NULL_TREE,
10837 /*init_const_expr_p=*/false,
10838 /*asmspec_tree=*/NULL_TREE,
10839 /*flags=*/0);
10840 /* Instantiate members marked with attribute used. */
10841 if (r != error_mark_node && DECL_PRESERVE_P (r))
10842 mark_used (r);
10844 else if (TREE_CODE (r) == FIELD_DECL)
10846 /* Determine whether R has a valid type and can be
10847 completed later. If R is invalid, then its type
10848 is replaced by error_mark_node. */
10849 tree rtype = TREE_TYPE (r);
10850 if (can_complete_type_without_circularity (rtype))
10851 complete_type (rtype);
10853 if (!complete_or_array_type_p (rtype))
10855 /* If R's type couldn't be completed and
10856 it isn't a flexible array member (whose
10857 type is incomplete by definition) give
10858 an error. */
10859 cxx_incomplete_type_error (r, rtype);
10860 TREE_TYPE (r) = error_mark_node;
10864 /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
10865 such a thing will already have been added to the field
10866 list by tsubst_enum in finish_member_declaration in the
10867 CLASSTYPE_NESTED_UTDS case above. */
10868 if (!(TREE_CODE (r) == TYPE_DECL
10869 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
10870 && DECL_ARTIFICIAL (r)))
10872 set_current_access_from_decl (r);
10873 finish_member_declaration (r);
10879 else
10881 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
10882 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10884 /* Build new CLASSTYPE_FRIEND_CLASSES. */
10886 tree friend_type = t;
10887 bool adjust_processing_template_decl = false;
10889 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
10891 /* template <class T> friend class C; */
10892 friend_type = tsubst_friend_class (friend_type, args);
10893 adjust_processing_template_decl = true;
10895 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
10897 /* template <class T> friend class C::D; */
10898 friend_type = tsubst (friend_type, args,
10899 tf_warning_or_error, NULL_TREE);
10900 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
10901 friend_type = TREE_TYPE (friend_type);
10902 adjust_processing_template_decl = true;
10904 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
10905 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
10907 /* This could be either
10909 friend class T::C;
10911 when dependent_type_p is false or
10913 template <class U> friend class T::C;
10915 otherwise. */
10916 /* Bump processing_template_decl in case this is something like
10917 template <class T> friend struct A<T>::B. */
10918 ++processing_template_decl;
10919 friend_type = tsubst (friend_type, args,
10920 tf_warning_or_error, NULL_TREE);
10921 if (dependent_type_p (friend_type))
10922 adjust_processing_template_decl = true;
10923 --processing_template_decl;
10925 else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
10926 && !CLASSTYPE_USE_TEMPLATE (friend_type)
10927 && TYPE_HIDDEN_P (friend_type))
10929 /* friend class C;
10931 where C hasn't been declared yet. Let's lookup name
10932 from namespace scope directly, bypassing any name that
10933 come from dependent base class. */
10934 tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
10936 /* The call to xref_tag_from_type does injection for friend
10937 classes. */
10938 push_nested_namespace (ns);
10939 friend_type =
10940 xref_tag_from_type (friend_type, NULL_TREE,
10941 /*tag_scope=*/ts_current);
10942 pop_nested_namespace (ns);
10944 else if (uses_template_parms (friend_type))
10945 /* friend class C<T>; */
10946 friend_type = tsubst (friend_type, args,
10947 tf_warning_or_error, NULL_TREE);
10948 /* Otherwise it's
10950 friend class C;
10952 where C is already declared or
10954 friend class C<int>;
10956 We don't have to do anything in these cases. */
10958 if (adjust_processing_template_decl)
10959 /* Trick make_friend_class into realizing that the friend
10960 we're adding is a template, not an ordinary class. It's
10961 important that we use make_friend_class since it will
10962 perform some error-checking and output cross-reference
10963 information. */
10964 ++processing_template_decl;
10966 if (friend_type != error_mark_node)
10967 make_friend_class (type, friend_type, /*complain=*/false);
10969 if (adjust_processing_template_decl)
10970 --processing_template_decl;
10972 else
10974 /* Build new DECL_FRIENDLIST. */
10975 tree r;
10977 /* The file and line for this declaration, to
10978 assist in error message reporting. Since we
10979 called push_tinst_level above, we don't need to
10980 restore these. */
10981 input_location = DECL_SOURCE_LOCATION (t);
10983 if (TREE_CODE (t) == TEMPLATE_DECL)
10985 ++processing_template_decl;
10986 push_deferring_access_checks (dk_no_check);
10989 r = tsubst_friend_function (t, args);
10990 add_friend (type, r, /*complain=*/false);
10991 if (TREE_CODE (t) == TEMPLATE_DECL)
10993 pop_deferring_access_checks ();
10994 --processing_template_decl;
11000 if (fn_context)
11002 /* Restore these before substituting into the lambda capture
11003 initializers. */
11004 cp_unevaluated_operand = saved_unevaluated_operand;
11005 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11008 /* Set the file and line number information to whatever is given for
11009 the class itself. This puts error messages involving generated
11010 implicit functions at a predictable point, and the same point
11011 that would be used for non-template classes. */
11012 input_location = DECL_SOURCE_LOCATION (typedecl);
11014 unreverse_member_declarations (type);
11015 finish_struct_1 (type);
11016 TYPE_BEING_DEFINED (type) = 0;
11018 /* We don't instantiate default arguments for member functions. 14.7.1:
11020 The implicit instantiation of a class template specialization causes
11021 the implicit instantiation of the declarations, but not of the
11022 definitions or default arguments, of the class member functions,
11023 member classes, static data members and member templates.... */
11025 /* Some typedefs referenced from within the template code need to be access
11026 checked at template instantiation time, i.e now. These types were
11027 added to the template at parsing time. Let's get those and perform
11028 the access checks then. */
11029 perform_typedefs_access_check (pattern, args);
11030 perform_deferred_access_checks (tf_warning_or_error);
11031 pop_nested_class ();
11032 maximum_field_alignment = saved_maximum_field_alignment;
11033 if (!fn_context)
11034 pop_from_top_level ();
11035 pop_deferring_access_checks ();
11036 pop_tinst_level ();
11038 /* The vtable for a template class can be emitted in any translation
11039 unit in which the class is instantiated. When there is no key
11040 method, however, finish_struct_1 will already have added TYPE to
11041 the keyed_classes. */
11042 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11043 vec_safe_push (keyed_classes, type);
11045 return type;
11048 /* Wrapper for instantiate_class_template_1. */
11050 tree
11051 instantiate_class_template (tree type)
11053 tree ret;
11054 timevar_push (TV_TEMPLATE_INST);
11055 ret = instantiate_class_template_1 (type);
11056 timevar_pop (TV_TEMPLATE_INST);
11057 return ret;
11060 static tree
11061 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11063 tree r;
11065 if (!t)
11066 r = t;
11067 else if (TYPE_P (t))
11068 r = tsubst (t, args, complain, in_decl);
11069 else
11071 if (!(complain & tf_warning))
11072 ++c_inhibit_evaluation_warnings;
11073 r = tsubst_expr (t, args, complain, in_decl,
11074 /*integral_constant_expression_p=*/true);
11075 if (!(complain & tf_warning))
11076 --c_inhibit_evaluation_warnings;
11078 return r;
11081 /* Given a function parameter pack TMPL_PARM and some function parameters
11082 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11083 and set *SPEC_P to point at the next point in the list. */
11085 tree
11086 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11088 /* Collect all of the extra "packed" parameters into an
11089 argument pack. */
11090 tree parmvec;
11091 tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11092 tree spec_parm = *spec_p;
11093 int i, len;
11095 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11096 if (tmpl_parm
11097 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11098 break;
11100 /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters. */
11101 parmvec = make_tree_vec (len);
11102 spec_parm = *spec_p;
11103 for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11105 tree elt = spec_parm;
11106 if (DECL_PACK_P (elt))
11107 elt = make_pack_expansion (elt);
11108 TREE_VEC_ELT (parmvec, i) = elt;
11111 /* Build the argument packs. */
11112 SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11113 *spec_p = spec_parm;
11115 return argpack;
11118 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11119 NONTYPE_ARGUMENT_PACK. */
11121 static tree
11122 make_fnparm_pack (tree spec_parm)
11124 return extract_fnparm_pack (NULL_TREE, &spec_parm);
11127 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11128 pack expansion with no extra args, 2 if it has extra args, or 0
11129 if it is not a pack expansion. */
11131 static int
11132 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11134 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11135 if (i >= TREE_VEC_LENGTH (vec))
11136 return 0;
11137 tree elt = TREE_VEC_ELT (vec, i);
11138 if (DECL_P (elt))
11139 /* A decl pack is itself an expansion. */
11140 elt = TREE_TYPE (elt);
11141 if (!PACK_EXPANSION_P (elt))
11142 return 0;
11143 if (PACK_EXPANSION_EXTRA_ARGS (elt))
11144 return 2;
11145 return 1;
11149 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
11151 static tree
11152 make_argument_pack_select (tree arg_pack, unsigned index)
11154 tree aps = make_node (ARGUMENT_PACK_SELECT);
11156 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11157 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11159 return aps;
11162 /* This is a subroutine of tsubst_pack_expansion.
11164 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11165 mechanism to store the (non complete list of) arguments of the
11166 substitution and return a non substituted pack expansion, in order
11167 to wait for when we have enough arguments to really perform the
11168 substitution. */
11170 static bool
11171 use_pack_expansion_extra_args_p (tree parm_packs,
11172 int arg_pack_len,
11173 bool has_empty_arg)
11175 /* If one pack has an expansion and another pack has a normal
11176 argument or if one pack has an empty argument and an another
11177 one hasn't then tsubst_pack_expansion cannot perform the
11178 substitution and need to fall back on the
11179 PACK_EXPANSION_EXTRA mechanism. */
11180 if (parm_packs == NULL_TREE)
11181 return false;
11182 else if (has_empty_arg)
11183 return true;
11185 bool has_expansion_arg = false;
11186 for (int i = 0 ; i < arg_pack_len; ++i)
11188 bool has_non_expansion_arg = false;
11189 for (tree parm_pack = parm_packs;
11190 parm_pack;
11191 parm_pack = TREE_CHAIN (parm_pack))
11193 tree arg = TREE_VALUE (parm_pack);
11195 int exp = argument_pack_element_is_expansion_p (arg, i);
11196 if (exp == 2)
11197 /* We can't substitute a pack expansion with extra args into
11198 our pattern. */
11199 return true;
11200 else if (exp)
11201 has_expansion_arg = true;
11202 else
11203 has_non_expansion_arg = true;
11206 if (has_expansion_arg && has_non_expansion_arg)
11207 return true;
11209 return false;
11212 /* [temp.variadic]/6 says that:
11214 The instantiation of a pack expansion [...]
11215 produces a list E1,E2, ..., En, where N is the number of elements
11216 in the pack expansion parameters.
11218 This subroutine of tsubst_pack_expansion produces one of these Ei.
11220 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
11221 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
11222 PATTERN, and each TREE_VALUE is its corresponding argument pack.
11223 INDEX is the index 'i' of the element Ei to produce. ARGS,
11224 COMPLAIN, and IN_DECL are the same parameters as for the
11225 tsubst_pack_expansion function.
11227 The function returns the resulting Ei upon successful completion,
11228 or error_mark_node.
11230 Note that this function possibly modifies the ARGS parameter, so
11231 it's the responsibility of the caller to restore it. */
11233 static tree
11234 gen_elem_of_pack_expansion_instantiation (tree pattern,
11235 tree parm_packs,
11236 unsigned index,
11237 tree args /* This parm gets
11238 modified. */,
11239 tsubst_flags_t complain,
11240 tree in_decl)
11242 tree t;
11243 bool ith_elem_is_expansion = false;
11245 /* For each parameter pack, change the substitution of the parameter
11246 pack to the ith argument in its argument pack, then expand the
11247 pattern. */
11248 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
11250 tree parm = TREE_PURPOSE (pack);
11251 tree arg_pack = TREE_VALUE (pack);
11252 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
11254 ith_elem_is_expansion |=
11255 argument_pack_element_is_expansion_p (arg_pack, index);
11257 /* Select the Ith argument from the pack. */
11258 if (TREE_CODE (parm) == PARM_DECL
11259 || VAR_P (parm)
11260 || TREE_CODE (parm) == FIELD_DECL)
11262 if (index == 0)
11264 aps = make_argument_pack_select (arg_pack, index);
11265 if (!mark_used (parm, complain) && !(complain & tf_error))
11266 return error_mark_node;
11267 register_local_specialization (aps, parm);
11269 else
11270 aps = retrieve_local_specialization (parm);
11272 else
11274 int idx, level;
11275 template_parm_level_and_index (parm, &level, &idx);
11277 if (index == 0)
11279 aps = make_argument_pack_select (arg_pack, index);
11280 /* Update the corresponding argument. */
11281 TMPL_ARG (args, level, idx) = aps;
11283 else
11284 /* Re-use the ARGUMENT_PACK_SELECT. */
11285 aps = TMPL_ARG (args, level, idx);
11287 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11290 /* Substitute into the PATTERN with the (possibly altered)
11291 arguments. */
11292 if (pattern == in_decl)
11293 /* Expanding a fixed parameter pack from
11294 coerce_template_parameter_pack. */
11295 t = tsubst_decl (pattern, args, complain);
11296 else if (pattern == error_mark_node)
11297 t = error_mark_node;
11298 else if (constraint_p (pattern))
11300 if (processing_template_decl)
11301 t = tsubst_constraint (pattern, args, complain, in_decl);
11302 else
11303 t = (constraints_satisfied_p (pattern, args)
11304 ? boolean_true_node : boolean_false_node);
11306 else if (!TYPE_P (pattern))
11307 t = tsubst_expr (pattern, args, complain, in_decl,
11308 /*integral_constant_expression_p=*/false);
11309 else
11310 t = tsubst (pattern, args, complain, in_decl);
11312 /* If the Ith argument pack element is a pack expansion, then
11313 the Ith element resulting from the substituting is going to
11314 be a pack expansion as well. */
11315 if (ith_elem_is_expansion)
11316 t = make_pack_expansion (t, complain);
11318 return t;
11321 /* When the unexpanded parameter pack in a fold expression expands to an empty
11322 sequence, the value of the expression is as follows; the program is
11323 ill-formed if the operator is not listed in this table.
11325 && true
11326 || false
11327 , void() */
11329 tree
11330 expand_empty_fold (tree t, tsubst_flags_t complain)
11332 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
11333 if (!FOLD_EXPR_MODIFY_P (t))
11334 switch (code)
11336 case TRUTH_ANDIF_EXPR:
11337 return boolean_true_node;
11338 case TRUTH_ORIF_EXPR:
11339 return boolean_false_node;
11340 case COMPOUND_EXPR:
11341 return void_node;
11342 default:
11343 break;
11346 if (complain & tf_error)
11347 error_at (location_of (t),
11348 "fold of empty expansion over %O", code);
11349 return error_mark_node;
11352 /* Given a fold-expression T and a current LEFT and RIGHT operand,
11353 form an expression that combines the two terms using the
11354 operator of T. */
11356 static tree
11357 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
11359 tree op = FOLD_EXPR_OP (t);
11360 tree_code code = (tree_code)TREE_INT_CST_LOW (op);
11362 // Handle compound assignment operators.
11363 if (FOLD_EXPR_MODIFY_P (t))
11364 return build_x_modify_expr (input_location, left, code, right, complain);
11366 switch (code)
11368 case COMPOUND_EXPR:
11369 return build_x_compound_expr (input_location, left, right, complain);
11370 case DOTSTAR_EXPR:
11371 return build_m_component_ref (left, right, complain);
11372 default:
11373 return build_x_binary_op (input_location, code,
11374 left, TREE_CODE (left),
11375 right, TREE_CODE (right),
11376 /*overload=*/NULL,
11377 complain);
11381 /* Substitute ARGS into the pack of a fold expression T. */
11383 static inline tree
11384 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11386 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11389 /* Substitute ARGS into the pack of a fold expression T. */
11391 static inline tree
11392 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11394 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11397 /* Expand a PACK of arguments into a grouped as left fold.
11398 Given a pack containing elements A0, A1, ..., An and an
11399 operator @, this builds the expression:
11401 ((A0 @ A1) @ A2) ... @ An
11403 Note that PACK must not be empty.
11405 The operator is defined by the original fold expression T. */
11407 static tree
11408 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11410 tree left = TREE_VEC_ELT (pack, 0);
11411 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11413 tree right = TREE_VEC_ELT (pack, i);
11414 left = fold_expression (t, left, right, complain);
11416 return left;
11419 /* Substitute into a unary left fold expression. */
11421 static tree
11422 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11423 tree in_decl)
11425 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11426 if (pack == error_mark_node)
11427 return error_mark_node;
11428 if (PACK_EXPANSION_P (pack))
11430 tree r = copy_node (t);
11431 FOLD_EXPR_PACK (r) = pack;
11432 return r;
11434 if (TREE_VEC_LENGTH (pack) == 0)
11435 return expand_empty_fold (t, complain);
11436 else
11437 return expand_left_fold (t, pack, complain);
11440 /* Substitute into a binary left fold expression.
11442 Do ths by building a single (non-empty) vector of argumnts and
11443 building the expression from those elements. */
11445 static tree
11446 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11447 tree in_decl)
11449 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11450 if (pack == error_mark_node)
11451 return error_mark_node;
11452 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11453 if (init == error_mark_node)
11454 return error_mark_node;
11456 if (PACK_EXPANSION_P (pack))
11458 tree r = copy_node (t);
11459 FOLD_EXPR_PACK (r) = pack;
11460 FOLD_EXPR_INIT (r) = init;
11461 return r;
11464 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11465 TREE_VEC_ELT (vec, 0) = init;
11466 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11467 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11469 return expand_left_fold (t, vec, complain);
11472 /* Expand a PACK of arguments into a grouped as right fold.
11473 Given a pack containing elementns A0, A1, ..., and an
11474 operator @, this builds the expression:
11476 A0@ ... (An-2 @ (An-1 @ An))
11478 Note that PACK must not be empty.
11480 The operator is defined by the original fold expression T. */
11482 tree
11483 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11485 // Build the expression.
11486 int n = TREE_VEC_LENGTH (pack);
11487 tree right = TREE_VEC_ELT (pack, n - 1);
11488 for (--n; n != 0; --n)
11490 tree left = TREE_VEC_ELT (pack, n - 1);
11491 right = fold_expression (t, left, right, complain);
11493 return right;
11496 /* Substitute into a unary right fold expression. */
11498 static tree
11499 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11500 tree in_decl)
11502 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11503 if (pack == error_mark_node)
11504 return error_mark_node;
11505 if (PACK_EXPANSION_P (pack))
11507 tree r = copy_node (t);
11508 FOLD_EXPR_PACK (r) = pack;
11509 return r;
11511 if (TREE_VEC_LENGTH (pack) == 0)
11512 return expand_empty_fold (t, complain);
11513 else
11514 return expand_right_fold (t, pack, complain);
11517 /* Substitute into a binary right fold expression.
11519 Do ths by building a single (non-empty) vector of arguments and
11520 building the expression from those elements. */
11522 static tree
11523 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11524 tree in_decl)
11526 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11527 if (pack == error_mark_node)
11528 return error_mark_node;
11529 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11530 if (init == error_mark_node)
11531 return error_mark_node;
11533 if (PACK_EXPANSION_P (pack))
11535 tree r = copy_node (t);
11536 FOLD_EXPR_PACK (r) = pack;
11537 FOLD_EXPR_INIT (r) = init;
11538 return r;
11541 int n = TREE_VEC_LENGTH (pack);
11542 tree vec = make_tree_vec (n + 1);
11543 for (int i = 0; i < n; ++i)
11544 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
11545 TREE_VEC_ELT (vec, n) = init;
11547 return expand_right_fold (t, vec, complain);
11550 /* Walk through the pattern of a pack expansion, adding everything in
11551 local_specializations to a list. */
11553 struct el_data
11555 tree extra;
11556 tsubst_flags_t complain;
11558 static tree
11559 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
11561 el_data &data = *reinterpret_cast<el_data*>(data_);
11562 tree *extra = &data.extra;
11563 tsubst_flags_t complain = data.complain;
11564 if (tree spec = retrieve_local_specialization (*tp))
11566 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11568 /* Maybe pull out the PARM_DECL for a partial instantiation. */
11569 tree args = ARGUMENT_PACK_ARGS (spec);
11570 if (TREE_VEC_LENGTH (args) == 1)
11572 tree elt = TREE_VEC_ELT (args, 0);
11573 if (PACK_EXPANSION_P (elt))
11574 elt = PACK_EXPANSION_PATTERN (elt);
11575 if (DECL_PACK_P (elt))
11576 spec = elt;
11578 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11580 /* Handle lambda capture here, since we aren't doing any
11581 substitution now, and so tsubst_copy won't call
11582 process_outer_var_ref. */
11583 tree args = ARGUMENT_PACK_ARGS (spec);
11584 int len = TREE_VEC_LENGTH (args);
11585 for (int i = 0; i < len; ++i)
11587 tree arg = TREE_VEC_ELT (args, i);
11588 tree carg = arg;
11589 if (outer_automatic_var_p (arg))
11590 carg = process_outer_var_ref (arg, complain);
11591 if (carg != arg)
11593 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
11594 proxies. */
11595 if (i == 0)
11597 spec = copy_node (spec);
11598 args = copy_node (args);
11599 SET_ARGUMENT_PACK_ARGS (spec, args);
11600 register_local_specialization (spec, *tp);
11602 TREE_VEC_ELT (args, i) = carg;
11607 if (outer_automatic_var_p (spec))
11608 spec = process_outer_var_ref (spec, complain);
11609 *extra = tree_cons (*tp, spec, *extra);
11611 return NULL_TREE;
11613 static tree
11614 extract_local_specs (tree pattern, tsubst_flags_t complain)
11616 el_data data = { NULL_TREE, complain };
11617 cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
11618 return data.extra;
11621 /* Substitute ARGS into T, which is an pack expansion
11622 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
11623 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
11624 (if only a partial substitution could be performed) or
11625 ERROR_MARK_NODE if there was an error. */
11626 tree
11627 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
11628 tree in_decl)
11630 tree pattern;
11631 tree pack, packs = NULL_TREE;
11632 bool unsubstituted_packs = false;
11633 bool unsubstituted_fn_pack = false;
11634 int i, len = -1;
11635 tree result;
11636 hash_map<tree, tree> *saved_local_specializations = NULL;
11637 bool need_local_specializations = false;
11638 int levels;
11640 gcc_assert (PACK_EXPANSION_P (t));
11641 pattern = PACK_EXPANSION_PATTERN (t);
11643 /* Add in any args remembered from an earlier partial instantiation. */
11644 tree extra = PACK_EXPANSION_EXTRA_ARGS (t);
11645 if (extra && TREE_CODE (extra) == TREE_LIST)
11647 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
11649 /* The partial instantiation involved local declarations collected in
11650 extract_local_specs; map from the general template to our local
11651 context. */
11652 tree gen = TREE_PURPOSE (elt);
11653 tree inst = TREE_VALUE (elt);
11654 if (DECL_P (inst))
11655 if (tree local = retrieve_local_specialization (inst))
11656 inst = local;
11657 /* else inst is already a full instantiation of the pack. */
11658 register_local_specialization (inst, gen);
11660 gcc_assert (!TREE_PURPOSE (extra));
11661 extra = TREE_VALUE (extra);
11663 args = add_to_template_args (extra, args);
11665 levels = TMPL_ARGS_DEPTH (args);
11667 /* Determine the argument packs that will instantiate the parameter
11668 packs used in the expansion expression. While we're at it,
11669 compute the number of arguments to be expanded and make sure it
11670 is consistent. */
11671 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
11672 pack = TREE_CHAIN (pack))
11674 tree parm_pack = TREE_VALUE (pack);
11675 tree arg_pack = NULL_TREE;
11676 tree orig_arg = NULL_TREE;
11677 int level = 0;
11679 if (TREE_CODE (parm_pack) == BASES)
11681 gcc_assert (parm_pack == pattern);
11682 if (BASES_DIRECT (parm_pack))
11683 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
11684 args, complain, in_decl, false));
11685 else
11686 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
11687 args, complain, in_decl, false));
11689 else if (builtin_pack_call_p (parm_pack))
11691 /* ??? Support use in other patterns. */
11692 gcc_assert (parm_pack == pattern);
11693 return expand_builtin_pack_call (parm_pack, args,
11694 complain, in_decl);
11696 else if (TREE_CODE (parm_pack) == PARM_DECL)
11698 /* We know we have correct local_specializations if this
11699 expansion is at function scope, or if we're dealing with a
11700 local parameter in a requires expression; for the latter,
11701 tsubst_requires_expr set it up appropriately. */
11702 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
11703 arg_pack = retrieve_local_specialization (parm_pack);
11704 else
11705 /* We can't rely on local_specializations for a parameter
11706 name used later in a function declaration (such as in a
11707 late-specified return type). Even if it exists, it might
11708 have the wrong value for a recursive call. */
11709 need_local_specializations = true;
11711 if (!arg_pack)
11713 /* This parameter pack was used in an unevaluated context. Just
11714 make a dummy decl, since it's only used for its type. */
11715 arg_pack = tsubst_decl (parm_pack, args, complain);
11716 if (arg_pack && DECL_PACK_P (arg_pack))
11717 /* Partial instantiation of the parm_pack, we can't build
11718 up an argument pack yet. */
11719 arg_pack = NULL_TREE;
11720 else
11721 arg_pack = make_fnparm_pack (arg_pack);
11723 else if (argument_pack_element_is_expansion_p (arg_pack, 0))
11724 /* This argument pack isn't fully instantiated yet. We set this
11725 flag rather than clear arg_pack because we do want to do the
11726 optimization below, and we don't want to substitute directly
11727 into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
11728 where it isn't expected). */
11729 unsubstituted_fn_pack = true;
11731 else if (is_normal_capture_proxy (parm_pack))
11733 arg_pack = retrieve_local_specialization (parm_pack);
11734 if (argument_pack_element_is_expansion_p (arg_pack, 0))
11735 unsubstituted_fn_pack = true;
11737 else
11739 int idx;
11740 template_parm_level_and_index (parm_pack, &level, &idx);
11742 if (level <= levels)
11743 arg_pack = TMPL_ARG (args, level, idx);
11746 orig_arg = arg_pack;
11747 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
11748 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
11750 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
11751 /* This can only happen if we forget to expand an argument
11752 pack somewhere else. Just return an error, silently. */
11754 result = make_tree_vec (1);
11755 TREE_VEC_ELT (result, 0) = error_mark_node;
11756 return result;
11759 if (arg_pack)
11761 int my_len =
11762 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
11764 /* Don't bother trying to do a partial substitution with
11765 incomplete packs; we'll try again after deduction. */
11766 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
11767 return t;
11769 if (len < 0)
11770 len = my_len;
11771 else if (len != my_len
11772 && !unsubstituted_fn_pack)
11774 if (!(complain & tf_error))
11775 /* Fail quietly. */;
11776 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
11777 error ("mismatched argument pack lengths while expanding %qT",
11778 pattern);
11779 else
11780 error ("mismatched argument pack lengths while expanding %qE",
11781 pattern);
11782 return error_mark_node;
11785 /* Keep track of the parameter packs and their corresponding
11786 argument packs. */
11787 packs = tree_cons (parm_pack, arg_pack, packs);
11788 TREE_TYPE (packs) = orig_arg;
11790 else
11792 /* We can't substitute for this parameter pack. We use a flag as
11793 well as the missing_level counter because function parameter
11794 packs don't have a level. */
11795 gcc_assert (processing_template_decl);
11796 unsubstituted_packs = true;
11800 /* If the expansion is just T..., return the matching argument pack, unless
11801 we need to call convert_from_reference on all the elements. This is an
11802 important optimization; see c++/68422. */
11803 if (!unsubstituted_packs
11804 && TREE_PURPOSE (packs) == pattern)
11806 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
11808 /* If the argument pack is a single pack expansion, pull it out. */
11809 if (TREE_VEC_LENGTH (args) == 1
11810 && pack_expansion_args_count (args))
11811 return TREE_VEC_ELT (args, 0);
11813 /* Types need no adjustment, nor does sizeof..., and if we still have
11814 some pack expansion args we won't do anything yet. */
11815 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
11816 || PACK_EXPANSION_SIZEOF_P (t)
11817 || pack_expansion_args_count (args))
11818 return args;
11819 /* Also optimize expression pack expansions if we can tell that the
11820 elements won't have reference type. */
11821 tree type = TREE_TYPE (pattern);
11822 if (type && TREE_CODE (type) != REFERENCE_TYPE
11823 && !PACK_EXPANSION_P (type)
11824 && !WILDCARD_TYPE_P (type))
11825 return args;
11826 /* Otherwise use the normal path so we get convert_from_reference. */
11829 /* We cannot expand this expansion expression, because we don't have
11830 all of the argument packs we need. */
11831 if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
11833 /* We got some full packs, but we can't substitute them in until we
11834 have values for all the packs. So remember these until then. */
11836 t = make_pack_expansion (pattern, complain);
11837 tree extra = args;
11838 if (local_specializations)
11839 if (tree locals = extract_local_specs (pattern, complain))
11840 extra = tree_cons (NULL_TREE, extra, locals);
11841 PACK_EXPANSION_EXTRA_ARGS (t) = extra;
11842 return t;
11844 else if (unsubstituted_packs)
11846 /* There were no real arguments, we're just replacing a parameter
11847 pack with another version of itself. Substitute into the
11848 pattern and return a PACK_EXPANSION_*. The caller will need to
11849 deal with that. */
11850 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
11851 t = tsubst_expr (pattern, args, complain, in_decl,
11852 /*integral_constant_expression_p=*/false);
11853 else
11854 t = tsubst (pattern, args, complain, in_decl);
11855 t = make_pack_expansion (t, complain);
11856 return t;
11859 gcc_assert (len >= 0);
11861 if (need_local_specializations)
11863 /* We're in a late-specified return type, so create our own local
11864 specializations map; the current map is either NULL or (in the
11865 case of recursive unification) might have bindings that we don't
11866 want to use or alter. */
11867 saved_local_specializations = local_specializations;
11868 local_specializations = new hash_map<tree, tree>;
11871 /* For each argument in each argument pack, substitute into the
11872 pattern. */
11873 result = make_tree_vec (len);
11874 tree elem_args = copy_template_args (args);
11875 for (i = 0; i < len; ++i)
11877 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
11879 elem_args, complain,
11880 in_decl);
11881 TREE_VEC_ELT (result, i) = t;
11882 if (t == error_mark_node)
11884 result = error_mark_node;
11885 break;
11889 /* Update ARGS to restore the substitution from parameter packs to
11890 their argument packs. */
11891 for (pack = packs; pack; pack = TREE_CHAIN (pack))
11893 tree parm = TREE_PURPOSE (pack);
11895 if (TREE_CODE (parm) == PARM_DECL
11896 || VAR_P (parm)
11897 || TREE_CODE (parm) == FIELD_DECL)
11898 register_local_specialization (TREE_TYPE (pack), parm);
11899 else
11901 int idx, level;
11903 if (TREE_VALUE (pack) == NULL_TREE)
11904 continue;
11906 template_parm_level_and_index (parm, &level, &idx);
11908 /* Update the corresponding argument. */
11909 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
11910 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
11911 TREE_TYPE (pack);
11912 else
11913 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
11917 if (need_local_specializations)
11919 delete local_specializations;
11920 local_specializations = saved_local_specializations;
11923 /* If the dependent pack arguments were such that we end up with only a
11924 single pack expansion again, there's no need to keep it in a TREE_VEC. */
11925 if (len == 1 && TREE_CODE (result) == TREE_VEC
11926 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
11927 return TREE_VEC_ELT (result, 0);
11929 return result;
11932 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
11933 TMPL. We do this using DECL_PARM_INDEX, which should work even with
11934 parameter packs; all parms generated from a function parameter pack will
11935 have the same DECL_PARM_INDEX. */
11937 tree
11938 get_pattern_parm (tree parm, tree tmpl)
11940 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
11941 tree patparm;
11943 if (DECL_ARTIFICIAL (parm))
11945 for (patparm = DECL_ARGUMENTS (pattern);
11946 patparm; patparm = DECL_CHAIN (patparm))
11947 if (DECL_ARTIFICIAL (patparm)
11948 && DECL_NAME (parm) == DECL_NAME (patparm))
11949 break;
11951 else
11953 patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
11954 patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
11955 gcc_assert (DECL_PARM_INDEX (patparm)
11956 == DECL_PARM_INDEX (parm));
11959 return patparm;
11962 /* Make an argument pack out of the TREE_VEC VEC. */
11964 static tree
11965 make_argument_pack (tree vec)
11967 tree pack;
11968 tree elt = TREE_VEC_ELT (vec, 0);
11969 if (TYPE_P (elt))
11970 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
11971 else
11973 pack = make_node (NONTYPE_ARGUMENT_PACK);
11974 TREE_CONSTANT (pack) = 1;
11976 SET_ARGUMENT_PACK_ARGS (pack, vec);
11977 return pack;
11980 /* Return an exact copy of template args T that can be modified
11981 independently. */
11983 static tree
11984 copy_template_args (tree t)
11986 if (t == error_mark_node)
11987 return t;
11989 int len = TREE_VEC_LENGTH (t);
11990 tree new_vec = make_tree_vec (len);
11992 for (int i = 0; i < len; ++i)
11994 tree elt = TREE_VEC_ELT (t, i);
11995 if (elt && TREE_CODE (elt) == TREE_VEC)
11996 elt = copy_template_args (elt);
11997 TREE_VEC_ELT (new_vec, i) = elt;
12000 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12001 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12003 return new_vec;
12006 /* Substitute ARGS into the vector or list of template arguments T. */
12008 static tree
12009 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12011 tree orig_t = t;
12012 int len, need_new = 0, i, expanded_len_adjust = 0, out;
12013 tree *elts;
12015 if (t == error_mark_node)
12016 return error_mark_node;
12018 len = TREE_VEC_LENGTH (t);
12019 elts = XALLOCAVEC (tree, len);
12021 for (i = 0; i < len; i++)
12023 tree orig_arg = TREE_VEC_ELT (t, i);
12024 tree new_arg;
12026 if (TREE_CODE (orig_arg) == TREE_VEC)
12027 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12028 else if (PACK_EXPANSION_P (orig_arg))
12030 /* Substitute into an expansion expression. */
12031 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12033 if (TREE_CODE (new_arg) == TREE_VEC)
12034 /* Add to the expanded length adjustment the number of
12035 expanded arguments. We subtract one from this
12036 measurement, because the argument pack expression
12037 itself is already counted as 1 in
12038 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12039 the argument pack is empty. */
12040 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12042 else if (ARGUMENT_PACK_P (orig_arg))
12044 /* Substitute into each of the arguments. */
12045 new_arg = TYPE_P (orig_arg)
12046 ? cxx_make_type (TREE_CODE (orig_arg))
12047 : make_node (TREE_CODE (orig_arg));
12049 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12050 args, complain, in_decl);
12051 if (pack_args == error_mark_node)
12052 new_arg = error_mark_node;
12053 else
12054 SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12056 if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12057 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12059 else
12060 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12062 if (new_arg == error_mark_node)
12063 return error_mark_node;
12065 elts[i] = new_arg;
12066 if (new_arg != orig_arg)
12067 need_new = 1;
12070 if (!need_new)
12071 return t;
12073 /* Make space for the expanded arguments coming from template
12074 argument packs. */
12075 t = make_tree_vec (len + expanded_len_adjust);
12076 /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12077 arguments for a member template.
12078 In that case each TREE_VEC in ORIG_T represents a level of template
12079 arguments, and ORIG_T won't carry any non defaulted argument count.
12080 It will rather be the nested TREE_VECs that will carry one.
12081 In other words, ORIG_T carries a non defaulted argument count only
12082 if it doesn't contain any nested TREE_VEC. */
12083 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12085 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12086 count += expanded_len_adjust;
12087 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12089 for (i = 0, out = 0; i < len; i++)
12091 if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12092 || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12093 && TREE_CODE (elts[i]) == TREE_VEC)
12095 int idx;
12097 /* Now expand the template argument pack "in place". */
12098 for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12099 TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12101 else
12103 TREE_VEC_ELT (t, out) = elts[i];
12104 out++;
12108 return t;
12111 /* Substitute ARGS into one level PARMS of template parameters. */
12113 static tree
12114 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12116 if (parms == error_mark_node)
12117 return error_mark_node;
12119 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12121 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12123 tree tuple = TREE_VEC_ELT (parms, i);
12125 if (tuple == error_mark_node)
12126 continue;
12128 TREE_VEC_ELT (new_vec, i) =
12129 tsubst_template_parm (tuple, args, complain);
12132 return new_vec;
12135 /* Return the result of substituting ARGS into the template parameters
12136 given by PARMS. If there are m levels of ARGS and m + n levels of
12137 PARMS, then the result will contain n levels of PARMS. For
12138 example, if PARMS is `template <class T> template <class U>
12139 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12140 result will be `template <int*, double, class V>'. */
12142 static tree
12143 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12145 tree r = NULL_TREE;
12146 tree* new_parms;
12148 /* When substituting into a template, we must set
12149 PROCESSING_TEMPLATE_DECL as the template parameters may be
12150 dependent if they are based on one-another, and the dependency
12151 predicates are short-circuit outside of templates. */
12152 ++processing_template_decl;
12154 for (new_parms = &r;
12155 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12156 new_parms = &(TREE_CHAIN (*new_parms)),
12157 parms = TREE_CHAIN (parms))
12159 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12160 args, complain);
12161 *new_parms =
12162 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12163 - TMPL_ARGS_DEPTH (args)),
12164 new_vec, NULL_TREE);
12167 --processing_template_decl;
12169 return r;
12172 /* Return the result of substituting ARGS into one template parameter
12173 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12174 parameter and which TREE_PURPOSE is the default argument of the
12175 template parameter. */
12177 static tree
12178 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12180 tree default_value, parm_decl;
12182 if (args == NULL_TREE
12183 || t == NULL_TREE
12184 || t == error_mark_node)
12185 return t;
12187 gcc_assert (TREE_CODE (t) == TREE_LIST);
12189 default_value = TREE_PURPOSE (t);
12190 parm_decl = TREE_VALUE (t);
12192 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12193 if (TREE_CODE (parm_decl) == PARM_DECL
12194 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12195 parm_decl = error_mark_node;
12196 default_value = tsubst_template_arg (default_value, args,
12197 complain, NULL_TREE);
12199 return build_tree_list (default_value, parm_decl);
12202 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12203 type T. If T is not an aggregate or enumeration type, it is
12204 handled as if by tsubst. IN_DECL is as for tsubst. If
12205 ENTERING_SCOPE is nonzero, T is the context for a template which
12206 we are presently tsubst'ing. Return the substituted value. */
12208 static tree
12209 tsubst_aggr_type (tree t,
12210 tree args,
12211 tsubst_flags_t complain,
12212 tree in_decl,
12213 int entering_scope)
12215 if (t == NULL_TREE)
12216 return NULL_TREE;
12218 switch (TREE_CODE (t))
12220 case RECORD_TYPE:
12221 if (TYPE_PTRMEMFUNC_P (t))
12222 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12224 /* Fall through. */
12225 case ENUMERAL_TYPE:
12226 case UNION_TYPE:
12227 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12229 tree argvec;
12230 tree context;
12231 tree r;
12232 int saved_unevaluated_operand;
12233 int saved_inhibit_evaluation_warnings;
12235 /* In "sizeof(X<I>)" we need to evaluate "I". */
12236 saved_unevaluated_operand = cp_unevaluated_operand;
12237 cp_unevaluated_operand = 0;
12238 saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12239 c_inhibit_evaluation_warnings = 0;
12241 /* First, determine the context for the type we are looking
12242 up. */
12243 context = TYPE_CONTEXT (t);
12244 if (context && TYPE_P (context))
12246 context = tsubst_aggr_type (context, args, complain,
12247 in_decl, /*entering_scope=*/1);
12248 /* If context is a nested class inside a class template,
12249 it may still need to be instantiated (c++/33959). */
12250 context = complete_type (context);
12253 /* Then, figure out what arguments are appropriate for the
12254 type we are trying to find. For example, given:
12256 template <class T> struct S;
12257 template <class T, class U> void f(T, U) { S<U> su; }
12259 and supposing that we are instantiating f<int, double>,
12260 then our ARGS will be {int, double}, but, when looking up
12261 S we only want {double}. */
12262 argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12263 complain, in_decl);
12264 if (argvec == error_mark_node)
12265 r = error_mark_node;
12266 else
12268 r = lookup_template_class (t, argvec, in_decl, context,
12269 entering_scope, complain);
12270 r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12273 cp_unevaluated_operand = saved_unevaluated_operand;
12274 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12276 return r;
12278 else
12279 /* This is not a template type, so there's nothing to do. */
12280 return t;
12282 default:
12283 return tsubst (t, args, complain, in_decl);
12287 static GTY((cache)) tree_cache_map *defarg_inst;
12289 /* Substitute into the default argument ARG (a default argument for
12290 FN), which has the indicated TYPE. */
12292 tree
12293 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12294 tsubst_flags_t complain)
12296 tree saved_class_ptr = NULL_TREE;
12297 tree saved_class_ref = NULL_TREE;
12298 int errs = errorcount + sorrycount;
12300 /* This can happen in invalid code. */
12301 if (TREE_CODE (arg) == DEFAULT_ARG)
12302 return arg;
12304 tree parm = FUNCTION_FIRST_USER_PARM (fn);
12305 parm = chain_index (parmnum, parm);
12306 tree parmtype = TREE_TYPE (parm);
12307 if (DECL_BY_REFERENCE (parm))
12308 parmtype = TREE_TYPE (parmtype);
12309 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12311 tree *slot;
12312 if (defarg_inst && (slot = defarg_inst->get (parm)))
12313 return *slot;
12315 /* This default argument came from a template. Instantiate the
12316 default argument here, not in tsubst. In the case of
12317 something like:
12319 template <class T>
12320 struct S {
12321 static T t();
12322 void f(T = t());
12325 we must be careful to do name lookup in the scope of S<T>,
12326 rather than in the current class. */
12327 push_access_scope (fn);
12328 /* The "this" pointer is not valid in a default argument. */
12329 if (cfun)
12331 saved_class_ptr = current_class_ptr;
12332 cp_function_chain->x_current_class_ptr = NULL_TREE;
12333 saved_class_ref = current_class_ref;
12334 cp_function_chain->x_current_class_ref = NULL_TREE;
12337 start_lambda_scope (parm);
12339 push_deferring_access_checks(dk_no_deferred);
12340 /* The default argument expression may cause implicitly defined
12341 member functions to be synthesized, which will result in garbage
12342 collection. We must treat this situation as if we were within
12343 the body of function so as to avoid collecting live data on the
12344 stack. */
12345 ++function_depth;
12346 arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12347 complain, NULL_TREE,
12348 /*integral_constant_expression_p=*/false);
12349 --function_depth;
12350 pop_deferring_access_checks();
12352 finish_lambda_scope ();
12354 /* Restore the "this" pointer. */
12355 if (cfun)
12357 cp_function_chain->x_current_class_ptr = saved_class_ptr;
12358 cp_function_chain->x_current_class_ref = saved_class_ref;
12361 if (errorcount+sorrycount > errs
12362 && (complain & tf_warning_or_error))
12363 inform (input_location,
12364 " when instantiating default argument for call to %qD", fn);
12366 /* Make sure the default argument is reasonable. */
12367 arg = check_default_argument (type, arg, complain);
12369 pop_access_scope (fn);
12371 if (arg != error_mark_node && !cp_unevaluated_operand)
12373 if (!defarg_inst)
12374 defarg_inst = tree_cache_map::create_ggc (37);
12375 defarg_inst->put (parm, arg);
12378 return arg;
12381 /* Substitute into all the default arguments for FN. */
12383 static void
12384 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12386 tree arg;
12387 tree tmpl_args;
12389 tmpl_args = DECL_TI_ARGS (fn);
12391 /* If this function is not yet instantiated, we certainly don't need
12392 its default arguments. */
12393 if (uses_template_parms (tmpl_args))
12394 return;
12395 /* Don't do this again for clones. */
12396 if (DECL_CLONED_FUNCTION_P (fn))
12397 return;
12399 int i = 0;
12400 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12401 arg;
12402 arg = TREE_CHAIN (arg), ++i)
12403 if (TREE_PURPOSE (arg))
12404 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12405 TREE_VALUE (arg),
12406 TREE_PURPOSE (arg),
12407 complain);
12410 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
12412 static tree
12413 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12414 tree lambda_fntype)
12416 tree gen_tmpl, argvec;
12417 hashval_t hash = 0;
12418 tree in_decl = t;
12420 /* Nobody should be tsubst'ing into non-template functions. */
12421 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12423 if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12425 /* If T is not dependent, just return it. */
12426 if (!uses_template_parms (DECL_TI_ARGS (t)))
12427 return t;
12429 /* Calculate the most general template of which R is a
12430 specialization. */
12431 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12433 /* We're substituting a lambda function under tsubst_lambda_expr but not
12434 directly from it; find the matching function we're already inside.
12435 But don't do this if T is a generic lambda with a single level of
12436 template parms, as in that case we're doing a normal instantiation. */
12437 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12438 && (!generic_lambda_fn_p (t)
12439 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12440 return enclosing_instantiation_of (t);
12442 /* Calculate the complete set of arguments used to
12443 specialize R. */
12444 argvec = tsubst_template_args (DECL_TI_ARGS
12445 (DECL_TEMPLATE_RESULT
12446 (DECL_TI_TEMPLATE (t))),
12447 args, complain, in_decl);
12448 if (argvec == error_mark_node)
12449 return error_mark_node;
12451 /* Check to see if we already have this specialization. */
12452 if (!lambda_fntype)
12454 hash = hash_tmpl_and_args (gen_tmpl, argvec);
12455 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12456 return spec;
12459 /* We can see more levels of arguments than parameters if
12460 there was a specialization of a member template, like
12461 this:
12463 template <class T> struct S { template <class U> void f(); }
12464 template <> template <class U> void S<int>::f(U);
12466 Here, we'll be substituting into the specialization,
12467 because that's where we can find the code we actually
12468 want to generate, but we'll have enough arguments for
12469 the most general template.
12471 We also deal with the peculiar case:
12473 template <class T> struct S {
12474 template <class U> friend void f();
12476 template <class U> void f() {}
12477 template S<int>;
12478 template void f<double>();
12480 Here, the ARGS for the instantiation of will be {int,
12481 double}. But, we only need as many ARGS as there are
12482 levels of template parameters in CODE_PATTERN. We are
12483 careful not to get fooled into reducing the ARGS in
12484 situations like:
12486 template <class T> struct S { template <class U> void f(U); }
12487 template <class T> template <> void S<T>::f(int) {}
12489 which we can spot because the pattern will be a
12490 specialization in this case. */
12491 int args_depth = TMPL_ARGS_DEPTH (args);
12492 int parms_depth =
12493 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
12495 if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
12496 args = get_innermost_template_args (args, parms_depth);
12498 else
12500 /* This special case arises when we have something like this:
12502 template <class T> struct S {
12503 friend void f<int>(int, double);
12506 Here, the DECL_TI_TEMPLATE for the friend declaration
12507 will be an IDENTIFIER_NODE. We are being called from
12508 tsubst_friend_function, and we want only to create a
12509 new decl (R) with appropriate types so that we can call
12510 determine_specialization. */
12511 gen_tmpl = NULL_TREE;
12512 argvec = NULL_TREE;
12515 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
12516 : NULL_TREE);
12517 tree ctx = closure ? closure : DECL_CONTEXT (t);
12518 bool member = ctx && TYPE_P (ctx);
12520 if (member && !closure)
12521 ctx = tsubst_aggr_type (ctx, args,
12522 complain, t, /*entering_scope=*/1);
12524 tree type = (lambda_fntype ? lambda_fntype
12525 : tsubst (TREE_TYPE (t), args,
12526 complain | tf_fndecl_type, in_decl));
12527 if (type == error_mark_node)
12528 return error_mark_node;
12530 /* If we hit excessive deduction depth, the type is bogus even if
12531 it isn't error_mark_node, so don't build a decl. */
12532 if (excessive_deduction_depth)
12533 return error_mark_node;
12535 /* We do NOT check for matching decls pushed separately at this
12536 point, as they may not represent instantiations of this
12537 template, and in any case are considered separate under the
12538 discrete model. */
12539 tree r = copy_decl (t);
12540 DECL_USE_TEMPLATE (r) = 0;
12541 TREE_TYPE (r) = type;
12542 /* Clear out the mangled name and RTL for the instantiation. */
12543 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12544 SET_DECL_RTL (r, NULL);
12545 /* Leave DECL_INITIAL set on deleted instantiations. */
12546 if (!DECL_DELETED_FN (r))
12547 DECL_INITIAL (r) = NULL_TREE;
12548 DECL_CONTEXT (r) = ctx;
12550 /* OpenMP UDRs have the only argument a reference to the declared
12551 type. We want to diagnose if the declared type is a reference,
12552 which is invalid, but as references to references are usually
12553 quietly merged, diagnose it here. */
12554 if (DECL_OMP_DECLARE_REDUCTION_P (t))
12556 tree argtype
12557 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
12558 argtype = tsubst (argtype, args, complain, in_decl);
12559 if (TREE_CODE (argtype) == REFERENCE_TYPE)
12560 error_at (DECL_SOURCE_LOCATION (t),
12561 "reference type %qT in "
12562 "%<#pragma omp declare reduction%>", argtype);
12563 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
12564 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
12565 argtype);
12568 if (member && DECL_CONV_FN_P (r))
12569 /* Type-conversion operator. Reconstruct the name, in
12570 case it's the name of one of the template's parameters. */
12571 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
12573 tree parms = DECL_ARGUMENTS (t);
12574 if (closure)
12575 parms = DECL_CHAIN (parms);
12576 parms = tsubst (parms, args, complain, t);
12577 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
12578 DECL_CONTEXT (parm) = r;
12579 if (closure)
12581 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
12582 DECL_CHAIN (tparm) = parms;
12583 parms = tparm;
12585 DECL_ARGUMENTS (r) = parms;
12586 DECL_RESULT (r) = NULL_TREE;
12588 TREE_STATIC (r) = 0;
12589 TREE_PUBLIC (r) = TREE_PUBLIC (t);
12590 DECL_EXTERNAL (r) = 1;
12591 /* If this is an instantiation of a function with internal
12592 linkage, we already know what object file linkage will be
12593 assigned to the instantiation. */
12594 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
12595 DECL_DEFER_OUTPUT (r) = 0;
12596 DECL_CHAIN (r) = NULL_TREE;
12597 DECL_PENDING_INLINE_INFO (r) = 0;
12598 DECL_PENDING_INLINE_P (r) = 0;
12599 DECL_SAVED_TREE (r) = NULL_TREE;
12600 DECL_STRUCT_FUNCTION (r) = NULL;
12601 TREE_USED (r) = 0;
12602 /* We'll re-clone as appropriate in instantiate_template. */
12603 DECL_CLONED_FUNCTION (r) = NULL_TREE;
12605 /* If we aren't complaining now, return on error before we register
12606 the specialization so that we'll complain eventually. */
12607 if ((complain & tf_error) == 0
12608 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
12609 && !grok_op_properties (r, /*complain=*/false))
12610 return error_mark_node;
12612 /* When instantiating a constrained member, substitute
12613 into the constraints to create a new constraint. */
12614 if (tree ci = get_constraints (t))
12615 if (member)
12617 ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
12618 set_constraints (r, ci);
12621 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
12622 this in the special friend case mentioned above where
12623 GEN_TMPL is NULL. */
12624 if (gen_tmpl && !closure)
12626 DECL_TEMPLATE_INFO (r)
12627 = build_template_info (gen_tmpl, argvec);
12628 SET_DECL_IMPLICIT_INSTANTIATION (r);
12630 tree new_r
12631 = register_specialization (r, gen_tmpl, argvec, false, hash);
12632 if (new_r != r)
12633 /* We instantiated this while substituting into
12634 the type earlier (template/friend54.C). */
12635 return new_r;
12637 /* We're not supposed to instantiate default arguments
12638 until they are called, for a template. But, for a
12639 declaration like:
12641 template <class T> void f ()
12642 { extern void g(int i = T()); }
12644 we should do the substitution when the template is
12645 instantiated. We handle the member function case in
12646 instantiate_class_template since the default arguments
12647 might refer to other members of the class. */
12648 if (!member
12649 && !PRIMARY_TEMPLATE_P (gen_tmpl)
12650 && !uses_template_parms (argvec))
12651 tsubst_default_arguments (r, complain);
12653 else
12654 DECL_TEMPLATE_INFO (r) = NULL_TREE;
12656 /* Copy the list of befriending classes. */
12657 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
12658 *friends;
12659 friends = &TREE_CHAIN (*friends))
12661 *friends = copy_node (*friends);
12662 TREE_VALUE (*friends)
12663 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
12666 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
12668 maybe_retrofit_in_chrg (r);
12669 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
12670 return error_mark_node;
12671 /* If this is an instantiation of a member template, clone it.
12672 If it isn't, that'll be handled by
12673 clone_constructors_and_destructors. */
12674 if (PRIMARY_TEMPLATE_P (gen_tmpl))
12675 clone_function_decl (r, /*update_methods=*/false);
12677 else if ((complain & tf_error) != 0
12678 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
12679 && !grok_op_properties (r, /*complain=*/true))
12680 return error_mark_node;
12682 if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
12683 SET_DECL_FRIEND_CONTEXT (r,
12684 tsubst (DECL_FRIEND_CONTEXT (t),
12685 args, complain, in_decl));
12687 /* Possibly limit visibility based on template args. */
12688 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
12689 if (DECL_VISIBILITY_SPECIFIED (t))
12691 DECL_VISIBILITY_SPECIFIED (r) = 0;
12692 DECL_ATTRIBUTES (r)
12693 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
12695 determine_visibility (r);
12696 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
12697 && !processing_template_decl)
12698 defaulted_late_check (r);
12700 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
12701 args, complain, in_decl);
12702 return r;
12705 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
12707 static tree
12708 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
12709 tree lambda_fntype)
12711 /* We can get here when processing a member function template,
12712 member class template, or template template parameter. */
12713 tree decl = DECL_TEMPLATE_RESULT (t);
12714 tree in_decl = t;
12715 tree spec;
12716 tree tmpl_args;
12717 tree full_args;
12718 tree r;
12719 hashval_t hash = 0;
12721 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12723 /* Template template parameter is treated here. */
12724 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12725 if (new_type == error_mark_node)
12726 r = error_mark_node;
12727 /* If we get a real template back, return it. This can happen in
12728 the context of most_specialized_partial_spec. */
12729 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
12730 r = new_type;
12731 else
12732 /* The new TEMPLATE_DECL was built in
12733 reduce_template_parm_level. */
12734 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
12735 return r;
12738 if (!lambda_fntype)
12740 /* We might already have an instance of this template.
12741 The ARGS are for the surrounding class type, so the
12742 full args contain the tsubst'd args for the context,
12743 plus the innermost args from the template decl. */
12744 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
12745 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
12746 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
12747 /* Because this is a template, the arguments will still be
12748 dependent, even after substitution. If
12749 PROCESSING_TEMPLATE_DECL is not set, the dependency
12750 predicates will short-circuit. */
12751 ++processing_template_decl;
12752 full_args = tsubst_template_args (tmpl_args, args,
12753 complain, in_decl);
12754 --processing_template_decl;
12755 if (full_args == error_mark_node)
12756 return error_mark_node;
12758 /* If this is a default template template argument,
12759 tsubst might not have changed anything. */
12760 if (full_args == tmpl_args)
12761 return t;
12763 hash = hash_tmpl_and_args (t, full_args);
12764 spec = retrieve_specialization (t, full_args, hash);
12765 if (spec != NULL_TREE)
12766 return spec;
12769 /* Make a new template decl. It will be similar to the
12770 original, but will record the current template arguments.
12771 We also create a new function declaration, which is just
12772 like the old one, but points to this new template, rather
12773 than the old one. */
12774 r = copy_decl (t);
12775 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
12776 DECL_CHAIN (r) = NULL_TREE;
12778 // Build new template info linking to the original template decl.
12779 if (!lambda_fntype)
12781 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
12782 SET_DECL_IMPLICIT_INSTANTIATION (r);
12784 else
12785 DECL_TEMPLATE_INFO (r) = NULL_TREE;
12787 /* The template parameters for this new template are all the
12788 template parameters for the old template, except the
12789 outermost level of parameters. */
12790 DECL_TEMPLATE_PARMS (r)
12791 = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
12792 complain);
12794 if (TREE_CODE (decl) == TYPE_DECL
12795 && !TYPE_DECL_ALIAS_P (decl))
12797 tree new_type;
12798 ++processing_template_decl;
12799 new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12800 --processing_template_decl;
12801 if (new_type == error_mark_node)
12802 return error_mark_node;
12804 TREE_TYPE (r) = new_type;
12805 /* For a partial specialization, we need to keep pointing to
12806 the primary template. */
12807 if (!DECL_TEMPLATE_SPECIALIZATION (t))
12808 CLASSTYPE_TI_TEMPLATE (new_type) = r;
12809 DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
12810 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
12811 DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
12813 else
12815 tree new_decl;
12816 ++processing_template_decl;
12817 if (TREE_CODE (decl) == FUNCTION_DECL)
12818 new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
12819 else
12820 new_decl = tsubst (decl, args, complain, in_decl);
12821 --processing_template_decl;
12822 if (new_decl == error_mark_node)
12823 return error_mark_node;
12825 DECL_TEMPLATE_RESULT (r) = new_decl;
12826 TREE_TYPE (r) = TREE_TYPE (new_decl);
12827 DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
12828 if (lambda_fntype)
12830 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
12831 DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
12833 else
12835 DECL_TI_TEMPLATE (new_decl) = r;
12836 DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
12840 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
12841 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
12843 if (PRIMARY_TEMPLATE_P (t))
12844 DECL_PRIMARY_TEMPLATE (r) = r;
12846 if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
12847 && !lambda_fntype)
12848 /* Record this non-type partial instantiation. */
12849 register_specialization (r, t,
12850 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
12851 false, hash);
12853 return r;
12856 /* True if FN is the op() for a lambda in an uninstantiated template. */
12858 bool
12859 lambda_fn_in_template_p (tree fn)
12861 if (!fn || !LAMBDA_FUNCTION_P (fn))
12862 return false;
12863 tree closure = DECL_CONTEXT (fn);
12864 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
12867 /* We're instantiating a variable from template function TCTX. Return the
12868 corresponding current enclosing scope. This gets complicated because lambda
12869 functions in templates are regenerated rather than instantiated, but generic
12870 lambda functions are subsequently instantiated. */
12872 static tree
12873 enclosing_instantiation_of (tree otctx)
12875 tree tctx = otctx;
12876 tree fn = current_function_decl;
12877 int lambda_count = 0;
12879 for (; tctx && lambda_fn_in_template_p (tctx);
12880 tctx = decl_function_context (tctx))
12881 ++lambda_count;
12882 for (; fn; fn = decl_function_context (fn))
12884 tree ofn = fn;
12885 int flambda_count = 0;
12886 for (; flambda_count < lambda_count && fn && LAMBDA_FUNCTION_P (fn);
12887 fn = decl_function_context (fn))
12888 ++flambda_count;
12889 if (DECL_TEMPLATE_INFO (fn)
12890 ? most_general_template (fn) != most_general_template (tctx)
12891 : fn != tctx)
12892 continue;
12893 gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
12894 || DECL_CONV_FN_P (ofn));
12895 return ofn;
12897 gcc_unreachable ();
12900 /* Substitute the ARGS into the T, which is a _DECL. Return the
12901 result of the substitution. Issue error and warning messages under
12902 control of COMPLAIN. */
12904 static tree
12905 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
12907 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
12908 location_t saved_loc;
12909 tree r = NULL_TREE;
12910 tree in_decl = t;
12911 hashval_t hash = 0;
12913 /* Set the filename and linenumber to improve error-reporting. */
12914 saved_loc = input_location;
12915 input_location = DECL_SOURCE_LOCATION (t);
12917 switch (TREE_CODE (t))
12919 case TEMPLATE_DECL:
12920 r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
12921 break;
12923 case FUNCTION_DECL:
12924 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
12925 break;
12927 case PARM_DECL:
12929 tree type = NULL_TREE;
12930 int i, len = 1;
12931 tree expanded_types = NULL_TREE;
12932 tree prev_r = NULL_TREE;
12933 tree first_r = NULL_TREE;
12935 if (DECL_PACK_P (t))
12937 /* If there is a local specialization that isn't a
12938 parameter pack, it means that we're doing a "simple"
12939 substitution from inside tsubst_pack_expansion. Just
12940 return the local specialization (which will be a single
12941 parm). */
12942 tree spec = retrieve_local_specialization (t);
12943 if (spec
12944 && TREE_CODE (spec) == PARM_DECL
12945 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
12946 RETURN (spec);
12948 /* Expand the TYPE_PACK_EXPANSION that provides the types for
12949 the parameters in this function parameter pack. */
12950 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
12951 complain, in_decl);
12952 if (TREE_CODE (expanded_types) == TREE_VEC)
12954 len = TREE_VEC_LENGTH (expanded_types);
12956 /* Zero-length parameter packs are boring. Just substitute
12957 into the chain. */
12958 if (len == 0)
12959 RETURN (tsubst (TREE_CHAIN (t), args, complain,
12960 TREE_CHAIN (t)));
12962 else
12964 /* All we did was update the type. Make a note of that. */
12965 type = expanded_types;
12966 expanded_types = NULL_TREE;
12970 /* Loop through all of the parameters we'll build. When T is
12971 a function parameter pack, LEN is the number of expanded
12972 types in EXPANDED_TYPES; otherwise, LEN is 1. */
12973 r = NULL_TREE;
12974 for (i = 0; i < len; ++i)
12976 prev_r = r;
12977 r = copy_node (t);
12978 if (DECL_TEMPLATE_PARM_P (t))
12979 SET_DECL_TEMPLATE_PARM_P (r);
12981 if (expanded_types)
12982 /* We're on the Ith parameter of the function parameter
12983 pack. */
12985 /* Get the Ith type. */
12986 type = TREE_VEC_ELT (expanded_types, i);
12988 /* Rename the parameter to include the index. */
12989 DECL_NAME (r)
12990 = make_ith_pack_parameter_name (DECL_NAME (r), i);
12992 else if (!type)
12993 /* We're dealing with a normal parameter. */
12994 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12996 type = type_decays_to (type);
12997 TREE_TYPE (r) = type;
12998 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13000 if (DECL_INITIAL (r))
13002 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13003 DECL_INITIAL (r) = TREE_TYPE (r);
13004 else
13005 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13006 complain, in_decl);
13009 DECL_CONTEXT (r) = NULL_TREE;
13011 if (!DECL_TEMPLATE_PARM_P (r))
13012 DECL_ARG_TYPE (r) = type_passed_as (type);
13014 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13015 args, complain, in_decl);
13017 /* Keep track of the first new parameter we
13018 generate. That's what will be returned to the
13019 caller. */
13020 if (!first_r)
13021 first_r = r;
13023 /* Build a proper chain of parameters when substituting
13024 into a function parameter pack. */
13025 if (prev_r)
13026 DECL_CHAIN (prev_r) = r;
13029 /* If cp_unevaluated_operand is set, we're just looking for a
13030 single dummy parameter, so don't keep going. */
13031 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13032 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13033 complain, DECL_CHAIN (t));
13035 /* FIRST_R contains the start of the chain we've built. */
13036 r = first_r;
13038 break;
13040 case FIELD_DECL:
13042 tree type = NULL_TREE;
13043 tree vec = NULL_TREE;
13044 tree expanded_types = NULL_TREE;
13045 int len = 1;
13047 if (PACK_EXPANSION_P (TREE_TYPE (t)))
13049 /* This field is a lambda capture pack. Return a TREE_VEC of
13050 the expanded fields to instantiate_class_template_1. */
13051 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13052 complain, in_decl);
13053 if (TREE_CODE (expanded_types) == TREE_VEC)
13055 len = TREE_VEC_LENGTH (expanded_types);
13056 vec = make_tree_vec (len);
13058 else
13060 /* All we did was update the type. Make a note of that. */
13061 type = expanded_types;
13062 expanded_types = NULL_TREE;
13066 for (int i = 0; i < len; ++i)
13068 r = copy_decl (t);
13069 if (expanded_types)
13071 type = TREE_VEC_ELT (expanded_types, i);
13072 DECL_NAME (r)
13073 = make_ith_pack_parameter_name (DECL_NAME (r), i);
13075 else if (!type)
13076 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13078 if (type == error_mark_node)
13079 RETURN (error_mark_node);
13080 TREE_TYPE (r) = type;
13081 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13083 if (DECL_C_BIT_FIELD (r))
13084 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13085 number of bits. */
13086 DECL_BIT_FIELD_REPRESENTATIVE (r)
13087 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13088 complain, in_decl,
13089 /*integral_constant_expression_p=*/true);
13090 if (DECL_INITIAL (t))
13092 /* Set up DECL_TEMPLATE_INFO so that we can get at the
13093 NSDMI in perform_member_init. Still set DECL_INITIAL
13094 so that we know there is one. */
13095 DECL_INITIAL (r) = void_node;
13096 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13097 retrofit_lang_decl (r);
13098 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13100 /* We don't have to set DECL_CONTEXT here; it is set by
13101 finish_member_declaration. */
13102 DECL_CHAIN (r) = NULL_TREE;
13104 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13105 args, complain, in_decl);
13107 if (vec)
13108 TREE_VEC_ELT (vec, i) = r;
13111 if (vec)
13112 r = vec;
13114 break;
13116 case USING_DECL:
13117 /* We reach here only for member using decls. We also need to check
13118 uses_template_parms because DECL_DEPENDENT_P is not set for a
13119 using-declaration that designates a member of the current
13120 instantiation (c++/53549). */
13121 if (DECL_DEPENDENT_P (t)
13122 || uses_template_parms (USING_DECL_SCOPE (t)))
13124 tree scope = USING_DECL_SCOPE (t);
13125 tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13126 if (PACK_EXPANSION_P (scope))
13128 tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13129 int len = TREE_VEC_LENGTH (vec);
13130 r = make_tree_vec (len);
13131 for (int i = 0; i < len; ++i)
13133 tree escope = TREE_VEC_ELT (vec, i);
13134 tree elt = do_class_using_decl (escope, name);
13135 if (!elt)
13137 r = error_mark_node;
13138 break;
13140 else
13142 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13143 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13145 TREE_VEC_ELT (r, i) = elt;
13148 else
13150 tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13151 complain, in_decl);
13152 r = do_class_using_decl (inst_scope, name);
13153 if (!r)
13154 r = error_mark_node;
13155 else
13157 TREE_PROTECTED (r) = TREE_PROTECTED (t);
13158 TREE_PRIVATE (r) = TREE_PRIVATE (t);
13162 else
13164 r = copy_node (t);
13165 DECL_CHAIN (r) = NULL_TREE;
13167 break;
13169 case TYPE_DECL:
13170 case VAR_DECL:
13172 tree argvec = NULL_TREE;
13173 tree gen_tmpl = NULL_TREE;
13174 tree spec;
13175 tree tmpl = NULL_TREE;
13176 tree ctx;
13177 tree type = NULL_TREE;
13178 bool local_p;
13180 if (TREE_TYPE (t) == error_mark_node)
13181 RETURN (error_mark_node);
13183 if (TREE_CODE (t) == TYPE_DECL
13184 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13186 /* If this is the canonical decl, we don't have to
13187 mess with instantiations, and often we can't (for
13188 typename, template type parms and such). Note that
13189 TYPE_NAME is not correct for the above test if
13190 we've copied the type for a typedef. */
13191 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13192 if (type == error_mark_node)
13193 RETURN (error_mark_node);
13194 r = TYPE_NAME (type);
13195 break;
13198 /* Check to see if we already have the specialization we
13199 need. */
13200 spec = NULL_TREE;
13201 if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13203 /* T is a static data member or namespace-scope entity.
13204 We have to substitute into namespace-scope variables
13205 (not just variable templates) because of cases like:
13207 template <class T> void f() { extern T t; }
13209 where the entity referenced is not known until
13210 instantiation time. */
13211 local_p = false;
13212 ctx = DECL_CONTEXT (t);
13213 if (DECL_CLASS_SCOPE_P (t))
13215 ctx = tsubst_aggr_type (ctx, args,
13216 complain,
13217 in_decl, /*entering_scope=*/1);
13218 /* If CTX is unchanged, then T is in fact the
13219 specialization we want. That situation occurs when
13220 referencing a static data member within in its own
13221 class. We can use pointer equality, rather than
13222 same_type_p, because DECL_CONTEXT is always
13223 canonical... */
13224 if (ctx == DECL_CONTEXT (t)
13225 /* ... unless T is a member template; in which
13226 case our caller can be willing to create a
13227 specialization of that template represented
13228 by T. */
13229 && !(DECL_TI_TEMPLATE (t)
13230 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13231 spec = t;
13234 if (!spec)
13236 tmpl = DECL_TI_TEMPLATE (t);
13237 gen_tmpl = most_general_template (tmpl);
13238 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13239 if (argvec != error_mark_node)
13240 argvec = (coerce_innermost_template_parms
13241 (DECL_TEMPLATE_PARMS (gen_tmpl),
13242 argvec, t, complain,
13243 /*all*/true, /*defarg*/true));
13244 if (argvec == error_mark_node)
13245 RETURN (error_mark_node);
13246 hash = hash_tmpl_and_args (gen_tmpl, argvec);
13247 spec = retrieve_specialization (gen_tmpl, argvec, hash);
13250 else
13252 /* A local variable. */
13253 local_p = true;
13254 /* Subsequent calls to pushdecl will fill this in. */
13255 ctx = NULL_TREE;
13256 /* Unless this is a reference to a static variable from an
13257 enclosing function, in which case we need to fill it in now. */
13258 if (TREE_STATIC (t))
13260 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13261 if (fn != current_function_decl)
13262 ctx = fn;
13264 spec = retrieve_local_specialization (t);
13266 /* If we already have the specialization we need, there is
13267 nothing more to do. */
13268 if (spec)
13270 r = spec;
13271 break;
13274 /* Create a new node for the specialization we need. */
13275 r = copy_decl (t);
13276 if (type == NULL_TREE)
13278 if (is_typedef_decl (t))
13279 type = DECL_ORIGINAL_TYPE (t);
13280 else
13281 type = TREE_TYPE (t);
13282 if (VAR_P (t)
13283 && VAR_HAD_UNKNOWN_BOUND (t)
13284 && type != error_mark_node)
13285 type = strip_array_domain (type);
13286 tree sub_args = args;
13287 if (tree auto_node = type_uses_auto (type))
13289 /* Mask off any template args past the variable's context so we
13290 don't replace the auto with an unrelated argument. */
13291 int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13292 int extra = TMPL_ARGS_DEPTH (args) - nouter;
13293 if (extra > 0)
13294 /* This should never happen with the new lambda instantiation
13295 model, but keep the handling just in case. */
13296 gcc_assert (!CHECKING_P),
13297 sub_args = strip_innermost_template_args (args, extra);
13299 type = tsubst (type, sub_args, complain, in_decl);
13301 if (VAR_P (r))
13303 /* Even if the original location is out of scope, the
13304 newly substituted one is not. */
13305 DECL_DEAD_FOR_LOCAL (r) = 0;
13306 DECL_INITIALIZED_P (r) = 0;
13307 DECL_TEMPLATE_INSTANTIATED (r) = 0;
13308 if (type == error_mark_node)
13309 RETURN (error_mark_node);
13310 if (TREE_CODE (type) == FUNCTION_TYPE)
13312 /* It may seem that this case cannot occur, since:
13314 typedef void f();
13315 void g() { f x; }
13317 declares a function, not a variable. However:
13319 typedef void f();
13320 template <typename T> void g() { T t; }
13321 template void g<f>();
13323 is an attempt to declare a variable with function
13324 type. */
13325 error ("variable %qD has function type",
13326 /* R is not yet sufficiently initialized, so we
13327 just use its name. */
13328 DECL_NAME (r));
13329 RETURN (error_mark_node);
13331 type = complete_type (type);
13332 /* Wait until cp_finish_decl to set this again, to handle
13333 circular dependency (template/instantiate6.C). */
13334 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13335 type = check_var_type (DECL_NAME (r), type);
13337 if (DECL_HAS_VALUE_EXPR_P (t))
13339 tree ve = DECL_VALUE_EXPR (t);
13340 ve = tsubst_expr (ve, args, complain, in_decl,
13341 /*constant_expression_p=*/false);
13342 if (REFERENCE_REF_P (ve))
13344 gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
13345 ve = TREE_OPERAND (ve, 0);
13347 SET_DECL_VALUE_EXPR (r, ve);
13349 if (CP_DECL_THREAD_LOCAL_P (r)
13350 && !processing_template_decl)
13351 set_decl_tls_model (r, decl_default_tls_model (r));
13353 else if (DECL_SELF_REFERENCE_P (t))
13354 SET_DECL_SELF_REFERENCE_P (r);
13355 TREE_TYPE (r) = type;
13356 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13357 DECL_CONTEXT (r) = ctx;
13358 /* Clear out the mangled name and RTL for the instantiation. */
13359 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13360 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13361 SET_DECL_RTL (r, NULL);
13362 /* The initializer must not be expanded until it is required;
13363 see [temp.inst]. */
13364 DECL_INITIAL (r) = NULL_TREE;
13365 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13366 if (VAR_P (r))
13368 if (DECL_LANG_SPECIFIC (r))
13369 SET_DECL_DEPENDENT_INIT_P (r, false);
13371 SET_DECL_MODE (r, VOIDmode);
13373 /* Possibly limit visibility based on template args. */
13374 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13375 if (DECL_VISIBILITY_SPECIFIED (t))
13377 DECL_VISIBILITY_SPECIFIED (r) = 0;
13378 DECL_ATTRIBUTES (r)
13379 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13381 determine_visibility (r);
13384 if (!local_p)
13386 /* A static data member declaration is always marked
13387 external when it is declared in-class, even if an
13388 initializer is present. We mimic the non-template
13389 processing here. */
13390 DECL_EXTERNAL (r) = 1;
13391 if (DECL_NAMESPACE_SCOPE_P (t))
13392 DECL_NOT_REALLY_EXTERN (r) = 1;
13394 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13395 SET_DECL_IMPLICIT_INSTANTIATION (r);
13396 register_specialization (r, gen_tmpl, argvec, false, hash);
13398 else
13400 if (DECL_LANG_SPECIFIC (r))
13401 DECL_TEMPLATE_INFO (r) = NULL_TREE;
13402 if (!cp_unevaluated_operand)
13403 register_local_specialization (r, t);
13406 DECL_CHAIN (r) = NULL_TREE;
13408 apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13409 /*flags=*/0,
13410 args, complain, in_decl);
13412 /* Preserve a typedef that names a type. */
13413 if (is_typedef_decl (r) && type != error_mark_node)
13415 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13416 set_underlying_type (r);
13417 if (TYPE_DECL_ALIAS_P (r))
13418 /* An alias template specialization can be dependent
13419 even if its underlying type is not. */
13420 TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13423 layout_decl (r, 0);
13425 break;
13427 default:
13428 gcc_unreachable ();
13430 #undef RETURN
13432 out:
13433 /* Restore the file and line information. */
13434 input_location = saved_loc;
13436 return r;
13439 /* Substitute into the ARG_TYPES of a function type.
13440 If END is a TREE_CHAIN, leave it and any following types
13441 un-substituted. */
13443 static tree
13444 tsubst_arg_types (tree arg_types,
13445 tree args,
13446 tree end,
13447 tsubst_flags_t complain,
13448 tree in_decl)
13450 tree remaining_arg_types;
13451 tree type = NULL_TREE;
13452 int i = 1;
13453 tree expanded_args = NULL_TREE;
13454 tree default_arg;
13456 if (!arg_types || arg_types == void_list_node || arg_types == end)
13457 return arg_types;
13459 remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
13460 args, end, complain, in_decl);
13461 if (remaining_arg_types == error_mark_node)
13462 return error_mark_node;
13464 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
13466 /* For a pack expansion, perform substitution on the
13467 entire expression. Later on, we'll handle the arguments
13468 one-by-one. */
13469 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
13470 args, complain, in_decl);
13472 if (TREE_CODE (expanded_args) == TREE_VEC)
13473 /* So that we'll spin through the parameters, one by one. */
13474 i = TREE_VEC_LENGTH (expanded_args);
13475 else
13477 /* We only partially substituted into the parameter
13478 pack. Our type is TYPE_PACK_EXPANSION. */
13479 type = expanded_args;
13480 expanded_args = NULL_TREE;
13484 while (i > 0) {
13485 --i;
13487 if (expanded_args)
13488 type = TREE_VEC_ELT (expanded_args, i);
13489 else if (!type)
13490 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
13492 if (type == error_mark_node)
13493 return error_mark_node;
13494 if (VOID_TYPE_P (type))
13496 if (complain & tf_error)
13498 error ("invalid parameter type %qT", type);
13499 if (in_decl)
13500 error ("in declaration %q+D", in_decl);
13502 return error_mark_node;
13504 /* DR 657. */
13505 if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
13506 return error_mark_node;
13508 /* Do array-to-pointer, function-to-pointer conversion, and ignore
13509 top-level qualifiers as required. */
13510 type = cv_unqualified (type_decays_to (type));
13512 /* We do not substitute into default arguments here. The standard
13513 mandates that they be instantiated only when needed, which is
13514 done in build_over_call. */
13515 default_arg = TREE_PURPOSE (arg_types);
13517 /* Except that we do substitute default arguments under tsubst_lambda_expr,
13518 since the new op() won't have any associated template arguments for us
13519 to refer to later. */
13520 if (lambda_fn_in_template_p (in_decl))
13521 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
13522 false/*fn*/, false/*constexpr*/);
13524 if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
13526 /* We've instantiated a template before its default arguments
13527 have been parsed. This can happen for a nested template
13528 class, and is not an error unless we require the default
13529 argument in a call of this function. */
13530 remaining_arg_types =
13531 tree_cons (default_arg, type, remaining_arg_types);
13532 vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
13534 else
13535 remaining_arg_types =
13536 hash_tree_cons (default_arg, type, remaining_arg_types);
13539 return remaining_arg_types;
13542 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
13543 *not* handle the exception-specification for FNTYPE, because the
13544 initial substitution of explicitly provided template parameters
13545 during argument deduction forbids substitution into the
13546 exception-specification:
13548 [temp.deduct]
13550 All references in the function type of the function template to the
13551 corresponding template parameters are replaced by the specified tem-
13552 plate argument values. If a substitution in a template parameter or
13553 in the function type of the function template results in an invalid
13554 type, type deduction fails. [Note: The equivalent substitution in
13555 exception specifications is done only when the function is instanti-
13556 ated, at which point a program is ill-formed if the substitution
13557 results in an invalid type.] */
13559 static tree
13560 tsubst_function_type (tree t,
13561 tree args,
13562 tsubst_flags_t complain,
13563 tree in_decl)
13565 tree return_type;
13566 tree arg_types = NULL_TREE;
13567 tree fntype;
13569 /* The TYPE_CONTEXT is not used for function/method types. */
13570 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
13572 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
13573 failure. */
13574 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13576 if (late_return_type_p)
13578 /* Substitute the argument types. */
13579 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
13580 complain, in_decl);
13581 if (arg_types == error_mark_node)
13582 return error_mark_node;
13584 tree save_ccp = current_class_ptr;
13585 tree save_ccr = current_class_ref;
13586 tree this_type = (TREE_CODE (t) == METHOD_TYPE
13587 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
13588 bool do_inject = this_type && CLASS_TYPE_P (this_type);
13589 if (do_inject)
13591 /* DR 1207: 'this' is in scope in the trailing return type. */
13592 inject_this_parameter (this_type, cp_type_quals (this_type));
13595 /* Substitute the return type. */
13596 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13598 if (do_inject)
13600 current_class_ptr = save_ccp;
13601 current_class_ref = save_ccr;
13604 else
13605 /* Substitute the return type. */
13606 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13608 if (return_type == error_mark_node)
13609 return error_mark_node;
13610 /* DR 486 clarifies that creation of a function type with an
13611 invalid return type is a deduction failure. */
13612 if (TREE_CODE (return_type) == ARRAY_TYPE
13613 || TREE_CODE (return_type) == FUNCTION_TYPE)
13615 if (complain & tf_error)
13617 if (TREE_CODE (return_type) == ARRAY_TYPE)
13618 error ("function returning an array");
13619 else
13620 error ("function returning a function");
13622 return error_mark_node;
13624 /* And DR 657. */
13625 if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
13626 return error_mark_node;
13628 if (!late_return_type_p)
13630 /* Substitute the argument types. */
13631 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
13632 complain, in_decl);
13633 if (arg_types == error_mark_node)
13634 return error_mark_node;
13637 /* Construct a new type node and return it. */
13638 if (TREE_CODE (t) == FUNCTION_TYPE)
13640 fntype = build_function_type (return_type, arg_types);
13641 fntype = apply_memfn_quals (fntype,
13642 type_memfn_quals (t),
13643 type_memfn_rqual (t));
13645 else
13647 tree r = TREE_TYPE (TREE_VALUE (arg_types));
13648 /* Don't pick up extra function qualifiers from the basetype. */
13649 r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
13650 if (! MAYBE_CLASS_TYPE_P (r))
13652 /* [temp.deduct]
13654 Type deduction may fail for any of the following
13655 reasons:
13657 -- Attempting to create "pointer to member of T" when T
13658 is not a class type. */
13659 if (complain & tf_error)
13660 error ("creating pointer to member function of non-class type %qT",
13662 return error_mark_node;
13665 fntype = build_method_type_directly (r, return_type,
13666 TREE_CHAIN (arg_types));
13667 fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
13669 fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
13671 if (late_return_type_p)
13672 TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
13674 return fntype;
13677 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
13678 ARGS into that specification, and return the substituted
13679 specification. If there is no specification, return NULL_TREE. */
13681 static tree
13682 tsubst_exception_specification (tree fntype,
13683 tree args,
13684 tsubst_flags_t complain,
13685 tree in_decl,
13686 bool defer_ok)
13688 tree specs;
13689 tree new_specs;
13691 specs = TYPE_RAISES_EXCEPTIONS (fntype);
13692 new_specs = NULL_TREE;
13693 if (specs && TREE_PURPOSE (specs))
13695 /* A noexcept-specifier. */
13696 tree expr = TREE_PURPOSE (specs);
13697 if (TREE_CODE (expr) == INTEGER_CST)
13698 new_specs = expr;
13699 else if (defer_ok)
13701 /* Defer instantiation of noexcept-specifiers to avoid
13702 excessive instantiations (c++/49107). */
13703 new_specs = make_node (DEFERRED_NOEXCEPT);
13704 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
13706 /* We already partially instantiated this member template,
13707 so combine the new args with the old. */
13708 DEFERRED_NOEXCEPT_PATTERN (new_specs)
13709 = DEFERRED_NOEXCEPT_PATTERN (expr);
13710 DEFERRED_NOEXCEPT_ARGS (new_specs)
13711 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
13713 else
13715 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
13716 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
13719 else
13720 new_specs = tsubst_copy_and_build
13721 (expr, args, complain, in_decl, /*function_p=*/false,
13722 /*integral_constant_expression_p=*/true);
13723 new_specs = build_noexcept_spec (new_specs, complain);
13725 else if (specs)
13727 if (! TREE_VALUE (specs))
13728 new_specs = specs;
13729 else
13730 while (specs)
13732 tree spec;
13733 int i, len = 1;
13734 tree expanded_specs = NULL_TREE;
13736 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
13738 /* Expand the pack expansion type. */
13739 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
13740 args, complain,
13741 in_decl);
13743 if (expanded_specs == error_mark_node)
13744 return error_mark_node;
13745 else if (TREE_CODE (expanded_specs) == TREE_VEC)
13746 len = TREE_VEC_LENGTH (expanded_specs);
13747 else
13749 /* We're substituting into a member template, so
13750 we got a TYPE_PACK_EXPANSION back. Add that
13751 expansion and move on. */
13752 gcc_assert (TREE_CODE (expanded_specs)
13753 == TYPE_PACK_EXPANSION);
13754 new_specs = add_exception_specifier (new_specs,
13755 expanded_specs,
13756 complain);
13757 specs = TREE_CHAIN (specs);
13758 continue;
13762 for (i = 0; i < len; ++i)
13764 if (expanded_specs)
13765 spec = TREE_VEC_ELT (expanded_specs, i);
13766 else
13767 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
13768 if (spec == error_mark_node)
13769 return spec;
13770 new_specs = add_exception_specifier (new_specs, spec,
13771 complain);
13774 specs = TREE_CHAIN (specs);
13777 return new_specs;
13780 /* Take the tree structure T and replace template parameters used
13781 therein with the argument vector ARGS. IN_DECL is an associated
13782 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
13783 Issue error and warning messages under control of COMPLAIN. Note
13784 that we must be relatively non-tolerant of extensions here, in
13785 order to preserve conformance; if we allow substitutions that
13786 should not be allowed, we may allow argument deductions that should
13787 not succeed, and therefore report ambiguous overload situations
13788 where there are none. In theory, we could allow the substitution,
13789 but indicate that it should have failed, and allow our caller to
13790 make sure that the right thing happens, but we don't try to do this
13791 yet.
13793 This function is used for dealing with types, decls and the like;
13794 for expressions, use tsubst_expr or tsubst_copy. */
13796 tree
13797 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13799 enum tree_code code;
13800 tree type, r = NULL_TREE;
13802 if (t == NULL_TREE || t == error_mark_node
13803 || t == integer_type_node
13804 || t == void_type_node
13805 || t == char_type_node
13806 || t == unknown_type_node
13807 || TREE_CODE (t) == NAMESPACE_DECL
13808 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
13809 return t;
13811 if (DECL_P (t))
13812 return tsubst_decl (t, args, complain);
13814 if (args == NULL_TREE)
13815 return t;
13817 code = TREE_CODE (t);
13819 if (code == IDENTIFIER_NODE)
13820 type = IDENTIFIER_TYPE_VALUE (t);
13821 else
13822 type = TREE_TYPE (t);
13824 gcc_assert (type != unknown_type_node);
13826 /* Reuse typedefs. We need to do this to handle dependent attributes,
13827 such as attribute aligned. */
13828 if (TYPE_P (t)
13829 && typedef_variant_p (t))
13831 tree decl = TYPE_NAME (t);
13833 if (alias_template_specialization_p (t))
13835 /* DECL represents an alias template and we want to
13836 instantiate it. */
13837 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
13838 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
13839 r = instantiate_alias_template (tmpl, gen_args, complain);
13841 else if (DECL_CLASS_SCOPE_P (decl)
13842 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
13843 && uses_template_parms (DECL_CONTEXT (decl)))
13845 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
13846 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
13847 r = retrieve_specialization (tmpl, gen_args, 0);
13849 else if (DECL_FUNCTION_SCOPE_P (decl)
13850 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
13851 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
13852 r = retrieve_local_specialization (decl);
13853 else
13854 /* The typedef is from a non-template context. */
13855 return t;
13857 if (r)
13859 r = TREE_TYPE (r);
13860 r = cp_build_qualified_type_real
13861 (r, cp_type_quals (t) | cp_type_quals (r),
13862 complain | tf_ignore_bad_quals);
13863 return r;
13865 else
13867 /* We don't have an instantiation yet, so drop the typedef. */
13868 int quals = cp_type_quals (t);
13869 t = DECL_ORIGINAL_TYPE (decl);
13870 t = cp_build_qualified_type_real (t, quals,
13871 complain | tf_ignore_bad_quals);
13875 bool fndecl_type = (complain & tf_fndecl_type);
13876 complain &= ~tf_fndecl_type;
13878 if (type
13879 && code != TYPENAME_TYPE
13880 && code != TEMPLATE_TYPE_PARM
13881 && code != TEMPLATE_PARM_INDEX
13882 && code != IDENTIFIER_NODE
13883 && code != FUNCTION_TYPE
13884 && code != METHOD_TYPE)
13885 type = tsubst (type, args, complain, in_decl);
13886 if (type == error_mark_node)
13887 return error_mark_node;
13889 switch (code)
13891 case RECORD_TYPE:
13892 case UNION_TYPE:
13893 case ENUMERAL_TYPE:
13894 return tsubst_aggr_type (t, args, complain, in_decl,
13895 /*entering_scope=*/0);
13897 case ERROR_MARK:
13898 case IDENTIFIER_NODE:
13899 case VOID_TYPE:
13900 case REAL_TYPE:
13901 case COMPLEX_TYPE:
13902 case VECTOR_TYPE:
13903 case BOOLEAN_TYPE:
13904 case NULLPTR_TYPE:
13905 case LANG_TYPE:
13906 return t;
13908 case INTEGER_TYPE:
13909 if (t == integer_type_node)
13910 return t;
13912 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
13913 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
13914 return t;
13917 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
13919 max = tsubst_expr (omax, args, complain, in_decl,
13920 /*integral_constant_expression_p=*/false);
13922 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
13923 needed. */
13924 if (TREE_CODE (max) == NOP_EXPR
13925 && TREE_SIDE_EFFECTS (omax)
13926 && !TREE_TYPE (max))
13927 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
13929 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
13930 with TREE_SIDE_EFFECTS that indicates this is not an integral
13931 constant expression. */
13932 if (processing_template_decl
13933 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
13935 gcc_assert (TREE_CODE (max) == NOP_EXPR);
13936 TREE_SIDE_EFFECTS (max) = 1;
13939 return compute_array_index_type (NULL_TREE, max, complain);
13942 case TEMPLATE_TYPE_PARM:
13943 case TEMPLATE_TEMPLATE_PARM:
13944 case BOUND_TEMPLATE_TEMPLATE_PARM:
13945 case TEMPLATE_PARM_INDEX:
13947 int idx;
13948 int level;
13949 int levels;
13950 tree arg = NULL_TREE;
13952 /* Early in template argument deduction substitution, we don't
13953 want to reduce the level of 'auto', or it will be confused
13954 with a normal template parm in subsequent deduction. */
13955 if (is_auto (t) && (complain & tf_partial))
13956 return t;
13958 r = NULL_TREE;
13960 gcc_assert (TREE_VEC_LENGTH (args) > 0);
13961 template_parm_level_and_index (t, &level, &idx);
13963 levels = TMPL_ARGS_DEPTH (args);
13964 if (level <= levels
13965 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
13967 arg = TMPL_ARG (args, level, idx);
13969 /* See through ARGUMENT_PACK_SELECT arguments. */
13970 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
13971 arg = argument_pack_select_arg (arg);
13974 if (arg == error_mark_node)
13975 return error_mark_node;
13976 else if (arg != NULL_TREE)
13978 if (ARGUMENT_PACK_P (arg))
13979 /* If ARG is an argument pack, we don't actually want to
13980 perform a substitution here, because substitutions
13981 for argument packs are only done
13982 element-by-element. We can get to this point when
13983 substituting the type of a non-type template
13984 parameter pack, when that type actually contains
13985 template parameter packs from an outer template, e.g.,
13987 template<typename... Types> struct A {
13988 template<Types... Values> struct B { };
13989 }; */
13990 return t;
13992 if (code == TEMPLATE_TYPE_PARM)
13994 int quals;
13995 gcc_assert (TYPE_P (arg));
13997 quals = cp_type_quals (arg) | cp_type_quals (t);
13999 return cp_build_qualified_type_real
14000 (arg, quals, complain | tf_ignore_bad_quals);
14002 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14004 /* We are processing a type constructed from a
14005 template template parameter. */
14006 tree argvec = tsubst (TYPE_TI_ARGS (t),
14007 args, complain, in_decl);
14008 if (argvec == error_mark_node)
14009 return error_mark_node;
14011 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14012 || TREE_CODE (arg) == TEMPLATE_DECL
14013 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14015 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14016 /* Consider this code:
14018 template <template <class> class Template>
14019 struct Internal {
14020 template <class Arg> using Bind = Template<Arg>;
14023 template <template <class> class Template, class Arg>
14024 using Instantiate = Template<Arg>; //#0
14026 template <template <class> class Template,
14027 class Argument>
14028 using Bind =
14029 Instantiate<Internal<Template>::template Bind,
14030 Argument>; //#1
14032 When #1 is parsed, the
14033 BOUND_TEMPLATE_TEMPLATE_PARM representing the
14034 parameter `Template' in #0 matches the
14035 UNBOUND_CLASS_TEMPLATE representing the argument
14036 `Internal<Template>::template Bind'; We then want
14037 to assemble the type `Bind<Argument>' that can't
14038 be fully created right now, because
14039 `Internal<Template>' not being complete, the Bind
14040 template cannot be looked up in that context. So
14041 we need to "store" `Bind<Argument>' for later
14042 when the context of Bind becomes complete. Let's
14043 store that in a TYPENAME_TYPE. */
14044 return make_typename_type (TYPE_CONTEXT (arg),
14045 build_nt (TEMPLATE_ID_EXPR,
14046 TYPE_IDENTIFIER (arg),
14047 argvec),
14048 typename_type,
14049 complain);
14051 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
14052 are resolving nested-types in the signature of a
14053 member function templates. Otherwise ARG is a
14054 TEMPLATE_DECL and is the real template to be
14055 instantiated. */
14056 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14057 arg = TYPE_NAME (arg);
14059 r = lookup_template_class (arg,
14060 argvec, in_decl,
14061 DECL_CONTEXT (arg),
14062 /*entering_scope=*/0,
14063 complain);
14064 return cp_build_qualified_type_real
14065 (r, cp_type_quals (t) | cp_type_quals (r), complain);
14067 else if (code == TEMPLATE_TEMPLATE_PARM)
14068 return arg;
14069 else
14070 /* TEMPLATE_PARM_INDEX. */
14071 return convert_from_reference (unshare_expr (arg));
14074 if (level == 1)
14075 /* This can happen during the attempted tsubst'ing in
14076 unify. This means that we don't yet have any information
14077 about the template parameter in question. */
14078 return t;
14080 /* If we get here, we must have been looking at a parm for a
14081 more deeply nested template. Make a new version of this
14082 template parameter, but with a lower level. */
14083 switch (code)
14085 case TEMPLATE_TYPE_PARM:
14086 case TEMPLATE_TEMPLATE_PARM:
14087 case BOUND_TEMPLATE_TEMPLATE_PARM:
14088 if (cp_type_quals (t))
14090 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14091 r = cp_build_qualified_type_real
14092 (r, cp_type_quals (t),
14093 complain | (code == TEMPLATE_TYPE_PARM
14094 ? tf_ignore_bad_quals : 0));
14096 else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14097 && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14098 && (r = (TEMPLATE_PARM_DESCENDANTS
14099 (TEMPLATE_TYPE_PARM_INDEX (t))))
14100 && (r = TREE_TYPE (r))
14101 && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14102 /* Break infinite recursion when substituting the constraints
14103 of a constrained placeholder. */;
14104 else
14106 r = copy_type (t);
14107 TEMPLATE_TYPE_PARM_INDEX (r)
14108 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14109 r, levels, args, complain);
14110 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14111 TYPE_MAIN_VARIANT (r) = r;
14112 TYPE_POINTER_TO (r) = NULL_TREE;
14113 TYPE_REFERENCE_TO (r) = NULL_TREE;
14115 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14117 /* Propagate constraints on placeholders. */
14118 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14119 PLACEHOLDER_TYPE_CONSTRAINTS (r)
14120 = tsubst_constraint (constr, args, complain, in_decl);
14121 else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14123 if (DECL_TEMPLATE_TEMPLATE_PARM_P (pl))
14124 pl = tsubst (pl, args, complain, in_decl);
14125 CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14129 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14130 /* We have reduced the level of the template
14131 template parameter, but not the levels of its
14132 template parameters, so canonical_type_parameter
14133 will not be able to find the canonical template
14134 template parameter for this level. Thus, we
14135 require structural equality checking to compare
14136 TEMPLATE_TEMPLATE_PARMs. */
14137 SET_TYPE_STRUCTURAL_EQUALITY (r);
14138 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14139 SET_TYPE_STRUCTURAL_EQUALITY (r);
14140 else
14141 TYPE_CANONICAL (r) = canonical_type_parameter (r);
14143 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14145 tree tinfo = TYPE_TEMPLATE_INFO (t);
14146 /* We might need to substitute into the types of non-type
14147 template parameters. */
14148 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14149 complain, in_decl);
14150 if (tmpl == error_mark_node)
14151 return error_mark_node;
14152 tree argvec = tsubst (TI_ARGS (tinfo), args,
14153 complain, in_decl);
14154 if (argvec == error_mark_node)
14155 return error_mark_node;
14157 TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14158 = build_template_info (tmpl, argvec);
14161 break;
14163 case TEMPLATE_PARM_INDEX:
14164 /* OK, now substitute the type of the non-type parameter. We
14165 couldn't do it earlier because it might be an auto parameter,
14166 and we wouldn't need to if we had an argument. */
14167 type = tsubst (type, args, complain, in_decl);
14168 if (type == error_mark_node)
14169 return error_mark_node;
14170 r = reduce_template_parm_level (t, type, levels, args, complain);
14171 break;
14173 default:
14174 gcc_unreachable ();
14177 return r;
14180 case TREE_LIST:
14182 tree purpose, value, chain;
14184 if (t == void_list_node)
14185 return t;
14187 purpose = TREE_PURPOSE (t);
14188 if (purpose)
14190 purpose = tsubst (purpose, args, complain, in_decl);
14191 if (purpose == error_mark_node)
14192 return error_mark_node;
14194 value = TREE_VALUE (t);
14195 if (value)
14197 value = tsubst (value, args, complain, in_decl);
14198 if (value == error_mark_node)
14199 return error_mark_node;
14201 chain = TREE_CHAIN (t);
14202 if (chain && chain != void_type_node)
14204 chain = tsubst (chain, args, complain, in_decl);
14205 if (chain == error_mark_node)
14206 return error_mark_node;
14208 if (purpose == TREE_PURPOSE (t)
14209 && value == TREE_VALUE (t)
14210 && chain == TREE_CHAIN (t))
14211 return t;
14212 return hash_tree_cons (purpose, value, chain);
14215 case TREE_BINFO:
14216 /* We should never be tsubsting a binfo. */
14217 gcc_unreachable ();
14219 case TREE_VEC:
14220 /* A vector of template arguments. */
14221 gcc_assert (!type);
14222 return tsubst_template_args (t, args, complain, in_decl);
14224 case POINTER_TYPE:
14225 case REFERENCE_TYPE:
14227 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14228 return t;
14230 /* [temp.deduct]
14232 Type deduction may fail for any of the following
14233 reasons:
14235 -- Attempting to create a pointer to reference type.
14236 -- Attempting to create a reference to a reference type or
14237 a reference to void.
14239 Core issue 106 says that creating a reference to a reference
14240 during instantiation is no longer a cause for failure. We
14241 only enforce this check in strict C++98 mode. */
14242 if ((TREE_CODE (type) == REFERENCE_TYPE
14243 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14244 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14246 static location_t last_loc;
14248 /* We keep track of the last time we issued this error
14249 message to avoid spewing a ton of messages during a
14250 single bad template instantiation. */
14251 if (complain & tf_error
14252 && last_loc != input_location)
14254 if (VOID_TYPE_P (type))
14255 error ("forming reference to void");
14256 else if (code == POINTER_TYPE)
14257 error ("forming pointer to reference type %qT", type);
14258 else
14259 error ("forming reference to reference type %qT", type);
14260 last_loc = input_location;
14263 return error_mark_node;
14265 else if (TREE_CODE (type) == FUNCTION_TYPE
14266 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14267 || type_memfn_rqual (type) != REF_QUAL_NONE))
14269 if (complain & tf_error)
14271 if (code == POINTER_TYPE)
14272 error ("forming pointer to qualified function type %qT",
14273 type);
14274 else
14275 error ("forming reference to qualified function type %qT",
14276 type);
14278 return error_mark_node;
14280 else if (code == POINTER_TYPE)
14282 r = build_pointer_type (type);
14283 if (TREE_CODE (type) == METHOD_TYPE)
14284 r = build_ptrmemfunc_type (r);
14286 else if (TREE_CODE (type) == REFERENCE_TYPE)
14287 /* In C++0x, during template argument substitution, when there is an
14288 attempt to create a reference to a reference type, reference
14289 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14291 "If a template-argument for a template-parameter T names a type
14292 that is a reference to a type A, an attempt to create the type
14293 'lvalue reference to cv T' creates the type 'lvalue reference to
14294 A,' while an attempt to create the type type rvalue reference to
14295 cv T' creates the type T"
14297 r = cp_build_reference_type
14298 (TREE_TYPE (type),
14299 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14300 else
14301 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14302 r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14304 if (r != error_mark_node)
14305 /* Will this ever be needed for TYPE_..._TO values? */
14306 layout_type (r);
14308 return r;
14310 case OFFSET_TYPE:
14312 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14313 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14315 /* [temp.deduct]
14317 Type deduction may fail for any of the following
14318 reasons:
14320 -- Attempting to create "pointer to member of T" when T
14321 is not a class type. */
14322 if (complain & tf_error)
14323 error ("creating pointer to member of non-class type %qT", r);
14324 return error_mark_node;
14326 if (TREE_CODE (type) == REFERENCE_TYPE)
14328 if (complain & tf_error)
14329 error ("creating pointer to member reference type %qT", type);
14330 return error_mark_node;
14332 if (VOID_TYPE_P (type))
14334 if (complain & tf_error)
14335 error ("creating pointer to member of type void");
14336 return error_mark_node;
14338 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14339 if (TREE_CODE (type) == FUNCTION_TYPE)
14341 /* The type of the implicit object parameter gets its
14342 cv-qualifiers from the FUNCTION_TYPE. */
14343 tree memptr;
14344 tree method_type
14345 = build_memfn_type (type, r, type_memfn_quals (type),
14346 type_memfn_rqual (type));
14347 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14348 return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14349 complain);
14351 else
14352 return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14353 cp_type_quals (t),
14354 complain);
14356 case FUNCTION_TYPE:
14357 case METHOD_TYPE:
14359 tree fntype;
14360 tree specs;
14361 fntype = tsubst_function_type (t, args, complain, in_decl);
14362 if (fntype == error_mark_node)
14363 return error_mark_node;
14365 /* Substitute the exception specification. */
14366 specs = tsubst_exception_specification (t, args, complain, in_decl,
14367 /*defer_ok*/fndecl_type);
14368 if (specs == error_mark_node)
14369 return error_mark_node;
14370 if (specs)
14371 fntype = build_exception_variant (fntype, specs);
14372 return fntype;
14374 case ARRAY_TYPE:
14376 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14377 if (domain == error_mark_node)
14378 return error_mark_node;
14380 /* As an optimization, we avoid regenerating the array type if
14381 it will obviously be the same as T. */
14382 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14383 return t;
14385 /* These checks should match the ones in create_array_type_for_decl.
14387 [temp.deduct]
14389 The deduction may fail for any of the following reasons:
14391 -- Attempting to create an array with an element type that
14392 is void, a function type, or a reference type, or [DR337]
14393 an abstract class type. */
14394 if (VOID_TYPE_P (type)
14395 || TREE_CODE (type) == FUNCTION_TYPE
14396 || (TREE_CODE (type) == ARRAY_TYPE
14397 && TYPE_DOMAIN (type) == NULL_TREE)
14398 || TREE_CODE (type) == REFERENCE_TYPE)
14400 if (complain & tf_error)
14401 error ("creating array of %qT", type);
14402 return error_mark_node;
14405 if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14406 return error_mark_node;
14408 r = build_cplus_array_type (type, domain);
14410 if (TYPE_USER_ALIGN (t))
14412 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
14413 TYPE_USER_ALIGN (r) = 1;
14416 return r;
14419 case TYPENAME_TYPE:
14421 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14422 in_decl, /*entering_scope=*/1);
14423 if (ctx == error_mark_node)
14424 return error_mark_node;
14426 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
14427 complain, in_decl);
14428 if (f == error_mark_node)
14429 return error_mark_node;
14431 if (!MAYBE_CLASS_TYPE_P (ctx))
14433 if (complain & tf_error)
14434 error ("%qT is not a class, struct, or union type", ctx);
14435 return error_mark_node;
14437 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
14439 /* Normally, make_typename_type does not require that the CTX
14440 have complete type in order to allow things like:
14442 template <class T> struct S { typename S<T>::X Y; };
14444 But, such constructs have already been resolved by this
14445 point, so here CTX really should have complete type, unless
14446 it's a partial instantiation. */
14447 ctx = complete_type (ctx);
14448 if (!COMPLETE_TYPE_P (ctx))
14450 if (complain & tf_error)
14451 cxx_incomplete_type_error (NULL_TREE, ctx);
14452 return error_mark_node;
14456 f = make_typename_type (ctx, f, typename_type,
14457 complain | tf_keep_type_decl);
14458 if (f == error_mark_node)
14459 return f;
14460 if (TREE_CODE (f) == TYPE_DECL)
14462 complain |= tf_ignore_bad_quals;
14463 f = TREE_TYPE (f);
14466 if (TREE_CODE (f) != TYPENAME_TYPE)
14468 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
14470 if (complain & tf_error)
14471 error ("%qT resolves to %qT, which is not an enumeration type",
14472 t, f);
14473 else
14474 return error_mark_node;
14476 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
14478 if (complain & tf_error)
14479 error ("%qT resolves to %qT, which is is not a class type",
14480 t, f);
14481 else
14482 return error_mark_node;
14486 return cp_build_qualified_type_real
14487 (f, cp_type_quals (f) | cp_type_quals (t), complain);
14490 case UNBOUND_CLASS_TEMPLATE:
14492 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14493 in_decl, /*entering_scope=*/1);
14494 tree name = TYPE_IDENTIFIER (t);
14495 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
14497 if (ctx == error_mark_node || name == error_mark_node)
14498 return error_mark_node;
14500 if (parm_list)
14501 parm_list = tsubst_template_parms (parm_list, args, complain);
14502 return make_unbound_class_template (ctx, name, parm_list, complain);
14505 case TYPEOF_TYPE:
14507 tree type;
14509 ++cp_unevaluated_operand;
14510 ++c_inhibit_evaluation_warnings;
14512 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
14513 complain, in_decl,
14514 /*integral_constant_expression_p=*/false);
14516 --cp_unevaluated_operand;
14517 --c_inhibit_evaluation_warnings;
14519 type = finish_typeof (type);
14520 return cp_build_qualified_type_real (type,
14521 cp_type_quals (t)
14522 | cp_type_quals (type),
14523 complain);
14526 case DECLTYPE_TYPE:
14528 tree type;
14530 ++cp_unevaluated_operand;
14531 ++c_inhibit_evaluation_warnings;
14533 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
14534 complain|tf_decltype, in_decl,
14535 /*function_p*/false,
14536 /*integral_constant_expression*/false);
14538 if (DECLTYPE_FOR_INIT_CAPTURE (t))
14540 if (type == NULL_TREE)
14542 if (complain & tf_error)
14543 error ("empty initializer in lambda init-capture");
14544 type = error_mark_node;
14546 else if (TREE_CODE (type) == TREE_LIST)
14547 type = build_x_compound_expr_from_list (type, ELK_INIT, complain);
14550 --cp_unevaluated_operand;
14551 --c_inhibit_evaluation_warnings;
14553 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
14554 type = lambda_capture_field_type (type,
14555 DECLTYPE_FOR_INIT_CAPTURE (t),
14556 DECLTYPE_FOR_REF_CAPTURE (t));
14557 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
14558 type = lambda_proxy_type (type);
14559 else
14561 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
14562 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
14563 && EXPR_P (type))
14564 /* In a template ~id could be either a complement expression
14565 or an unqualified-id naming a destructor; if instantiating
14566 it produces an expression, it's not an id-expression or
14567 member access. */
14568 id = false;
14569 type = finish_decltype_type (type, id, complain);
14571 return cp_build_qualified_type_real (type,
14572 cp_type_quals (t)
14573 | cp_type_quals (type),
14574 complain | tf_ignore_bad_quals);
14577 case UNDERLYING_TYPE:
14579 tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
14580 complain, in_decl);
14581 return finish_underlying_type (type);
14584 case TYPE_ARGUMENT_PACK:
14585 case NONTYPE_ARGUMENT_PACK:
14587 tree r;
14589 if (code == NONTYPE_ARGUMENT_PACK)
14590 r = make_node (code);
14591 else
14592 r = cxx_make_type (code);
14594 tree pack_args = ARGUMENT_PACK_ARGS (t);
14595 pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
14596 SET_ARGUMENT_PACK_ARGS (r, pack_args);
14598 return r;
14601 case VOID_CST:
14602 case INTEGER_CST:
14603 case REAL_CST:
14604 case STRING_CST:
14605 case PLUS_EXPR:
14606 case MINUS_EXPR:
14607 case NEGATE_EXPR:
14608 case NOP_EXPR:
14609 case INDIRECT_REF:
14610 case ADDR_EXPR:
14611 case CALL_EXPR:
14612 case ARRAY_REF:
14613 case SCOPE_REF:
14614 /* We should use one of the expression tsubsts for these codes. */
14615 gcc_unreachable ();
14617 default:
14618 sorry ("use of %qs in template", get_tree_code_name (code));
14619 return error_mark_node;
14623 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
14624 expression on the left-hand side of the "." or "->" operator. We
14625 only do the lookup if we had a dependent BASELINK. Otherwise we
14626 adjust it onto the instantiated heirarchy. */
14628 static tree
14629 tsubst_baselink (tree baselink, tree object_type,
14630 tree args, tsubst_flags_t complain, tree in_decl)
14632 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
14633 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
14634 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
14636 tree optype = BASELINK_OPTYPE (baselink);
14637 optype = tsubst (optype, args, complain, in_decl);
14639 tree template_args = NULL_TREE;
14640 bool template_id_p = false;
14641 tree fns = BASELINK_FUNCTIONS (baselink);
14642 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
14644 template_id_p = true;
14645 template_args = TREE_OPERAND (fns, 1);
14646 fns = TREE_OPERAND (fns, 0);
14647 if (template_args)
14648 template_args = tsubst_template_args (template_args, args,
14649 complain, in_decl);
14652 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
14653 binfo_type = tsubst (binfo_type, args, complain, in_decl);
14654 bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
14656 if (dependent_p)
14658 tree name = OVL_NAME (fns);
14659 if (IDENTIFIER_CONV_OP_P (name))
14660 name = make_conv_op_name (optype);
14662 if (name == complete_dtor_identifier)
14663 /* Treat as-if non-dependent below. */
14664 dependent_p = false;
14666 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
14667 if (!baselink)
14669 if ((complain & tf_error)
14670 && constructor_name_p (name, qualifying_scope))
14671 error ("cannot call constructor %<%T::%D%> directly",
14672 qualifying_scope, name);
14673 return error_mark_node;
14676 if (BASELINK_P (baselink))
14677 fns = BASELINK_FUNCTIONS (baselink);
14679 else
14680 /* We're going to overwrite pieces below, make a duplicate. */
14681 baselink = copy_node (baselink);
14683 /* If lookup found a single function, mark it as used at this point.
14684 (If lookup found multiple functions the one selected later by
14685 overload resolution will be marked as used at that point.) */
14686 if (!template_id_p && !really_overloaded_fn (fns)
14687 && !mark_used (OVL_FIRST (fns), complain) && !(complain & tf_error))
14688 return error_mark_node;
14690 if (BASELINK_P (baselink))
14692 /* Add back the template arguments, if present. */
14693 if (template_id_p)
14694 BASELINK_FUNCTIONS (baselink)
14695 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
14697 /* Update the conversion operator type. */
14698 BASELINK_OPTYPE (baselink) = optype;
14701 if (!object_type)
14702 object_type = current_class_type;
14704 if (qualified_p || !dependent_p)
14706 baselink = adjust_result_of_qualified_name_lookup (baselink,
14707 qualifying_scope,
14708 object_type);
14709 if (!qualified_p)
14710 /* We need to call adjust_result_of_qualified_name_lookup in case the
14711 destructor names a base class, but we unset BASELINK_QUALIFIED_P
14712 so that we still get virtual function binding. */
14713 BASELINK_QUALIFIED_P (baselink) = false;
14716 return baselink;
14719 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
14720 true if the qualified-id will be a postfix-expression in-and-of
14721 itself; false if more of the postfix-expression follows the
14722 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
14723 of "&". */
14725 static tree
14726 tsubst_qualified_id (tree qualified_id, tree args,
14727 tsubst_flags_t complain, tree in_decl,
14728 bool done, bool address_p)
14730 tree expr;
14731 tree scope;
14732 tree name;
14733 bool is_template;
14734 tree template_args;
14735 location_t loc = UNKNOWN_LOCATION;
14737 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
14739 /* Figure out what name to look up. */
14740 name = TREE_OPERAND (qualified_id, 1);
14741 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
14743 is_template = true;
14744 loc = EXPR_LOCATION (name);
14745 template_args = TREE_OPERAND (name, 1);
14746 if (template_args)
14747 template_args = tsubst_template_args (template_args, args,
14748 complain, in_decl);
14749 if (template_args == error_mark_node)
14750 return error_mark_node;
14751 name = TREE_OPERAND (name, 0);
14753 else
14755 is_template = false;
14756 template_args = NULL_TREE;
14759 /* Substitute into the qualifying scope. When there are no ARGS, we
14760 are just trying to simplify a non-dependent expression. In that
14761 case the qualifying scope may be dependent, and, in any case,
14762 substituting will not help. */
14763 scope = TREE_OPERAND (qualified_id, 0);
14764 if (args)
14766 scope = tsubst (scope, args, complain, in_decl);
14767 expr = tsubst_copy (name, args, complain, in_decl);
14769 else
14770 expr = name;
14772 if (dependent_scope_p (scope))
14774 if (is_template)
14775 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
14776 tree r = build_qualified_name (NULL_TREE, scope, expr,
14777 QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
14778 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
14779 return r;
14782 if (!BASELINK_P (name) && !DECL_P (expr))
14784 if (TREE_CODE (expr) == BIT_NOT_EXPR)
14786 /* A BIT_NOT_EXPR is used to represent a destructor. */
14787 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
14789 error ("qualifying type %qT does not match destructor name ~%qT",
14790 scope, TREE_OPERAND (expr, 0));
14791 expr = error_mark_node;
14793 else
14794 expr = lookup_qualified_name (scope, complete_dtor_identifier,
14795 /*is_type_p=*/0, false);
14797 else
14798 expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
14799 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
14800 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
14802 if (complain & tf_error)
14804 error ("dependent-name %qE is parsed as a non-type, but "
14805 "instantiation yields a type", qualified_id);
14806 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
14808 return error_mark_node;
14812 if (DECL_P (expr))
14814 check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
14815 scope);
14816 /* Remember that there was a reference to this entity. */
14817 if (!mark_used (expr, complain) && !(complain & tf_error))
14818 return error_mark_node;
14821 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
14823 if (complain & tf_error)
14824 qualified_name_lookup_error (scope,
14825 TREE_OPERAND (qualified_id, 1),
14826 expr, input_location);
14827 return error_mark_node;
14830 if (is_template)
14832 if (variable_template_p (expr))
14833 expr = lookup_and_finish_template_variable (expr, template_args,
14834 complain);
14835 else
14836 expr = lookup_template_function (expr, template_args);
14839 if (expr == error_mark_node && complain & tf_error)
14840 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
14841 expr, input_location);
14842 else if (TYPE_P (scope))
14844 expr = (adjust_result_of_qualified_name_lookup
14845 (expr, scope, current_nonlambda_class_type ()));
14846 expr = (finish_qualified_id_expr
14847 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
14848 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
14849 /*template_arg_p=*/false, complain));
14852 /* Expressions do not generally have reference type. */
14853 if (TREE_CODE (expr) != SCOPE_REF
14854 /* However, if we're about to form a pointer-to-member, we just
14855 want the referenced member referenced. */
14856 && TREE_CODE (expr) != OFFSET_REF)
14857 expr = convert_from_reference (expr);
14859 if (REF_PARENTHESIZED_P (qualified_id))
14860 expr = force_paren_expr (expr);
14862 return expr;
14865 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
14866 initializer, DECL is the substituted VAR_DECL. Other arguments are as
14867 for tsubst. */
14869 static tree
14870 tsubst_init (tree init, tree decl, tree args,
14871 tsubst_flags_t complain, tree in_decl)
14873 if (!init)
14874 return NULL_TREE;
14876 init = tsubst_expr (init, args, complain, in_decl, false);
14878 if (!init && TREE_TYPE (decl) != error_mark_node)
14880 /* If we had an initializer but it
14881 instantiated to nothing,
14882 value-initialize the object. This will
14883 only occur when the initializer was a
14884 pack expansion where the parameter packs
14885 used in that expansion were of length
14886 zero. */
14887 init = build_value_init (TREE_TYPE (decl),
14888 complain);
14889 if (TREE_CODE (init) == AGGR_INIT_EXPR)
14890 init = get_target_expr_sfinae (init, complain);
14891 if (TREE_CODE (init) == TARGET_EXPR)
14892 TARGET_EXPR_DIRECT_INIT_P (init) = true;
14895 return init;
14898 /* Like tsubst, but deals with expressions. This function just replaces
14899 template parms; to finish processing the resultant expression, use
14900 tsubst_copy_and_build or tsubst_expr. */
14902 static tree
14903 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14905 enum tree_code code;
14906 tree r;
14908 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
14909 return t;
14911 code = TREE_CODE (t);
14913 switch (code)
14915 case PARM_DECL:
14916 r = retrieve_local_specialization (t);
14918 if (r == NULL_TREE)
14920 /* We get here for a use of 'this' in an NSDMI. */
14921 if (DECL_NAME (t) == this_identifier && current_class_ptr)
14922 return current_class_ptr;
14924 /* This can happen for a parameter name used later in a function
14925 declaration (such as in a late-specified return type). Just
14926 make a dummy decl, since it's only used for its type. */
14927 gcc_assert (cp_unevaluated_operand != 0);
14928 r = tsubst_decl (t, args, complain);
14929 /* Give it the template pattern as its context; its true context
14930 hasn't been instantiated yet and this is good enough for
14931 mangling. */
14932 DECL_CONTEXT (r) = DECL_CONTEXT (t);
14935 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
14936 r = argument_pack_select_arg (r);
14937 if (!mark_used (r, complain) && !(complain & tf_error))
14938 return error_mark_node;
14939 return r;
14941 case CONST_DECL:
14943 tree enum_type;
14944 tree v;
14946 if (DECL_TEMPLATE_PARM_P (t))
14947 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
14948 /* There is no need to substitute into namespace-scope
14949 enumerators. */
14950 if (DECL_NAMESPACE_SCOPE_P (t))
14951 return t;
14952 /* If ARGS is NULL, then T is known to be non-dependent. */
14953 if (args == NULL_TREE)
14954 return scalar_constant_value (t);
14956 /* Unfortunately, we cannot just call lookup_name here.
14957 Consider:
14959 template <int I> int f() {
14960 enum E { a = I };
14961 struct S { void g() { E e = a; } };
14964 When we instantiate f<7>::S::g(), say, lookup_name is not
14965 clever enough to find f<7>::a. */
14966 enum_type
14967 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
14968 /*entering_scope=*/0);
14970 for (v = TYPE_VALUES (enum_type);
14971 v != NULL_TREE;
14972 v = TREE_CHAIN (v))
14973 if (TREE_PURPOSE (v) == DECL_NAME (t))
14974 return TREE_VALUE (v);
14976 /* We didn't find the name. That should never happen; if
14977 name-lookup found it during preliminary parsing, we
14978 should find it again here during instantiation. */
14979 gcc_unreachable ();
14981 return t;
14983 case FIELD_DECL:
14984 if (DECL_CONTEXT (t))
14986 tree ctx;
14988 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
14989 /*entering_scope=*/1);
14990 if (ctx != DECL_CONTEXT (t))
14992 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
14993 if (!r)
14995 if (complain & tf_error)
14996 error ("using invalid field %qD", t);
14997 return error_mark_node;
14999 return r;
15003 return t;
15005 case VAR_DECL:
15006 case FUNCTION_DECL:
15007 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15008 r = tsubst (t, args, complain, in_decl);
15009 else if (local_variable_p (t)
15010 && uses_template_parms (DECL_CONTEXT (t)))
15012 r = retrieve_local_specialization (t);
15013 if (r == NULL_TREE)
15015 /* First try name lookup to find the instantiation. */
15016 r = lookup_name (DECL_NAME (t));
15017 if (r && !is_capture_proxy (r))
15019 /* Make sure that the one we found is the one we want. */
15020 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15021 if (ctx != DECL_CONTEXT (r))
15022 r = NULL_TREE;
15025 if (r)
15026 /* OK */;
15027 else
15029 /* This can happen for a variable used in a
15030 late-specified return type of a local lambda, or for a
15031 local static or constant. Building a new VAR_DECL
15032 should be OK in all those cases. */
15033 r = tsubst_decl (t, args, complain);
15034 if (local_specializations)
15035 /* Avoid infinite recursion (79640). */
15036 register_local_specialization (r, t);
15037 if (decl_maybe_constant_var_p (r))
15039 /* We can't call cp_finish_decl, so handle the
15040 initializer by hand. */
15041 tree init = tsubst_init (DECL_INITIAL (t), r, args,
15042 complain, in_decl);
15043 if (!processing_template_decl)
15044 init = maybe_constant_init (init);
15045 if (processing_template_decl
15046 ? potential_constant_expression (init)
15047 : reduced_constant_expression_p (init))
15048 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15049 = TREE_CONSTANT (r) = true;
15050 DECL_INITIAL (r) = init;
15051 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15052 TREE_TYPE (r)
15053 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15054 complain, adc_variable_type);
15056 gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15057 || decl_constant_var_p (r)
15058 || errorcount || sorrycount);
15059 if (!processing_template_decl
15060 && !TREE_STATIC (r))
15061 r = process_outer_var_ref (r, complain);
15063 /* Remember this for subsequent uses. */
15064 if (local_specializations)
15065 register_local_specialization (r, t);
15067 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15068 r = argument_pack_select_arg (r);
15070 else
15071 r = t;
15072 if (!mark_used (r, complain))
15073 return error_mark_node;
15074 return r;
15076 case NAMESPACE_DECL:
15077 return t;
15079 case OVERLOAD:
15080 /* An OVERLOAD will always be a non-dependent overload set; an
15081 overload set from function scope will just be represented with an
15082 IDENTIFIER_NODE, and from class scope with a BASELINK. */
15083 gcc_assert (!uses_template_parms (t));
15084 /* We must have marked any lookups as persistent. */
15085 gcc_assert (!OVL_LOOKUP_P (t) || OVL_USED_P (t));
15086 return t;
15088 case BASELINK:
15089 return tsubst_baselink (t, current_nonlambda_class_type (),
15090 args, complain, in_decl);
15092 case TEMPLATE_DECL:
15093 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15094 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15095 args, complain, in_decl);
15096 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15097 return tsubst (t, args, complain, in_decl);
15098 else if (DECL_CLASS_SCOPE_P (t)
15099 && uses_template_parms (DECL_CONTEXT (t)))
15101 /* Template template argument like the following example need
15102 special treatment:
15104 template <template <class> class TT> struct C {};
15105 template <class T> struct D {
15106 template <class U> struct E {};
15107 C<E> c; // #1
15109 D<int> d; // #2
15111 We are processing the template argument `E' in #1 for
15112 the template instantiation #2. Originally, `E' is a
15113 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
15114 have to substitute this with one having context `D<int>'. */
15116 tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15117 if (dependent_scope_p (context))
15119 /* When rewriting a constructor into a deduction guide, a
15120 non-dependent name can become dependent, so memtmpl<args>
15121 becomes context::template memtmpl<args>. */
15122 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15123 return build_qualified_name (type, context, DECL_NAME (t),
15124 /*template*/true);
15126 return lookup_field (context, DECL_NAME(t), 0, false);
15128 else
15129 /* Ordinary template template argument. */
15130 return t;
15132 case NON_LVALUE_EXPR:
15133 case VIEW_CONVERT_EXPR:
15135 /* Handle location wrappers by substituting the wrapped node
15136 first, *then* reusing the resulting type. Doing the type
15137 first ensures that we handle template parameters and
15138 parameter pack expansions. */
15139 gcc_assert (location_wrapper_p (t));
15140 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15141 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15144 case CAST_EXPR:
15145 case REINTERPRET_CAST_EXPR:
15146 case CONST_CAST_EXPR:
15147 case STATIC_CAST_EXPR:
15148 case DYNAMIC_CAST_EXPR:
15149 case IMPLICIT_CONV_EXPR:
15150 case CONVERT_EXPR:
15151 case NOP_EXPR:
15153 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15154 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15155 return build1 (code, type, op0);
15158 case SIZEOF_EXPR:
15159 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15160 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15162 tree expanded, op = TREE_OPERAND (t, 0);
15163 int len = 0;
15165 if (SIZEOF_EXPR_TYPE_P (t))
15166 op = TREE_TYPE (op);
15168 ++cp_unevaluated_operand;
15169 ++c_inhibit_evaluation_warnings;
15170 /* We only want to compute the number of arguments. */
15171 if (PACK_EXPANSION_P (op))
15172 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15173 else
15174 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15175 args, complain, in_decl);
15176 --cp_unevaluated_operand;
15177 --c_inhibit_evaluation_warnings;
15179 if (TREE_CODE (expanded) == TREE_VEC)
15181 len = TREE_VEC_LENGTH (expanded);
15182 /* Set TREE_USED for the benefit of -Wunused. */
15183 for (int i = 0; i < len; i++)
15184 if (DECL_P (TREE_VEC_ELT (expanded, i)))
15185 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15188 if (expanded == error_mark_node)
15189 return error_mark_node;
15190 else if (PACK_EXPANSION_P (expanded)
15191 || (TREE_CODE (expanded) == TREE_VEC
15192 && pack_expansion_args_count (expanded)))
15195 if (PACK_EXPANSION_P (expanded))
15196 /* OK. */;
15197 else if (TREE_VEC_LENGTH (expanded) == 1)
15198 expanded = TREE_VEC_ELT (expanded, 0);
15199 else
15200 expanded = make_argument_pack (expanded);
15202 if (TYPE_P (expanded))
15203 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15204 complain & tf_error);
15205 else
15206 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15207 complain & tf_error);
15209 else
15210 return build_int_cst (size_type_node, len);
15212 if (SIZEOF_EXPR_TYPE_P (t))
15214 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15215 args, complain, in_decl);
15216 r = build1 (NOP_EXPR, r, error_mark_node);
15217 r = build1 (SIZEOF_EXPR,
15218 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15219 SIZEOF_EXPR_TYPE_P (r) = 1;
15220 return r;
15222 /* Fall through */
15224 case INDIRECT_REF:
15225 case NEGATE_EXPR:
15226 case TRUTH_NOT_EXPR:
15227 case BIT_NOT_EXPR:
15228 case ADDR_EXPR:
15229 case UNARY_PLUS_EXPR: /* Unary + */
15230 case ALIGNOF_EXPR:
15231 case AT_ENCODE_EXPR:
15232 case ARROW_EXPR:
15233 case THROW_EXPR:
15234 case TYPEID_EXPR:
15235 case REALPART_EXPR:
15236 case IMAGPART_EXPR:
15237 case PAREN_EXPR:
15239 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15240 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15241 return build1 (code, type, op0);
15244 case COMPONENT_REF:
15246 tree object;
15247 tree name;
15249 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15250 name = TREE_OPERAND (t, 1);
15251 if (TREE_CODE (name) == BIT_NOT_EXPR)
15253 name = tsubst_copy (TREE_OPERAND (name, 0), args,
15254 complain, in_decl);
15255 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15257 else if (TREE_CODE (name) == SCOPE_REF
15258 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15260 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15261 complain, in_decl);
15262 name = TREE_OPERAND (name, 1);
15263 name = tsubst_copy (TREE_OPERAND (name, 0), args,
15264 complain, in_decl);
15265 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15266 name = build_qualified_name (/*type=*/NULL_TREE,
15267 base, name,
15268 /*template_p=*/false);
15270 else if (BASELINK_P (name))
15271 name = tsubst_baselink (name,
15272 non_reference (TREE_TYPE (object)),
15273 args, complain,
15274 in_decl);
15275 else
15276 name = tsubst_copy (name, args, complain, in_decl);
15277 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15280 case PLUS_EXPR:
15281 case MINUS_EXPR:
15282 case MULT_EXPR:
15283 case TRUNC_DIV_EXPR:
15284 case CEIL_DIV_EXPR:
15285 case FLOOR_DIV_EXPR:
15286 case ROUND_DIV_EXPR:
15287 case EXACT_DIV_EXPR:
15288 case BIT_AND_EXPR:
15289 case BIT_IOR_EXPR:
15290 case BIT_XOR_EXPR:
15291 case TRUNC_MOD_EXPR:
15292 case FLOOR_MOD_EXPR:
15293 case TRUTH_ANDIF_EXPR:
15294 case TRUTH_ORIF_EXPR:
15295 case TRUTH_AND_EXPR:
15296 case TRUTH_OR_EXPR:
15297 case RSHIFT_EXPR:
15298 case LSHIFT_EXPR:
15299 case RROTATE_EXPR:
15300 case LROTATE_EXPR:
15301 case EQ_EXPR:
15302 case NE_EXPR:
15303 case MAX_EXPR:
15304 case MIN_EXPR:
15305 case LE_EXPR:
15306 case GE_EXPR:
15307 case LT_EXPR:
15308 case GT_EXPR:
15309 case COMPOUND_EXPR:
15310 case DOTSTAR_EXPR:
15311 case MEMBER_REF:
15312 case PREDECREMENT_EXPR:
15313 case PREINCREMENT_EXPR:
15314 case POSTDECREMENT_EXPR:
15315 case POSTINCREMENT_EXPR:
15317 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15318 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15319 return build_nt (code, op0, op1);
15322 case SCOPE_REF:
15324 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15325 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15326 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15327 QUALIFIED_NAME_IS_TEMPLATE (t));
15330 case ARRAY_REF:
15332 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15333 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15334 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15337 case CALL_EXPR:
15339 int n = VL_EXP_OPERAND_LENGTH (t);
15340 tree result = build_vl_exp (CALL_EXPR, n);
15341 int i;
15342 for (i = 0; i < n; i++)
15343 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15344 complain, in_decl);
15345 return result;
15348 case COND_EXPR:
15349 case MODOP_EXPR:
15350 case PSEUDO_DTOR_EXPR:
15351 case VEC_PERM_EXPR:
15353 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15354 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15355 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15356 r = build_nt (code, op0, op1, op2);
15357 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15358 return r;
15361 case NEW_EXPR:
15363 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15364 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15365 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15366 r = build_nt (code, op0, op1, op2);
15367 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
15368 return r;
15371 case DELETE_EXPR:
15373 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15374 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15375 r = build_nt (code, op0, op1);
15376 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
15377 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
15378 return r;
15381 case TEMPLATE_ID_EXPR:
15383 /* Substituted template arguments */
15384 tree fn = TREE_OPERAND (t, 0);
15385 tree targs = TREE_OPERAND (t, 1);
15387 fn = tsubst_copy (fn, args, complain, in_decl);
15388 if (targs)
15389 targs = tsubst_template_args (targs, args, complain, in_decl);
15391 return lookup_template_function (fn, targs);
15394 case TREE_LIST:
15396 tree purpose, value, chain;
15398 if (t == void_list_node)
15399 return t;
15401 purpose = TREE_PURPOSE (t);
15402 if (purpose)
15403 purpose = tsubst_copy (purpose, args, complain, in_decl);
15404 value = TREE_VALUE (t);
15405 if (value)
15406 value = tsubst_copy (value, args, complain, in_decl);
15407 chain = TREE_CHAIN (t);
15408 if (chain && chain != void_type_node)
15409 chain = tsubst_copy (chain, args, complain, in_decl);
15410 if (purpose == TREE_PURPOSE (t)
15411 && value == TREE_VALUE (t)
15412 && chain == TREE_CHAIN (t))
15413 return t;
15414 return tree_cons (purpose, value, chain);
15417 case RECORD_TYPE:
15418 case UNION_TYPE:
15419 case ENUMERAL_TYPE:
15420 case INTEGER_TYPE:
15421 case TEMPLATE_TYPE_PARM:
15422 case TEMPLATE_TEMPLATE_PARM:
15423 case BOUND_TEMPLATE_TEMPLATE_PARM:
15424 case TEMPLATE_PARM_INDEX:
15425 case POINTER_TYPE:
15426 case REFERENCE_TYPE:
15427 case OFFSET_TYPE:
15428 case FUNCTION_TYPE:
15429 case METHOD_TYPE:
15430 case ARRAY_TYPE:
15431 case TYPENAME_TYPE:
15432 case UNBOUND_CLASS_TEMPLATE:
15433 case TYPEOF_TYPE:
15434 case DECLTYPE_TYPE:
15435 case TYPE_DECL:
15436 return tsubst (t, args, complain, in_decl);
15438 case USING_DECL:
15439 t = DECL_NAME (t);
15440 /* Fall through. */
15441 case IDENTIFIER_NODE:
15442 if (IDENTIFIER_CONV_OP_P (t))
15444 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15445 return make_conv_op_name (new_type);
15447 else
15448 return t;
15450 case CONSTRUCTOR:
15451 /* This is handled by tsubst_copy_and_build. */
15452 gcc_unreachable ();
15454 case VA_ARG_EXPR:
15456 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15457 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15458 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
15461 case CLEANUP_POINT_EXPR:
15462 /* We shouldn't have built any of these during initial template
15463 generation. Instead, they should be built during instantiation
15464 in response to the saved STMT_IS_FULL_EXPR_P setting. */
15465 gcc_unreachable ();
15467 case OFFSET_REF:
15469 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15470 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15471 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15472 r = build2 (code, type, op0, op1);
15473 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
15474 if (!mark_used (TREE_OPERAND (r, 1), complain)
15475 && !(complain & tf_error))
15476 return error_mark_node;
15477 return r;
15480 case EXPR_PACK_EXPANSION:
15481 error ("invalid use of pack expansion expression");
15482 return error_mark_node;
15484 case NONTYPE_ARGUMENT_PACK:
15485 error ("use %<...%> to expand argument pack");
15486 return error_mark_node;
15488 case VOID_CST:
15489 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
15490 return t;
15492 case INTEGER_CST:
15493 case REAL_CST:
15494 case STRING_CST:
15495 case COMPLEX_CST:
15497 /* Instantiate any typedefs in the type. */
15498 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15499 r = fold_convert (type, t);
15500 gcc_assert (TREE_CODE (r) == code);
15501 return r;
15504 case PTRMEM_CST:
15505 /* These can sometimes show up in a partial instantiation, but never
15506 involve template parms. */
15507 gcc_assert (!uses_template_parms (t));
15508 return t;
15510 case UNARY_LEFT_FOLD_EXPR:
15511 return tsubst_unary_left_fold (t, args, complain, in_decl);
15512 case UNARY_RIGHT_FOLD_EXPR:
15513 return tsubst_unary_right_fold (t, args, complain, in_decl);
15514 case BINARY_LEFT_FOLD_EXPR:
15515 return tsubst_binary_left_fold (t, args, complain, in_decl);
15516 case BINARY_RIGHT_FOLD_EXPR:
15517 return tsubst_binary_right_fold (t, args, complain, in_decl);
15518 case PREDICT_EXPR:
15519 return t;
15521 case DEBUG_BEGIN_STMT:
15522 /* ??? There's no point in copying it for now, but maybe some
15523 day it will contain more information, such as a pointer back
15524 to the containing function, inlined copy or so. */
15525 return t;
15527 default:
15528 /* We shouldn't get here, but keep going if !flag_checking. */
15529 if (flag_checking)
15530 gcc_unreachable ();
15531 return t;
15535 /* Helper function for tsubst_omp_clauses, used for instantiation of
15536 OMP_CLAUSE_DECL of clauses. */
15538 static tree
15539 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
15540 tree in_decl)
15542 if (decl == NULL_TREE)
15543 return NULL_TREE;
15545 /* Handle an OpenMP array section represented as a TREE_LIST (or
15546 OMP_CLAUSE_DEPEND_KIND). An OMP_CLAUSE_DEPEND (with a depend
15547 kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
15548 TREE_LIST. We can handle it exactly the same as an array section
15549 (purpose, value, and a chain), even though the nomenclature
15550 (low_bound, length, etc) is different. */
15551 if (TREE_CODE (decl) == TREE_LIST)
15553 tree low_bound
15554 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
15555 /*integral_constant_expression_p=*/false);
15556 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
15557 /*integral_constant_expression_p=*/false);
15558 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
15559 in_decl);
15560 if (TREE_PURPOSE (decl) == low_bound
15561 && TREE_VALUE (decl) == length
15562 && TREE_CHAIN (decl) == chain)
15563 return decl;
15564 tree ret = tree_cons (low_bound, length, chain);
15565 OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
15566 = OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
15567 return ret;
15569 tree ret = tsubst_expr (decl, args, complain, in_decl,
15570 /*integral_constant_expression_p=*/false);
15571 /* Undo convert_from_reference tsubst_expr could have called. */
15572 if (decl
15573 && REFERENCE_REF_P (ret)
15574 && !REFERENCE_REF_P (decl))
15575 ret = TREE_OPERAND (ret, 0);
15576 return ret;
15579 /* Like tsubst_copy, but specifically for OpenMP clauses. */
15581 static tree
15582 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
15583 tree args, tsubst_flags_t complain, tree in_decl)
15585 tree new_clauses = NULL_TREE, nc, oc;
15586 tree linear_no_step = NULL_TREE;
15588 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
15590 nc = copy_node (oc);
15591 OMP_CLAUSE_CHAIN (nc) = new_clauses;
15592 new_clauses = nc;
15594 switch (OMP_CLAUSE_CODE (nc))
15596 case OMP_CLAUSE_LASTPRIVATE:
15597 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
15599 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
15600 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
15601 in_decl, /*integral_constant_expression_p=*/false);
15602 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
15603 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
15605 /* FALLTHRU */
15606 case OMP_CLAUSE_PRIVATE:
15607 case OMP_CLAUSE_SHARED:
15608 case OMP_CLAUSE_FIRSTPRIVATE:
15609 case OMP_CLAUSE_COPYIN:
15610 case OMP_CLAUSE_COPYPRIVATE:
15611 case OMP_CLAUSE_UNIFORM:
15612 case OMP_CLAUSE_DEPEND:
15613 case OMP_CLAUSE_FROM:
15614 case OMP_CLAUSE_TO:
15615 case OMP_CLAUSE_MAP:
15616 case OMP_CLAUSE_USE_DEVICE_PTR:
15617 case OMP_CLAUSE_IS_DEVICE_PTR:
15618 OMP_CLAUSE_DECL (nc)
15619 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
15620 in_decl);
15621 break;
15622 case OMP_CLAUSE_TILE:
15623 case OMP_CLAUSE_IF:
15624 case OMP_CLAUSE_NUM_THREADS:
15625 case OMP_CLAUSE_SCHEDULE:
15626 case OMP_CLAUSE_COLLAPSE:
15627 case OMP_CLAUSE_FINAL:
15628 case OMP_CLAUSE_DEVICE:
15629 case OMP_CLAUSE_DIST_SCHEDULE:
15630 case OMP_CLAUSE_NUM_TEAMS:
15631 case OMP_CLAUSE_THREAD_LIMIT:
15632 case OMP_CLAUSE_SAFELEN:
15633 case OMP_CLAUSE_SIMDLEN:
15634 case OMP_CLAUSE_NUM_TASKS:
15635 case OMP_CLAUSE_GRAINSIZE:
15636 case OMP_CLAUSE_PRIORITY:
15637 case OMP_CLAUSE_ORDERED:
15638 case OMP_CLAUSE_HINT:
15639 case OMP_CLAUSE_NUM_GANGS:
15640 case OMP_CLAUSE_NUM_WORKERS:
15641 case OMP_CLAUSE_VECTOR_LENGTH:
15642 case OMP_CLAUSE_WORKER:
15643 case OMP_CLAUSE_VECTOR:
15644 case OMP_CLAUSE_ASYNC:
15645 case OMP_CLAUSE_WAIT:
15646 OMP_CLAUSE_OPERAND (nc, 0)
15647 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
15648 in_decl, /*integral_constant_expression_p=*/false);
15649 break;
15650 case OMP_CLAUSE_REDUCTION:
15651 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
15653 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
15654 if (TREE_CODE (placeholder) == SCOPE_REF)
15656 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
15657 complain, in_decl);
15658 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
15659 = build_qualified_name (NULL_TREE, scope,
15660 TREE_OPERAND (placeholder, 1),
15661 false);
15663 else
15664 gcc_assert (identifier_p (placeholder));
15666 OMP_CLAUSE_DECL (nc)
15667 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
15668 in_decl);
15669 break;
15670 case OMP_CLAUSE_GANG:
15671 case OMP_CLAUSE_ALIGNED:
15672 OMP_CLAUSE_DECL (nc)
15673 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
15674 in_decl);
15675 OMP_CLAUSE_OPERAND (nc, 1)
15676 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
15677 in_decl, /*integral_constant_expression_p=*/false);
15678 break;
15679 case OMP_CLAUSE_LINEAR:
15680 OMP_CLAUSE_DECL (nc)
15681 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
15682 in_decl);
15683 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
15685 gcc_assert (!linear_no_step);
15686 linear_no_step = nc;
15688 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
15689 OMP_CLAUSE_LINEAR_STEP (nc)
15690 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
15691 complain, in_decl);
15692 else
15693 OMP_CLAUSE_LINEAR_STEP (nc)
15694 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
15695 in_decl,
15696 /*integral_constant_expression_p=*/false);
15697 break;
15698 case OMP_CLAUSE_NOWAIT:
15699 case OMP_CLAUSE_DEFAULT:
15700 case OMP_CLAUSE_UNTIED:
15701 case OMP_CLAUSE_MERGEABLE:
15702 case OMP_CLAUSE_INBRANCH:
15703 case OMP_CLAUSE_NOTINBRANCH:
15704 case OMP_CLAUSE_PROC_BIND:
15705 case OMP_CLAUSE_FOR:
15706 case OMP_CLAUSE_PARALLEL:
15707 case OMP_CLAUSE_SECTIONS:
15708 case OMP_CLAUSE_TASKGROUP:
15709 case OMP_CLAUSE_NOGROUP:
15710 case OMP_CLAUSE_THREADS:
15711 case OMP_CLAUSE_SIMD:
15712 case OMP_CLAUSE_DEFAULTMAP:
15713 case OMP_CLAUSE_INDEPENDENT:
15714 case OMP_CLAUSE_AUTO:
15715 case OMP_CLAUSE_SEQ:
15716 break;
15717 default:
15718 gcc_unreachable ();
15720 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
15721 switch (OMP_CLAUSE_CODE (nc))
15723 case OMP_CLAUSE_SHARED:
15724 case OMP_CLAUSE_PRIVATE:
15725 case OMP_CLAUSE_FIRSTPRIVATE:
15726 case OMP_CLAUSE_LASTPRIVATE:
15727 case OMP_CLAUSE_COPYPRIVATE:
15728 case OMP_CLAUSE_LINEAR:
15729 case OMP_CLAUSE_REDUCTION:
15730 case OMP_CLAUSE_USE_DEVICE_PTR:
15731 case OMP_CLAUSE_IS_DEVICE_PTR:
15732 /* tsubst_expr on SCOPE_REF results in returning
15733 finish_non_static_data_member result. Undo that here. */
15734 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
15735 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
15736 == IDENTIFIER_NODE))
15738 tree t = OMP_CLAUSE_DECL (nc);
15739 tree v = t;
15740 while (v)
15741 switch (TREE_CODE (v))
15743 case COMPONENT_REF:
15744 case MEM_REF:
15745 case INDIRECT_REF:
15746 CASE_CONVERT:
15747 case POINTER_PLUS_EXPR:
15748 v = TREE_OPERAND (v, 0);
15749 continue;
15750 case PARM_DECL:
15751 if (DECL_CONTEXT (v) == current_function_decl
15752 && DECL_ARTIFICIAL (v)
15753 && DECL_NAME (v) == this_identifier)
15754 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
15755 /* FALLTHRU */
15756 default:
15757 v = NULL_TREE;
15758 break;
15761 else if (VAR_P (OMP_CLAUSE_DECL (oc))
15762 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
15763 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
15764 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
15765 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
15767 tree decl = OMP_CLAUSE_DECL (nc);
15768 if (VAR_P (decl))
15770 retrofit_lang_decl (decl);
15771 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
15774 break;
15775 default:
15776 break;
15780 new_clauses = nreverse (new_clauses);
15781 if (ort != C_ORT_OMP_DECLARE_SIMD)
15783 new_clauses = finish_omp_clauses (new_clauses, ort);
15784 if (linear_no_step)
15785 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
15786 if (nc == linear_no_step)
15788 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
15789 break;
15792 return new_clauses;
15795 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
15797 static tree
15798 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
15799 tree in_decl)
15801 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
15803 tree purpose, value, chain;
15805 if (t == NULL)
15806 return t;
15808 if (TREE_CODE (t) != TREE_LIST)
15809 return tsubst_copy_and_build (t, args, complain, in_decl,
15810 /*function_p=*/false,
15811 /*integral_constant_expression_p=*/false);
15813 if (t == void_list_node)
15814 return t;
15816 purpose = TREE_PURPOSE (t);
15817 if (purpose)
15818 purpose = RECUR (purpose);
15819 value = TREE_VALUE (t);
15820 if (value)
15822 if (TREE_CODE (value) != LABEL_DECL)
15823 value = RECUR (value);
15824 else
15826 value = lookup_label (DECL_NAME (value));
15827 gcc_assert (TREE_CODE (value) == LABEL_DECL);
15828 TREE_USED (value) = 1;
15831 chain = TREE_CHAIN (t);
15832 if (chain && chain != void_type_node)
15833 chain = RECUR (chain);
15834 return tree_cons (purpose, value, chain);
15835 #undef RECUR
15838 /* Used to temporarily communicate the list of #pragma omp parallel
15839 clauses to #pragma omp for instantiation if they are combined
15840 together. */
15842 static tree *omp_parallel_combined_clauses;
15844 /* Substitute one OMP_FOR iterator. */
15846 static void
15847 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
15848 tree initv, tree condv, tree incrv, tree *clauses,
15849 tree args, tsubst_flags_t complain, tree in_decl,
15850 bool integral_constant_expression_p)
15852 #define RECUR(NODE) \
15853 tsubst_expr ((NODE), args, complain, in_decl, \
15854 integral_constant_expression_p)
15855 tree decl, init, cond, incr;
15857 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
15858 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
15860 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
15862 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
15863 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
15866 decl = TREE_OPERAND (init, 0);
15867 init = TREE_OPERAND (init, 1);
15868 tree decl_expr = NULL_TREE;
15869 if (init && TREE_CODE (init) == DECL_EXPR)
15871 /* We need to jump through some hoops to handle declarations in the
15872 init-statement, since we might need to handle auto deduction,
15873 but we need to keep control of initialization. */
15874 decl_expr = init;
15875 init = DECL_INITIAL (DECL_EXPR_DECL (init));
15876 decl = tsubst_decl (decl, args, complain);
15878 else
15880 if (TREE_CODE (decl) == SCOPE_REF)
15882 decl = RECUR (decl);
15883 if (TREE_CODE (decl) == COMPONENT_REF)
15885 tree v = decl;
15886 while (v)
15887 switch (TREE_CODE (v))
15889 case COMPONENT_REF:
15890 case MEM_REF:
15891 case INDIRECT_REF:
15892 CASE_CONVERT:
15893 case POINTER_PLUS_EXPR:
15894 v = TREE_OPERAND (v, 0);
15895 continue;
15896 case PARM_DECL:
15897 if (DECL_CONTEXT (v) == current_function_decl
15898 && DECL_ARTIFICIAL (v)
15899 && DECL_NAME (v) == this_identifier)
15901 decl = TREE_OPERAND (decl, 1);
15902 decl = omp_privatize_field (decl, false);
15904 /* FALLTHRU */
15905 default:
15906 v = NULL_TREE;
15907 break;
15911 else
15912 decl = RECUR (decl);
15914 init = RECUR (init);
15916 tree auto_node = type_uses_auto (TREE_TYPE (decl));
15917 if (auto_node && init)
15918 TREE_TYPE (decl)
15919 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
15921 gcc_assert (!type_dependent_expression_p (decl));
15923 if (!CLASS_TYPE_P (TREE_TYPE (decl)))
15925 if (decl_expr)
15927 /* Declare the variable, but don't let that initialize it. */
15928 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
15929 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
15930 RECUR (decl_expr);
15931 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
15934 cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
15935 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
15936 if (TREE_CODE (incr) == MODIFY_EXPR)
15938 tree lhs = RECUR (TREE_OPERAND (incr, 0));
15939 tree rhs = RECUR (TREE_OPERAND (incr, 1));
15940 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
15941 NOP_EXPR, rhs, complain);
15943 else
15944 incr = RECUR (incr);
15945 TREE_VEC_ELT (declv, i) = decl;
15946 TREE_VEC_ELT (initv, i) = init;
15947 TREE_VEC_ELT (condv, i) = cond;
15948 TREE_VEC_ELT (incrv, i) = incr;
15949 return;
15952 if (decl_expr)
15954 /* Declare and initialize the variable. */
15955 RECUR (decl_expr);
15956 init = NULL_TREE;
15958 else if (init)
15960 tree *pc;
15961 int j;
15962 for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
15964 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
15966 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
15967 && OMP_CLAUSE_DECL (*pc) == decl)
15968 break;
15969 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
15970 && OMP_CLAUSE_DECL (*pc) == decl)
15972 if (j)
15973 break;
15974 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
15975 tree c = *pc;
15976 *pc = OMP_CLAUSE_CHAIN (c);
15977 OMP_CLAUSE_CHAIN (c) = *clauses;
15978 *clauses = c;
15980 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
15981 && OMP_CLAUSE_DECL (*pc) == decl)
15983 error ("iteration variable %qD should not be firstprivate",
15984 decl);
15985 *pc = OMP_CLAUSE_CHAIN (*pc);
15987 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
15988 && OMP_CLAUSE_DECL (*pc) == decl)
15990 error ("iteration variable %qD should not be reduction",
15991 decl);
15992 *pc = OMP_CLAUSE_CHAIN (*pc);
15994 else
15995 pc = &OMP_CLAUSE_CHAIN (*pc);
15997 if (*pc)
15998 break;
16000 if (*pc == NULL_TREE)
16002 tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
16003 OMP_CLAUSE_DECL (c) = decl;
16004 c = finish_omp_clauses (c, C_ORT_OMP);
16005 if (c)
16007 OMP_CLAUSE_CHAIN (c) = *clauses;
16008 *clauses = c;
16012 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16013 if (COMPARISON_CLASS_P (cond))
16015 tree op0 = RECUR (TREE_OPERAND (cond, 0));
16016 tree op1 = RECUR (TREE_OPERAND (cond, 1));
16017 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16019 else
16020 cond = RECUR (cond);
16021 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16022 switch (TREE_CODE (incr))
16024 case PREINCREMENT_EXPR:
16025 case PREDECREMENT_EXPR:
16026 case POSTINCREMENT_EXPR:
16027 case POSTDECREMENT_EXPR:
16028 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16029 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16030 break;
16031 case MODIFY_EXPR:
16032 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16033 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16035 tree rhs = TREE_OPERAND (incr, 1);
16036 tree lhs = RECUR (TREE_OPERAND (incr, 0));
16037 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16038 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16039 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16040 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16041 rhs0, rhs1));
16043 else
16044 incr = RECUR (incr);
16045 break;
16046 case MODOP_EXPR:
16047 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16048 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16050 tree lhs = RECUR (TREE_OPERAND (incr, 0));
16051 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16052 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16053 TREE_TYPE (decl), lhs,
16054 RECUR (TREE_OPERAND (incr, 2))));
16056 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16057 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16058 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16060 tree rhs = TREE_OPERAND (incr, 2);
16061 tree lhs = RECUR (TREE_OPERAND (incr, 0));
16062 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16063 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16064 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16065 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16066 rhs0, rhs1));
16068 else
16069 incr = RECUR (incr);
16070 break;
16071 default:
16072 incr = RECUR (incr);
16073 break;
16076 TREE_VEC_ELT (declv, i) = decl;
16077 TREE_VEC_ELT (initv, i) = init;
16078 TREE_VEC_ELT (condv, i) = cond;
16079 TREE_VEC_ELT (incrv, i) = incr;
16080 #undef RECUR
16083 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16084 of OMP_TARGET's body. */
16086 static tree
16087 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16089 *walk_subtrees = 0;
16090 switch (TREE_CODE (*tp))
16092 case OMP_TEAMS:
16093 return *tp;
16094 case BIND_EXPR:
16095 case STATEMENT_LIST:
16096 *walk_subtrees = 1;
16097 break;
16098 default:
16099 break;
16101 return NULL_TREE;
16104 /* Helper function for tsubst_expr. For decomposition declaration
16105 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16106 also the corresponding decls representing the identifiers
16107 of the decomposition declaration. Return DECL if successful
16108 or error_mark_node otherwise, set *FIRST to the first decl
16109 in the list chained through DECL_CHAIN and *CNT to the number
16110 of such decls. */
16112 static tree
16113 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16114 tsubst_flags_t complain, tree in_decl, tree *first,
16115 unsigned int *cnt)
16117 tree decl2, decl3, prev = decl;
16118 *cnt = 0;
16119 gcc_assert (DECL_NAME (decl) == NULL_TREE);
16120 for (decl2 = DECL_CHAIN (pattern_decl);
16121 decl2
16122 && VAR_P (decl2)
16123 && DECL_DECOMPOSITION_P (decl2)
16124 && DECL_NAME (decl2);
16125 decl2 = DECL_CHAIN (decl2))
16127 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16129 gcc_assert (errorcount);
16130 return error_mark_node;
16132 (*cnt)++;
16133 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16134 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16135 tree v = DECL_VALUE_EXPR (decl2);
16136 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16137 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16138 decl3 = tsubst (decl2, args, complain, in_decl);
16139 SET_DECL_VALUE_EXPR (decl2, v);
16140 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16141 if (VAR_P (decl3))
16142 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16143 maybe_push_decl (decl3);
16144 if (error_operand_p (decl3))
16145 decl = error_mark_node;
16146 else if (decl != error_mark_node
16147 && DECL_CHAIN (decl3) != prev)
16149 gcc_assert (errorcount);
16150 decl = error_mark_node;
16152 else
16153 prev = decl3;
16155 *first = prev;
16156 return decl;
16159 /* Like tsubst_copy for expressions, etc. but also does semantic
16160 processing. */
16162 tree
16163 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
16164 bool integral_constant_expression_p)
16166 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
16167 #define RECUR(NODE) \
16168 tsubst_expr ((NODE), args, complain, in_decl, \
16169 integral_constant_expression_p)
16171 tree stmt, tmp;
16172 tree r;
16173 location_t loc;
16175 if (t == NULL_TREE || t == error_mark_node)
16176 return t;
16178 loc = input_location;
16179 if (EXPR_HAS_LOCATION (t))
16180 input_location = EXPR_LOCATION (t);
16181 if (STATEMENT_CODE_P (TREE_CODE (t)))
16182 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
16184 switch (TREE_CODE (t))
16186 case STATEMENT_LIST:
16188 tree_stmt_iterator i;
16189 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
16190 RECUR (tsi_stmt (i));
16191 break;
16194 case CTOR_INITIALIZER:
16195 finish_mem_initializers (tsubst_initializer_list
16196 (TREE_OPERAND (t, 0), args));
16197 break;
16199 case RETURN_EXPR:
16200 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
16201 break;
16203 case EXPR_STMT:
16204 tmp = RECUR (EXPR_STMT_EXPR (t));
16205 if (EXPR_STMT_STMT_EXPR_RESULT (t))
16206 finish_stmt_expr_expr (tmp, cur_stmt_expr);
16207 else
16208 finish_expr_stmt (tmp);
16209 break;
16211 case USING_STMT:
16212 finish_local_using_directive (USING_STMT_NAMESPACE (t),
16213 /*attribs=*/NULL_TREE);
16214 break;
16216 case DECL_EXPR:
16218 tree decl, pattern_decl;
16219 tree init;
16221 pattern_decl = decl = DECL_EXPR_DECL (t);
16222 if (TREE_CODE (decl) == LABEL_DECL)
16223 finish_label_decl (DECL_NAME (decl));
16224 else if (TREE_CODE (decl) == USING_DECL)
16226 tree scope = USING_DECL_SCOPE (decl);
16227 tree name = DECL_NAME (decl);
16229 scope = tsubst (scope, args, complain, in_decl);
16230 decl = lookup_qualified_name (scope, name,
16231 /*is_type_p=*/false,
16232 /*complain=*/false);
16233 if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
16234 qualified_name_lookup_error (scope, name, decl, input_location);
16235 else
16236 finish_local_using_decl (decl, scope, name);
16238 else if (is_capture_proxy (decl)
16239 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
16241 /* We're in tsubst_lambda_expr, we've already inserted a new
16242 capture proxy, so look it up and register it. */
16243 tree inst;
16244 if (DECL_PACK_P (decl))
16246 inst = (retrieve_local_specialization
16247 (DECL_CAPTURED_VARIABLE (decl)));
16248 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
16250 else
16252 inst = lookup_name_real (DECL_NAME (decl), 0, 0,
16253 /*block_p=*/true, 0, LOOKUP_HIDDEN);
16254 gcc_assert (inst != decl && is_capture_proxy (inst));
16256 register_local_specialization (inst, decl);
16257 break;
16259 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
16260 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
16261 /* Don't copy the old closure; we'll create a new one in
16262 tsubst_lambda_expr. */
16263 break;
16264 else
16266 init = DECL_INITIAL (decl);
16267 decl = tsubst (decl, args, complain, in_decl);
16268 if (decl != error_mark_node)
16270 /* By marking the declaration as instantiated, we avoid
16271 trying to instantiate it. Since instantiate_decl can't
16272 handle local variables, and since we've already done
16273 all that needs to be done, that's the right thing to
16274 do. */
16275 if (VAR_P (decl))
16276 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16277 if (VAR_P (decl)
16278 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
16279 /* Anonymous aggregates are a special case. */
16280 finish_anon_union (decl);
16281 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
16283 DECL_CONTEXT (decl) = current_function_decl;
16284 if (DECL_NAME (decl) == this_identifier)
16286 tree lam = DECL_CONTEXT (current_function_decl);
16287 lam = CLASSTYPE_LAMBDA_EXPR (lam);
16288 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
16290 insert_capture_proxy (decl);
16292 else if (DECL_IMPLICIT_TYPEDEF_P (t))
16293 /* We already did a pushtag. */;
16294 else if (TREE_CODE (decl) == FUNCTION_DECL
16295 && DECL_OMP_DECLARE_REDUCTION_P (decl)
16296 && DECL_FUNCTION_SCOPE_P (pattern_decl))
16298 DECL_CONTEXT (decl) = NULL_TREE;
16299 pushdecl (decl);
16300 DECL_CONTEXT (decl) = current_function_decl;
16301 cp_check_omp_declare_reduction (decl);
16303 else
16305 int const_init = false;
16306 maybe_push_decl (decl);
16307 if (VAR_P (decl)
16308 && DECL_PRETTY_FUNCTION_P (decl))
16310 /* For __PRETTY_FUNCTION__ we have to adjust the
16311 initializer. */
16312 const char *const name
16313 = cxx_printable_name (current_function_decl, 2);
16314 init = cp_fname_init (name, &TREE_TYPE (decl));
16316 else
16317 init = tsubst_init (init, decl, args, complain, in_decl);
16319 if (VAR_P (decl))
16320 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
16321 (pattern_decl));
16322 if (VAR_P (decl)
16323 && DECL_DECOMPOSITION_P (decl)
16324 && TREE_TYPE (pattern_decl) != error_mark_node)
16326 unsigned int cnt;
16327 tree first;
16328 tree ndecl
16329 = tsubst_decomp_names (decl, pattern_decl, args,
16330 complain, in_decl, &first, &cnt);
16331 if (ndecl != error_mark_node)
16332 cp_maybe_mangle_decomp (ndecl, first, cnt);
16333 cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16334 if (ndecl != error_mark_node)
16335 cp_finish_decomp (ndecl, first, cnt);
16337 else
16338 cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16343 break;
16346 case FOR_STMT:
16347 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
16348 RECUR (FOR_INIT_STMT (t));
16349 finish_init_stmt (stmt);
16350 tmp = RECUR (FOR_COND (t));
16351 finish_for_cond (tmp, stmt, false, 0);
16352 tmp = RECUR (FOR_EXPR (t));
16353 finish_for_expr (tmp, stmt);
16355 bool prev = note_iteration_stmt_body_start ();
16356 RECUR (FOR_BODY (t));
16357 note_iteration_stmt_body_end (prev);
16359 finish_for_stmt (stmt);
16360 break;
16362 case RANGE_FOR_STMT:
16364 /* Construct another range_for, if this is not a final
16365 substitution (for inside inside a generic lambda of a
16366 template). Otherwise convert to a regular for. */
16367 tree decl, expr;
16368 stmt = (processing_template_decl
16369 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
16370 : begin_for_stmt (NULL_TREE, NULL_TREE));
16371 decl = RANGE_FOR_DECL (t);
16372 decl = tsubst (decl, args, complain, in_decl);
16373 maybe_push_decl (decl);
16374 expr = RECUR (RANGE_FOR_EXPR (t));
16376 tree decomp_first = NULL_TREE;
16377 unsigned decomp_cnt = 0;
16378 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
16379 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
16380 complain, in_decl,
16381 &decomp_first, &decomp_cnt);
16383 if (processing_template_decl)
16385 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
16386 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
16387 finish_range_for_decl (stmt, decl, expr);
16389 else
16391 unsigned short unroll = (RANGE_FOR_UNROLL (t)
16392 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
16393 stmt = cp_convert_range_for (stmt, decl, expr,
16394 decomp_first, decomp_cnt,
16395 RANGE_FOR_IVDEP (t), unroll);
16398 bool prev = note_iteration_stmt_body_start ();
16399 RECUR (RANGE_FOR_BODY (t));
16400 note_iteration_stmt_body_end (prev);
16401 finish_for_stmt (stmt);
16403 break;
16405 case WHILE_STMT:
16406 stmt = begin_while_stmt ();
16407 tmp = RECUR (WHILE_COND (t));
16408 finish_while_stmt_cond (tmp, stmt, false, 0);
16410 bool prev = note_iteration_stmt_body_start ();
16411 RECUR (WHILE_BODY (t));
16412 note_iteration_stmt_body_end (prev);
16414 finish_while_stmt (stmt);
16415 break;
16417 case DO_STMT:
16418 stmt = begin_do_stmt ();
16420 bool prev = note_iteration_stmt_body_start ();
16421 RECUR (DO_BODY (t));
16422 note_iteration_stmt_body_end (prev);
16424 finish_do_body (stmt);
16425 tmp = RECUR (DO_COND (t));
16426 finish_do_stmt (tmp, stmt, false, 0);
16427 break;
16429 case IF_STMT:
16430 stmt = begin_if_stmt ();
16431 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
16432 tmp = RECUR (IF_COND (t));
16433 tmp = finish_if_stmt_cond (tmp, stmt);
16434 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
16435 /* Don't instantiate the THEN_CLAUSE. */;
16436 else
16438 bool inhibit = integer_zerop (fold_non_dependent_expr (tmp));
16439 if (inhibit)
16440 ++c_inhibit_evaluation_warnings;
16441 RECUR (THEN_CLAUSE (t));
16442 if (inhibit)
16443 --c_inhibit_evaluation_warnings;
16445 finish_then_clause (stmt);
16447 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
16448 /* Don't instantiate the ELSE_CLAUSE. */;
16449 else if (ELSE_CLAUSE (t))
16451 bool inhibit = integer_nonzerop (fold_non_dependent_expr (tmp));
16452 begin_else_clause (stmt);
16453 if (inhibit)
16454 ++c_inhibit_evaluation_warnings;
16455 RECUR (ELSE_CLAUSE (t));
16456 if (inhibit)
16457 --c_inhibit_evaluation_warnings;
16458 finish_else_clause (stmt);
16461 finish_if_stmt (stmt);
16462 break;
16464 case BIND_EXPR:
16465 if (BIND_EXPR_BODY_BLOCK (t))
16466 stmt = begin_function_body ();
16467 else
16468 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
16469 ? BCS_TRY_BLOCK : 0);
16471 RECUR (BIND_EXPR_BODY (t));
16473 if (BIND_EXPR_BODY_BLOCK (t))
16474 finish_function_body (stmt);
16475 else
16476 finish_compound_stmt (stmt);
16477 break;
16479 case BREAK_STMT:
16480 finish_break_stmt ();
16481 break;
16483 case CONTINUE_STMT:
16484 finish_continue_stmt ();
16485 break;
16487 case SWITCH_STMT:
16488 stmt = begin_switch_stmt ();
16489 tmp = RECUR (SWITCH_STMT_COND (t));
16490 finish_switch_cond (tmp, stmt);
16491 RECUR (SWITCH_STMT_BODY (t));
16492 finish_switch_stmt (stmt);
16493 break;
16495 case CASE_LABEL_EXPR:
16497 tree low = RECUR (CASE_LOW (t));
16498 tree high = RECUR (CASE_HIGH (t));
16499 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
16500 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
16501 FALLTHROUGH_LABEL_P (CASE_LABEL (l))
16502 = FALLTHROUGH_LABEL_P (CASE_LABEL (t));
16504 break;
16506 case LABEL_EXPR:
16508 tree decl = LABEL_EXPR_LABEL (t);
16509 tree label;
16511 label = finish_label_stmt (DECL_NAME (decl));
16512 if (TREE_CODE (label) == LABEL_DECL)
16513 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
16514 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
16515 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
16517 break;
16519 case GOTO_EXPR:
16520 tmp = GOTO_DESTINATION (t);
16521 if (TREE_CODE (tmp) != LABEL_DECL)
16522 /* Computed goto's must be tsubst'd into. On the other hand,
16523 non-computed gotos must not be; the identifier in question
16524 will have no binding. */
16525 tmp = RECUR (tmp);
16526 else
16527 tmp = DECL_NAME (tmp);
16528 finish_goto_stmt (tmp);
16529 break;
16531 case ASM_EXPR:
16533 tree string = RECUR (ASM_STRING (t));
16534 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
16535 complain, in_decl);
16536 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
16537 complain, in_decl);
16538 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
16539 complain, in_decl);
16540 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
16541 complain, in_decl);
16542 tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
16543 clobbers, labels);
16544 tree asm_expr = tmp;
16545 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
16546 asm_expr = TREE_OPERAND (asm_expr, 0);
16547 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
16549 break;
16551 case TRY_BLOCK:
16552 if (CLEANUP_P (t))
16554 stmt = begin_try_block ();
16555 RECUR (TRY_STMTS (t));
16556 finish_cleanup_try_block (stmt);
16557 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
16559 else
16561 tree compound_stmt = NULL_TREE;
16563 if (FN_TRY_BLOCK_P (t))
16564 stmt = begin_function_try_block (&compound_stmt);
16565 else
16566 stmt = begin_try_block ();
16568 RECUR (TRY_STMTS (t));
16570 if (FN_TRY_BLOCK_P (t))
16571 finish_function_try_block (stmt);
16572 else
16573 finish_try_block (stmt);
16575 RECUR (TRY_HANDLERS (t));
16576 if (FN_TRY_BLOCK_P (t))
16577 finish_function_handler_sequence (stmt, compound_stmt);
16578 else
16579 finish_handler_sequence (stmt);
16581 break;
16583 case HANDLER:
16585 tree decl = HANDLER_PARMS (t);
16587 if (decl)
16589 decl = tsubst (decl, args, complain, in_decl);
16590 /* Prevent instantiate_decl from trying to instantiate
16591 this variable. We've already done all that needs to be
16592 done. */
16593 if (decl != error_mark_node)
16594 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16596 stmt = begin_handler ();
16597 finish_handler_parms (decl, stmt);
16598 RECUR (HANDLER_BODY (t));
16599 finish_handler (stmt);
16601 break;
16603 case TAG_DEFN:
16604 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
16605 if (CLASS_TYPE_P (tmp))
16607 /* Local classes are not independent templates; they are
16608 instantiated along with their containing function. And this
16609 way we don't have to deal with pushing out of one local class
16610 to instantiate a member of another local class. */
16611 /* Closures are handled by the LAMBDA_EXPR. */
16612 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
16613 complete_type (tmp);
16614 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
16615 if ((VAR_P (fld)
16616 || (TREE_CODE (fld) == FUNCTION_DECL
16617 && !DECL_ARTIFICIAL (fld)))
16618 && DECL_TEMPLATE_INSTANTIATION (fld))
16619 instantiate_decl (fld, /*defer_ok=*/false,
16620 /*expl_inst_class=*/false);
16622 break;
16624 case STATIC_ASSERT:
16626 tree condition;
16628 ++c_inhibit_evaluation_warnings;
16629 condition =
16630 tsubst_expr (STATIC_ASSERT_CONDITION (t),
16631 args,
16632 complain, in_decl,
16633 /*integral_constant_expression_p=*/true);
16634 --c_inhibit_evaluation_warnings;
16636 finish_static_assert (condition,
16637 STATIC_ASSERT_MESSAGE (t),
16638 STATIC_ASSERT_SOURCE_LOCATION (t),
16639 /*member_p=*/false);
16641 break;
16643 case OACC_KERNELS:
16644 case OACC_PARALLEL:
16645 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
16646 in_decl);
16647 stmt = begin_omp_parallel ();
16648 RECUR (OMP_BODY (t));
16649 finish_omp_construct (TREE_CODE (t), stmt, tmp);
16650 break;
16652 case OMP_PARALLEL:
16653 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
16654 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
16655 complain, in_decl);
16656 if (OMP_PARALLEL_COMBINED (t))
16657 omp_parallel_combined_clauses = &tmp;
16658 stmt = begin_omp_parallel ();
16659 RECUR (OMP_PARALLEL_BODY (t));
16660 gcc_assert (omp_parallel_combined_clauses == NULL);
16661 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
16662 = OMP_PARALLEL_COMBINED (t);
16663 pop_omp_privatization_clauses (r);
16664 break;
16666 case OMP_TASK:
16667 r = push_omp_privatization_clauses (false);
16668 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
16669 complain, in_decl);
16670 stmt = begin_omp_task ();
16671 RECUR (OMP_TASK_BODY (t));
16672 finish_omp_task (tmp, stmt);
16673 pop_omp_privatization_clauses (r);
16674 break;
16676 case OMP_FOR:
16677 case OMP_SIMD:
16678 case OMP_DISTRIBUTE:
16679 case OMP_TASKLOOP:
16680 case OACC_LOOP:
16682 tree clauses, body, pre_body;
16683 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
16684 tree orig_declv = NULL_TREE;
16685 tree incrv = NULL_TREE;
16686 enum c_omp_region_type ort = C_ORT_OMP;
16687 int i;
16689 if (TREE_CODE (t) == OACC_LOOP)
16690 ort = C_ORT_ACC;
16692 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
16693 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
16694 in_decl);
16695 if (OMP_FOR_INIT (t) != NULL_TREE)
16697 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
16698 if (OMP_FOR_ORIG_DECLS (t))
16699 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
16700 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
16701 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
16702 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
16705 stmt = begin_omp_structured_block ();
16707 pre_body = push_stmt_list ();
16708 RECUR (OMP_FOR_PRE_BODY (t));
16709 pre_body = pop_stmt_list (pre_body);
16711 if (OMP_FOR_INIT (t) != NULL_TREE)
16712 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
16713 tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
16714 incrv, &clauses, args, complain, in_decl,
16715 integral_constant_expression_p);
16716 omp_parallel_combined_clauses = NULL;
16718 body = push_stmt_list ();
16719 RECUR (OMP_FOR_BODY (t));
16720 body = pop_stmt_list (body);
16722 if (OMP_FOR_INIT (t) != NULL_TREE)
16723 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
16724 orig_declv, initv, condv, incrv, body, pre_body,
16725 NULL, clauses);
16726 else
16728 t = make_node (TREE_CODE (t));
16729 TREE_TYPE (t) = void_type_node;
16730 OMP_FOR_BODY (t) = body;
16731 OMP_FOR_PRE_BODY (t) = pre_body;
16732 OMP_FOR_CLAUSES (t) = clauses;
16733 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
16734 add_stmt (t);
16737 add_stmt (finish_omp_structured_block (stmt));
16738 pop_omp_privatization_clauses (r);
16740 break;
16742 case OMP_SECTIONS:
16743 omp_parallel_combined_clauses = NULL;
16744 /* FALLTHRU */
16745 case OMP_SINGLE:
16746 case OMP_TEAMS:
16747 case OMP_CRITICAL:
16748 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
16749 && OMP_TEAMS_COMBINED (t));
16750 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
16751 in_decl);
16752 stmt = push_stmt_list ();
16753 RECUR (OMP_BODY (t));
16754 stmt = pop_stmt_list (stmt);
16756 t = copy_node (t);
16757 OMP_BODY (t) = stmt;
16758 OMP_CLAUSES (t) = tmp;
16759 add_stmt (t);
16760 pop_omp_privatization_clauses (r);
16761 break;
16763 case OACC_DATA:
16764 case OMP_TARGET_DATA:
16765 case OMP_TARGET:
16766 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
16767 ? C_ORT_ACC : C_ORT_OMP, args, complain,
16768 in_decl);
16769 keep_next_level (true);
16770 stmt = begin_omp_structured_block ();
16772 RECUR (OMP_BODY (t));
16773 stmt = finish_omp_structured_block (stmt);
16775 t = copy_node (t);
16776 OMP_BODY (t) = stmt;
16777 OMP_CLAUSES (t) = tmp;
16778 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
16780 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
16781 if (teams)
16783 /* For combined target teams, ensure the num_teams and
16784 thread_limit clause expressions are evaluated on the host,
16785 before entering the target construct. */
16786 tree c;
16787 for (c = OMP_TEAMS_CLAUSES (teams);
16788 c; c = OMP_CLAUSE_CHAIN (c))
16789 if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
16790 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
16791 && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
16793 tree expr = OMP_CLAUSE_OPERAND (c, 0);
16794 expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
16795 if (expr == error_mark_node)
16796 continue;
16797 tmp = TARGET_EXPR_SLOT (expr);
16798 add_stmt (expr);
16799 OMP_CLAUSE_OPERAND (c, 0) = expr;
16800 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
16801 OMP_CLAUSE_FIRSTPRIVATE);
16802 OMP_CLAUSE_DECL (tc) = tmp;
16803 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
16804 OMP_TARGET_CLAUSES (t) = tc;
16808 add_stmt (t);
16809 break;
16811 case OACC_DECLARE:
16812 t = copy_node (t);
16813 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
16814 complain, in_decl);
16815 OACC_DECLARE_CLAUSES (t) = tmp;
16816 add_stmt (t);
16817 break;
16819 case OMP_TARGET_UPDATE:
16820 case OMP_TARGET_ENTER_DATA:
16821 case OMP_TARGET_EXIT_DATA:
16822 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
16823 complain, in_decl);
16824 t = copy_node (t);
16825 OMP_STANDALONE_CLAUSES (t) = tmp;
16826 add_stmt (t);
16827 break;
16829 case OACC_ENTER_DATA:
16830 case OACC_EXIT_DATA:
16831 case OACC_UPDATE:
16832 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
16833 complain, in_decl);
16834 t = copy_node (t);
16835 OMP_STANDALONE_CLAUSES (t) = tmp;
16836 add_stmt (t);
16837 break;
16839 case OMP_ORDERED:
16840 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
16841 complain, in_decl);
16842 stmt = push_stmt_list ();
16843 RECUR (OMP_BODY (t));
16844 stmt = pop_stmt_list (stmt);
16846 t = copy_node (t);
16847 OMP_BODY (t) = stmt;
16848 OMP_ORDERED_CLAUSES (t) = tmp;
16849 add_stmt (t);
16850 break;
16852 case OMP_SECTION:
16853 case OMP_MASTER:
16854 case OMP_TASKGROUP:
16855 stmt = push_stmt_list ();
16856 RECUR (OMP_BODY (t));
16857 stmt = pop_stmt_list (stmt);
16859 t = copy_node (t);
16860 OMP_BODY (t) = stmt;
16861 add_stmt (t);
16862 break;
16864 case OMP_ATOMIC:
16865 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
16866 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
16868 tree op1 = TREE_OPERAND (t, 1);
16869 tree rhs1 = NULL_TREE;
16870 tree lhs, rhs;
16871 if (TREE_CODE (op1) == COMPOUND_EXPR)
16873 rhs1 = RECUR (TREE_OPERAND (op1, 0));
16874 op1 = TREE_OPERAND (op1, 1);
16876 lhs = RECUR (TREE_OPERAND (op1, 0));
16877 rhs = RECUR (TREE_OPERAND (op1, 1));
16878 finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
16879 NULL_TREE, NULL_TREE, rhs1,
16880 OMP_ATOMIC_SEQ_CST (t));
16882 else
16884 tree op1 = TREE_OPERAND (t, 1);
16885 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
16886 tree rhs1 = NULL_TREE;
16887 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
16888 enum tree_code opcode = NOP_EXPR;
16889 if (code == OMP_ATOMIC_READ)
16891 v = RECUR (TREE_OPERAND (op1, 0));
16892 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
16894 else if (code == OMP_ATOMIC_CAPTURE_OLD
16895 || code == OMP_ATOMIC_CAPTURE_NEW)
16897 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
16898 v = RECUR (TREE_OPERAND (op1, 0));
16899 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
16900 if (TREE_CODE (op11) == COMPOUND_EXPR)
16902 rhs1 = RECUR (TREE_OPERAND (op11, 0));
16903 op11 = TREE_OPERAND (op11, 1);
16905 lhs = RECUR (TREE_OPERAND (op11, 0));
16906 rhs = RECUR (TREE_OPERAND (op11, 1));
16907 opcode = TREE_CODE (op11);
16908 if (opcode == MODIFY_EXPR)
16909 opcode = NOP_EXPR;
16911 else
16913 code = OMP_ATOMIC;
16914 lhs = RECUR (TREE_OPERAND (op1, 0));
16915 rhs = RECUR (TREE_OPERAND (op1, 1));
16917 finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
16918 OMP_ATOMIC_SEQ_CST (t));
16920 break;
16922 case TRANSACTION_EXPR:
16924 int flags = 0;
16925 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
16926 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
16928 if (TRANSACTION_EXPR_IS_STMT (t))
16930 tree body = TRANSACTION_EXPR_BODY (t);
16931 tree noex = NULL_TREE;
16932 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
16934 noex = MUST_NOT_THROW_COND (body);
16935 if (noex == NULL_TREE)
16936 noex = boolean_true_node;
16937 body = TREE_OPERAND (body, 0);
16939 stmt = begin_transaction_stmt (input_location, NULL, flags);
16940 RECUR (body);
16941 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
16943 else
16945 stmt = build_transaction_expr (EXPR_LOCATION (t),
16946 RECUR (TRANSACTION_EXPR_BODY (t)),
16947 flags, NULL_TREE);
16948 RETURN (stmt);
16951 break;
16953 case MUST_NOT_THROW_EXPR:
16955 tree op0 = RECUR (TREE_OPERAND (t, 0));
16956 tree cond = RECUR (MUST_NOT_THROW_COND (t));
16957 RETURN (build_must_not_throw_expr (op0, cond));
16960 case EXPR_PACK_EXPANSION:
16961 error ("invalid use of pack expansion expression");
16962 RETURN (error_mark_node);
16964 case NONTYPE_ARGUMENT_PACK:
16965 error ("use %<...%> to expand argument pack");
16966 RETURN (error_mark_node);
16968 case COMPOUND_EXPR:
16969 tmp = RECUR (TREE_OPERAND (t, 0));
16970 if (tmp == NULL_TREE)
16971 /* If the first operand was a statement, we're done with it. */
16972 RETURN (RECUR (TREE_OPERAND (t, 1)));
16973 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
16974 RECUR (TREE_OPERAND (t, 1)),
16975 complain));
16977 case ANNOTATE_EXPR:
16978 tmp = RECUR (TREE_OPERAND (t, 0));
16979 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
16980 TREE_TYPE (tmp), tmp,
16981 RECUR (TREE_OPERAND (t, 1)),
16982 RECUR (TREE_OPERAND (t, 2))));
16984 default:
16985 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
16987 RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
16988 /*function_p=*/false,
16989 integral_constant_expression_p));
16992 RETURN (NULL_TREE);
16993 out:
16994 input_location = loc;
16995 return r;
16996 #undef RECUR
16997 #undef RETURN
17000 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17001 function. For description of the body see comment above
17002 cp_parser_omp_declare_reduction_exprs. */
17004 static void
17005 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17007 if (t == NULL_TREE || t == error_mark_node)
17008 return;
17010 gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17012 tree_stmt_iterator tsi;
17013 int i;
17014 tree stmts[7];
17015 memset (stmts, 0, sizeof stmts);
17016 for (i = 0, tsi = tsi_start (t);
17017 i < 7 && !tsi_end_p (tsi);
17018 i++, tsi_next (&tsi))
17019 stmts[i] = tsi_stmt (tsi);
17020 gcc_assert (tsi_end_p (tsi));
17022 if (i >= 3)
17024 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17025 && TREE_CODE (stmts[1]) == DECL_EXPR);
17026 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17027 args, complain, in_decl);
17028 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17029 args, complain, in_decl);
17030 DECL_CONTEXT (omp_out) = current_function_decl;
17031 DECL_CONTEXT (omp_in) = current_function_decl;
17032 keep_next_level (true);
17033 tree block = begin_omp_structured_block ();
17034 tsubst_expr (stmts[2], args, complain, in_decl, false);
17035 block = finish_omp_structured_block (block);
17036 block = maybe_cleanup_point_expr_void (block);
17037 add_decl_expr (omp_out);
17038 if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17039 TREE_NO_WARNING (omp_out) = 1;
17040 add_decl_expr (omp_in);
17041 finish_expr_stmt (block);
17043 if (i >= 6)
17045 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17046 && TREE_CODE (stmts[4]) == DECL_EXPR);
17047 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17048 args, complain, in_decl);
17049 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17050 args, complain, in_decl);
17051 DECL_CONTEXT (omp_priv) = current_function_decl;
17052 DECL_CONTEXT (omp_orig) = current_function_decl;
17053 keep_next_level (true);
17054 tree block = begin_omp_structured_block ();
17055 tsubst_expr (stmts[5], args, complain, in_decl, false);
17056 block = finish_omp_structured_block (block);
17057 block = maybe_cleanup_point_expr_void (block);
17058 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17059 add_decl_expr (omp_priv);
17060 add_decl_expr (omp_orig);
17061 finish_expr_stmt (block);
17062 if (i == 7)
17063 add_decl_expr (omp_orig);
17067 /* T is a postfix-expression that is not being used in a function
17068 call. Return the substituted version of T. */
17070 static tree
17071 tsubst_non_call_postfix_expression (tree t, tree args,
17072 tsubst_flags_t complain,
17073 tree in_decl)
17075 if (TREE_CODE (t) == SCOPE_REF)
17076 t = tsubst_qualified_id (t, args, complain, in_decl,
17077 /*done=*/false, /*address_p=*/false);
17078 else
17079 t = tsubst_copy_and_build (t, args, complain, in_decl,
17080 /*function_p=*/false,
17081 /*integral_constant_expression_p=*/false);
17083 return t;
17086 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
17087 instantiation context. Instantiating a pack expansion containing a lambda
17088 might result in multiple lambdas all based on the same lambda in the
17089 template. */
17091 tree
17092 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17094 tree oldfn = lambda_function (t);
17095 in_decl = oldfn;
17097 tree r = build_lambda_expr ();
17099 LAMBDA_EXPR_LOCATION (r)
17100 = LAMBDA_EXPR_LOCATION (t);
17101 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17102 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17103 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17105 if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
17106 LAMBDA_EXPR_EXTRA_SCOPE (r) = NULL_TREE;
17107 else
17108 record_lambda_scope (r);
17110 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17111 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17113 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
17114 cap = TREE_CHAIN (cap))
17116 tree field = TREE_PURPOSE (cap);
17117 if (PACK_EXPANSION_P (field))
17118 field = PACK_EXPANSION_PATTERN (field);
17119 field = tsubst_decl (field, args, complain);
17121 if (field == error_mark_node)
17122 return error_mark_node;
17124 tree init = TREE_VALUE (cap);
17125 if (PACK_EXPANSION_P (init))
17126 init = tsubst_pack_expansion (init, args, complain, in_decl);
17127 else
17128 init = tsubst_copy_and_build (init, args, complain, in_decl,
17129 /*fn*/false, /*constexpr*/false);
17131 if (TREE_CODE (field) == TREE_VEC)
17133 int len = TREE_VEC_LENGTH (field);
17134 gcc_assert (TREE_CODE (init) == TREE_VEC
17135 && TREE_VEC_LENGTH (init) == len);
17136 for (int i = 0; i < len; ++i)
17137 LAMBDA_EXPR_CAPTURE_LIST (r)
17138 = tree_cons (TREE_VEC_ELT (field, i),
17139 TREE_VEC_ELT (init, i),
17140 LAMBDA_EXPR_CAPTURE_LIST (r));
17142 else
17144 LAMBDA_EXPR_CAPTURE_LIST (r)
17145 = tree_cons (field, init, LAMBDA_EXPR_CAPTURE_LIST (r));
17147 if (id_equal (DECL_NAME (field), "__this"))
17148 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
17152 tree type = begin_lambda_type (r);
17154 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
17155 determine_visibility (TYPE_NAME (type));
17157 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
17159 tree oldtmpl = (generic_lambda_fn_p (oldfn)
17160 ? DECL_TI_TEMPLATE (oldfn)
17161 : NULL_TREE);
17163 tree fntype = static_fn_type (oldfn);
17164 if (oldtmpl)
17165 ++processing_template_decl;
17166 fntype = tsubst (fntype, args, complain, in_decl);
17167 if (oldtmpl)
17168 --processing_template_decl;
17170 if (fntype == error_mark_node)
17171 r = error_mark_node;
17172 else
17174 /* Fix the type of 'this'. */
17175 fntype = build_memfn_type (fntype, type,
17176 type_memfn_quals (fntype),
17177 type_memfn_rqual (fntype));
17178 tree fn, tmpl;
17179 if (oldtmpl)
17181 tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
17182 fn = DECL_TEMPLATE_RESULT (tmpl);
17183 finish_member_declaration (tmpl);
17185 else
17187 tmpl = NULL_TREE;
17188 fn = tsubst_function_decl (oldfn, args, complain, fntype);
17189 finish_member_declaration (fn);
17192 /* Let finish_function set this. */
17193 DECL_DECLARED_CONSTEXPR_P (fn) = false;
17195 bool nested = cfun;
17196 if (nested)
17197 push_function_context ();
17198 else
17199 /* Still increment function_depth so that we don't GC in the
17200 middle of an expression. */
17201 ++function_depth;
17203 local_specialization_stack s (lss_copy);
17205 tree body = start_lambda_function (fn, r);
17207 register_parameter_specializations (oldfn, fn);
17209 tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
17210 /*constexpr*/false);
17212 finish_lambda_function (body);
17214 if (nested)
17215 pop_function_context ();
17216 else
17217 --function_depth;
17219 /* The capture list was built up in reverse order; fix that now. */
17220 LAMBDA_EXPR_CAPTURE_LIST (r)
17221 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
17223 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17225 maybe_add_lambda_conv_op (type);
17228 finish_struct (type, /*attr*/NULL_TREE);
17230 insert_pending_capture_proxies ();
17232 return r;
17235 /* Like tsubst but deals with expressions and performs semantic
17236 analysis. FUNCTION_P is true if T is the "F" in "F (ARGS)". */
17238 tree
17239 tsubst_copy_and_build (tree t,
17240 tree args,
17241 tsubst_flags_t complain,
17242 tree in_decl,
17243 bool function_p,
17244 bool integral_constant_expression_p)
17246 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
17247 #define RECUR(NODE) \
17248 tsubst_copy_and_build (NODE, args, complain, in_decl, \
17249 /*function_p=*/false, \
17250 integral_constant_expression_p)
17252 tree retval, op1;
17253 location_t loc;
17255 if (t == NULL_TREE || t == error_mark_node)
17256 return t;
17258 loc = input_location;
17259 if (EXPR_HAS_LOCATION (t))
17260 input_location = EXPR_LOCATION (t);
17262 /* N3276 decltype magic only applies to calls at the top level or on the
17263 right side of a comma. */
17264 tsubst_flags_t decltype_flag = (complain & tf_decltype);
17265 complain &= ~tf_decltype;
17267 switch (TREE_CODE (t))
17269 case USING_DECL:
17270 t = DECL_NAME (t);
17271 /* Fall through. */
17272 case IDENTIFIER_NODE:
17274 tree decl;
17275 cp_id_kind idk;
17276 bool non_integral_constant_expression_p;
17277 const char *error_msg;
17279 if (IDENTIFIER_CONV_OP_P (t))
17281 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17282 t = make_conv_op_name (new_type);
17285 /* Look up the name. */
17286 decl = lookup_name (t);
17288 /* By convention, expressions use ERROR_MARK_NODE to indicate
17289 failure, not NULL_TREE. */
17290 if (decl == NULL_TREE)
17291 decl = error_mark_node;
17293 decl = finish_id_expression (t, decl, NULL_TREE,
17294 &idk,
17295 integral_constant_expression_p,
17296 /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
17297 &non_integral_constant_expression_p,
17298 /*template_p=*/false,
17299 /*done=*/true,
17300 /*address_p=*/false,
17301 /*template_arg_p=*/false,
17302 &error_msg,
17303 input_location);
17304 if (error_msg)
17305 error (error_msg);
17306 if (!function_p && identifier_p (decl))
17308 if (complain & tf_error)
17309 unqualified_name_lookup_error (decl);
17310 decl = error_mark_node;
17312 RETURN (decl);
17315 case TEMPLATE_ID_EXPR:
17317 tree object;
17318 tree templ = RECUR (TREE_OPERAND (t, 0));
17319 tree targs = TREE_OPERAND (t, 1);
17321 if (targs)
17322 targs = tsubst_template_args (targs, args, complain, in_decl);
17323 if (targs == error_mark_node)
17324 RETURN (error_mark_node);
17326 if (TREE_CODE (templ) == SCOPE_REF)
17328 tree name = TREE_OPERAND (templ, 1);
17329 tree tid = lookup_template_function (name, targs);
17330 TREE_OPERAND (templ, 1) = tid;
17331 RETURN (templ);
17334 if (variable_template_p (templ))
17335 RETURN (lookup_and_finish_template_variable (templ, targs, complain));
17337 if (TREE_CODE (templ) == COMPONENT_REF)
17339 object = TREE_OPERAND (templ, 0);
17340 templ = TREE_OPERAND (templ, 1);
17342 else
17343 object = NULL_TREE;
17344 templ = lookup_template_function (templ, targs);
17346 if (object)
17347 RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
17348 object, templ, NULL_TREE));
17349 else
17350 RETURN (baselink_for_fns (templ));
17353 case INDIRECT_REF:
17355 tree r = RECUR (TREE_OPERAND (t, 0));
17357 if (REFERENCE_REF_P (t))
17359 /* A type conversion to reference type will be enclosed in
17360 such an indirect ref, but the substitution of the cast
17361 will have also added such an indirect ref. */
17362 r = convert_from_reference (r);
17364 else
17365 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
17366 complain|decltype_flag);
17368 if (REF_PARENTHESIZED_P (t))
17369 r = force_paren_expr (r);
17371 RETURN (r);
17374 case NOP_EXPR:
17376 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17377 tree op0 = RECUR (TREE_OPERAND (t, 0));
17378 RETURN (build_nop (type, op0));
17381 case IMPLICIT_CONV_EXPR:
17383 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17384 tree expr = RECUR (TREE_OPERAND (t, 0));
17385 if (dependent_type_p (type) || type_dependent_expression_p (expr))
17387 retval = copy_node (t);
17388 TREE_TYPE (retval) = type;
17389 TREE_OPERAND (retval, 0) = expr;
17390 RETURN (retval);
17392 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
17393 /* We'll pass this to convert_nontype_argument again, we don't need
17394 to actually perform any conversion here. */
17395 RETURN (expr);
17396 int flags = LOOKUP_IMPLICIT;
17397 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
17398 flags = LOOKUP_NORMAL;
17399 RETURN (perform_implicit_conversion_flags (type, expr, complain,
17400 flags));
17403 case CONVERT_EXPR:
17405 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17406 tree op0 = RECUR (TREE_OPERAND (t, 0));
17407 if (op0 == error_mark_node)
17408 RETURN (error_mark_node);
17409 RETURN (build1 (CONVERT_EXPR, type, op0));
17412 case CAST_EXPR:
17413 case REINTERPRET_CAST_EXPR:
17414 case CONST_CAST_EXPR:
17415 case DYNAMIC_CAST_EXPR:
17416 case STATIC_CAST_EXPR:
17418 tree type;
17419 tree op, r = NULL_TREE;
17421 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17422 if (integral_constant_expression_p
17423 && !cast_valid_in_integral_constant_expression_p (type))
17425 if (complain & tf_error)
17426 error ("a cast to a type other than an integral or "
17427 "enumeration type cannot appear in a constant-expression");
17428 RETURN (error_mark_node);
17431 op = RECUR (TREE_OPERAND (t, 0));
17433 warning_sentinel s(warn_useless_cast);
17434 warning_sentinel s2(warn_ignored_qualifiers);
17435 switch (TREE_CODE (t))
17437 case CAST_EXPR:
17438 r = build_functional_cast (type, op, complain);
17439 break;
17440 case REINTERPRET_CAST_EXPR:
17441 r = build_reinterpret_cast (type, op, complain);
17442 break;
17443 case CONST_CAST_EXPR:
17444 r = build_const_cast (type, op, complain);
17445 break;
17446 case DYNAMIC_CAST_EXPR:
17447 r = build_dynamic_cast (type, op, complain);
17448 break;
17449 case STATIC_CAST_EXPR:
17450 r = build_static_cast (type, op, complain);
17451 break;
17452 default:
17453 gcc_unreachable ();
17456 RETURN (r);
17459 case POSTDECREMENT_EXPR:
17460 case POSTINCREMENT_EXPR:
17461 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17462 args, complain, in_decl);
17463 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
17464 complain|decltype_flag));
17466 case PREDECREMENT_EXPR:
17467 case PREINCREMENT_EXPR:
17468 case NEGATE_EXPR:
17469 case BIT_NOT_EXPR:
17470 case ABS_EXPR:
17471 case TRUTH_NOT_EXPR:
17472 case UNARY_PLUS_EXPR: /* Unary + */
17473 case REALPART_EXPR:
17474 case IMAGPART_EXPR:
17475 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
17476 RECUR (TREE_OPERAND (t, 0)),
17477 complain|decltype_flag));
17479 case FIX_TRUNC_EXPR:
17480 RETURN (cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
17481 false, complain));
17483 case ADDR_EXPR:
17484 op1 = TREE_OPERAND (t, 0);
17485 if (TREE_CODE (op1) == LABEL_DECL)
17486 RETURN (finish_label_address_expr (DECL_NAME (op1),
17487 EXPR_LOCATION (op1)));
17488 if (TREE_CODE (op1) == SCOPE_REF)
17489 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
17490 /*done=*/true, /*address_p=*/true);
17491 else
17492 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
17493 in_decl);
17494 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
17495 complain|decltype_flag));
17497 case PLUS_EXPR:
17498 case MINUS_EXPR:
17499 case MULT_EXPR:
17500 case TRUNC_DIV_EXPR:
17501 case CEIL_DIV_EXPR:
17502 case FLOOR_DIV_EXPR:
17503 case ROUND_DIV_EXPR:
17504 case EXACT_DIV_EXPR:
17505 case BIT_AND_EXPR:
17506 case BIT_IOR_EXPR:
17507 case BIT_XOR_EXPR:
17508 case TRUNC_MOD_EXPR:
17509 case FLOOR_MOD_EXPR:
17510 case TRUTH_ANDIF_EXPR:
17511 case TRUTH_ORIF_EXPR:
17512 case TRUTH_AND_EXPR:
17513 case TRUTH_OR_EXPR:
17514 case RSHIFT_EXPR:
17515 case LSHIFT_EXPR:
17516 case RROTATE_EXPR:
17517 case LROTATE_EXPR:
17518 case EQ_EXPR:
17519 case NE_EXPR:
17520 case MAX_EXPR:
17521 case MIN_EXPR:
17522 case LE_EXPR:
17523 case GE_EXPR:
17524 case LT_EXPR:
17525 case GT_EXPR:
17526 case MEMBER_REF:
17527 case DOTSTAR_EXPR:
17529 warning_sentinel s1(warn_type_limits);
17530 warning_sentinel s2(warn_div_by_zero);
17531 warning_sentinel s3(warn_logical_op);
17532 warning_sentinel s4(warn_tautological_compare);
17533 tree op0 = RECUR (TREE_OPERAND (t, 0));
17534 tree op1 = RECUR (TREE_OPERAND (t, 1));
17535 tree r = build_x_binary_op
17536 (input_location, TREE_CODE (t),
17537 op0,
17538 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
17539 ? ERROR_MARK
17540 : TREE_CODE (TREE_OPERAND (t, 0))),
17541 op1,
17542 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
17543 ? ERROR_MARK
17544 : TREE_CODE (TREE_OPERAND (t, 1))),
17545 /*overload=*/NULL,
17546 complain|decltype_flag);
17547 if (EXPR_P (r) && TREE_NO_WARNING (t))
17548 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
17550 RETURN (r);
17553 case POINTER_PLUS_EXPR:
17555 tree op0 = RECUR (TREE_OPERAND (t, 0));
17556 tree op1 = RECUR (TREE_OPERAND (t, 1));
17557 RETURN (fold_build_pointer_plus (op0, op1));
17560 case SCOPE_REF:
17561 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
17562 /*address_p=*/false));
17563 case ARRAY_REF:
17564 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17565 args, complain, in_decl);
17566 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
17567 RECUR (TREE_OPERAND (t, 1)),
17568 complain|decltype_flag));
17570 case SIZEOF_EXPR:
17571 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17572 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17573 RETURN (tsubst_copy (t, args, complain, in_decl));
17574 /* Fall through */
17576 case ALIGNOF_EXPR:
17578 tree r;
17580 op1 = TREE_OPERAND (t, 0);
17581 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
17582 op1 = TREE_TYPE (op1);
17583 if (!args)
17585 /* When there are no ARGS, we are trying to evaluate a
17586 non-dependent expression from the parser. Trying to do
17587 the substitutions may not work. */
17588 if (!TYPE_P (op1))
17589 op1 = TREE_TYPE (op1);
17591 else
17593 ++cp_unevaluated_operand;
17594 ++c_inhibit_evaluation_warnings;
17595 if (TYPE_P (op1))
17596 op1 = tsubst (op1, args, complain, in_decl);
17597 else
17598 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
17599 /*function_p=*/false,
17600 /*integral_constant_expression_p=*/
17601 false);
17602 --cp_unevaluated_operand;
17603 --c_inhibit_evaluation_warnings;
17605 if (TYPE_P (op1))
17606 r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
17607 complain & tf_error);
17608 else
17609 r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
17610 complain & tf_error);
17611 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
17613 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
17615 if (!processing_template_decl && TYPE_P (op1))
17617 r = build_min (SIZEOF_EXPR, size_type_node,
17618 build1 (NOP_EXPR, op1, error_mark_node));
17619 SIZEOF_EXPR_TYPE_P (r) = 1;
17621 else
17622 r = build_min (SIZEOF_EXPR, size_type_node, op1);
17623 TREE_SIDE_EFFECTS (r) = 0;
17624 TREE_READONLY (r) = 1;
17626 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17628 RETURN (r);
17631 case AT_ENCODE_EXPR:
17633 op1 = TREE_OPERAND (t, 0);
17634 ++cp_unevaluated_operand;
17635 ++c_inhibit_evaluation_warnings;
17636 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
17637 /*function_p=*/false,
17638 /*integral_constant_expression_p=*/false);
17639 --cp_unevaluated_operand;
17640 --c_inhibit_evaluation_warnings;
17641 RETURN (objc_build_encode_expr (op1));
17644 case NOEXCEPT_EXPR:
17645 op1 = TREE_OPERAND (t, 0);
17646 ++cp_unevaluated_operand;
17647 ++c_inhibit_evaluation_warnings;
17648 ++cp_noexcept_operand;
17649 op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
17650 /*function_p=*/false,
17651 /*integral_constant_expression_p=*/false);
17652 --cp_unevaluated_operand;
17653 --c_inhibit_evaluation_warnings;
17654 --cp_noexcept_operand;
17655 RETURN (finish_noexcept_expr (op1, complain));
17657 case MODOP_EXPR:
17659 warning_sentinel s(warn_div_by_zero);
17660 tree lhs = RECUR (TREE_OPERAND (t, 0));
17661 tree rhs = RECUR (TREE_OPERAND (t, 2));
17662 tree r = build_x_modify_expr
17663 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
17664 complain|decltype_flag);
17665 /* TREE_NO_WARNING must be set if either the expression was
17666 parenthesized or it uses an operator such as >>= rather
17667 than plain assignment. In the former case, it was already
17668 set and must be copied. In the latter case,
17669 build_x_modify_expr sets it and it must not be reset
17670 here. */
17671 if (TREE_NO_WARNING (t))
17672 TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
17674 RETURN (r);
17677 case ARROW_EXPR:
17678 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17679 args, complain, in_decl);
17680 /* Remember that there was a reference to this entity. */
17681 if (DECL_P (op1)
17682 && !mark_used (op1, complain) && !(complain & tf_error))
17683 RETURN (error_mark_node);
17684 RETURN (build_x_arrow (input_location, op1, complain));
17686 case NEW_EXPR:
17688 tree placement = RECUR (TREE_OPERAND (t, 0));
17689 tree init = RECUR (TREE_OPERAND (t, 3));
17690 vec<tree, va_gc> *placement_vec;
17691 vec<tree, va_gc> *init_vec;
17692 tree ret;
17694 if (placement == NULL_TREE)
17695 placement_vec = NULL;
17696 else
17698 placement_vec = make_tree_vector ();
17699 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
17700 vec_safe_push (placement_vec, TREE_VALUE (placement));
17703 /* If there was an initializer in the original tree, but it
17704 instantiated to an empty list, then we should pass a
17705 non-NULL empty vector to tell build_new that it was an
17706 empty initializer() rather than no initializer. This can
17707 only happen when the initializer is a pack expansion whose
17708 parameter packs are of length zero. */
17709 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
17710 init_vec = NULL;
17711 else
17713 init_vec = make_tree_vector ();
17714 if (init == void_node)
17715 gcc_assert (init_vec != NULL);
17716 else
17718 for (; init != NULL_TREE; init = TREE_CHAIN (init))
17719 vec_safe_push (init_vec, TREE_VALUE (init));
17723 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
17724 tree op2 = RECUR (TREE_OPERAND (t, 2));
17725 ret = build_new (&placement_vec, op1, op2, &init_vec,
17726 NEW_EXPR_USE_GLOBAL (t),
17727 complain);
17729 if (placement_vec != NULL)
17730 release_tree_vector (placement_vec);
17731 if (init_vec != NULL)
17732 release_tree_vector (init_vec);
17734 RETURN (ret);
17737 case DELETE_EXPR:
17739 tree op0 = RECUR (TREE_OPERAND (t, 0));
17740 tree op1 = RECUR (TREE_OPERAND (t, 1));
17741 RETURN (delete_sanity (op0, op1,
17742 DELETE_EXPR_USE_VEC (t),
17743 DELETE_EXPR_USE_GLOBAL (t),
17744 complain));
17747 case COMPOUND_EXPR:
17749 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
17750 complain & ~tf_decltype, in_decl,
17751 /*function_p=*/false,
17752 integral_constant_expression_p);
17753 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
17754 op0,
17755 RECUR (TREE_OPERAND (t, 1)),
17756 complain|decltype_flag));
17759 case CALL_EXPR:
17761 tree function;
17762 vec<tree, va_gc> *call_args;
17763 unsigned int nargs, i;
17764 bool qualified_p;
17765 bool koenig_p;
17766 tree ret;
17768 function = CALL_EXPR_FN (t);
17769 /* Internal function with no arguments. */
17770 if (function == NULL_TREE && call_expr_nargs (t) == 0)
17771 RETURN (t);
17773 /* When we parsed the expression, we determined whether or
17774 not Koenig lookup should be performed. */
17775 koenig_p = KOENIG_LOOKUP_P (t);
17776 if (function == NULL_TREE)
17778 koenig_p = false;
17779 qualified_p = false;
17781 else if (TREE_CODE (function) == SCOPE_REF)
17783 qualified_p = true;
17784 function = tsubst_qualified_id (function, args, complain, in_decl,
17785 /*done=*/false,
17786 /*address_p=*/false);
17788 else if (koenig_p && identifier_p (function))
17790 /* Do nothing; calling tsubst_copy_and_build on an identifier
17791 would incorrectly perform unqualified lookup again.
17793 Note that we can also have an IDENTIFIER_NODE if the earlier
17794 unqualified lookup found a member function; in that case
17795 koenig_p will be false and we do want to do the lookup
17796 again to find the instantiated member function.
17798 FIXME but doing that causes c++/15272, so we need to stop
17799 using IDENTIFIER_NODE in that situation. */
17800 qualified_p = false;
17802 else
17804 if (TREE_CODE (function) == COMPONENT_REF)
17806 tree op = TREE_OPERAND (function, 1);
17808 qualified_p = (TREE_CODE (op) == SCOPE_REF
17809 || (BASELINK_P (op)
17810 && BASELINK_QUALIFIED_P (op)));
17812 else
17813 qualified_p = false;
17815 if (TREE_CODE (function) == ADDR_EXPR
17816 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
17817 /* Avoid error about taking the address of a constructor. */
17818 function = TREE_OPERAND (function, 0);
17820 function = tsubst_copy_and_build (function, args, complain,
17821 in_decl,
17822 !qualified_p,
17823 integral_constant_expression_p);
17825 if (BASELINK_P (function))
17826 qualified_p = true;
17829 nargs = call_expr_nargs (t);
17830 call_args = make_tree_vector ();
17831 for (i = 0; i < nargs; ++i)
17833 tree arg = CALL_EXPR_ARG (t, i);
17835 if (!PACK_EXPANSION_P (arg))
17836 vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
17837 else
17839 /* Expand the pack expansion and push each entry onto
17840 CALL_ARGS. */
17841 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
17842 if (TREE_CODE (arg) == TREE_VEC)
17844 unsigned int len, j;
17846 len = TREE_VEC_LENGTH (arg);
17847 for (j = 0; j < len; ++j)
17849 tree value = TREE_VEC_ELT (arg, j);
17850 if (value != NULL_TREE)
17851 value = convert_from_reference (value);
17852 vec_safe_push (call_args, value);
17855 else
17857 /* A partial substitution. Add one entry. */
17858 vec_safe_push (call_args, arg);
17863 /* We do not perform argument-dependent lookup if normal
17864 lookup finds a non-function, in accordance with the
17865 expected resolution of DR 218. */
17866 if (koenig_p
17867 && ((is_overloaded_fn (function)
17868 /* If lookup found a member function, the Koenig lookup is
17869 not appropriate, even if an unqualified-name was used
17870 to denote the function. */
17871 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
17872 || identifier_p (function))
17873 /* Only do this when substitution turns a dependent call
17874 into a non-dependent call. */
17875 && type_dependent_expression_p_push (t)
17876 && !any_type_dependent_arguments_p (call_args))
17877 function = perform_koenig_lookup (function, call_args, tf_none);
17879 if (function != NULL_TREE
17880 && identifier_p (function)
17881 && !any_type_dependent_arguments_p (call_args))
17883 if (koenig_p && (complain & tf_warning_or_error))
17885 /* For backwards compatibility and good diagnostics, try
17886 the unqualified lookup again if we aren't in SFINAE
17887 context. */
17888 tree unq = (tsubst_copy_and_build
17889 (function, args, complain, in_decl, true,
17890 integral_constant_expression_p));
17891 if (unq == error_mark_node)
17893 release_tree_vector (call_args);
17894 RETURN (error_mark_node);
17897 if (unq != function)
17899 /* In a lambda fn, we have to be careful to not
17900 introduce new this captures. Legacy code can't
17901 be using lambdas anyway, so it's ok to be
17902 stricter. */
17903 bool in_lambda = (current_class_type
17904 && LAMBDA_TYPE_P (current_class_type));
17905 char const *const msg
17906 = G_("%qD was not declared in this scope, "
17907 "and no declarations were found by "
17908 "argument-dependent lookup at the point "
17909 "of instantiation");
17911 bool diag = true;
17912 if (in_lambda)
17913 error_at (EXPR_LOC_OR_LOC (t, input_location),
17914 msg, function);
17915 else
17916 diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
17917 msg, function);
17918 if (diag)
17920 tree fn = unq;
17922 if (INDIRECT_REF_P (fn))
17923 fn = TREE_OPERAND (fn, 0);
17924 if (is_overloaded_fn (fn))
17925 fn = get_first_fn (fn);
17927 if (!DECL_P (fn))
17928 /* Can't say anything more. */;
17929 else if (DECL_CLASS_SCOPE_P (fn))
17931 location_t loc = EXPR_LOC_OR_LOC (t,
17932 input_location);
17933 inform (loc,
17934 "declarations in dependent base %qT are "
17935 "not found by unqualified lookup",
17936 DECL_CLASS_CONTEXT (fn));
17937 if (current_class_ptr)
17938 inform (loc,
17939 "use %<this->%D%> instead", function);
17940 else
17941 inform (loc,
17942 "use %<%T::%D%> instead",
17943 current_class_name, function);
17945 else
17946 inform (DECL_SOURCE_LOCATION (fn),
17947 "%qD declared here, later in the "
17948 "translation unit", fn);
17949 if (in_lambda)
17951 release_tree_vector (call_args);
17952 RETURN (error_mark_node);
17956 function = unq;
17959 if (identifier_p (function))
17961 if (complain & tf_error)
17962 unqualified_name_lookup_error (function);
17963 release_tree_vector (call_args);
17964 RETURN (error_mark_node);
17968 /* Remember that there was a reference to this entity. */
17969 if (function != NULL_TREE
17970 && DECL_P (function)
17971 && !mark_used (function, complain) && !(complain & tf_error))
17973 release_tree_vector (call_args);
17974 RETURN (error_mark_node);
17977 /* Put back tf_decltype for the actual call. */
17978 complain |= decltype_flag;
17980 if (function == NULL_TREE)
17981 switch (CALL_EXPR_IFN (t))
17983 case IFN_LAUNDER:
17984 gcc_assert (nargs == 1);
17985 if (vec_safe_length (call_args) != 1)
17987 error_at (EXPR_LOC_OR_LOC (t, input_location),
17988 "wrong number of arguments to "
17989 "%<__builtin_launder%>");
17990 ret = error_mark_node;
17992 else
17993 ret = finish_builtin_launder (EXPR_LOC_OR_LOC (t,
17994 input_location),
17995 (*call_args)[0], complain);
17996 break;
17998 default:
17999 /* Unsupported internal function with arguments. */
18000 gcc_unreachable ();
18002 else if (TREE_CODE (function) == OFFSET_REF)
18003 ret = build_offset_ref_call_from_tree (function, &call_args,
18004 complain);
18005 else if (TREE_CODE (function) == COMPONENT_REF)
18007 tree instance = TREE_OPERAND (function, 0);
18008 tree fn = TREE_OPERAND (function, 1);
18010 if (processing_template_decl
18011 && (type_dependent_expression_p (instance)
18012 || (!BASELINK_P (fn)
18013 && TREE_CODE (fn) != FIELD_DECL)
18014 || type_dependent_expression_p (fn)
18015 || any_type_dependent_arguments_p (call_args)))
18016 ret = build_min_nt_call_vec (function, call_args);
18017 else if (!BASELINK_P (fn))
18018 ret = finish_call_expr (function, &call_args,
18019 /*disallow_virtual=*/false,
18020 /*koenig_p=*/false,
18021 complain);
18022 else
18023 ret = (build_new_method_call
18024 (instance, fn,
18025 &call_args, NULL_TREE,
18026 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
18027 /*fn_p=*/NULL,
18028 complain));
18030 else
18031 ret = finish_call_expr (function, &call_args,
18032 /*disallow_virtual=*/qualified_p,
18033 koenig_p,
18034 complain);
18036 release_tree_vector (call_args);
18038 if (ret != error_mark_node)
18040 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
18041 bool ord = CALL_EXPR_ORDERED_ARGS (t);
18042 bool rev = CALL_EXPR_REVERSE_ARGS (t);
18043 bool thk = CALL_FROM_THUNK_P (t);
18044 if (op || ord || rev || thk)
18046 function = extract_call_expr (ret);
18047 CALL_EXPR_OPERATOR_SYNTAX (function) = op;
18048 CALL_EXPR_ORDERED_ARGS (function) = ord;
18049 CALL_EXPR_REVERSE_ARGS (function) = rev;
18050 if (thk)
18052 if (TREE_CODE (function) == CALL_EXPR)
18053 CALL_FROM_THUNK_P (function) = true;
18054 else
18055 AGGR_INIT_FROM_THUNK_P (function) = true;
18056 /* The thunk location is not interesting. */
18057 SET_EXPR_LOCATION (function, UNKNOWN_LOCATION);
18062 RETURN (ret);
18065 case COND_EXPR:
18067 tree cond = RECUR (TREE_OPERAND (t, 0));
18068 tree folded_cond = fold_non_dependent_expr (cond);
18069 tree exp1, exp2;
18071 if (TREE_CODE (folded_cond) == INTEGER_CST)
18073 if (integer_zerop (folded_cond))
18075 ++c_inhibit_evaluation_warnings;
18076 exp1 = RECUR (TREE_OPERAND (t, 1));
18077 --c_inhibit_evaluation_warnings;
18078 exp2 = RECUR (TREE_OPERAND (t, 2));
18080 else
18082 exp1 = RECUR (TREE_OPERAND (t, 1));
18083 ++c_inhibit_evaluation_warnings;
18084 exp2 = RECUR (TREE_OPERAND (t, 2));
18085 --c_inhibit_evaluation_warnings;
18087 cond = folded_cond;
18089 else
18091 exp1 = RECUR (TREE_OPERAND (t, 1));
18092 exp2 = RECUR (TREE_OPERAND (t, 2));
18095 warning_sentinel s(warn_duplicated_branches);
18096 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
18097 cond, exp1, exp2, complain));
18100 case PSEUDO_DTOR_EXPR:
18102 tree op0 = RECUR (TREE_OPERAND (t, 0));
18103 tree op1 = RECUR (TREE_OPERAND (t, 1));
18104 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
18105 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
18106 input_location));
18109 case TREE_LIST:
18111 tree purpose, value, chain;
18113 if (t == void_list_node)
18114 RETURN (t);
18116 if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
18117 || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
18119 /* We have pack expansions, so expand those and
18120 create a new list out of it. */
18121 tree purposevec = NULL_TREE;
18122 tree valuevec = NULL_TREE;
18123 tree chain;
18124 int i, len = -1;
18126 /* Expand the argument expressions. */
18127 if (TREE_PURPOSE (t))
18128 purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
18129 complain, in_decl);
18130 if (TREE_VALUE (t))
18131 valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
18132 complain, in_decl);
18134 /* Build the rest of the list. */
18135 chain = TREE_CHAIN (t);
18136 if (chain && chain != void_type_node)
18137 chain = RECUR (chain);
18139 /* Determine the number of arguments. */
18140 if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
18142 len = TREE_VEC_LENGTH (purposevec);
18143 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
18145 else if (TREE_CODE (valuevec) == TREE_VEC)
18146 len = TREE_VEC_LENGTH (valuevec);
18147 else
18149 /* Since we only performed a partial substitution into
18150 the argument pack, we only RETURN (a single list
18151 node. */
18152 if (purposevec == TREE_PURPOSE (t)
18153 && valuevec == TREE_VALUE (t)
18154 && chain == TREE_CHAIN (t))
18155 RETURN (t);
18157 RETURN (tree_cons (purposevec, valuevec, chain));
18160 /* Convert the argument vectors into a TREE_LIST */
18161 i = len;
18162 while (i > 0)
18164 /* Grab the Ith values. */
18165 i--;
18166 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
18167 : NULL_TREE;
18168 value
18169 = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
18170 : NULL_TREE;
18172 /* Build the list (backwards). */
18173 chain = tree_cons (purpose, value, chain);
18176 RETURN (chain);
18179 purpose = TREE_PURPOSE (t);
18180 if (purpose)
18181 purpose = RECUR (purpose);
18182 value = TREE_VALUE (t);
18183 if (value)
18184 value = RECUR (value);
18185 chain = TREE_CHAIN (t);
18186 if (chain && chain != void_type_node)
18187 chain = RECUR (chain);
18188 if (purpose == TREE_PURPOSE (t)
18189 && value == TREE_VALUE (t)
18190 && chain == TREE_CHAIN (t))
18191 RETURN (t);
18192 RETURN (tree_cons (purpose, value, chain));
18195 case COMPONENT_REF:
18197 tree object;
18198 tree object_type;
18199 tree member;
18200 tree r;
18202 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18203 args, complain, in_decl);
18204 /* Remember that there was a reference to this entity. */
18205 if (DECL_P (object)
18206 && !mark_used (object, complain) && !(complain & tf_error))
18207 RETURN (error_mark_node);
18208 object_type = TREE_TYPE (object);
18210 member = TREE_OPERAND (t, 1);
18211 if (BASELINK_P (member))
18212 member = tsubst_baselink (member,
18213 non_reference (TREE_TYPE (object)),
18214 args, complain, in_decl);
18215 else
18216 member = tsubst_copy (member, args, complain, in_decl);
18217 if (member == error_mark_node)
18218 RETURN (error_mark_node);
18220 if (TREE_CODE (member) == FIELD_DECL)
18222 r = finish_non_static_data_member (member, object, NULL_TREE);
18223 if (TREE_CODE (r) == COMPONENT_REF)
18224 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18225 RETURN (r);
18227 else if (type_dependent_expression_p (object))
18228 /* We can't do much here. */;
18229 else if (!CLASS_TYPE_P (object_type))
18231 if (scalarish_type_p (object_type))
18233 tree s = NULL_TREE;
18234 tree dtor = member;
18236 if (TREE_CODE (dtor) == SCOPE_REF)
18238 s = TREE_OPERAND (dtor, 0);
18239 dtor = TREE_OPERAND (dtor, 1);
18241 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
18243 dtor = TREE_OPERAND (dtor, 0);
18244 if (TYPE_P (dtor))
18245 RETURN (finish_pseudo_destructor_expr
18246 (object, s, dtor, input_location));
18250 else if (TREE_CODE (member) == SCOPE_REF
18251 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
18253 /* Lookup the template functions now that we know what the
18254 scope is. */
18255 tree scope = TREE_OPERAND (member, 0);
18256 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
18257 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
18258 member = lookup_qualified_name (scope, tmpl,
18259 /*is_type_p=*/false,
18260 /*complain=*/false);
18261 if (BASELINK_P (member))
18263 BASELINK_FUNCTIONS (member)
18264 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
18265 args);
18266 member = (adjust_result_of_qualified_name_lookup
18267 (member, BINFO_TYPE (BASELINK_BINFO (member)),
18268 object_type));
18270 else
18272 qualified_name_lookup_error (scope, tmpl, member,
18273 input_location);
18274 RETURN (error_mark_node);
18277 else if (TREE_CODE (member) == SCOPE_REF
18278 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
18279 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
18281 if (complain & tf_error)
18283 if (TYPE_P (TREE_OPERAND (member, 0)))
18284 error ("%qT is not a class or namespace",
18285 TREE_OPERAND (member, 0));
18286 else
18287 error ("%qD is not a class or namespace",
18288 TREE_OPERAND (member, 0));
18290 RETURN (error_mark_node);
18293 r = finish_class_member_access_expr (object, member,
18294 /*template_p=*/false,
18295 complain);
18296 if (TREE_CODE (r) == COMPONENT_REF)
18297 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18298 RETURN (r);
18301 case THROW_EXPR:
18302 RETURN (build_throw
18303 (RECUR (TREE_OPERAND (t, 0))));
18305 case CONSTRUCTOR:
18307 vec<constructor_elt, va_gc> *n;
18308 constructor_elt *ce;
18309 unsigned HOST_WIDE_INT idx;
18310 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18311 bool process_index_p;
18312 int newlen;
18313 bool need_copy_p = false;
18314 tree r;
18316 if (type == error_mark_node)
18317 RETURN (error_mark_node);
18319 /* We do not want to process the index of aggregate
18320 initializers as they are identifier nodes which will be
18321 looked up by digest_init. */
18322 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
18324 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
18325 newlen = vec_safe_length (n);
18326 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
18328 if (ce->index && process_index_p
18329 /* An identifier index is looked up in the type
18330 being initialized, not the current scope. */
18331 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
18332 ce->index = RECUR (ce->index);
18334 if (PACK_EXPANSION_P (ce->value))
18336 /* Substitute into the pack expansion. */
18337 ce->value = tsubst_pack_expansion (ce->value, args, complain,
18338 in_decl);
18340 if (ce->value == error_mark_node
18341 || PACK_EXPANSION_P (ce->value))
18343 else if (TREE_VEC_LENGTH (ce->value) == 1)
18344 /* Just move the argument into place. */
18345 ce->value = TREE_VEC_ELT (ce->value, 0);
18346 else
18348 /* Update the length of the final CONSTRUCTOR
18349 arguments vector, and note that we will need to
18350 copy.*/
18351 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
18352 need_copy_p = true;
18355 else
18356 ce->value = RECUR (ce->value);
18359 if (need_copy_p)
18361 vec<constructor_elt, va_gc> *old_n = n;
18363 vec_alloc (n, newlen);
18364 FOR_EACH_VEC_ELT (*old_n, idx, ce)
18366 if (TREE_CODE (ce->value) == TREE_VEC)
18368 int i, len = TREE_VEC_LENGTH (ce->value);
18369 for (i = 0; i < len; ++i)
18370 CONSTRUCTOR_APPEND_ELT (n, 0,
18371 TREE_VEC_ELT (ce->value, i));
18373 else
18374 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
18378 r = build_constructor (init_list_type_node, n);
18379 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
18381 if (TREE_HAS_CONSTRUCTOR (t))
18383 fcl_t cl = fcl_functional;
18384 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
18385 cl = fcl_c99;
18386 RETURN (finish_compound_literal (type, r, complain, cl));
18389 TREE_TYPE (r) = type;
18390 RETURN (r);
18393 case TYPEID_EXPR:
18395 tree operand_0 = TREE_OPERAND (t, 0);
18396 if (TYPE_P (operand_0))
18398 operand_0 = tsubst (operand_0, args, complain, in_decl);
18399 RETURN (get_typeid (operand_0, complain));
18401 else
18403 operand_0 = RECUR (operand_0);
18404 RETURN (build_typeid (operand_0, complain));
18408 case VAR_DECL:
18409 if (!args)
18410 RETURN (t);
18411 /* Fall through */
18413 case PARM_DECL:
18415 tree r = tsubst_copy (t, args, complain, in_decl);
18416 /* ??? We're doing a subset of finish_id_expression here. */
18417 if (VAR_P (r)
18418 && !processing_template_decl
18419 && !cp_unevaluated_operand
18420 && (TREE_STATIC (r) || DECL_EXTERNAL (r))
18421 && CP_DECL_THREAD_LOCAL_P (r))
18423 if (tree wrap = get_tls_wrapper_fn (r))
18424 /* Replace an evaluated use of the thread_local variable with
18425 a call to its wrapper. */
18426 r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
18428 else if (outer_automatic_var_p (r))
18429 r = process_outer_var_ref (r, complain);
18431 if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
18432 /* If the original type was a reference, we'll be wrapped in
18433 the appropriate INDIRECT_REF. */
18434 r = convert_from_reference (r);
18435 RETURN (r);
18438 case VA_ARG_EXPR:
18440 tree op0 = RECUR (TREE_OPERAND (t, 0));
18441 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18442 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
18445 case OFFSETOF_EXPR:
18447 tree object_ptr
18448 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
18449 in_decl, /*function_p=*/false,
18450 /*integral_constant_expression_p=*/false);
18451 RETURN (finish_offsetof (object_ptr,
18452 RECUR (TREE_OPERAND (t, 0)),
18453 EXPR_LOCATION (t)));
18456 case ADDRESSOF_EXPR:
18457 RETURN (cp_build_addressof (EXPR_LOCATION (t),
18458 RECUR (TREE_OPERAND (t, 0)), complain));
18460 case TRAIT_EXPR:
18462 tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
18463 complain, in_decl);
18465 tree type2 = TRAIT_EXPR_TYPE2 (t);
18466 if (type2 && TREE_CODE (type2) == TREE_LIST)
18467 type2 = RECUR (type2);
18468 else if (type2)
18469 type2 = tsubst (type2, args, complain, in_decl);
18471 RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
18474 case STMT_EXPR:
18476 tree old_stmt_expr = cur_stmt_expr;
18477 tree stmt_expr = begin_stmt_expr ();
18479 cur_stmt_expr = stmt_expr;
18480 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
18481 integral_constant_expression_p);
18482 stmt_expr = finish_stmt_expr (stmt_expr, false);
18483 cur_stmt_expr = old_stmt_expr;
18485 /* If the resulting list of expression statement is empty,
18486 fold it further into void_node. */
18487 if (empty_expr_stmt_p (stmt_expr))
18488 stmt_expr = void_node;
18490 RETURN (stmt_expr);
18493 case LAMBDA_EXPR:
18495 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
18497 RETURN (build_lambda_object (r));
18500 case TARGET_EXPR:
18501 /* We can get here for a constant initializer of non-dependent type.
18502 FIXME stop folding in cp_parser_initializer_clause. */
18504 tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
18505 complain);
18506 RETURN (r);
18509 case TRANSACTION_EXPR:
18510 RETURN (tsubst_expr(t, args, complain, in_decl,
18511 integral_constant_expression_p));
18513 case PAREN_EXPR:
18514 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
18516 case VEC_PERM_EXPR:
18518 tree op0 = RECUR (TREE_OPERAND (t, 0));
18519 tree op1 = RECUR (TREE_OPERAND (t, 1));
18520 tree op2 = RECUR (TREE_OPERAND (t, 2));
18521 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
18522 complain));
18525 case REQUIRES_EXPR:
18526 RETURN (tsubst_requires_expr (t, args, complain, in_decl));
18528 case NON_LVALUE_EXPR:
18529 case VIEW_CONVERT_EXPR:
18530 /* We should only see these for location wrapper nodes, or within
18531 instantiate_non_dependent_expr (when args is NULL_TREE). */
18532 gcc_assert (location_wrapper_p (t) || args == NULL_TREE);
18533 if (location_wrapper_p (t))
18534 RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
18535 EXPR_LOCATION (t)));
18536 /* fallthrough. */
18538 default:
18539 /* Handle Objective-C++ constructs, if appropriate. */
18541 tree subst
18542 = objcp_tsubst_copy_and_build (t, args, complain,
18543 in_decl, /*function_p=*/false);
18544 if (subst)
18545 RETURN (subst);
18547 RETURN (tsubst_copy (t, args, complain, in_decl));
18550 #undef RECUR
18551 #undef RETURN
18552 out:
18553 input_location = loc;
18554 return retval;
18557 /* Verify that the instantiated ARGS are valid. For type arguments,
18558 make sure that the type's linkage is ok. For non-type arguments,
18559 make sure they are constants if they are integral or enumerations.
18560 Emit an error under control of COMPLAIN, and return TRUE on error. */
18562 static bool
18563 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
18565 if (dependent_template_arg_p (t))
18566 return false;
18567 if (ARGUMENT_PACK_P (t))
18569 tree vec = ARGUMENT_PACK_ARGS (t);
18570 int len = TREE_VEC_LENGTH (vec);
18571 bool result = false;
18572 int i;
18574 for (i = 0; i < len; ++i)
18575 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
18576 result = true;
18577 return result;
18579 else if (TYPE_P (t))
18581 /* [basic.link]: A name with no linkage (notably, the name
18582 of a class or enumeration declared in a local scope)
18583 shall not be used to declare an entity with linkage.
18584 This implies that names with no linkage cannot be used as
18585 template arguments
18587 DR 757 relaxes this restriction for C++0x. */
18588 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
18589 : no_linkage_check (t, /*relaxed_p=*/false));
18591 if (nt)
18593 /* DR 488 makes use of a type with no linkage cause
18594 type deduction to fail. */
18595 if (complain & tf_error)
18597 if (TYPE_UNNAMED_P (nt))
18598 error ("%qT is/uses unnamed type", t);
18599 else
18600 error ("template argument for %qD uses local type %qT",
18601 tmpl, t);
18603 return true;
18605 /* In order to avoid all sorts of complications, we do not
18606 allow variably-modified types as template arguments. */
18607 else if (variably_modified_type_p (t, NULL_TREE))
18609 if (complain & tf_error)
18610 error ("%qT is a variably modified type", t);
18611 return true;
18614 /* Class template and alias template arguments should be OK. */
18615 else if (DECL_TYPE_TEMPLATE_P (t))
18617 /* A non-type argument of integral or enumerated type must be a
18618 constant. */
18619 else if (TREE_TYPE (t)
18620 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
18621 && !REFERENCE_REF_P (t)
18622 && !TREE_CONSTANT (t))
18624 if (complain & tf_error)
18625 error ("integral expression %qE is not constant", t);
18626 return true;
18628 return false;
18631 static bool
18632 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
18634 int ix, len = DECL_NTPARMS (tmpl);
18635 bool result = false;
18637 for (ix = 0; ix != len; ix++)
18639 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
18640 result = true;
18642 if (result && (complain & tf_error))
18643 error (" trying to instantiate %qD", tmpl);
18644 return result;
18647 /* We're out of SFINAE context now, so generate diagnostics for the access
18648 errors we saw earlier when instantiating D from TMPL and ARGS. */
18650 static void
18651 recheck_decl_substitution (tree d, tree tmpl, tree args)
18653 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
18654 tree type = TREE_TYPE (pattern);
18655 location_t loc = input_location;
18657 push_access_scope (d);
18658 push_deferring_access_checks (dk_no_deferred);
18659 input_location = DECL_SOURCE_LOCATION (pattern);
18660 tsubst (type, args, tf_warning_or_error, d);
18661 input_location = loc;
18662 pop_deferring_access_checks ();
18663 pop_access_scope (d);
18666 /* Instantiate the indicated variable, function, or alias template TMPL with
18667 the template arguments in TARG_PTR. */
18669 static tree
18670 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
18672 tree targ_ptr = orig_args;
18673 tree fndecl;
18674 tree gen_tmpl;
18675 tree spec;
18676 bool access_ok = true;
18678 if (tmpl == error_mark_node)
18679 return error_mark_node;
18681 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
18683 /* If this function is a clone, handle it specially. */
18684 if (DECL_CLONED_FUNCTION_P (tmpl))
18686 tree spec;
18687 tree clone;
18689 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
18690 DECL_CLONED_FUNCTION. */
18691 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
18692 targ_ptr, complain);
18693 if (spec == error_mark_node)
18694 return error_mark_node;
18696 /* Look for the clone. */
18697 FOR_EACH_CLONE (clone, spec)
18698 if (DECL_NAME (clone) == DECL_NAME (tmpl))
18699 return clone;
18700 /* We should always have found the clone by now. */
18701 gcc_unreachable ();
18702 return NULL_TREE;
18705 if (targ_ptr == error_mark_node)
18706 return error_mark_node;
18708 /* Check to see if we already have this specialization. */
18709 gen_tmpl = most_general_template (tmpl);
18710 if (TMPL_ARGS_DEPTH (targ_ptr)
18711 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
18712 /* targ_ptr only has the innermost template args, so add the outer ones
18713 from tmpl, which could be either a partial instantiation or gen_tmpl (in
18714 the case of a non-dependent call within a template definition). */
18715 targ_ptr = (add_outermost_template_args
18716 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
18717 targ_ptr));
18719 /* It would be nice to avoid hashing here and then again in tsubst_decl,
18720 but it doesn't seem to be on the hot path. */
18721 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
18723 gcc_assert (tmpl == gen_tmpl
18724 || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
18725 == spec)
18726 || fndecl == NULL_TREE);
18728 if (spec != NULL_TREE)
18730 if (FNDECL_HAS_ACCESS_ERRORS (spec))
18732 if (complain & tf_error)
18733 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
18734 return error_mark_node;
18736 return spec;
18739 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
18740 complain))
18741 return error_mark_node;
18743 /* We are building a FUNCTION_DECL, during which the access of its
18744 parameters and return types have to be checked. However this
18745 FUNCTION_DECL which is the desired context for access checking
18746 is not built yet. We solve this chicken-and-egg problem by
18747 deferring all checks until we have the FUNCTION_DECL. */
18748 push_deferring_access_checks (dk_deferred);
18750 /* Instantiation of the function happens in the context of the function
18751 template, not the context of the overload resolution we're doing. */
18752 push_to_top_level ();
18753 /* If there are dependent arguments, e.g. because we're doing partial
18754 ordering, make sure processing_template_decl stays set. */
18755 if (uses_template_parms (targ_ptr))
18756 ++processing_template_decl;
18757 if (DECL_CLASS_SCOPE_P (gen_tmpl))
18759 tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
18760 complain, gen_tmpl, true);
18761 push_nested_class (ctx);
18764 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
18766 fndecl = NULL_TREE;
18767 if (VAR_P (pattern))
18769 /* We need to determine if we're using a partial or explicit
18770 specialization now, because the type of the variable could be
18771 different. */
18772 tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
18773 tree elt = most_specialized_partial_spec (tid, complain);
18774 if (elt == error_mark_node)
18775 pattern = error_mark_node;
18776 else if (elt)
18778 tree partial_tmpl = TREE_VALUE (elt);
18779 tree partial_args = TREE_PURPOSE (elt);
18780 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
18781 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
18785 /* Substitute template parameters to obtain the specialization. */
18786 if (fndecl == NULL_TREE)
18787 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
18788 if (DECL_CLASS_SCOPE_P (gen_tmpl))
18789 pop_nested_class ();
18790 pop_from_top_level ();
18792 if (fndecl == error_mark_node)
18794 pop_deferring_access_checks ();
18795 return error_mark_node;
18798 /* The DECL_TI_TEMPLATE should always be the immediate parent
18799 template, not the most general template. */
18800 DECL_TI_TEMPLATE (fndecl) = tmpl;
18801 DECL_TI_ARGS (fndecl) = targ_ptr;
18803 /* Now we know the specialization, compute access previously
18804 deferred. Do no access control for inheriting constructors,
18805 as we already checked access for the inherited constructor. */
18806 if (!(flag_new_inheriting_ctors
18807 && DECL_INHERITED_CTOR (fndecl)))
18809 push_access_scope (fndecl);
18810 if (!perform_deferred_access_checks (complain))
18811 access_ok = false;
18812 pop_access_scope (fndecl);
18814 pop_deferring_access_checks ();
18816 /* If we've just instantiated the main entry point for a function,
18817 instantiate all the alternate entry points as well. We do this
18818 by cloning the instantiation of the main entry point, not by
18819 instantiating the template clones. */
18820 if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
18821 clone_function_decl (fndecl, /*update_methods=*/false);
18823 if (!access_ok)
18825 if (!(complain & tf_error))
18827 /* Remember to reinstantiate when we're out of SFINAE so the user
18828 can see the errors. */
18829 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
18831 return error_mark_node;
18833 return fndecl;
18836 /* Wrapper for instantiate_template_1. */
18838 tree
18839 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
18841 tree ret;
18842 timevar_push (TV_TEMPLATE_INST);
18843 ret = instantiate_template_1 (tmpl, orig_args, complain);
18844 timevar_pop (TV_TEMPLATE_INST);
18845 return ret;
18848 /* Instantiate the alias template TMPL with ARGS. Also push a template
18849 instantiation level, which instantiate_template doesn't do because
18850 functions and variables have sufficient context established by the
18851 callers. */
18853 static tree
18854 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
18856 struct pending_template *old_last_pend = last_pending_template;
18857 struct tinst_level *old_error_tinst = last_error_tinst_level;
18858 if (tmpl == error_mark_node || args == error_mark_node)
18859 return error_mark_node;
18860 tree tinst = build_tree_list (tmpl, args);
18861 if (!push_tinst_level (tinst))
18863 ggc_free (tinst);
18864 return error_mark_node;
18867 args =
18868 coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
18869 args, tmpl, complain,
18870 /*require_all_args=*/true,
18871 /*use_default_args=*/true);
18873 tree r = instantiate_template (tmpl, args, complain);
18874 pop_tinst_level ();
18875 /* We can't free this if a pending_template entry or last_error_tinst_level
18876 is pointing at it. */
18877 if (last_pending_template == old_last_pend
18878 && last_error_tinst_level == old_error_tinst)
18879 ggc_free (tinst);
18881 return r;
18884 /* PARM is a template parameter pack for FN. Returns true iff
18885 PARM is used in a deducible way in the argument list of FN. */
18887 static bool
18888 pack_deducible_p (tree parm, tree fn)
18890 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
18891 for (; t; t = TREE_CHAIN (t))
18893 tree type = TREE_VALUE (t);
18894 tree packs;
18895 if (!PACK_EXPANSION_P (type))
18896 continue;
18897 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
18898 packs; packs = TREE_CHAIN (packs))
18899 if (template_args_equal (TREE_VALUE (packs), parm))
18901 /* The template parameter pack is used in a function parameter
18902 pack. If this is the end of the parameter list, the
18903 template parameter pack is deducible. */
18904 if (TREE_CHAIN (t) == void_list_node)
18905 return true;
18906 else
18907 /* Otherwise, not. Well, it could be deduced from
18908 a non-pack parameter, but doing so would end up with
18909 a deduction mismatch, so don't bother. */
18910 return false;
18913 /* The template parameter pack isn't used in any function parameter
18914 packs, but it might be used deeper, e.g. tuple<Args...>. */
18915 return true;
18918 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
18919 NARGS elements of the arguments that are being used when calling
18920 it. TARGS is a vector into which the deduced template arguments
18921 are placed.
18923 Returns either a FUNCTION_DECL for the matching specialization of FN or
18924 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
18925 true, diagnostics will be printed to explain why it failed.
18927 If FN is a conversion operator, or we are trying to produce a specific
18928 specialization, RETURN_TYPE is the return type desired.
18930 The EXPLICIT_TARGS are explicit template arguments provided via a
18931 template-id.
18933 The parameter STRICT is one of:
18935 DEDUCE_CALL:
18936 We are deducing arguments for a function call, as in
18937 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
18938 deducing arguments for a call to the result of a conversion
18939 function template, as in [over.call.object].
18941 DEDUCE_CONV:
18942 We are deducing arguments for a conversion function, as in
18943 [temp.deduct.conv].
18945 DEDUCE_EXACT:
18946 We are deducing arguments when doing an explicit instantiation
18947 as in [temp.explicit], when determining an explicit specialization
18948 as in [temp.expl.spec], or when taking the address of a function
18949 template, as in [temp.deduct.funcaddr]. */
18951 tree
18952 fn_type_unification (tree fn,
18953 tree explicit_targs,
18954 tree targs,
18955 const tree *args,
18956 unsigned int nargs,
18957 tree return_type,
18958 unification_kind_t strict,
18959 int flags,
18960 bool explain_p,
18961 bool decltype_p)
18963 tree parms;
18964 tree fntype;
18965 tree decl = NULL_TREE;
18966 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
18967 bool ok;
18968 static int deduction_depth;
18969 struct pending_template *old_last_pend = last_pending_template;
18970 struct tinst_level *old_error_tinst = last_error_tinst_level;
18972 tree orig_fn = fn;
18973 if (flag_new_inheriting_ctors)
18974 fn = strip_inheriting_ctors (fn);
18976 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
18977 tree tinst;
18978 tree r = error_mark_node;
18980 tree full_targs = targs;
18981 if (TMPL_ARGS_DEPTH (targs)
18982 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
18983 full_targs = (add_outermost_template_args
18984 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
18985 targs));
18987 if (decltype_p)
18988 complain |= tf_decltype;
18990 /* In C++0x, it's possible to have a function template whose type depends
18991 on itself recursively. This is most obvious with decltype, but can also
18992 occur with enumeration scope (c++/48969). So we need to catch infinite
18993 recursion and reject the substitution at deduction time; this function
18994 will return error_mark_node for any repeated substitution.
18996 This also catches excessive recursion such as when f<N> depends on
18997 f<N-1> across all integers, and returns error_mark_node for all the
18998 substitutions back up to the initial one.
19000 This is, of course, not reentrant. */
19001 if (excessive_deduction_depth)
19002 return error_mark_node;
19003 tinst = build_tree_list (fn, NULL_TREE);
19004 ++deduction_depth;
19006 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
19008 fntype = TREE_TYPE (fn);
19009 if (explicit_targs)
19011 /* [temp.deduct]
19013 The specified template arguments must match the template
19014 parameters in kind (i.e., type, nontype, template), and there
19015 must not be more arguments than there are parameters;
19016 otherwise type deduction fails.
19018 Nontype arguments must match the types of the corresponding
19019 nontype template parameters, or must be convertible to the
19020 types of the corresponding nontype parameters as specified in
19021 _temp.arg.nontype_, otherwise type deduction fails.
19023 All references in the function type of the function template
19024 to the corresponding template parameters are replaced by the
19025 specified template argument values. If a substitution in a
19026 template parameter or in the function type of the function
19027 template results in an invalid type, type deduction fails. */
19028 int i, len = TREE_VEC_LENGTH (tparms);
19029 location_t loc = input_location;
19030 bool incomplete = false;
19032 if (explicit_targs == error_mark_node)
19033 goto fail;
19035 if (TMPL_ARGS_DEPTH (explicit_targs)
19036 < TMPL_ARGS_DEPTH (full_targs))
19037 explicit_targs = add_outermost_template_args (full_targs,
19038 explicit_targs);
19040 /* Adjust any explicit template arguments before entering the
19041 substitution context. */
19042 explicit_targs
19043 = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
19044 complain,
19045 /*require_all_args=*/false,
19046 /*use_default_args=*/false));
19047 if (explicit_targs == error_mark_node)
19048 goto fail;
19050 /* Substitute the explicit args into the function type. This is
19051 necessary so that, for instance, explicitly declared function
19052 arguments can match null pointed constants. If we were given
19053 an incomplete set of explicit args, we must not do semantic
19054 processing during substitution as we could create partial
19055 instantiations. */
19056 for (i = 0; i < len; i++)
19058 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
19059 bool parameter_pack = false;
19060 tree targ = TREE_VEC_ELT (explicit_targs, i);
19062 /* Dig out the actual parm. */
19063 if (TREE_CODE (parm) == TYPE_DECL
19064 || TREE_CODE (parm) == TEMPLATE_DECL)
19066 parm = TREE_TYPE (parm);
19067 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
19069 else if (TREE_CODE (parm) == PARM_DECL)
19071 parm = DECL_INITIAL (parm);
19072 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
19075 if (!parameter_pack && targ == NULL_TREE)
19076 /* No explicit argument for this template parameter. */
19077 incomplete = true;
19079 if (parameter_pack && pack_deducible_p (parm, fn))
19081 /* Mark the argument pack as "incomplete". We could
19082 still deduce more arguments during unification.
19083 We remove this mark in type_unification_real. */
19084 if (targ)
19086 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
19087 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
19088 = ARGUMENT_PACK_ARGS (targ);
19091 /* We have some incomplete argument packs. */
19092 incomplete = true;
19096 TREE_VALUE (tinst) = explicit_targs;
19097 if (!push_tinst_level (tinst))
19099 excessive_deduction_depth = true;
19100 goto fail;
19102 processing_template_decl += incomplete;
19103 input_location = DECL_SOURCE_LOCATION (fn);
19104 /* Ignore any access checks; we'll see them again in
19105 instantiate_template and they might have the wrong
19106 access path at this point. */
19107 push_deferring_access_checks (dk_deferred);
19108 fntype = tsubst (TREE_TYPE (fn), explicit_targs,
19109 complain | tf_partial | tf_fndecl_type, NULL_TREE);
19110 pop_deferring_access_checks ();
19111 input_location = loc;
19112 processing_template_decl -= incomplete;
19113 pop_tinst_level ();
19115 if (fntype == error_mark_node)
19116 goto fail;
19118 /* Place the explicitly specified arguments in TARGS. */
19119 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
19120 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
19121 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
19124 /* Never do unification on the 'this' parameter. */
19125 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
19127 if (return_type && strict == DEDUCE_CALL)
19129 /* We're deducing for a call to the result of a template conversion
19130 function. The parms we really want are in return_type. */
19131 if (POINTER_TYPE_P (return_type))
19132 return_type = TREE_TYPE (return_type);
19133 parms = TYPE_ARG_TYPES (return_type);
19135 else if (return_type)
19137 tree *new_args;
19139 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
19140 new_args = XALLOCAVEC (tree, nargs + 1);
19141 new_args[0] = return_type;
19142 memcpy (new_args + 1, args, nargs * sizeof (tree));
19143 args = new_args;
19144 ++nargs;
19147 /* We allow incomplete unification without an error message here
19148 because the standard doesn't seem to explicitly prohibit it. Our
19149 callers must be ready to deal with unification failures in any
19150 event. */
19152 TREE_VALUE (tinst) = targs;
19153 /* If we aren't explaining yet, push tinst context so we can see where
19154 any errors (e.g. from class instantiations triggered by instantiation
19155 of default template arguments) come from. If we are explaining, this
19156 context is redundant. */
19157 if (!explain_p && !push_tinst_level (tinst))
19159 excessive_deduction_depth = true;
19160 goto fail;
19163 /* type_unification_real will pass back any access checks from default
19164 template argument substitution. */
19165 vec<deferred_access_check, va_gc> *checks;
19166 checks = NULL;
19168 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
19169 full_targs, parms, args, nargs, /*subr=*/0,
19170 strict, flags, &checks, explain_p);
19171 if (!explain_p)
19172 pop_tinst_level ();
19173 if (!ok)
19174 goto fail;
19176 /* Now that we have bindings for all of the template arguments,
19177 ensure that the arguments deduced for the template template
19178 parameters have compatible template parameter lists. We cannot
19179 check this property before we have deduced all template
19180 arguments, because the template parameter types of a template
19181 template parameter might depend on prior template parameters
19182 deduced after the template template parameter. The following
19183 ill-formed example illustrates this issue:
19185 template<typename T, template<T> class C> void f(C<5>, T);
19187 template<int N> struct X {};
19189 void g() {
19190 f(X<5>(), 5l); // error: template argument deduction fails
19193 The template parameter list of 'C' depends on the template type
19194 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
19195 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
19196 time that we deduce 'C'. */
19197 if (!template_template_parm_bindings_ok_p
19198 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
19200 unify_inconsistent_template_template_parameters (explain_p);
19201 goto fail;
19204 /* All is well so far. Now, check:
19206 [temp.deduct]
19208 When all template arguments have been deduced, all uses of
19209 template parameters in nondeduced contexts are replaced with
19210 the corresponding deduced argument values. If the
19211 substitution results in an invalid type, as described above,
19212 type deduction fails. */
19213 TREE_VALUE (tinst) = targs;
19214 if (!push_tinst_level (tinst))
19216 excessive_deduction_depth = true;
19217 goto fail;
19220 /* Also collect access checks from the instantiation. */
19221 reopen_deferring_access_checks (checks);
19223 decl = instantiate_template (fn, targs, complain);
19225 checks = get_deferred_access_checks ();
19226 pop_deferring_access_checks ();
19228 pop_tinst_level ();
19230 if (decl == error_mark_node)
19231 goto fail;
19233 /* Now perform any access checks encountered during substitution. */
19234 push_access_scope (decl);
19235 ok = perform_access_checks (checks, complain);
19236 pop_access_scope (decl);
19237 if (!ok)
19238 goto fail;
19240 /* If we're looking for an exact match, check that what we got
19241 is indeed an exact match. It might not be if some template
19242 parameters are used in non-deduced contexts. But don't check
19243 for an exact match if we have dependent template arguments;
19244 in that case we're doing partial ordering, and we already know
19245 that we have two candidates that will provide the actual type. */
19246 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
19248 tree substed = TREE_TYPE (decl);
19249 unsigned int i;
19251 tree sarg
19252 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
19253 if (return_type)
19254 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
19255 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
19256 if (!same_type_p (args[i], TREE_VALUE (sarg)))
19258 unify_type_mismatch (explain_p, args[i],
19259 TREE_VALUE (sarg));
19260 goto fail;
19264 /* After doing deduction with the inherited constructor, actually return an
19265 instantiation of the inheriting constructor. */
19266 if (orig_fn != fn)
19267 decl = instantiate_template (orig_fn, targs, complain);
19269 r = decl;
19271 fail:
19272 --deduction_depth;
19273 if (excessive_deduction_depth)
19275 if (deduction_depth == 0)
19276 /* Reset once we're all the way out. */
19277 excessive_deduction_depth = false;
19280 /* We can't free this if a pending_template entry or last_error_tinst_level
19281 is pointing at it. */
19282 if (last_pending_template == old_last_pend
19283 && last_error_tinst_level == old_error_tinst)
19284 ggc_free (tinst);
19286 return r;
19289 /* Adjust types before performing type deduction, as described in
19290 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
19291 sections are symmetric. PARM is the type of a function parameter
19292 or the return type of the conversion function. ARG is the type of
19293 the argument passed to the call, or the type of the value
19294 initialized with the result of the conversion function.
19295 ARG_EXPR is the original argument expression, which may be null. */
19297 static int
19298 maybe_adjust_types_for_deduction (unification_kind_t strict,
19299 tree* parm,
19300 tree* arg,
19301 tree arg_expr)
19303 int result = 0;
19305 switch (strict)
19307 case DEDUCE_CALL:
19308 break;
19310 case DEDUCE_CONV:
19311 /* Swap PARM and ARG throughout the remainder of this
19312 function; the handling is precisely symmetric since PARM
19313 will initialize ARG rather than vice versa. */
19314 std::swap (parm, arg);
19315 break;
19317 case DEDUCE_EXACT:
19318 /* Core issue #873: Do the DR606 thing (see below) for these cases,
19319 too, but here handle it by stripping the reference from PARM
19320 rather than by adding it to ARG. */
19321 if (TREE_CODE (*parm) == REFERENCE_TYPE
19322 && TYPE_REF_IS_RVALUE (*parm)
19323 && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19324 && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19325 && TREE_CODE (*arg) == REFERENCE_TYPE
19326 && !TYPE_REF_IS_RVALUE (*arg))
19327 *parm = TREE_TYPE (*parm);
19328 /* Nothing else to do in this case. */
19329 return 0;
19331 default:
19332 gcc_unreachable ();
19335 if (TREE_CODE (*parm) != REFERENCE_TYPE)
19337 /* [temp.deduct.call]
19339 If P is not a reference type:
19341 --If A is an array type, the pointer type produced by the
19342 array-to-pointer standard conversion (_conv.array_) is
19343 used in place of A for type deduction; otherwise,
19345 --If A is a function type, the pointer type produced by
19346 the function-to-pointer standard conversion
19347 (_conv.func_) is used in place of A for type deduction;
19348 otherwise,
19350 --If A is a cv-qualified type, the top level
19351 cv-qualifiers of A's type are ignored for type
19352 deduction. */
19353 if (TREE_CODE (*arg) == ARRAY_TYPE)
19354 *arg = build_pointer_type (TREE_TYPE (*arg));
19355 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
19356 *arg = build_pointer_type (*arg);
19357 else
19358 *arg = TYPE_MAIN_VARIANT (*arg);
19361 /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
19362 reference to a cv-unqualified template parameter that does not represent a
19363 template parameter of a class template (during class template argument
19364 deduction (13.3.1.8)). If P is a forwarding reference and the argument is
19365 an lvalue, the type "lvalue reference to A" is used in place of A for type
19366 deduction. */
19367 if (TREE_CODE (*parm) == REFERENCE_TYPE
19368 && TYPE_REF_IS_RVALUE (*parm)
19369 && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19370 && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
19371 && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19372 && (arg_expr ? lvalue_p (arg_expr)
19373 /* try_one_overload doesn't provide an arg_expr, but
19374 functions are always lvalues. */
19375 : TREE_CODE (*arg) == FUNCTION_TYPE))
19376 *arg = build_reference_type (*arg);
19378 /* [temp.deduct.call]
19380 If P is a cv-qualified type, the top level cv-qualifiers
19381 of P's type are ignored for type deduction. If P is a
19382 reference type, the type referred to by P is used for
19383 type deduction. */
19384 *parm = TYPE_MAIN_VARIANT (*parm);
19385 if (TREE_CODE (*parm) == REFERENCE_TYPE)
19387 *parm = TREE_TYPE (*parm);
19388 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19391 /* DR 322. For conversion deduction, remove a reference type on parm
19392 too (which has been swapped into ARG). */
19393 if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
19394 *arg = TREE_TYPE (*arg);
19396 return result;
19399 /* Subroutine of unify_one_argument. PARM is a function parameter of a
19400 template which does contain any deducible template parameters; check if
19401 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
19402 unify_one_argument. */
19404 static int
19405 check_non_deducible_conversion (tree parm, tree arg, int strict,
19406 int flags, bool explain_p)
19408 tree type;
19410 if (!TYPE_P (arg))
19411 type = TREE_TYPE (arg);
19412 else
19413 type = arg;
19415 if (same_type_p (parm, type))
19416 return unify_success (explain_p);
19418 if (strict == DEDUCE_CONV)
19420 if (can_convert_arg (type, parm, NULL_TREE, flags,
19421 explain_p ? tf_warning_or_error : tf_none))
19422 return unify_success (explain_p);
19424 else if (strict != DEDUCE_EXACT)
19426 if (can_convert_arg (parm, type,
19427 TYPE_P (arg) ? NULL_TREE : arg,
19428 flags, explain_p ? tf_warning_or_error : tf_none))
19429 return unify_success (explain_p);
19432 if (strict == DEDUCE_EXACT)
19433 return unify_type_mismatch (explain_p, parm, arg);
19434 else
19435 return unify_arg_conversion (explain_p, parm, type, arg);
19438 static bool uses_deducible_template_parms (tree type);
19440 /* Returns true iff the expression EXPR is one from which a template
19441 argument can be deduced. In other words, if it's an undecorated
19442 use of a template non-type parameter. */
19444 static bool
19445 deducible_expression (tree expr)
19447 /* Strip implicit conversions. */
19448 while (CONVERT_EXPR_P (expr))
19449 expr = TREE_OPERAND (expr, 0);
19450 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
19453 /* Returns true iff the array domain DOMAIN uses a template parameter in a
19454 deducible way; that is, if it has a max value of <PARM> - 1. */
19456 static bool
19457 deducible_array_bound (tree domain)
19459 if (domain == NULL_TREE)
19460 return false;
19462 tree max = TYPE_MAX_VALUE (domain);
19463 if (TREE_CODE (max) != MINUS_EXPR)
19464 return false;
19466 return deducible_expression (TREE_OPERAND (max, 0));
19469 /* Returns true iff the template arguments ARGS use a template parameter
19470 in a deducible way. */
19472 static bool
19473 deducible_template_args (tree args)
19475 for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
19477 bool deducible;
19478 tree elt = TREE_VEC_ELT (args, i);
19479 if (ARGUMENT_PACK_P (elt))
19480 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
19481 else
19483 if (PACK_EXPANSION_P (elt))
19484 elt = PACK_EXPANSION_PATTERN (elt);
19485 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
19486 deducible = true;
19487 else if (TYPE_P (elt))
19488 deducible = uses_deducible_template_parms (elt);
19489 else
19490 deducible = deducible_expression (elt);
19492 if (deducible)
19493 return true;
19495 return false;
19498 /* Returns true iff TYPE contains any deducible references to template
19499 parameters, as per 14.8.2.5. */
19501 static bool
19502 uses_deducible_template_parms (tree type)
19504 if (PACK_EXPANSION_P (type))
19505 type = PACK_EXPANSION_PATTERN (type);
19507 /* T
19508 cv-list T
19509 TT<T>
19510 TT<i>
19511 TT<> */
19512 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19513 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19514 return true;
19516 /* T*
19518 T&& */
19519 if (POINTER_TYPE_P (type))
19520 return uses_deducible_template_parms (TREE_TYPE (type));
19522 /* T[integer-constant ]
19523 type [i] */
19524 if (TREE_CODE (type) == ARRAY_TYPE)
19525 return (uses_deducible_template_parms (TREE_TYPE (type))
19526 || deducible_array_bound (TYPE_DOMAIN (type)));
19528 /* T type ::*
19529 type T::*
19530 T T::*
19531 T (type ::*)()
19532 type (T::*)()
19533 type (type ::*)(T)
19534 type (T::*)(T)
19535 T (type ::*)(T)
19536 T (T::*)()
19537 T (T::*)(T) */
19538 if (TYPE_PTRMEM_P (type))
19539 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
19540 || (uses_deducible_template_parms
19541 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
19543 /* template-name <T> (where template-name refers to a class template)
19544 template-name <i> (where template-name refers to a class template) */
19545 if (CLASS_TYPE_P (type)
19546 && CLASSTYPE_TEMPLATE_INFO (type)
19547 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
19548 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
19549 (CLASSTYPE_TI_ARGS (type)));
19551 /* type (T)
19553 T(T) */
19554 if (TREE_CODE (type) == FUNCTION_TYPE
19555 || TREE_CODE (type) == METHOD_TYPE)
19557 if (uses_deducible_template_parms (TREE_TYPE (type)))
19558 return true;
19559 tree parm = TYPE_ARG_TYPES (type);
19560 if (TREE_CODE (type) == METHOD_TYPE)
19561 parm = TREE_CHAIN (parm);
19562 for (; parm; parm = TREE_CHAIN (parm))
19563 if (uses_deducible_template_parms (TREE_VALUE (parm)))
19564 return true;
19567 return false;
19570 /* Subroutine of type_unification_real and unify_pack_expansion to
19571 handle unification of a single P/A pair. Parameters are as
19572 for those functions. */
19574 static int
19575 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
19576 int subr, unification_kind_t strict,
19577 bool explain_p)
19579 tree arg_expr = NULL_TREE;
19580 int arg_strict;
19582 if (arg == error_mark_node || parm == error_mark_node)
19583 return unify_invalid (explain_p);
19584 if (arg == unknown_type_node)
19585 /* We can't deduce anything from this, but we might get all the
19586 template args from other function args. */
19587 return unify_success (explain_p);
19589 /* Implicit conversions (Clause 4) will be performed on a function
19590 argument to convert it to the type of the corresponding function
19591 parameter if the parameter type contains no template-parameters that
19592 participate in template argument deduction. */
19593 if (strict != DEDUCE_EXACT
19594 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
19595 /* For function parameters with no deducible template parameters,
19596 just return. We'll check non-dependent conversions later. */
19597 return unify_success (explain_p);
19599 switch (strict)
19601 case DEDUCE_CALL:
19602 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
19603 | UNIFY_ALLOW_MORE_CV_QUAL
19604 | UNIFY_ALLOW_DERIVED);
19605 break;
19607 case DEDUCE_CONV:
19608 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
19609 break;
19611 case DEDUCE_EXACT:
19612 arg_strict = UNIFY_ALLOW_NONE;
19613 break;
19615 default:
19616 gcc_unreachable ();
19619 /* We only do these transformations if this is the top-level
19620 parameter_type_list in a call or declaration matching; in other
19621 situations (nested function declarators, template argument lists) we
19622 won't be comparing a type to an expression, and we don't do any type
19623 adjustments. */
19624 if (!subr)
19626 if (!TYPE_P (arg))
19628 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
19629 if (type_unknown_p (arg))
19631 /* [temp.deduct.type] A template-argument can be
19632 deduced from a pointer to function or pointer
19633 to member function argument if the set of
19634 overloaded functions does not contain function
19635 templates and at most one of a set of
19636 overloaded functions provides a unique
19637 match. */
19638 resolve_overloaded_unification (tparms, targs, parm,
19639 arg, strict,
19640 arg_strict, explain_p);
19641 /* If a unique match was not found, this is a
19642 non-deduced context, so we still succeed. */
19643 return unify_success (explain_p);
19646 arg_expr = arg;
19647 arg = unlowered_expr_type (arg);
19648 if (arg == error_mark_node)
19649 return unify_invalid (explain_p);
19652 arg_strict |=
19653 maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
19655 else
19656 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
19657 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
19658 return unify_template_argument_mismatch (explain_p, parm, arg);
19660 /* For deduction from an init-list we need the actual list. */
19661 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
19662 arg = arg_expr;
19663 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
19666 /* for_each_template_parm callback that always returns 0. */
19668 static int
19669 zero_r (tree, void *)
19671 return 0;
19674 /* for_each_template_parm any_fn callback to handle deduction of a template
19675 type argument from the type of an array bound. */
19677 static int
19678 array_deduction_r (tree t, void *data)
19680 tree_pair_p d = (tree_pair_p)data;
19681 tree &tparms = d->purpose;
19682 tree &targs = d->value;
19684 if (TREE_CODE (t) == ARRAY_TYPE)
19685 if (tree dom = TYPE_DOMAIN (t))
19686 if (tree max = TYPE_MAX_VALUE (dom))
19688 if (TREE_CODE (max) == MINUS_EXPR)
19689 max = TREE_OPERAND (max, 0);
19690 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
19691 unify (tparms, targs, TREE_TYPE (max), size_type_node,
19692 UNIFY_ALLOW_NONE, /*explain*/false);
19695 /* Keep walking. */
19696 return 0;
19699 /* Try to deduce any not-yet-deduced template type arguments from the type of
19700 an array bound. This is handled separately from unify because 14.8.2.5 says
19701 "The type of a type parameter is only deduced from an array bound if it is
19702 not otherwise deduced." */
19704 static void
19705 try_array_deduction (tree tparms, tree targs, tree parm)
19707 tree_pair_s data = { tparms, targs };
19708 hash_set<tree> visited;
19709 for_each_template_parm (parm, zero_r, &data, &visited,
19710 /*nondeduced*/false, array_deduction_r);
19713 /* Most parms like fn_type_unification.
19715 If SUBR is 1, we're being called recursively (to unify the
19716 arguments of a function or method parameter of a function
19717 template).
19719 CHECKS is a pointer to a vector of access checks encountered while
19720 substituting default template arguments. */
19722 static int
19723 type_unification_real (tree tparms,
19724 tree full_targs,
19725 tree xparms,
19726 const tree *xargs,
19727 unsigned int xnargs,
19728 int subr,
19729 unification_kind_t strict,
19730 int flags,
19731 vec<deferred_access_check, va_gc> **checks,
19732 bool explain_p)
19734 tree parm, arg;
19735 int i;
19736 int ntparms = TREE_VEC_LENGTH (tparms);
19737 int saw_undeduced = 0;
19738 tree parms;
19739 const tree *args;
19740 unsigned int nargs;
19741 unsigned int ia;
19743 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
19744 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
19745 gcc_assert (ntparms > 0);
19747 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
19749 /* Reset the number of non-defaulted template arguments contained
19750 in TARGS. */
19751 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
19753 again:
19754 parms = xparms;
19755 args = xargs;
19756 nargs = xnargs;
19758 ia = 0;
19759 while (parms && parms != void_list_node
19760 && ia < nargs)
19762 parm = TREE_VALUE (parms);
19764 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
19765 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
19766 /* For a function parameter pack that occurs at the end of the
19767 parameter-declaration-list, the type A of each remaining
19768 argument of the call is compared with the type P of the
19769 declarator-id of the function parameter pack. */
19770 break;
19772 parms = TREE_CHAIN (parms);
19774 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
19775 /* For a function parameter pack that does not occur at the
19776 end of the parameter-declaration-list, the type of the
19777 parameter pack is a non-deduced context. */
19778 continue;
19780 arg = args[ia];
19781 ++ia;
19783 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
19784 explain_p))
19785 return 1;
19788 if (parms
19789 && parms != void_list_node
19790 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
19792 /* Unify the remaining arguments with the pack expansion type. */
19793 tree argvec;
19794 tree parmvec = make_tree_vec (1);
19796 /* Allocate a TREE_VEC and copy in all of the arguments */
19797 argvec = make_tree_vec (nargs - ia);
19798 for (i = 0; ia < nargs; ++ia, ++i)
19799 TREE_VEC_ELT (argvec, i) = args[ia];
19801 /* Copy the parameter into parmvec. */
19802 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
19803 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
19804 /*subr=*/subr, explain_p))
19805 return 1;
19807 /* Advance to the end of the list of parameters. */
19808 parms = TREE_CHAIN (parms);
19811 /* Fail if we've reached the end of the parm list, and more args
19812 are present, and the parm list isn't variadic. */
19813 if (ia < nargs && parms == void_list_node)
19814 return unify_too_many_arguments (explain_p, nargs, ia);
19815 /* Fail if parms are left and they don't have default values and
19816 they aren't all deduced as empty packs (c++/57397). This is
19817 consistent with sufficient_parms_p. */
19818 if (parms && parms != void_list_node
19819 && TREE_PURPOSE (parms) == NULL_TREE)
19821 unsigned int count = nargs;
19822 tree p = parms;
19823 bool type_pack_p;
19826 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
19827 if (!type_pack_p)
19828 count++;
19829 p = TREE_CHAIN (p);
19831 while (p && p != void_list_node);
19832 if (count != nargs)
19833 return unify_too_few_arguments (explain_p, ia, count,
19834 type_pack_p);
19837 if (!subr)
19839 tsubst_flags_t complain = (explain_p
19840 ? tf_warning_or_error
19841 : tf_none);
19842 bool tried_array_deduction = (cxx_dialect < cxx17);
19844 for (i = 0; i < ntparms; i++)
19846 tree targ = TREE_VEC_ELT (targs, i);
19847 tree tparm = TREE_VEC_ELT (tparms, i);
19849 /* Clear the "incomplete" flags on all argument packs now so that
19850 substituting them into later default arguments works. */
19851 if (targ && ARGUMENT_PACK_P (targ))
19853 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
19854 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
19857 if (targ || tparm == error_mark_node)
19858 continue;
19859 tparm = TREE_VALUE (tparm);
19861 if (TREE_CODE (tparm) == TYPE_DECL
19862 && !tried_array_deduction)
19864 try_array_deduction (tparms, targs, xparms);
19865 tried_array_deduction = true;
19866 if (TREE_VEC_ELT (targs, i))
19867 continue;
19870 /* If this is an undeduced nontype parameter that depends on
19871 a type parameter, try another pass; its type may have been
19872 deduced from a later argument than the one from which
19873 this parameter can be deduced. */
19874 if (TREE_CODE (tparm) == PARM_DECL
19875 && uses_template_parms (TREE_TYPE (tparm))
19876 && saw_undeduced < 2)
19878 saw_undeduced = 1;
19879 continue;
19882 /* Core issue #226 (C++0x) [temp.deduct]:
19884 If a template argument has not been deduced, its
19885 default template argument, if any, is used.
19887 When we are in C++98 mode, TREE_PURPOSE will either
19888 be NULL_TREE or ERROR_MARK_NODE, so we do not need
19889 to explicitly check cxx_dialect here. */
19890 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
19891 /* OK, there is a default argument. Wait until after the
19892 conversion check to do substitution. */
19893 continue;
19895 /* If the type parameter is a parameter pack, then it will
19896 be deduced to an empty parameter pack. */
19897 if (template_parameter_pack_p (tparm))
19899 tree arg;
19901 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
19903 arg = make_node (NONTYPE_ARGUMENT_PACK);
19904 TREE_CONSTANT (arg) = 1;
19906 else
19907 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
19909 SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
19911 TREE_VEC_ELT (targs, i) = arg;
19912 continue;
19915 return unify_parameter_deduction_failure (explain_p, tparm);
19918 /* DR 1391: All parameters have args, now check non-dependent parms for
19919 convertibility. */
19920 if (saw_undeduced < 2)
19921 for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
19922 parms && parms != void_list_node && ia < nargs; )
19924 parm = TREE_VALUE (parms);
19926 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
19927 && (!TREE_CHAIN (parms)
19928 || TREE_CHAIN (parms) == void_list_node))
19929 /* For a function parameter pack that occurs at the end of the
19930 parameter-declaration-list, the type A of each remaining
19931 argument of the call is compared with the type P of the
19932 declarator-id of the function parameter pack. */
19933 break;
19935 parms = TREE_CHAIN (parms);
19937 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
19938 /* For a function parameter pack that does not occur at the
19939 end of the parameter-declaration-list, the type of the
19940 parameter pack is a non-deduced context. */
19941 continue;
19943 arg = args[ia];
19944 ++ia;
19946 if (uses_template_parms (parm))
19947 continue;
19948 if (check_non_deducible_conversion (parm, arg, strict, flags,
19949 explain_p))
19950 return 1;
19953 /* Now substitute into the default template arguments. */
19954 for (i = 0; i < ntparms; i++)
19956 tree targ = TREE_VEC_ELT (targs, i);
19957 tree tparm = TREE_VEC_ELT (tparms, i);
19959 if (targ || tparm == error_mark_node)
19960 continue;
19961 tree parm = TREE_VALUE (tparm);
19963 tsubst_flags_t fcomplain = complain;
19964 if (saw_undeduced == 1)
19966 /* When saw_undeduced == 1, substitution into parm and arg might
19967 fail or not replace all template parameters, and that's
19968 fine. */
19969 fcomplain = tf_none;
19970 if (TREE_CODE (parm) == PARM_DECL
19971 && uses_template_parms (TREE_TYPE (parm)))
19972 continue;
19975 tree arg = TREE_PURPOSE (tparm);
19976 reopen_deferring_access_checks (*checks);
19977 location_t save_loc = input_location;
19978 if (DECL_P (parm))
19979 input_location = DECL_SOURCE_LOCATION (parm);
19980 arg = tsubst_template_arg (arg, full_targs, fcomplain, NULL_TREE);
19981 if (arg != error_mark_node && !uses_template_parms (arg))
19982 arg = convert_template_argument (parm, arg, full_targs, complain,
19983 i, NULL_TREE);
19984 else if (saw_undeduced == 1)
19985 arg = NULL_TREE;
19986 else
19987 arg = error_mark_node;
19988 input_location = save_loc;
19989 *checks = get_deferred_access_checks ();
19990 pop_deferring_access_checks ();
19991 if (arg == error_mark_node)
19992 return 1;
19993 else if (arg)
19995 TREE_VEC_ELT (targs, i) = arg;
19996 /* The position of the first default template argument,
19997 is also the number of non-defaulted arguments in TARGS.
19998 Record that. */
19999 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20000 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
20004 if (saw_undeduced++ == 1)
20005 goto again;
20008 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20009 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
20011 return unify_success (explain_p);
20014 /* Subroutine of type_unification_real. Args are like the variables
20015 at the call site. ARG is an overloaded function (or template-id);
20016 we try deducing template args from each of the overloads, and if
20017 only one succeeds, we go with that. Modifies TARGS and returns
20018 true on success. */
20020 static bool
20021 resolve_overloaded_unification (tree tparms,
20022 tree targs,
20023 tree parm,
20024 tree arg,
20025 unification_kind_t strict,
20026 int sub_strict,
20027 bool explain_p)
20029 tree tempargs = copy_node (targs);
20030 int good = 0;
20031 tree goodfn = NULL_TREE;
20032 bool addr_p;
20034 if (TREE_CODE (arg) == ADDR_EXPR)
20036 arg = TREE_OPERAND (arg, 0);
20037 addr_p = true;
20039 else
20040 addr_p = false;
20042 if (TREE_CODE (arg) == COMPONENT_REF)
20043 /* Handle `&x' where `x' is some static or non-static member
20044 function name. */
20045 arg = TREE_OPERAND (arg, 1);
20047 if (TREE_CODE (arg) == OFFSET_REF)
20048 arg = TREE_OPERAND (arg, 1);
20050 /* Strip baselink information. */
20051 if (BASELINK_P (arg))
20052 arg = BASELINK_FUNCTIONS (arg);
20054 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
20056 /* If we got some explicit template args, we need to plug them into
20057 the affected templates before we try to unify, in case the
20058 explicit args will completely resolve the templates in question. */
20060 int ok = 0;
20061 tree expl_subargs = TREE_OPERAND (arg, 1);
20062 arg = TREE_OPERAND (arg, 0);
20064 for (lkp_iterator iter (arg); iter; ++iter)
20066 tree fn = *iter;
20067 tree subargs, elem;
20069 if (TREE_CODE (fn) != TEMPLATE_DECL)
20070 continue;
20072 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20073 expl_subargs, NULL_TREE, tf_none,
20074 /*require_all_args=*/true,
20075 /*use_default_args=*/true);
20076 if (subargs != error_mark_node
20077 && !any_dependent_template_arguments_p (subargs))
20079 elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
20080 if (try_one_overload (tparms, targs, tempargs, parm,
20081 elem, strict, sub_strict, addr_p, explain_p)
20082 && (!goodfn || !same_type_p (goodfn, elem)))
20084 goodfn = elem;
20085 ++good;
20088 else if (subargs)
20089 ++ok;
20091 /* If no templates (or more than one) are fully resolved by the
20092 explicit arguments, this template-id is a non-deduced context; it
20093 could still be OK if we deduce all template arguments for the
20094 enclosing call through other arguments. */
20095 if (good != 1)
20096 good = ok;
20098 else if (TREE_CODE (arg) != OVERLOAD
20099 && TREE_CODE (arg) != FUNCTION_DECL)
20100 /* If ARG is, for example, "(0, &f)" then its type will be unknown
20101 -- but the deduction does not succeed because the expression is
20102 not just the function on its own. */
20103 return false;
20104 else
20105 for (lkp_iterator iter (arg); iter; ++iter)
20107 tree fn = *iter;
20108 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
20109 strict, sub_strict, addr_p, explain_p)
20110 && (!goodfn || !decls_match (goodfn, fn)))
20112 goodfn = fn;
20113 ++good;
20117 /* [temp.deduct.type] A template-argument can be deduced from a pointer
20118 to function or pointer to member function argument if the set of
20119 overloaded functions does not contain function templates and at most
20120 one of a set of overloaded functions provides a unique match.
20122 So if we found multiple possibilities, we return success but don't
20123 deduce anything. */
20125 if (good == 1)
20127 int i = TREE_VEC_LENGTH (targs);
20128 for (; i--; )
20129 if (TREE_VEC_ELT (tempargs, i))
20131 tree old = TREE_VEC_ELT (targs, i);
20132 tree new_ = TREE_VEC_ELT (tempargs, i);
20133 if (new_ && old && ARGUMENT_PACK_P (old)
20134 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
20135 /* Don't forget explicit template arguments in a pack. */
20136 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
20137 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
20138 TREE_VEC_ELT (targs, i) = new_;
20141 if (good)
20142 return true;
20144 return false;
20147 /* Core DR 115: In contexts where deduction is done and fails, or in
20148 contexts where deduction is not done, if a template argument list is
20149 specified and it, along with any default template arguments, identifies
20150 a single function template specialization, then the template-id is an
20151 lvalue for the function template specialization. */
20153 tree
20154 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
20156 tree expr, offset, baselink;
20157 bool addr;
20159 if (!type_unknown_p (orig_expr))
20160 return orig_expr;
20162 expr = orig_expr;
20163 addr = false;
20164 offset = NULL_TREE;
20165 baselink = NULL_TREE;
20167 if (TREE_CODE (expr) == ADDR_EXPR)
20169 expr = TREE_OPERAND (expr, 0);
20170 addr = true;
20172 if (TREE_CODE (expr) == OFFSET_REF)
20174 offset = expr;
20175 expr = TREE_OPERAND (expr, 1);
20177 if (BASELINK_P (expr))
20179 baselink = expr;
20180 expr = BASELINK_FUNCTIONS (expr);
20183 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
20185 int good = 0;
20186 tree goodfn = NULL_TREE;
20188 /* If we got some explicit template args, we need to plug them into
20189 the affected templates before we try to unify, in case the
20190 explicit args will completely resolve the templates in question. */
20192 tree expl_subargs = TREE_OPERAND (expr, 1);
20193 tree arg = TREE_OPERAND (expr, 0);
20194 tree badfn = NULL_TREE;
20195 tree badargs = NULL_TREE;
20197 for (lkp_iterator iter (arg); iter; ++iter)
20199 tree fn = *iter;
20200 tree subargs, elem;
20202 if (TREE_CODE (fn) != TEMPLATE_DECL)
20203 continue;
20205 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20206 expl_subargs, NULL_TREE, tf_none,
20207 /*require_all_args=*/true,
20208 /*use_default_args=*/true);
20209 if (subargs != error_mark_node
20210 && !any_dependent_template_arguments_p (subargs))
20212 elem = instantiate_template (fn, subargs, tf_none);
20213 if (elem == error_mark_node)
20215 badfn = fn;
20216 badargs = subargs;
20218 else if (elem && (!goodfn || !decls_match (goodfn, elem)))
20220 goodfn = elem;
20221 ++good;
20225 if (good == 1)
20227 mark_used (goodfn);
20228 expr = goodfn;
20229 if (baselink)
20230 expr = build_baselink (BASELINK_BINFO (baselink),
20231 BASELINK_ACCESS_BINFO (baselink),
20232 expr, BASELINK_OPTYPE (baselink));
20233 if (offset)
20235 tree base
20236 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
20237 expr = build_offset_ref (base, expr, addr, complain);
20239 if (addr)
20240 expr = cp_build_addr_expr (expr, complain);
20241 return expr;
20243 else if (good == 0 && badargs && (complain & tf_error))
20244 /* There were no good options and at least one bad one, so let the
20245 user know what the problem is. */
20246 instantiate_template (badfn, badargs, complain);
20248 return orig_expr;
20251 /* Subroutine of resolve_overloaded_unification; does deduction for a single
20252 overload. Fills TARGS with any deduced arguments, or error_mark_node if
20253 different overloads deduce different arguments for a given parm.
20254 ADDR_P is true if the expression for which deduction is being
20255 performed was of the form "& fn" rather than simply "fn".
20257 Returns 1 on success. */
20259 static int
20260 try_one_overload (tree tparms,
20261 tree orig_targs,
20262 tree targs,
20263 tree parm,
20264 tree arg,
20265 unification_kind_t strict,
20266 int sub_strict,
20267 bool addr_p,
20268 bool explain_p)
20270 int nargs;
20271 tree tempargs;
20272 int i;
20274 if (arg == error_mark_node)
20275 return 0;
20277 /* [temp.deduct.type] A template-argument can be deduced from a pointer
20278 to function or pointer to member function argument if the set of
20279 overloaded functions does not contain function templates and at most
20280 one of a set of overloaded functions provides a unique match.
20282 So if this is a template, just return success. */
20284 if (uses_template_parms (arg))
20285 return 1;
20287 if (TREE_CODE (arg) == METHOD_TYPE)
20288 arg = build_ptrmemfunc_type (build_pointer_type (arg));
20289 else if (addr_p)
20290 arg = build_pointer_type (arg);
20292 sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
20294 /* We don't copy orig_targs for this because if we have already deduced
20295 some template args from previous args, unify would complain when we
20296 try to deduce a template parameter for the same argument, even though
20297 there isn't really a conflict. */
20298 nargs = TREE_VEC_LENGTH (targs);
20299 tempargs = make_tree_vec (nargs);
20301 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
20302 return 0;
20304 /* First make sure we didn't deduce anything that conflicts with
20305 explicitly specified args. */
20306 for (i = nargs; i--; )
20308 tree elt = TREE_VEC_ELT (tempargs, i);
20309 tree oldelt = TREE_VEC_ELT (orig_targs, i);
20311 if (!elt)
20312 /*NOP*/;
20313 else if (uses_template_parms (elt))
20314 /* Since we're unifying against ourselves, we will fill in
20315 template args used in the function parm list with our own
20316 template parms. Discard them. */
20317 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
20318 else if (oldelt && ARGUMENT_PACK_P (oldelt))
20320 /* Check that the argument at each index of the deduced argument pack
20321 is equivalent to the corresponding explicitly specified argument.
20322 We may have deduced more arguments than were explicitly specified,
20323 and that's OK. */
20325 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
20326 that's wrong if we deduce the same argument pack from multiple
20327 function arguments: it's only incomplete the first time. */
20329 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
20330 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
20332 if (TREE_VEC_LENGTH (deduced_pack)
20333 < TREE_VEC_LENGTH (explicit_pack))
20334 return 0;
20336 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
20337 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
20338 TREE_VEC_ELT (deduced_pack, j)))
20339 return 0;
20341 else if (oldelt && !template_args_equal (oldelt, elt))
20342 return 0;
20345 for (i = nargs; i--; )
20347 tree elt = TREE_VEC_ELT (tempargs, i);
20349 if (elt)
20350 TREE_VEC_ELT (targs, i) = elt;
20353 return 1;
20356 /* PARM is a template class (perhaps with unbound template
20357 parameters). ARG is a fully instantiated type. If ARG can be
20358 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
20359 TARGS are as for unify. */
20361 static tree
20362 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
20363 bool explain_p)
20365 tree copy_of_targs;
20367 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
20368 return NULL_TREE;
20369 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20370 /* Matches anything. */;
20371 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
20372 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
20373 return NULL_TREE;
20375 /* We need to make a new template argument vector for the call to
20376 unify. If we used TARGS, we'd clutter it up with the result of
20377 the attempted unification, even if this class didn't work out.
20378 We also don't want to commit ourselves to all the unifications
20379 we've already done, since unification is supposed to be done on
20380 an argument-by-argument basis. In other words, consider the
20381 following pathological case:
20383 template <int I, int J, int K>
20384 struct S {};
20386 template <int I, int J>
20387 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
20389 template <int I, int J, int K>
20390 void f(S<I, J, K>, S<I, I, I>);
20392 void g() {
20393 S<0, 0, 0> s0;
20394 S<0, 1, 2> s2;
20396 f(s0, s2);
20399 Now, by the time we consider the unification involving `s2', we
20400 already know that we must have `f<0, 0, 0>'. But, even though
20401 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
20402 because there are two ways to unify base classes of S<0, 1, 2>
20403 with S<I, I, I>. If we kept the already deduced knowledge, we
20404 would reject the possibility I=1. */
20405 copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
20407 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20409 if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
20410 return NULL_TREE;
20411 return arg;
20414 /* If unification failed, we're done. */
20415 if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
20416 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
20417 return NULL_TREE;
20419 return arg;
20422 /* Given a template type PARM and a class type ARG, find the unique
20423 base type in ARG that is an instance of PARM. We do not examine
20424 ARG itself; only its base-classes. If there is not exactly one
20425 appropriate base class, return NULL_TREE. PARM may be the type of
20426 a partial specialization, as well as a plain template type. Used
20427 by unify. */
20429 static enum template_base_result
20430 get_template_base (tree tparms, tree targs, tree parm, tree arg,
20431 bool explain_p, tree *result)
20433 tree rval = NULL_TREE;
20434 tree binfo;
20436 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
20438 binfo = TYPE_BINFO (complete_type (arg));
20439 if (!binfo)
20441 /* The type could not be completed. */
20442 *result = NULL_TREE;
20443 return tbr_incomplete_type;
20446 /* Walk in inheritance graph order. The search order is not
20447 important, and this avoids multiple walks of virtual bases. */
20448 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
20450 tree r = try_class_unification (tparms, targs, parm,
20451 BINFO_TYPE (binfo), explain_p);
20453 if (r)
20455 /* If there is more than one satisfactory baseclass, then:
20457 [temp.deduct.call]
20459 If they yield more than one possible deduced A, the type
20460 deduction fails.
20462 applies. */
20463 if (rval && !same_type_p (r, rval))
20465 *result = NULL_TREE;
20466 return tbr_ambiguous_baseclass;
20469 rval = r;
20473 *result = rval;
20474 return tbr_success;
20477 /* Returns the level of DECL, which declares a template parameter. */
20479 static int
20480 template_decl_level (tree decl)
20482 switch (TREE_CODE (decl))
20484 case TYPE_DECL:
20485 case TEMPLATE_DECL:
20486 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
20488 case PARM_DECL:
20489 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
20491 default:
20492 gcc_unreachable ();
20494 return 0;
20497 /* Decide whether ARG can be unified with PARM, considering only the
20498 cv-qualifiers of each type, given STRICT as documented for unify.
20499 Returns nonzero iff the unification is OK on that basis. */
20501 static int
20502 check_cv_quals_for_unify (int strict, tree arg, tree parm)
20504 int arg_quals = cp_type_quals (arg);
20505 int parm_quals = cp_type_quals (parm);
20507 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
20508 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
20510 /* Although a CVR qualifier is ignored when being applied to a
20511 substituted template parameter ([8.3.2]/1 for example), that
20512 does not allow us to unify "const T" with "int&" because both
20513 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
20514 It is ok when we're allowing additional CV qualifiers
20515 at the outer level [14.8.2.1]/3,1st bullet. */
20516 if ((TREE_CODE (arg) == REFERENCE_TYPE
20517 || TREE_CODE (arg) == FUNCTION_TYPE
20518 || TREE_CODE (arg) == METHOD_TYPE)
20519 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
20520 return 0;
20522 if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
20523 && (parm_quals & TYPE_QUAL_RESTRICT))
20524 return 0;
20527 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
20528 && (arg_quals & parm_quals) != parm_quals)
20529 return 0;
20531 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
20532 && (parm_quals & arg_quals) != arg_quals)
20533 return 0;
20535 return 1;
20538 /* Determines the LEVEL and INDEX for the template parameter PARM. */
20539 void
20540 template_parm_level_and_index (tree parm, int* level, int* index)
20542 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
20543 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
20544 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20546 *index = TEMPLATE_TYPE_IDX (parm);
20547 *level = TEMPLATE_TYPE_LEVEL (parm);
20549 else
20551 *index = TEMPLATE_PARM_IDX (parm);
20552 *level = TEMPLATE_PARM_LEVEL (parm);
20556 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
20557 do { \
20558 if (unify (TP, TA, P, A, S, EP)) \
20559 return 1; \
20560 } while (0)
20562 /* Unifies the remaining arguments in PACKED_ARGS with the pack
20563 expansion at the end of PACKED_PARMS. Returns 0 if the type
20564 deduction succeeds, 1 otherwise. STRICT is the same as in
20565 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
20566 function call argument list. We'll need to adjust the arguments to make them
20567 types. SUBR tells us if this is from a recursive call to
20568 type_unification_real, or for comparing two template argument
20569 lists. */
20571 static int
20572 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
20573 tree packed_args, unification_kind_t strict,
20574 bool subr, bool explain_p)
20576 tree parm
20577 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
20578 tree pattern = PACK_EXPANSION_PATTERN (parm);
20579 tree pack, packs = NULL_TREE;
20580 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
20582 /* Add in any args remembered from an earlier partial instantiation. */
20583 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
20584 int levels = TMPL_ARGS_DEPTH (targs);
20586 packed_args = expand_template_argument_pack (packed_args);
20588 int len = TREE_VEC_LENGTH (packed_args);
20590 /* Determine the parameter packs we will be deducing from the
20591 pattern, and record their current deductions. */
20592 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
20593 pack; pack = TREE_CHAIN (pack))
20595 tree parm_pack = TREE_VALUE (pack);
20596 int idx, level;
20598 /* Determine the index and level of this parameter pack. */
20599 template_parm_level_and_index (parm_pack, &level, &idx);
20600 if (level < levels)
20601 continue;
20603 /* Keep track of the parameter packs and their corresponding
20604 argument packs. */
20605 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
20606 TREE_TYPE (packs) = make_tree_vec (len - start);
20609 /* Loop through all of the arguments that have not yet been
20610 unified and unify each with the pattern. */
20611 for (i = start; i < len; i++)
20613 tree parm;
20614 bool any_explicit = false;
20615 tree arg = TREE_VEC_ELT (packed_args, i);
20617 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
20618 or the element of its argument pack at the current index if
20619 this argument was explicitly specified. */
20620 for (pack = packs; pack; pack = TREE_CHAIN (pack))
20622 int idx, level;
20623 tree arg, pargs;
20624 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
20626 arg = NULL_TREE;
20627 if (TREE_VALUE (pack)
20628 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
20629 && (i - start < TREE_VEC_LENGTH (pargs)))
20631 any_explicit = true;
20632 arg = TREE_VEC_ELT (pargs, i - start);
20634 TMPL_ARG (targs, level, idx) = arg;
20637 /* If we had explicit template arguments, substitute them into the
20638 pattern before deduction. */
20639 if (any_explicit)
20641 /* Some arguments might still be unspecified or dependent. */
20642 bool dependent;
20643 ++processing_template_decl;
20644 dependent = any_dependent_template_arguments_p (targs);
20645 if (!dependent)
20646 --processing_template_decl;
20647 parm = tsubst (pattern, targs,
20648 explain_p ? tf_warning_or_error : tf_none,
20649 NULL_TREE);
20650 if (dependent)
20651 --processing_template_decl;
20652 if (parm == error_mark_node)
20653 return 1;
20655 else
20656 parm = pattern;
20658 /* Unify the pattern with the current argument. */
20659 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
20660 explain_p))
20661 return 1;
20663 /* For each parameter pack, collect the deduced value. */
20664 for (pack = packs; pack; pack = TREE_CHAIN (pack))
20666 int idx, level;
20667 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
20669 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
20670 TMPL_ARG (targs, level, idx);
20674 /* Verify that the results of unification with the parameter packs
20675 produce results consistent with what we've seen before, and make
20676 the deduced argument packs available. */
20677 for (pack = packs; pack; pack = TREE_CHAIN (pack))
20679 tree old_pack = TREE_VALUE (pack);
20680 tree new_args = TREE_TYPE (pack);
20681 int i, len = TREE_VEC_LENGTH (new_args);
20682 int idx, level;
20683 bool nondeduced_p = false;
20685 /* By default keep the original deduced argument pack.
20686 If necessary, more specific code is going to update the
20687 resulting deduced argument later down in this function. */
20688 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
20689 TMPL_ARG (targs, level, idx) = old_pack;
20691 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
20692 actually deduce anything. */
20693 for (i = 0; i < len && !nondeduced_p; ++i)
20694 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
20695 nondeduced_p = true;
20696 if (nondeduced_p)
20697 continue;
20699 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
20701 /* If we had fewer function args than explicit template args,
20702 just use the explicits. */
20703 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
20704 int explicit_len = TREE_VEC_LENGTH (explicit_args);
20705 if (len < explicit_len)
20706 new_args = explicit_args;
20709 if (!old_pack)
20711 tree result;
20712 /* Build the deduced *_ARGUMENT_PACK. */
20713 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
20715 result = make_node (NONTYPE_ARGUMENT_PACK);
20716 TREE_CONSTANT (result) = 1;
20718 else
20719 result = cxx_make_type (TYPE_ARGUMENT_PACK);
20721 SET_ARGUMENT_PACK_ARGS (result, new_args);
20723 /* Note the deduced argument packs for this parameter
20724 pack. */
20725 TMPL_ARG (targs, level, idx) = result;
20727 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
20728 && (ARGUMENT_PACK_ARGS (old_pack)
20729 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
20731 /* We only had the explicitly-provided arguments before, but
20732 now we have a complete set of arguments. */
20733 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
20735 SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
20736 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
20737 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
20739 else
20741 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
20742 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
20744 if (!comp_template_args (old_args, new_args,
20745 &bad_old_arg, &bad_new_arg))
20746 /* Inconsistent unification of this parameter pack. */
20747 return unify_parameter_pack_inconsistent (explain_p,
20748 bad_old_arg,
20749 bad_new_arg);
20753 return unify_success (explain_p);
20756 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
20757 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
20758 parameters and return value are as for unify. */
20760 static int
20761 unify_array_domain (tree tparms, tree targs,
20762 tree parm_dom, tree arg_dom,
20763 bool explain_p)
20765 tree parm_max;
20766 tree arg_max;
20767 bool parm_cst;
20768 bool arg_cst;
20770 /* Our representation of array types uses "N - 1" as the
20771 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
20772 not an integer constant. We cannot unify arbitrarily
20773 complex expressions, so we eliminate the MINUS_EXPRs
20774 here. */
20775 parm_max = TYPE_MAX_VALUE (parm_dom);
20776 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
20777 if (!parm_cst)
20779 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
20780 parm_max = TREE_OPERAND (parm_max, 0);
20782 arg_max = TYPE_MAX_VALUE (arg_dom);
20783 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
20784 if (!arg_cst)
20786 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
20787 trying to unify the type of a variable with the type
20788 of a template parameter. For example:
20790 template <unsigned int N>
20791 void f (char (&) [N]);
20792 int g();
20793 void h(int i) {
20794 char a[g(i)];
20795 f(a);
20798 Here, the type of the ARG will be "int [g(i)]", and
20799 may be a SAVE_EXPR, etc. */
20800 if (TREE_CODE (arg_max) != MINUS_EXPR)
20801 return unify_vla_arg (explain_p, arg_dom);
20802 arg_max = TREE_OPERAND (arg_max, 0);
20805 /* If only one of the bounds used a MINUS_EXPR, compensate
20806 by adding one to the other bound. */
20807 if (parm_cst && !arg_cst)
20808 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
20809 integer_type_node,
20810 parm_max,
20811 integer_one_node);
20812 else if (arg_cst && !parm_cst)
20813 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
20814 integer_type_node,
20815 arg_max,
20816 integer_one_node);
20818 return unify (tparms, targs, parm_max, arg_max,
20819 UNIFY_ALLOW_INTEGER, explain_p);
20822 /* Returns whether T, a P or A in unify, is a type, template or expression. */
20824 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
20826 static pa_kind_t
20827 pa_kind (tree t)
20829 if (PACK_EXPANSION_P (t))
20830 t = PACK_EXPANSION_PATTERN (t);
20831 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
20832 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
20833 || DECL_TYPE_TEMPLATE_P (t))
20834 return pa_tmpl;
20835 else if (TYPE_P (t))
20836 return pa_type;
20837 else
20838 return pa_expr;
20841 /* Deduce the value of template parameters. TPARMS is the (innermost)
20842 set of template parameters to a template. TARGS is the bindings
20843 for those template parameters, as determined thus far; TARGS may
20844 include template arguments for outer levels of template parameters
20845 as well. PARM is a parameter to a template function, or a
20846 subcomponent of that parameter; ARG is the corresponding argument.
20847 This function attempts to match PARM with ARG in a manner
20848 consistent with the existing assignments in TARGS. If more values
20849 are deduced, then TARGS is updated.
20851 Returns 0 if the type deduction succeeds, 1 otherwise. The
20852 parameter STRICT is a bitwise or of the following flags:
20854 UNIFY_ALLOW_NONE:
20855 Require an exact match between PARM and ARG.
20856 UNIFY_ALLOW_MORE_CV_QUAL:
20857 Allow the deduced ARG to be more cv-qualified (by qualification
20858 conversion) than ARG.
20859 UNIFY_ALLOW_LESS_CV_QUAL:
20860 Allow the deduced ARG to be less cv-qualified than ARG.
20861 UNIFY_ALLOW_DERIVED:
20862 Allow the deduced ARG to be a template base class of ARG,
20863 or a pointer to a template base class of the type pointed to by
20864 ARG.
20865 UNIFY_ALLOW_INTEGER:
20866 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
20867 case for more information.
20868 UNIFY_ALLOW_OUTER_LEVEL:
20869 This is the outermost level of a deduction. Used to determine validity
20870 of qualification conversions. A valid qualification conversion must
20871 have const qualified pointers leading up to the inner type which
20872 requires additional CV quals, except at the outer level, where const
20873 is not required [conv.qual]. It would be normal to set this flag in
20874 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
20875 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
20876 This is the outermost level of a deduction, and PARM can be more CV
20877 qualified at this point.
20878 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
20879 This is the outermost level of a deduction, and PARM can be less CV
20880 qualified at this point. */
20882 static int
20883 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
20884 bool explain_p)
20886 int idx;
20887 tree targ;
20888 tree tparm;
20889 int strict_in = strict;
20890 tsubst_flags_t complain = (explain_p
20891 ? tf_warning_or_error
20892 : tf_none);
20894 /* I don't think this will do the right thing with respect to types.
20895 But the only case I've seen it in so far has been array bounds, where
20896 signedness is the only information lost, and I think that will be
20897 okay. */
20898 while (CONVERT_EXPR_P (parm))
20899 parm = TREE_OPERAND (parm, 0);
20901 if (arg == error_mark_node)
20902 return unify_invalid (explain_p);
20903 if (arg == unknown_type_node
20904 || arg == init_list_type_node)
20905 /* We can't deduce anything from this, but we might get all the
20906 template args from other function args. */
20907 return unify_success (explain_p);
20909 if (parm == any_targ_node || arg == any_targ_node)
20910 return unify_success (explain_p);
20912 /* If PARM uses template parameters, then we can't bail out here,
20913 even if ARG == PARM, since we won't record unifications for the
20914 template parameters. We might need them if we're trying to
20915 figure out which of two things is more specialized. */
20916 if (arg == parm && !uses_template_parms (parm))
20917 return unify_success (explain_p);
20919 /* Handle init lists early, so the rest of the function can assume
20920 we're dealing with a type. */
20921 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
20923 tree elt, elttype;
20924 unsigned i;
20925 tree orig_parm = parm;
20927 /* Replace T with std::initializer_list<T> for deduction. */
20928 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
20929 && flag_deduce_init_list)
20930 parm = listify (parm);
20932 if (!is_std_init_list (parm)
20933 && TREE_CODE (parm) != ARRAY_TYPE)
20934 /* We can only deduce from an initializer list argument if the
20935 parameter is std::initializer_list or an array; otherwise this
20936 is a non-deduced context. */
20937 return unify_success (explain_p);
20939 if (TREE_CODE (parm) == ARRAY_TYPE)
20940 elttype = TREE_TYPE (parm);
20941 else
20943 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
20944 /* Deduction is defined in terms of a single type, so just punt
20945 on the (bizarre) std::initializer_list<T...>. */
20946 if (PACK_EXPANSION_P (elttype))
20947 return unify_success (explain_p);
20950 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
20952 int elt_strict = strict;
20954 if (elt == error_mark_node)
20955 return unify_invalid (explain_p);
20957 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
20959 tree type = TREE_TYPE (elt);
20960 if (type == error_mark_node)
20961 return unify_invalid (explain_p);
20962 /* It should only be possible to get here for a call. */
20963 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
20964 elt_strict |= maybe_adjust_types_for_deduction
20965 (DEDUCE_CALL, &elttype, &type, elt);
20966 elt = type;
20969 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
20970 explain_p);
20973 if (TREE_CODE (parm) == ARRAY_TYPE
20974 && deducible_array_bound (TYPE_DOMAIN (parm)))
20976 /* Also deduce from the length of the initializer list. */
20977 tree max = size_int (CONSTRUCTOR_NELTS (arg));
20978 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
20979 if (idx == error_mark_node)
20980 return unify_invalid (explain_p);
20981 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
20982 idx, explain_p);
20985 /* If the std::initializer_list<T> deduction worked, replace the
20986 deduced A with std::initializer_list<A>. */
20987 if (orig_parm != parm)
20989 idx = TEMPLATE_TYPE_IDX (orig_parm);
20990 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
20991 targ = listify (targ);
20992 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
20994 return unify_success (explain_p);
20997 /* If parm and arg aren't the same kind of thing (template, type, or
20998 expression), fail early. */
20999 if (pa_kind (parm) != pa_kind (arg))
21000 return unify_invalid (explain_p);
21002 /* Immediately reject some pairs that won't unify because of
21003 cv-qualification mismatches. */
21004 if (TREE_CODE (arg) == TREE_CODE (parm)
21005 && TYPE_P (arg)
21006 /* It is the elements of the array which hold the cv quals of an array
21007 type, and the elements might be template type parms. We'll check
21008 when we recurse. */
21009 && TREE_CODE (arg) != ARRAY_TYPE
21010 /* We check the cv-qualifiers when unifying with template type
21011 parameters below. We want to allow ARG `const T' to unify with
21012 PARM `T' for example, when computing which of two templates
21013 is more specialized, for example. */
21014 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
21015 && !check_cv_quals_for_unify (strict_in, arg, parm))
21016 return unify_cv_qual_mismatch (explain_p, parm, arg);
21018 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
21019 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
21020 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
21021 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
21022 strict &= ~UNIFY_ALLOW_DERIVED;
21023 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21024 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
21026 switch (TREE_CODE (parm))
21028 case TYPENAME_TYPE:
21029 case SCOPE_REF:
21030 case UNBOUND_CLASS_TEMPLATE:
21031 /* In a type which contains a nested-name-specifier, template
21032 argument values cannot be deduced for template parameters used
21033 within the nested-name-specifier. */
21034 return unify_success (explain_p);
21036 case TEMPLATE_TYPE_PARM:
21037 case TEMPLATE_TEMPLATE_PARM:
21038 case BOUND_TEMPLATE_TEMPLATE_PARM:
21039 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21040 if (error_operand_p (tparm))
21041 return unify_invalid (explain_p);
21043 if (TEMPLATE_TYPE_LEVEL (parm)
21044 != template_decl_level (tparm))
21045 /* The PARM is not one we're trying to unify. Just check
21046 to see if it matches ARG. */
21048 if (TREE_CODE (arg) == TREE_CODE (parm)
21049 && (is_auto (parm) ? is_auto (arg)
21050 : same_type_p (parm, arg)))
21051 return unify_success (explain_p);
21052 else
21053 return unify_type_mismatch (explain_p, parm, arg);
21055 idx = TEMPLATE_TYPE_IDX (parm);
21056 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21057 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
21058 if (error_operand_p (tparm))
21059 return unify_invalid (explain_p);
21061 /* Check for mixed types and values. */
21062 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21063 && TREE_CODE (tparm) != TYPE_DECL)
21064 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21065 && TREE_CODE (tparm) != TEMPLATE_DECL))
21066 gcc_unreachable ();
21068 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21070 if ((strict_in & UNIFY_ALLOW_DERIVED)
21071 && CLASS_TYPE_P (arg))
21073 /* First try to match ARG directly. */
21074 tree t = try_class_unification (tparms, targs, parm, arg,
21075 explain_p);
21076 if (!t)
21078 /* Otherwise, look for a suitable base of ARG, as below. */
21079 enum template_base_result r;
21080 r = get_template_base (tparms, targs, parm, arg,
21081 explain_p, &t);
21082 if (!t)
21083 return unify_no_common_base (explain_p, r, parm, arg);
21084 arg = t;
21087 /* ARG must be constructed from a template class or a template
21088 template parameter. */
21089 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
21090 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21091 return unify_template_deduction_failure (explain_p, parm, arg);
21093 /* Deduce arguments T, i from TT<T> or TT<i>. */
21094 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
21095 return 1;
21097 arg = TYPE_TI_TEMPLATE (arg);
21099 /* Fall through to deduce template name. */
21102 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21103 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21105 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
21107 /* Simple cases: Value already set, does match or doesn't. */
21108 if (targ != NULL_TREE && template_args_equal (targ, arg))
21109 return unify_success (explain_p);
21110 else if (targ)
21111 return unify_inconsistency (explain_p, parm, targ, arg);
21113 else
21115 /* If PARM is `const T' and ARG is only `int', we don't have
21116 a match unless we are allowing additional qualification.
21117 If ARG is `const int' and PARM is just `T' that's OK;
21118 that binds `const int' to `T'. */
21119 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
21120 arg, parm))
21121 return unify_cv_qual_mismatch (explain_p, parm, arg);
21123 /* Consider the case where ARG is `const volatile int' and
21124 PARM is `const T'. Then, T should be `volatile int'. */
21125 arg = cp_build_qualified_type_real
21126 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
21127 if (arg == error_mark_node)
21128 return unify_invalid (explain_p);
21130 /* Simple cases: Value already set, does match or doesn't. */
21131 if (targ != NULL_TREE && same_type_p (targ, arg))
21132 return unify_success (explain_p);
21133 else if (targ)
21134 return unify_inconsistency (explain_p, parm, targ, arg);
21136 /* Make sure that ARG is not a variable-sized array. (Note
21137 that were talking about variable-sized arrays (like
21138 `int[n]'), rather than arrays of unknown size (like
21139 `int[]').) We'll get very confused by such a type since
21140 the bound of the array is not constant, and therefore
21141 not mangleable. Besides, such types are not allowed in
21142 ISO C++, so we can do as we please here. We do allow
21143 them for 'auto' deduction, since that isn't ABI-exposed. */
21144 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
21145 return unify_vla_arg (explain_p, arg);
21147 /* Strip typedefs as in convert_template_argument. */
21148 arg = canonicalize_type_argument (arg, tf_none);
21151 /* If ARG is a parameter pack or an expansion, we cannot unify
21152 against it unless PARM is also a parameter pack. */
21153 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21154 && !template_parameter_pack_p (parm))
21155 return unify_parameter_pack_mismatch (explain_p, parm, arg);
21157 /* If the argument deduction results is a METHOD_TYPE,
21158 then there is a problem.
21159 METHOD_TYPE doesn't map to any real C++ type the result of
21160 the deduction can not be of that type. */
21161 if (TREE_CODE (arg) == METHOD_TYPE)
21162 return unify_method_type_error (explain_p, arg);
21164 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21165 return unify_success (explain_p);
21167 case TEMPLATE_PARM_INDEX:
21168 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21169 if (error_operand_p (tparm))
21170 return unify_invalid (explain_p);
21172 if (TEMPLATE_PARM_LEVEL (parm)
21173 != template_decl_level (tparm))
21175 /* The PARM is not one we're trying to unify. Just check
21176 to see if it matches ARG. */
21177 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
21178 && cp_tree_equal (parm, arg));
21179 if (result)
21180 unify_expression_unequal (explain_p, parm, arg);
21181 return result;
21184 idx = TEMPLATE_PARM_IDX (parm);
21185 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21187 if (targ)
21189 if ((strict & UNIFY_ALLOW_INTEGER)
21190 && TREE_TYPE (targ) && TREE_TYPE (arg)
21191 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
21192 /* We're deducing from an array bound, the type doesn't matter. */
21193 arg = fold_convert (TREE_TYPE (targ), arg);
21194 int x = !cp_tree_equal (targ, arg);
21195 if (x)
21196 unify_inconsistency (explain_p, parm, targ, arg);
21197 return x;
21200 /* [temp.deduct.type] If, in the declaration of a function template
21201 with a non-type template-parameter, the non-type
21202 template-parameter is used in an expression in the function
21203 parameter-list and, if the corresponding template-argument is
21204 deduced, the template-argument type shall match the type of the
21205 template-parameter exactly, except that a template-argument
21206 deduced from an array bound may be of any integral type.
21207 The non-type parameter might use already deduced type parameters. */
21208 ++processing_template_decl;
21209 tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
21210 --processing_template_decl;
21211 if (tree a = type_uses_auto (tparm))
21213 tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
21214 if (tparm == error_mark_node)
21215 return 1;
21218 if (!TREE_TYPE (arg))
21219 /* Template-parameter dependent expression. Just accept it for now.
21220 It will later be processed in convert_template_argument. */
21222 else if (same_type_p (non_reference (TREE_TYPE (arg)),
21223 non_reference (tparm)))
21224 /* OK */;
21225 else if ((strict & UNIFY_ALLOW_INTEGER)
21226 && CP_INTEGRAL_TYPE_P (tparm))
21227 /* Convert the ARG to the type of PARM; the deduced non-type
21228 template argument must exactly match the types of the
21229 corresponding parameter. */
21230 arg = fold (build_nop (tparm, arg));
21231 else if (uses_template_parms (tparm))
21233 /* We haven't deduced the type of this parameter yet. */
21234 if (cxx_dialect >= cxx17
21235 /* We deduce from array bounds in try_array_deduction. */
21236 && !(strict & UNIFY_ALLOW_INTEGER))
21238 /* Deduce it from the non-type argument. */
21239 tree atype = TREE_TYPE (arg);
21240 RECUR_AND_CHECK_FAILURE (tparms, targs,
21241 tparm, atype,
21242 UNIFY_ALLOW_NONE, explain_p);
21244 else
21245 /* Try again later. */
21246 return unify_success (explain_p);
21248 else
21249 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
21251 /* If ARG is a parameter pack or an expansion, we cannot unify
21252 against it unless PARM is also a parameter pack. */
21253 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21254 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
21255 return unify_parameter_pack_mismatch (explain_p, parm, arg);
21258 bool removed_attr = false;
21259 arg = strip_typedefs_expr (arg, &removed_attr);
21261 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21262 return unify_success (explain_p);
21264 case PTRMEM_CST:
21266 /* A pointer-to-member constant can be unified only with
21267 another constant. */
21268 if (TREE_CODE (arg) != PTRMEM_CST)
21269 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
21271 /* Just unify the class member. It would be useless (and possibly
21272 wrong, depending on the strict flags) to unify also
21273 PTRMEM_CST_CLASS, because we want to be sure that both parm and
21274 arg refer to the same variable, even if through different
21275 classes. For instance:
21277 struct A { int x; };
21278 struct B : A { };
21280 Unification of &A::x and &B::x must succeed. */
21281 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
21282 PTRMEM_CST_MEMBER (arg), strict, explain_p);
21285 case POINTER_TYPE:
21287 if (!TYPE_PTR_P (arg))
21288 return unify_type_mismatch (explain_p, parm, arg);
21290 /* [temp.deduct.call]
21292 A can be another pointer or pointer to member type that can
21293 be converted to the deduced A via a qualification
21294 conversion (_conv.qual_).
21296 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
21297 This will allow for additional cv-qualification of the
21298 pointed-to types if appropriate. */
21300 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
21301 /* The derived-to-base conversion only persists through one
21302 level of pointers. */
21303 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
21305 return unify (tparms, targs, TREE_TYPE (parm),
21306 TREE_TYPE (arg), strict, explain_p);
21309 case REFERENCE_TYPE:
21310 if (TREE_CODE (arg) != REFERENCE_TYPE)
21311 return unify_type_mismatch (explain_p, parm, arg);
21312 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21313 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21315 case ARRAY_TYPE:
21316 if (TREE_CODE (arg) != ARRAY_TYPE)
21317 return unify_type_mismatch (explain_p, parm, arg);
21318 if ((TYPE_DOMAIN (parm) == NULL_TREE)
21319 != (TYPE_DOMAIN (arg) == NULL_TREE))
21320 return unify_type_mismatch (explain_p, parm, arg);
21321 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21322 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21323 if (TYPE_DOMAIN (parm) != NULL_TREE)
21324 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21325 TYPE_DOMAIN (arg), explain_p);
21326 return unify_success (explain_p);
21328 case REAL_TYPE:
21329 case COMPLEX_TYPE:
21330 case VECTOR_TYPE:
21331 case INTEGER_TYPE:
21332 case BOOLEAN_TYPE:
21333 case ENUMERAL_TYPE:
21334 case VOID_TYPE:
21335 case NULLPTR_TYPE:
21336 if (TREE_CODE (arg) != TREE_CODE (parm))
21337 return unify_type_mismatch (explain_p, parm, arg);
21339 /* We have already checked cv-qualification at the top of the
21340 function. */
21341 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
21342 return unify_type_mismatch (explain_p, parm, arg);
21344 /* As far as unification is concerned, this wins. Later checks
21345 will invalidate it if necessary. */
21346 return unify_success (explain_p);
21348 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
21349 /* Type INTEGER_CST can come from ordinary constant template args. */
21350 case INTEGER_CST:
21351 while (CONVERT_EXPR_P (arg))
21352 arg = TREE_OPERAND (arg, 0);
21354 if (TREE_CODE (arg) != INTEGER_CST)
21355 return unify_template_argument_mismatch (explain_p, parm, arg);
21356 return (tree_int_cst_equal (parm, arg)
21357 ? unify_success (explain_p)
21358 : unify_template_argument_mismatch (explain_p, parm, arg));
21360 case TREE_VEC:
21362 int i, len, argslen;
21363 int parm_variadic_p = 0;
21365 if (TREE_CODE (arg) != TREE_VEC)
21366 return unify_template_argument_mismatch (explain_p, parm, arg);
21368 len = TREE_VEC_LENGTH (parm);
21369 argslen = TREE_VEC_LENGTH (arg);
21371 /* Check for pack expansions in the parameters. */
21372 for (i = 0; i < len; ++i)
21374 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
21376 if (i == len - 1)
21377 /* We can unify against something with a trailing
21378 parameter pack. */
21379 parm_variadic_p = 1;
21380 else
21381 /* [temp.deduct.type]/9: If the template argument list of
21382 P contains a pack expansion that is not the last
21383 template argument, the entire template argument list
21384 is a non-deduced context. */
21385 return unify_success (explain_p);
21389 /* If we don't have enough arguments to satisfy the parameters
21390 (not counting the pack expression at the end), or we have
21391 too many arguments for a parameter list that doesn't end in
21392 a pack expression, we can't unify. */
21393 if (parm_variadic_p
21394 ? argslen < len - parm_variadic_p
21395 : argslen != len)
21396 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
21398 /* Unify all of the parameters that precede the (optional)
21399 pack expression. */
21400 for (i = 0; i < len - parm_variadic_p; ++i)
21402 RECUR_AND_CHECK_FAILURE (tparms, targs,
21403 TREE_VEC_ELT (parm, i),
21404 TREE_VEC_ELT (arg, i),
21405 UNIFY_ALLOW_NONE, explain_p);
21407 if (parm_variadic_p)
21408 return unify_pack_expansion (tparms, targs, parm, arg,
21409 DEDUCE_EXACT,
21410 /*subr=*/true, explain_p);
21411 return unify_success (explain_p);
21414 case RECORD_TYPE:
21415 case UNION_TYPE:
21416 if (TREE_CODE (arg) != TREE_CODE (parm))
21417 return unify_type_mismatch (explain_p, parm, arg);
21419 if (TYPE_PTRMEMFUNC_P (parm))
21421 if (!TYPE_PTRMEMFUNC_P (arg))
21422 return unify_type_mismatch (explain_p, parm, arg);
21424 return unify (tparms, targs,
21425 TYPE_PTRMEMFUNC_FN_TYPE (parm),
21426 TYPE_PTRMEMFUNC_FN_TYPE (arg),
21427 strict, explain_p);
21429 else if (TYPE_PTRMEMFUNC_P (arg))
21430 return unify_type_mismatch (explain_p, parm, arg);
21432 if (CLASSTYPE_TEMPLATE_INFO (parm))
21434 tree t = NULL_TREE;
21436 if (strict_in & UNIFY_ALLOW_DERIVED)
21438 /* First, we try to unify the PARM and ARG directly. */
21439 t = try_class_unification (tparms, targs,
21440 parm, arg, explain_p);
21442 if (!t)
21444 /* Fallback to the special case allowed in
21445 [temp.deduct.call]:
21447 If P is a class, and P has the form
21448 template-id, then A can be a derived class of
21449 the deduced A. Likewise, if P is a pointer to
21450 a class of the form template-id, A can be a
21451 pointer to a derived class pointed to by the
21452 deduced A. */
21453 enum template_base_result r;
21454 r = get_template_base (tparms, targs, parm, arg,
21455 explain_p, &t);
21457 if (!t)
21459 /* Don't give the derived diagnostic if we're
21460 already dealing with the same template. */
21461 bool same_template
21462 = (CLASSTYPE_TEMPLATE_INFO (arg)
21463 && (CLASSTYPE_TI_TEMPLATE (parm)
21464 == CLASSTYPE_TI_TEMPLATE (arg)));
21465 return unify_no_common_base (explain_p && !same_template,
21466 r, parm, arg);
21470 else if (CLASSTYPE_TEMPLATE_INFO (arg)
21471 && (CLASSTYPE_TI_TEMPLATE (parm)
21472 == CLASSTYPE_TI_TEMPLATE (arg)))
21473 /* Perhaps PARM is something like S<U> and ARG is S<int>.
21474 Then, we should unify `int' and `U'. */
21475 t = arg;
21476 else
21477 /* There's no chance of unification succeeding. */
21478 return unify_type_mismatch (explain_p, parm, arg);
21480 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
21481 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
21483 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
21484 return unify_type_mismatch (explain_p, parm, arg);
21485 return unify_success (explain_p);
21487 case METHOD_TYPE:
21488 case FUNCTION_TYPE:
21490 unsigned int nargs;
21491 tree *args;
21492 tree a;
21493 unsigned int i;
21495 if (TREE_CODE (arg) != TREE_CODE (parm))
21496 return unify_type_mismatch (explain_p, parm, arg);
21498 /* CV qualifications for methods can never be deduced, they must
21499 match exactly. We need to check them explicitly here,
21500 because type_unification_real treats them as any other
21501 cv-qualified parameter. */
21502 if (TREE_CODE (parm) == METHOD_TYPE
21503 && (!check_cv_quals_for_unify
21504 (UNIFY_ALLOW_NONE,
21505 class_of_this_parm (arg),
21506 class_of_this_parm (parm))))
21507 return unify_cv_qual_mismatch (explain_p, parm, arg);
21508 if (TREE_CODE (arg) == FUNCTION_TYPE
21509 && type_memfn_quals (parm) != type_memfn_quals (arg))
21510 return unify_cv_qual_mismatch (explain_p, parm, arg);
21511 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
21512 return unify_type_mismatch (explain_p, parm, arg);
21514 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
21515 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
21517 nargs = list_length (TYPE_ARG_TYPES (arg));
21518 args = XALLOCAVEC (tree, nargs);
21519 for (a = TYPE_ARG_TYPES (arg), i = 0;
21520 a != NULL_TREE && a != void_list_node;
21521 a = TREE_CHAIN (a), ++i)
21522 args[i] = TREE_VALUE (a);
21523 nargs = i;
21525 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
21526 args, nargs, 1, DEDUCE_EXACT,
21527 LOOKUP_NORMAL, NULL, explain_p))
21528 return 1;
21530 if (flag_noexcept_type)
21532 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
21533 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
21534 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
21535 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
21536 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
21537 && uses_template_parms (TREE_PURPOSE (pspec)))
21538 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
21539 TREE_PURPOSE (aspec),
21540 UNIFY_ALLOW_NONE, explain_p);
21541 else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
21542 return unify_type_mismatch (explain_p, parm, arg);
21545 return 0;
21548 case OFFSET_TYPE:
21549 /* Unify a pointer to member with a pointer to member function, which
21550 deduces the type of the member as a function type. */
21551 if (TYPE_PTRMEMFUNC_P (arg))
21553 /* Check top-level cv qualifiers */
21554 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
21555 return unify_cv_qual_mismatch (explain_p, parm, arg);
21557 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
21558 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
21559 UNIFY_ALLOW_NONE, explain_p);
21561 /* Determine the type of the function we are unifying against. */
21562 tree fntype = static_fn_type (arg);
21564 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
21567 if (TREE_CODE (arg) != OFFSET_TYPE)
21568 return unify_type_mismatch (explain_p, parm, arg);
21569 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
21570 TYPE_OFFSET_BASETYPE (arg),
21571 UNIFY_ALLOW_NONE, explain_p);
21572 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21573 strict, explain_p);
21575 case CONST_DECL:
21576 if (DECL_TEMPLATE_PARM_P (parm))
21577 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
21578 if (arg != scalar_constant_value (parm))
21579 return unify_template_argument_mismatch (explain_p, parm, arg);
21580 return unify_success (explain_p);
21582 case FIELD_DECL:
21583 case TEMPLATE_DECL:
21584 /* Matched cases are handled by the ARG == PARM test above. */
21585 return unify_template_argument_mismatch (explain_p, parm, arg);
21587 case VAR_DECL:
21588 /* We might get a variable as a non-type template argument in parm if the
21589 corresponding parameter is type-dependent. Make any necessary
21590 adjustments based on whether arg is a reference. */
21591 if (CONSTANT_CLASS_P (arg))
21592 parm = fold_non_dependent_expr (parm);
21593 else if (REFERENCE_REF_P (arg))
21595 tree sub = TREE_OPERAND (arg, 0);
21596 STRIP_NOPS (sub);
21597 if (TREE_CODE (sub) == ADDR_EXPR)
21598 arg = TREE_OPERAND (sub, 0);
21600 /* Now use the normal expression code to check whether they match. */
21601 goto expr;
21603 case TYPE_ARGUMENT_PACK:
21604 case NONTYPE_ARGUMENT_PACK:
21605 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
21606 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
21608 case TYPEOF_TYPE:
21609 case DECLTYPE_TYPE:
21610 case UNDERLYING_TYPE:
21611 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
21612 or UNDERLYING_TYPE nodes. */
21613 return unify_success (explain_p);
21615 case ERROR_MARK:
21616 /* Unification fails if we hit an error node. */
21617 return unify_invalid (explain_p);
21619 case INDIRECT_REF:
21620 if (REFERENCE_REF_P (parm))
21622 bool pexp = PACK_EXPANSION_P (arg);
21623 if (pexp)
21624 arg = PACK_EXPANSION_PATTERN (arg);
21625 if (REFERENCE_REF_P (arg))
21626 arg = TREE_OPERAND (arg, 0);
21627 if (pexp)
21628 arg = make_pack_expansion (arg, complain);
21629 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
21630 strict, explain_p);
21632 /* FALLTHRU */
21634 default:
21635 /* An unresolved overload is a nondeduced context. */
21636 if (is_overloaded_fn (parm) || type_unknown_p (parm))
21637 return unify_success (explain_p);
21638 gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
21639 expr:
21640 /* We must be looking at an expression. This can happen with
21641 something like:
21643 template <int I>
21644 void foo(S<I>, S<I + 2>);
21646 This is a "nondeduced context":
21648 [deduct.type]
21650 The nondeduced contexts are:
21652 --A type that is a template-id in which one or more of
21653 the template-arguments is an expression that references
21654 a template-parameter.
21656 In these cases, we assume deduction succeeded, but don't
21657 actually infer any unifications. */
21659 if (!uses_template_parms (parm)
21660 && !template_args_equal (parm, arg))
21661 return unify_expression_unequal (explain_p, parm, arg);
21662 else
21663 return unify_success (explain_p);
21666 #undef RECUR_AND_CHECK_FAILURE
21668 /* Note that DECL can be defined in this translation unit, if
21669 required. */
21671 static void
21672 mark_definable (tree decl)
21674 tree clone;
21675 DECL_NOT_REALLY_EXTERN (decl) = 1;
21676 FOR_EACH_CLONE (clone, decl)
21677 DECL_NOT_REALLY_EXTERN (clone) = 1;
21680 /* Called if RESULT is explicitly instantiated, or is a member of an
21681 explicitly instantiated class. */
21683 void
21684 mark_decl_instantiated (tree result, int extern_p)
21686 SET_DECL_EXPLICIT_INSTANTIATION (result);
21688 /* If this entity has already been written out, it's too late to
21689 make any modifications. */
21690 if (TREE_ASM_WRITTEN (result))
21691 return;
21693 /* For anonymous namespace we don't need to do anything. */
21694 if (decl_anon_ns_mem_p (result))
21696 gcc_assert (!TREE_PUBLIC (result));
21697 return;
21700 if (TREE_CODE (result) != FUNCTION_DECL)
21701 /* The TREE_PUBLIC flag for function declarations will have been
21702 set correctly by tsubst. */
21703 TREE_PUBLIC (result) = 1;
21705 /* This might have been set by an earlier implicit instantiation. */
21706 DECL_COMDAT (result) = 0;
21708 if (extern_p)
21709 DECL_NOT_REALLY_EXTERN (result) = 0;
21710 else
21712 mark_definable (result);
21713 mark_needed (result);
21714 /* Always make artificials weak. */
21715 if (DECL_ARTIFICIAL (result) && flag_weak)
21716 comdat_linkage (result);
21717 /* For WIN32 we also want to put explicit instantiations in
21718 linkonce sections. */
21719 else if (TREE_PUBLIC (result))
21720 maybe_make_one_only (result);
21723 /* If EXTERN_P, then this function will not be emitted -- unless
21724 followed by an explicit instantiation, at which point its linkage
21725 will be adjusted. If !EXTERN_P, then this function will be
21726 emitted here. In neither circumstance do we want
21727 import_export_decl to adjust the linkage. */
21728 DECL_INTERFACE_KNOWN (result) = 1;
21731 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
21732 important template arguments. If any are missing, we check whether
21733 they're important by using error_mark_node for substituting into any
21734 args that were used for partial ordering (the ones between ARGS and END)
21735 and seeing if it bubbles up. */
21737 static bool
21738 check_undeduced_parms (tree targs, tree args, tree end)
21740 bool found = false;
21741 int i;
21742 for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
21743 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
21745 found = true;
21746 TREE_VEC_ELT (targs, i) = error_mark_node;
21748 if (found)
21750 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
21751 if (substed == error_mark_node)
21752 return true;
21754 return false;
21757 /* Given two function templates PAT1 and PAT2, return:
21759 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
21760 -1 if PAT2 is more specialized than PAT1.
21761 0 if neither is more specialized.
21763 LEN indicates the number of parameters we should consider
21764 (defaulted parameters should not be considered).
21766 The 1998 std underspecified function template partial ordering, and
21767 DR214 addresses the issue. We take pairs of arguments, one from
21768 each of the templates, and deduce them against each other. One of
21769 the templates will be more specialized if all the *other*
21770 template's arguments deduce against its arguments and at least one
21771 of its arguments *does* *not* deduce against the other template's
21772 corresponding argument. Deduction is done as for class templates.
21773 The arguments used in deduction have reference and top level cv
21774 qualifiers removed. Iff both arguments were originally reference
21775 types *and* deduction succeeds in both directions, an lvalue reference
21776 wins against an rvalue reference and otherwise the template
21777 with the more cv-qualified argument wins for that pairing (if
21778 neither is more cv-qualified, they both are equal). Unlike regular
21779 deduction, after all the arguments have been deduced in this way,
21780 we do *not* verify the deduced template argument values can be
21781 substituted into non-deduced contexts.
21783 The logic can be a bit confusing here, because we look at deduce1 and
21784 targs1 to see if pat2 is at least as specialized, and vice versa; if we
21785 can find template arguments for pat1 to make arg1 look like arg2, that
21786 means that arg2 is at least as specialized as arg1. */
21789 more_specialized_fn (tree pat1, tree pat2, int len)
21791 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
21792 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
21793 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
21794 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
21795 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
21796 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
21797 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
21798 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
21799 tree origs1, origs2;
21800 bool lose1 = false;
21801 bool lose2 = false;
21803 /* Remove the this parameter from non-static member functions. If
21804 one is a non-static member function and the other is not a static
21805 member function, remove the first parameter from that function
21806 also. This situation occurs for operator functions where we
21807 locate both a member function (with this pointer) and non-member
21808 operator (with explicit first operand). */
21809 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
21811 len--; /* LEN is the number of significant arguments for DECL1 */
21812 args1 = TREE_CHAIN (args1);
21813 if (!DECL_STATIC_FUNCTION_P (decl2))
21814 args2 = TREE_CHAIN (args2);
21816 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
21818 args2 = TREE_CHAIN (args2);
21819 if (!DECL_STATIC_FUNCTION_P (decl1))
21821 len--;
21822 args1 = TREE_CHAIN (args1);
21826 /* If only one is a conversion operator, they are unordered. */
21827 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
21828 return 0;
21830 /* Consider the return type for a conversion function */
21831 if (DECL_CONV_FN_P (decl1))
21833 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
21834 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
21835 len++;
21838 processing_template_decl++;
21840 origs1 = args1;
21841 origs2 = args2;
21843 while (len--
21844 /* Stop when an ellipsis is seen. */
21845 && args1 != NULL_TREE && args2 != NULL_TREE)
21847 tree arg1 = TREE_VALUE (args1);
21848 tree arg2 = TREE_VALUE (args2);
21849 int deduce1, deduce2;
21850 int quals1 = -1;
21851 int quals2 = -1;
21852 int ref1 = 0;
21853 int ref2 = 0;
21855 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
21856 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
21858 /* When both arguments are pack expansions, we need only
21859 unify the patterns themselves. */
21860 arg1 = PACK_EXPANSION_PATTERN (arg1);
21861 arg2 = PACK_EXPANSION_PATTERN (arg2);
21863 /* This is the last comparison we need to do. */
21864 len = 0;
21867 /* DR 1847: If a particular P contains no template-parameters that
21868 participate in template argument deduction, that P is not used to
21869 determine the ordering. */
21870 if (!uses_deducible_template_parms (arg1)
21871 && !uses_deducible_template_parms (arg2))
21872 goto next;
21874 if (TREE_CODE (arg1) == REFERENCE_TYPE)
21876 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
21877 arg1 = TREE_TYPE (arg1);
21878 quals1 = cp_type_quals (arg1);
21881 if (TREE_CODE (arg2) == REFERENCE_TYPE)
21883 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
21884 arg2 = TREE_TYPE (arg2);
21885 quals2 = cp_type_quals (arg2);
21888 arg1 = TYPE_MAIN_VARIANT (arg1);
21889 arg2 = TYPE_MAIN_VARIANT (arg2);
21891 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
21893 int i, len2 = remaining_arguments (args2);
21894 tree parmvec = make_tree_vec (1);
21895 tree argvec = make_tree_vec (len2);
21896 tree ta = args2;
21898 /* Setup the parameter vector, which contains only ARG1. */
21899 TREE_VEC_ELT (parmvec, 0) = arg1;
21901 /* Setup the argument vector, which contains the remaining
21902 arguments. */
21903 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
21904 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
21906 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
21907 argvec, DEDUCE_EXACT,
21908 /*subr=*/true, /*explain_p=*/false)
21909 == 0);
21911 /* We cannot deduce in the other direction, because ARG1 is
21912 a pack expansion but ARG2 is not. */
21913 deduce2 = 0;
21915 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
21917 int i, len1 = remaining_arguments (args1);
21918 tree parmvec = make_tree_vec (1);
21919 tree argvec = make_tree_vec (len1);
21920 tree ta = args1;
21922 /* Setup the parameter vector, which contains only ARG1. */
21923 TREE_VEC_ELT (parmvec, 0) = arg2;
21925 /* Setup the argument vector, which contains the remaining
21926 arguments. */
21927 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
21928 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
21930 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
21931 argvec, DEDUCE_EXACT,
21932 /*subr=*/true, /*explain_p=*/false)
21933 == 0);
21935 /* We cannot deduce in the other direction, because ARG2 is
21936 a pack expansion but ARG1 is not.*/
21937 deduce1 = 0;
21940 else
21942 /* The normal case, where neither argument is a pack
21943 expansion. */
21944 deduce1 = (unify (tparms1, targs1, arg1, arg2,
21945 UNIFY_ALLOW_NONE, /*explain_p=*/false)
21946 == 0);
21947 deduce2 = (unify (tparms2, targs2, arg2, arg1,
21948 UNIFY_ALLOW_NONE, /*explain_p=*/false)
21949 == 0);
21952 /* If we couldn't deduce arguments for tparms1 to make arg1 match
21953 arg2, then arg2 is not as specialized as arg1. */
21954 if (!deduce1)
21955 lose2 = true;
21956 if (!deduce2)
21957 lose1 = true;
21959 /* "If, for a given type, deduction succeeds in both directions
21960 (i.e., the types are identical after the transformations above)
21961 and both P and A were reference types (before being replaced with
21962 the type referred to above):
21963 - if the type from the argument template was an lvalue reference and
21964 the type from the parameter template was not, the argument type is
21965 considered to be more specialized than the other; otherwise,
21966 - if the type from the argument template is more cv-qualified
21967 than the type from the parameter template (as described above),
21968 the argument type is considered to be more specialized than the other;
21969 otherwise,
21970 - neither type is more specialized than the other." */
21972 if (deduce1 && deduce2)
21974 if (ref1 && ref2 && ref1 != ref2)
21976 if (ref1 > ref2)
21977 lose1 = true;
21978 else
21979 lose2 = true;
21981 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
21983 if ((quals1 & quals2) == quals2)
21984 lose2 = true;
21985 if ((quals1 & quals2) == quals1)
21986 lose1 = true;
21990 if (lose1 && lose2)
21991 /* We've failed to deduce something in either direction.
21992 These must be unordered. */
21993 break;
21995 next:
21997 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
21998 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
21999 /* We have already processed all of the arguments in our
22000 handing of the pack expansion type. */
22001 len = 0;
22003 args1 = TREE_CHAIN (args1);
22004 args2 = TREE_CHAIN (args2);
22007 /* "In most cases, all template parameters must have values in order for
22008 deduction to succeed, but for partial ordering purposes a template
22009 parameter may remain without a value provided it is not used in the
22010 types being used for partial ordering."
22012 Thus, if we are missing any of the targs1 we need to substitute into
22013 origs1, then pat2 is not as specialized as pat1. This can happen when
22014 there is a nondeduced context. */
22015 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
22016 lose2 = true;
22017 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
22018 lose1 = true;
22020 processing_template_decl--;
22022 /* If both deductions succeed, the partial ordering selects the more
22023 constrained template. */
22024 if (!lose1 && !lose2)
22026 tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
22027 tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
22028 lose1 = !subsumes_constraints (c1, c2);
22029 lose2 = !subsumes_constraints (c2, c1);
22032 /* All things being equal, if the next argument is a pack expansion
22033 for one function but not for the other, prefer the
22034 non-variadic function. FIXME this is bogus; see c++/41958. */
22035 if (lose1 == lose2
22036 && args1 && TREE_VALUE (args1)
22037 && args2 && TREE_VALUE (args2))
22039 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
22040 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
22043 if (lose1 == lose2)
22044 return 0;
22045 else if (!lose1)
22046 return 1;
22047 else
22048 return -1;
22051 /* Determine which of two partial specializations of TMPL is more
22052 specialized.
22054 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
22055 to the first partial specialization. The TREE_PURPOSE is the
22056 innermost set of template parameters for the partial
22057 specialization. PAT2 is similar, but for the second template.
22059 Return 1 if the first partial specialization is more specialized;
22060 -1 if the second is more specialized; 0 if neither is more
22061 specialized.
22063 See [temp.class.order] for information about determining which of
22064 two templates is more specialized. */
22066 static int
22067 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
22069 tree targs;
22070 int winner = 0;
22071 bool any_deductions = false;
22073 tree tmpl1 = TREE_VALUE (pat1);
22074 tree tmpl2 = TREE_VALUE (pat2);
22075 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
22076 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
22078 /* Just like what happens for functions, if we are ordering between
22079 different template specializations, we may encounter dependent
22080 types in the arguments, and we need our dependency check functions
22081 to behave correctly. */
22082 ++processing_template_decl;
22083 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
22084 if (targs)
22086 --winner;
22087 any_deductions = true;
22090 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
22091 if (targs)
22093 ++winner;
22094 any_deductions = true;
22096 --processing_template_decl;
22098 /* If both deductions succeed, the partial ordering selects the more
22099 constrained template. */
22100 if (!winner && any_deductions)
22101 return more_constrained (tmpl1, tmpl2);
22103 /* In the case of a tie where at least one of the templates
22104 has a parameter pack at the end, the template with the most
22105 non-packed parameters wins. */
22106 if (winner == 0
22107 && any_deductions
22108 && (template_args_variadic_p (TREE_PURPOSE (pat1))
22109 || template_args_variadic_p (TREE_PURPOSE (pat2))))
22111 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
22112 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
22113 int len1 = TREE_VEC_LENGTH (args1);
22114 int len2 = TREE_VEC_LENGTH (args2);
22116 /* We don't count the pack expansion at the end. */
22117 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
22118 --len1;
22119 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
22120 --len2;
22122 if (len1 > len2)
22123 return 1;
22124 else if (len1 < len2)
22125 return -1;
22128 return winner;
22131 /* Return the template arguments that will produce the function signature
22132 DECL from the function template FN, with the explicit template
22133 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
22134 also match. Return NULL_TREE if no satisfactory arguments could be
22135 found. */
22137 static tree
22138 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
22140 int ntparms = DECL_NTPARMS (fn);
22141 tree targs = make_tree_vec (ntparms);
22142 tree decl_type = TREE_TYPE (decl);
22143 tree decl_arg_types;
22144 tree *args;
22145 unsigned int nargs, ix;
22146 tree arg;
22148 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
22150 /* Never do unification on the 'this' parameter. */
22151 decl_arg_types = skip_artificial_parms_for (decl,
22152 TYPE_ARG_TYPES (decl_type));
22154 nargs = list_length (decl_arg_types);
22155 args = XALLOCAVEC (tree, nargs);
22156 for (arg = decl_arg_types, ix = 0;
22157 arg != NULL_TREE && arg != void_list_node;
22158 arg = TREE_CHAIN (arg), ++ix)
22159 args[ix] = TREE_VALUE (arg);
22161 if (fn_type_unification (fn, explicit_args, targs,
22162 args, ix,
22163 (check_rettype || DECL_CONV_FN_P (fn)
22164 ? TREE_TYPE (decl_type) : NULL_TREE),
22165 DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
22166 /*decltype*/false)
22167 == error_mark_node)
22168 return NULL_TREE;
22170 return targs;
22173 /* Return the innermost template arguments that, when applied to a partial
22174 specialization SPEC_TMPL of TMPL, yield the ARGS.
22176 For example, suppose we have:
22178 template <class T, class U> struct S {};
22179 template <class T> struct S<T*, int> {};
22181 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
22182 partial specialization and the ARGS will be {double*, int}. The resulting
22183 vector will be {double}, indicating that `T' is bound to `double'. */
22185 static tree
22186 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
22188 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
22189 tree spec_args
22190 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
22191 int i, ntparms = TREE_VEC_LENGTH (tparms);
22192 tree deduced_args;
22193 tree innermost_deduced_args;
22195 innermost_deduced_args = make_tree_vec (ntparms);
22196 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22198 deduced_args = copy_node (args);
22199 SET_TMPL_ARGS_LEVEL (deduced_args,
22200 TMPL_ARGS_DEPTH (deduced_args),
22201 innermost_deduced_args);
22203 else
22204 deduced_args = innermost_deduced_args;
22206 bool tried_array_deduction = (cxx_dialect < cxx17);
22207 again:
22208 if (unify (tparms, deduced_args,
22209 INNERMOST_TEMPLATE_ARGS (spec_args),
22210 INNERMOST_TEMPLATE_ARGS (args),
22211 UNIFY_ALLOW_NONE, /*explain_p=*/false))
22212 return NULL_TREE;
22214 for (i = 0; i < ntparms; ++i)
22215 if (! TREE_VEC_ELT (innermost_deduced_args, i))
22217 if (!tried_array_deduction)
22219 try_array_deduction (tparms, innermost_deduced_args,
22220 INNERMOST_TEMPLATE_ARGS (spec_args));
22221 tried_array_deduction = true;
22222 if (TREE_VEC_ELT (innermost_deduced_args, i))
22223 goto again;
22225 return NULL_TREE;
22228 tree tinst = build_tree_list (spec_tmpl, deduced_args);
22229 if (!push_tinst_level (tinst))
22231 excessive_deduction_depth = true;
22232 return NULL_TREE;
22235 /* Verify that nondeduced template arguments agree with the type
22236 obtained from argument deduction.
22238 For example:
22240 struct A { typedef int X; };
22241 template <class T, class U> struct C {};
22242 template <class T> struct C<T, typename T::X> {};
22244 Then with the instantiation `C<A, int>', we can deduce that
22245 `T' is `A' but unify () does not check whether `typename T::X'
22246 is `int'. */
22247 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
22249 if (spec_args != error_mark_node)
22250 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
22251 INNERMOST_TEMPLATE_ARGS (spec_args),
22252 tmpl, tf_none, false, false);
22254 pop_tinst_level ();
22256 if (spec_args == error_mark_node
22257 /* We only need to check the innermost arguments; the other
22258 arguments will always agree. */
22259 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
22260 INNERMOST_TEMPLATE_ARGS (args)))
22261 return NULL_TREE;
22263 /* Now that we have bindings for all of the template arguments,
22264 ensure that the arguments deduced for the template template
22265 parameters have compatible template parameter lists. See the use
22266 of template_template_parm_bindings_ok_p in fn_type_unification
22267 for more information. */
22268 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
22269 return NULL_TREE;
22271 return deduced_args;
22274 // Compare two function templates T1 and T2 by deducing bindings
22275 // from one against the other. If both deductions succeed, compare
22276 // constraints to see which is more constrained.
22277 static int
22278 more_specialized_inst (tree t1, tree t2)
22280 int fate = 0;
22281 int count = 0;
22283 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
22285 --fate;
22286 ++count;
22289 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
22291 ++fate;
22292 ++count;
22295 // If both deductions succeed, then one may be more constrained.
22296 if (count == 2 && fate == 0)
22297 fate = more_constrained (t1, t2);
22299 return fate;
22302 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
22303 Return the TREE_LIST node with the most specialized template, if
22304 any. If there is no most specialized template, the error_mark_node
22305 is returned.
22307 Note that this function does not look at, or modify, the
22308 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
22309 returned is one of the elements of INSTANTIATIONS, callers may
22310 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
22311 and retrieve it from the value returned. */
22313 tree
22314 most_specialized_instantiation (tree templates)
22316 tree fn, champ;
22318 ++processing_template_decl;
22320 champ = templates;
22321 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
22323 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
22324 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
22325 if (fate == -1)
22326 champ = fn;
22327 else if (!fate)
22329 /* Equally specialized, move to next function. If there
22330 is no next function, nothing's most specialized. */
22331 fn = TREE_CHAIN (fn);
22332 champ = fn;
22333 if (!fn)
22334 break;
22338 if (champ)
22339 /* Now verify that champ is better than everything earlier in the
22340 instantiation list. */
22341 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
22342 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
22344 champ = NULL_TREE;
22345 break;
22349 processing_template_decl--;
22351 if (!champ)
22352 return error_mark_node;
22354 return champ;
22357 /* If DECL is a specialization of some template, return the most
22358 general such template. Otherwise, returns NULL_TREE.
22360 For example, given:
22362 template <class T> struct S { template <class U> void f(U); };
22364 if TMPL is `template <class U> void S<int>::f(U)' this will return
22365 the full template. This function will not trace past partial
22366 specializations, however. For example, given in addition:
22368 template <class T> struct S<T*> { template <class U> void f(U); };
22370 if TMPL is `template <class U> void S<int*>::f(U)' this will return
22371 `template <class T> template <class U> S<T*>::f(U)'. */
22373 tree
22374 most_general_template (tree decl)
22376 if (TREE_CODE (decl) != TEMPLATE_DECL)
22378 if (tree tinfo = get_template_info (decl))
22379 decl = TI_TEMPLATE (tinfo);
22380 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
22381 template friend, or a FIELD_DECL for a capture pack. */
22382 if (TREE_CODE (decl) != TEMPLATE_DECL)
22383 return NULL_TREE;
22386 /* Look for more and more general templates. */
22387 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
22389 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
22390 (See cp-tree.h for details.) */
22391 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
22392 break;
22394 if (CLASS_TYPE_P (TREE_TYPE (decl))
22395 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
22396 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
22397 break;
22399 /* Stop if we run into an explicitly specialized class template. */
22400 if (!DECL_NAMESPACE_SCOPE_P (decl)
22401 && DECL_CONTEXT (decl)
22402 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
22403 break;
22405 decl = DECL_TI_TEMPLATE (decl);
22408 return decl;
22411 /* Return the most specialized of the template partial specializations
22412 which can produce TARGET, a specialization of some class or variable
22413 template. The value returned is actually a TREE_LIST; the TREE_VALUE is
22414 a TEMPLATE_DECL node corresponding to the partial specialization, while
22415 the TREE_PURPOSE is the set of template arguments that must be
22416 substituted into the template pattern in order to generate TARGET.
22418 If the choice of partial specialization is ambiguous, a diagnostic
22419 is issued, and the error_mark_node is returned. If there are no
22420 partial specializations matching TARGET, then NULL_TREE is
22421 returned, indicating that the primary template should be used. */
22423 static tree
22424 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
22426 tree list = NULL_TREE;
22427 tree t;
22428 tree champ;
22429 int fate;
22430 bool ambiguous_p;
22431 tree outer_args = NULL_TREE;
22432 tree tmpl, args;
22434 if (TYPE_P (target))
22436 tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
22437 tmpl = TI_TEMPLATE (tinfo);
22438 args = TI_ARGS (tinfo);
22440 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
22442 tmpl = TREE_OPERAND (target, 0);
22443 args = TREE_OPERAND (target, 1);
22445 else if (VAR_P (target))
22447 tree tinfo = DECL_TEMPLATE_INFO (target);
22448 tmpl = TI_TEMPLATE (tinfo);
22449 args = TI_ARGS (tinfo);
22451 else
22452 gcc_unreachable ();
22454 tree main_tmpl = most_general_template (tmpl);
22456 /* For determining which partial specialization to use, only the
22457 innermost args are interesting. */
22458 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22460 outer_args = strip_innermost_template_args (args, 1);
22461 args = INNERMOST_TEMPLATE_ARGS (args);
22464 for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
22466 tree spec_args;
22467 tree spec_tmpl = TREE_VALUE (t);
22469 if (outer_args)
22471 /* Substitute in the template args from the enclosing class. */
22472 ++processing_template_decl;
22473 spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
22474 --processing_template_decl;
22477 if (spec_tmpl == error_mark_node)
22478 return error_mark_node;
22480 spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
22481 if (spec_args)
22483 if (outer_args)
22484 spec_args = add_to_template_args (outer_args, spec_args);
22486 /* Keep the candidate only if the constraints are satisfied,
22487 or if we're not compiling with concepts. */
22488 if (!flag_concepts
22489 || constraints_satisfied_p (spec_tmpl, spec_args))
22491 list = tree_cons (spec_args, TREE_VALUE (t), list);
22492 TREE_TYPE (list) = TREE_TYPE (t);
22497 if (! list)
22498 return NULL_TREE;
22500 ambiguous_p = false;
22501 t = list;
22502 champ = t;
22503 t = TREE_CHAIN (t);
22504 for (; t; t = TREE_CHAIN (t))
22506 fate = more_specialized_partial_spec (tmpl, champ, t);
22507 if (fate == 1)
22509 else
22511 if (fate == 0)
22513 t = TREE_CHAIN (t);
22514 if (! t)
22516 ambiguous_p = true;
22517 break;
22520 champ = t;
22524 if (!ambiguous_p)
22525 for (t = list; t && t != champ; t = TREE_CHAIN (t))
22527 fate = more_specialized_partial_spec (tmpl, champ, t);
22528 if (fate != 1)
22530 ambiguous_p = true;
22531 break;
22535 if (ambiguous_p)
22537 const char *str;
22538 char *spaces = NULL;
22539 if (!(complain & tf_error))
22540 return error_mark_node;
22541 if (TYPE_P (target))
22542 error ("ambiguous template instantiation for %q#T", target);
22543 else
22544 error ("ambiguous template instantiation for %q#D", target);
22545 str = ngettext ("candidate is:", "candidates are:", list_length (list));
22546 for (t = list; t; t = TREE_CHAIN (t))
22548 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
22549 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
22550 "%s %#qS", spaces ? spaces : str, subst);
22551 spaces = spaces ? spaces : get_spaces (str);
22553 free (spaces);
22554 return error_mark_node;
22557 return champ;
22560 /* Explicitly instantiate DECL. */
22562 void
22563 do_decl_instantiation (tree decl, tree storage)
22565 tree result = NULL_TREE;
22566 int extern_p = 0;
22568 if (!decl || decl == error_mark_node)
22569 /* An error occurred, for which grokdeclarator has already issued
22570 an appropriate message. */
22571 return;
22572 else if (! DECL_LANG_SPECIFIC (decl))
22574 error ("explicit instantiation of non-template %q#D", decl);
22575 return;
22578 bool var_templ = (DECL_TEMPLATE_INFO (decl)
22579 && variable_template_p (DECL_TI_TEMPLATE (decl)));
22581 if (VAR_P (decl) && !var_templ)
22583 /* There is an asymmetry here in the way VAR_DECLs and
22584 FUNCTION_DECLs are handled by grokdeclarator. In the case of
22585 the latter, the DECL we get back will be marked as a
22586 template instantiation, and the appropriate
22587 DECL_TEMPLATE_INFO will be set up. This does not happen for
22588 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
22589 should handle VAR_DECLs as it currently handles
22590 FUNCTION_DECLs. */
22591 if (!DECL_CLASS_SCOPE_P (decl))
22593 error ("%qD is not a static data member of a class template", decl);
22594 return;
22596 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
22597 if (!result || !VAR_P (result))
22599 error ("no matching template for %qD found", decl);
22600 return;
22602 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
22604 error ("type %qT for explicit instantiation %qD does not match "
22605 "declared type %qT", TREE_TYPE (result), decl,
22606 TREE_TYPE (decl));
22607 return;
22610 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
22612 error ("explicit instantiation of %q#D", decl);
22613 return;
22615 else
22616 result = decl;
22618 /* Check for various error cases. Note that if the explicit
22619 instantiation is valid the RESULT will currently be marked as an
22620 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
22621 until we get here. */
22623 if (DECL_TEMPLATE_SPECIALIZATION (result))
22625 /* DR 259 [temp.spec].
22627 Both an explicit instantiation and a declaration of an explicit
22628 specialization shall not appear in a program unless the explicit
22629 instantiation follows a declaration of the explicit specialization.
22631 For a given set of template parameters, if an explicit
22632 instantiation of a template appears after a declaration of an
22633 explicit specialization for that template, the explicit
22634 instantiation has no effect. */
22635 return;
22637 else if (DECL_EXPLICIT_INSTANTIATION (result))
22639 /* [temp.spec]
22641 No program shall explicitly instantiate any template more
22642 than once.
22644 We check DECL_NOT_REALLY_EXTERN so as not to complain when
22645 the first instantiation was `extern' and the second is not,
22646 and EXTERN_P for the opposite case. */
22647 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
22648 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
22649 /* If an "extern" explicit instantiation follows an ordinary
22650 explicit instantiation, the template is instantiated. */
22651 if (extern_p)
22652 return;
22654 else if (!DECL_IMPLICIT_INSTANTIATION (result))
22656 error ("no matching template for %qD found", result);
22657 return;
22659 else if (!DECL_TEMPLATE_INFO (result))
22661 permerror (input_location, "explicit instantiation of non-template %q#D", result);
22662 return;
22665 if (storage == NULL_TREE)
22667 else if (storage == ridpointers[(int) RID_EXTERN])
22669 if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
22670 pedwarn (input_location, OPT_Wpedantic,
22671 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
22672 "instantiations");
22673 extern_p = 1;
22675 else
22676 error ("storage class %qD applied to template instantiation", storage);
22678 check_explicit_instantiation_namespace (result);
22679 mark_decl_instantiated (result, extern_p);
22680 if (! extern_p)
22681 instantiate_decl (result, /*defer_ok=*/true,
22682 /*expl_inst_class_mem_p=*/false);
22685 static void
22686 mark_class_instantiated (tree t, int extern_p)
22688 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
22689 SET_CLASSTYPE_INTERFACE_KNOWN (t);
22690 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
22691 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
22692 if (! extern_p)
22694 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
22695 rest_of_type_compilation (t, 1);
22699 /* Called from do_type_instantiation through binding_table_foreach to
22700 do recursive instantiation for the type bound in ENTRY. */
22701 static void
22702 bt_instantiate_type_proc (binding_entry entry, void *data)
22704 tree storage = *(tree *) data;
22706 if (MAYBE_CLASS_TYPE_P (entry->type)
22707 && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
22708 do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
22711 /* Perform an explicit instantiation of template class T. STORAGE, if
22712 non-null, is the RID for extern, inline or static. COMPLAIN is
22713 nonzero if this is called from the parser, zero if called recursively,
22714 since the standard is unclear (as detailed below). */
22716 void
22717 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
22719 int extern_p = 0;
22720 int nomem_p = 0;
22721 int static_p = 0;
22722 int previous_instantiation_extern_p = 0;
22724 if (TREE_CODE (t) == TYPE_DECL)
22725 t = TREE_TYPE (t);
22727 if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
22729 tree tmpl =
22730 (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
22731 if (tmpl)
22732 error ("explicit instantiation of non-class template %qD", tmpl);
22733 else
22734 error ("explicit instantiation of non-template type %qT", t);
22735 return;
22738 complete_type (t);
22740 if (!COMPLETE_TYPE_P (t))
22742 if (complain & tf_error)
22743 error ("explicit instantiation of %q#T before definition of template",
22745 return;
22748 if (storage != NULL_TREE)
22750 if (!in_system_header_at (input_location))
22752 if (storage == ridpointers[(int) RID_EXTERN])
22754 if (cxx_dialect == cxx98)
22755 pedwarn (input_location, OPT_Wpedantic,
22756 "ISO C++ 1998 forbids the use of %<extern%> on "
22757 "explicit instantiations");
22759 else
22760 pedwarn (input_location, OPT_Wpedantic,
22761 "ISO C++ forbids the use of %qE"
22762 " on explicit instantiations", storage);
22765 if (storage == ridpointers[(int) RID_INLINE])
22766 nomem_p = 1;
22767 else if (storage == ridpointers[(int) RID_EXTERN])
22768 extern_p = 1;
22769 else if (storage == ridpointers[(int) RID_STATIC])
22770 static_p = 1;
22771 else
22773 error ("storage class %qD applied to template instantiation",
22774 storage);
22775 extern_p = 0;
22779 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
22781 /* DR 259 [temp.spec].
22783 Both an explicit instantiation and a declaration of an explicit
22784 specialization shall not appear in a program unless the explicit
22785 instantiation follows a declaration of the explicit specialization.
22787 For a given set of template parameters, if an explicit
22788 instantiation of a template appears after a declaration of an
22789 explicit specialization for that template, the explicit
22790 instantiation has no effect. */
22791 return;
22793 else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
22795 /* [temp.spec]
22797 No program shall explicitly instantiate any template more
22798 than once.
22800 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
22801 instantiation was `extern'. If EXTERN_P then the second is.
22802 These cases are OK. */
22803 previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
22805 if (!previous_instantiation_extern_p && !extern_p
22806 && (complain & tf_error))
22807 permerror (input_location, "duplicate explicit instantiation of %q#T", t);
22809 /* If we've already instantiated the template, just return now. */
22810 if (!CLASSTYPE_INTERFACE_ONLY (t))
22811 return;
22814 check_explicit_instantiation_namespace (TYPE_NAME (t));
22815 mark_class_instantiated (t, extern_p);
22817 if (nomem_p)
22818 return;
22820 /* In contrast to implicit instantiation, where only the
22821 declarations, and not the definitions, of members are
22822 instantiated, we have here:
22824 [temp.explicit]
22826 The explicit instantiation of a class template specialization
22827 implies the instantiation of all of its members not
22828 previously explicitly specialized in the translation unit
22829 containing the explicit instantiation.
22831 Of course, we can't instantiate member template classes, since we
22832 don't have any arguments for them. Note that the standard is
22833 unclear on whether the instantiation of the members are
22834 *explicit* instantiations or not. However, the most natural
22835 interpretation is that it should be an explicit
22836 instantiation. */
22837 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
22838 if ((VAR_P (fld)
22839 || (TREE_CODE (fld) == FUNCTION_DECL
22840 && !static_p
22841 && user_provided_p (fld)))
22842 && DECL_TEMPLATE_INSTANTIATION (fld))
22844 mark_decl_instantiated (fld, extern_p);
22845 if (! extern_p)
22846 instantiate_decl (fld, /*defer_ok=*/true,
22847 /*expl_inst_class_mem_p=*/true);
22850 if (CLASSTYPE_NESTED_UTDS (t))
22851 binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
22852 bt_instantiate_type_proc, &storage);
22855 /* Given a function DECL, which is a specialization of TMPL, modify
22856 DECL to be a re-instantiation of TMPL with the same template
22857 arguments. TMPL should be the template into which tsubst'ing
22858 should occur for DECL, not the most general template.
22860 One reason for doing this is a scenario like this:
22862 template <class T>
22863 void f(const T&, int i);
22865 void g() { f(3, 7); }
22867 template <class T>
22868 void f(const T& t, const int i) { }
22870 Note that when the template is first instantiated, with
22871 instantiate_template, the resulting DECL will have no name for the
22872 first parameter, and the wrong type for the second. So, when we go
22873 to instantiate the DECL, we regenerate it. */
22875 static void
22876 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
22878 /* The arguments used to instantiate DECL, from the most general
22879 template. */
22880 tree code_pattern;
22882 code_pattern = DECL_TEMPLATE_RESULT (tmpl);
22884 /* Make sure that we can see identifiers, and compute access
22885 correctly. */
22886 push_access_scope (decl);
22888 if (TREE_CODE (decl) == FUNCTION_DECL)
22890 tree decl_parm;
22891 tree pattern_parm;
22892 tree specs;
22893 int args_depth;
22894 int parms_depth;
22896 args_depth = TMPL_ARGS_DEPTH (args);
22897 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
22898 if (args_depth > parms_depth)
22899 args = get_innermost_template_args (args, parms_depth);
22901 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
22902 args, tf_error, NULL_TREE,
22903 /*defer_ok*/false);
22904 if (specs && specs != error_mark_node)
22905 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
22906 specs);
22908 /* Merge parameter declarations. */
22909 decl_parm = skip_artificial_parms_for (decl,
22910 DECL_ARGUMENTS (decl));
22911 pattern_parm
22912 = skip_artificial_parms_for (code_pattern,
22913 DECL_ARGUMENTS (code_pattern));
22914 while (decl_parm && !DECL_PACK_P (pattern_parm))
22916 tree parm_type;
22917 tree attributes;
22919 if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
22920 DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
22921 parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
22922 NULL_TREE);
22923 parm_type = type_decays_to (parm_type);
22924 if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
22925 TREE_TYPE (decl_parm) = parm_type;
22926 attributes = DECL_ATTRIBUTES (pattern_parm);
22927 if (DECL_ATTRIBUTES (decl_parm) != attributes)
22929 DECL_ATTRIBUTES (decl_parm) = attributes;
22930 cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
22932 decl_parm = DECL_CHAIN (decl_parm);
22933 pattern_parm = DECL_CHAIN (pattern_parm);
22935 /* Merge any parameters that match with the function parameter
22936 pack. */
22937 if (pattern_parm && DECL_PACK_P (pattern_parm))
22939 int i, len;
22940 tree expanded_types;
22941 /* Expand the TYPE_PACK_EXPANSION that provides the types for
22942 the parameters in this function parameter pack. */
22943 expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
22944 args, tf_error, NULL_TREE);
22945 len = TREE_VEC_LENGTH (expanded_types);
22946 for (i = 0; i < len; i++)
22948 tree parm_type;
22949 tree attributes;
22951 if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
22952 /* Rename the parameter to include the index. */
22953 DECL_NAME (decl_parm) =
22954 make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
22955 parm_type = TREE_VEC_ELT (expanded_types, i);
22956 parm_type = type_decays_to (parm_type);
22957 if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
22958 TREE_TYPE (decl_parm) = parm_type;
22959 attributes = DECL_ATTRIBUTES (pattern_parm);
22960 if (DECL_ATTRIBUTES (decl_parm) != attributes)
22962 DECL_ATTRIBUTES (decl_parm) = attributes;
22963 cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
22965 decl_parm = DECL_CHAIN (decl_parm);
22968 /* Merge additional specifiers from the CODE_PATTERN. */
22969 if (DECL_DECLARED_INLINE_P (code_pattern)
22970 && !DECL_DECLARED_INLINE_P (decl))
22971 DECL_DECLARED_INLINE_P (decl) = 1;
22973 else if (VAR_P (decl))
22975 start_lambda_scope (decl);
22976 DECL_INITIAL (decl) =
22977 tsubst_expr (DECL_INITIAL (code_pattern), args,
22978 tf_error, DECL_TI_TEMPLATE (decl),
22979 /*integral_constant_expression_p=*/false);
22980 finish_lambda_scope ();
22981 if (VAR_HAD_UNKNOWN_BOUND (decl))
22982 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
22983 tf_error, DECL_TI_TEMPLATE (decl));
22985 else
22986 gcc_unreachable ();
22988 pop_access_scope (decl);
22991 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
22992 substituted to get DECL. */
22994 tree
22995 template_for_substitution (tree decl)
22997 tree tmpl = DECL_TI_TEMPLATE (decl);
22999 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
23000 for the instantiation. This is not always the most general
23001 template. Consider, for example:
23003 template <class T>
23004 struct S { template <class U> void f();
23005 template <> void f<int>(); };
23007 and an instantiation of S<double>::f<int>. We want TD to be the
23008 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
23009 while (/* An instantiation cannot have a definition, so we need a
23010 more general template. */
23011 DECL_TEMPLATE_INSTANTIATION (tmpl)
23012 /* We must also deal with friend templates. Given:
23014 template <class T> struct S {
23015 template <class U> friend void f() {};
23018 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
23019 so far as the language is concerned, but that's still
23020 where we get the pattern for the instantiation from. On
23021 other hand, if the definition comes outside the class, say:
23023 template <class T> struct S {
23024 template <class U> friend void f();
23026 template <class U> friend void f() {}
23028 we don't need to look any further. That's what the check for
23029 DECL_INITIAL is for. */
23030 || (TREE_CODE (decl) == FUNCTION_DECL
23031 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
23032 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
23034 /* The present template, TD, should not be a definition. If it
23035 were a definition, we should be using it! Note that we
23036 cannot restructure the loop to just keep going until we find
23037 a template with a definition, since that might go too far if
23038 a specialization was declared, but not defined. */
23040 /* Fetch the more general template. */
23041 tmpl = DECL_TI_TEMPLATE (tmpl);
23044 return tmpl;
23047 /* Returns true if we need to instantiate this template instance even if we
23048 know we aren't going to emit it. */
23050 bool
23051 always_instantiate_p (tree decl)
23053 /* We always instantiate inline functions so that we can inline them. An
23054 explicit instantiation declaration prohibits implicit instantiation of
23055 non-inline functions. With high levels of optimization, we would
23056 normally inline non-inline functions -- but we're not allowed to do
23057 that for "extern template" functions. Therefore, we check
23058 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
23059 return ((TREE_CODE (decl) == FUNCTION_DECL
23060 && (DECL_DECLARED_INLINE_P (decl)
23061 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
23062 /* And we need to instantiate static data members so that
23063 their initializers are available in integral constant
23064 expressions. */
23065 || (VAR_P (decl)
23066 && decl_maybe_constant_var_p (decl)));
23069 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
23070 instantiate it now, modifying TREE_TYPE (fn). Returns false on
23071 error, true otherwise. */
23073 bool
23074 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
23076 tree fntype, spec, noex, clone;
23078 /* Don't instantiate a noexcept-specification from template context. */
23079 if (processing_template_decl)
23080 return true;
23082 if (DECL_CLONED_FUNCTION_P (fn))
23083 fn = DECL_CLONED_FUNCTION (fn);
23084 fntype = TREE_TYPE (fn);
23085 spec = TYPE_RAISES_EXCEPTIONS (fntype);
23087 if (!spec || !TREE_PURPOSE (spec))
23088 return true;
23090 noex = TREE_PURPOSE (spec);
23092 if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
23094 static hash_set<tree>* fns = new hash_set<tree>;
23095 bool added = false;
23096 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
23097 spec = get_defaulted_eh_spec (fn, complain);
23098 else if (!(added = !fns->add (fn)))
23100 /* If hash_set::add returns true, the element was already there. */
23101 location_t loc = EXPR_LOC_OR_LOC (DEFERRED_NOEXCEPT_PATTERN (noex),
23102 DECL_SOURCE_LOCATION (fn));
23103 error_at (loc,
23104 "exception specification of %qD depends on itself",
23105 fn);
23106 spec = noexcept_false_spec;
23108 else if (push_tinst_level (fn))
23110 push_access_scope (fn);
23111 push_deferring_access_checks (dk_no_deferred);
23112 input_location = DECL_SOURCE_LOCATION (fn);
23113 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
23114 DEFERRED_NOEXCEPT_ARGS (noex),
23115 tf_warning_or_error, fn,
23116 /*function_p=*/false,
23117 /*integral_constant_expression_p=*/true);
23118 pop_deferring_access_checks ();
23119 pop_access_scope (fn);
23120 pop_tinst_level ();
23121 spec = build_noexcept_spec (noex, tf_warning_or_error);
23122 if (spec == error_mark_node)
23123 spec = noexcept_false_spec;
23125 else
23126 spec = noexcept_false_spec;
23128 if (added)
23129 fns->remove (fn);
23131 if (spec == error_mark_node)
23132 return false;
23134 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
23137 FOR_EACH_CLONE (clone, fn)
23139 if (TREE_TYPE (clone) == fntype)
23140 TREE_TYPE (clone) = TREE_TYPE (fn);
23141 else
23142 TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
23145 return true;
23148 /* We're starting to process the function INST, an instantiation of PATTERN;
23149 add their parameters to local_specializations. */
23151 static void
23152 register_parameter_specializations (tree pattern, tree inst)
23154 tree tmpl_parm = DECL_ARGUMENTS (pattern);
23155 tree spec_parm = DECL_ARGUMENTS (inst);
23156 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
23158 register_local_specialization (spec_parm, tmpl_parm);
23159 spec_parm = skip_artificial_parms_for (inst, spec_parm);
23160 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
23162 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
23164 if (!DECL_PACK_P (tmpl_parm))
23166 register_local_specialization (spec_parm, tmpl_parm);
23167 spec_parm = DECL_CHAIN (spec_parm);
23169 else
23171 /* Register the (value) argument pack as a specialization of
23172 TMPL_PARM, then move on. */
23173 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
23174 register_local_specialization (argpack, tmpl_parm);
23177 gcc_assert (!spec_parm);
23180 /* Produce the definition of D, a _DECL generated from a template. If
23181 DEFER_OK is true, then we don't have to actually do the
23182 instantiation now; we just have to do it sometime. Normally it is
23183 an error if this is an explicit instantiation but D is undefined.
23184 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
23185 instantiated class template. */
23187 tree
23188 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
23190 tree tmpl = DECL_TI_TEMPLATE (d);
23191 tree gen_args;
23192 tree args;
23193 tree td;
23194 tree code_pattern;
23195 tree spec;
23196 tree gen_tmpl;
23197 bool pattern_defined;
23198 location_t saved_loc = input_location;
23199 int saved_unevaluated_operand = cp_unevaluated_operand;
23200 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
23201 bool external_p;
23202 bool deleted_p;
23204 /* This function should only be used to instantiate templates for
23205 functions and static member variables. */
23206 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
23208 /* A concept is never instantiated. */
23209 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
23211 /* Variables are never deferred; if instantiation is required, they
23212 are instantiated right away. That allows for better code in the
23213 case that an expression refers to the value of the variable --
23214 if the variable has a constant value the referring expression can
23215 take advantage of that fact. */
23216 if (VAR_P (d))
23217 defer_ok = false;
23219 /* Don't instantiate cloned functions. Instead, instantiate the
23220 functions they cloned. */
23221 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
23222 d = DECL_CLONED_FUNCTION (d);
23224 if (DECL_TEMPLATE_INSTANTIATED (d)
23225 || (TREE_CODE (d) == FUNCTION_DECL
23226 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
23227 || DECL_TEMPLATE_SPECIALIZATION (d))
23228 /* D has already been instantiated or explicitly specialized, so
23229 there's nothing for us to do here.
23231 It might seem reasonable to check whether or not D is an explicit
23232 instantiation, and, if so, stop here. But when an explicit
23233 instantiation is deferred until the end of the compilation,
23234 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
23235 the instantiation. */
23236 return d;
23238 /* Check to see whether we know that this template will be
23239 instantiated in some other file, as with "extern template"
23240 extension. */
23241 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
23243 /* In general, we do not instantiate such templates. */
23244 if (external_p && !always_instantiate_p (d))
23245 return d;
23247 gen_tmpl = most_general_template (tmpl);
23248 gen_args = DECL_TI_ARGS (d);
23250 if (tmpl != gen_tmpl)
23251 /* We should already have the extra args. */
23252 gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
23253 == TMPL_ARGS_DEPTH (gen_args));
23254 /* And what's in the hash table should match D. */
23255 gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
23256 || spec == NULL_TREE);
23258 /* This needs to happen before any tsubsting. */
23259 if (! push_tinst_level (d))
23260 return d;
23262 timevar_push (TV_TEMPLATE_INST);
23264 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
23265 for the instantiation. */
23266 td = template_for_substitution (d);
23267 args = gen_args;
23269 if (VAR_P (d))
23271 /* Look up an explicit specialization, if any. */
23272 tree tid = lookup_template_variable (gen_tmpl, gen_args);
23273 tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
23274 if (elt && elt != error_mark_node)
23276 td = TREE_VALUE (elt);
23277 args = TREE_PURPOSE (elt);
23281 code_pattern = DECL_TEMPLATE_RESULT (td);
23283 /* We should never be trying to instantiate a member of a class
23284 template or partial specialization. */
23285 gcc_assert (d != code_pattern);
23287 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
23288 || DECL_TEMPLATE_SPECIALIZATION (td))
23289 /* In the case of a friend template whose definition is provided
23290 outside the class, we may have too many arguments. Drop the
23291 ones we don't need. The same is true for specializations. */
23292 args = get_innermost_template_args
23293 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
23295 if (TREE_CODE (d) == FUNCTION_DECL)
23297 deleted_p = DECL_DELETED_FN (code_pattern);
23298 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
23299 && DECL_INITIAL (code_pattern) != error_mark_node)
23300 || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
23301 || deleted_p);
23303 else
23305 deleted_p = false;
23306 if (DECL_CLASS_SCOPE_P (code_pattern))
23307 pattern_defined = (! DECL_IN_AGGR_P (code_pattern)
23308 || DECL_INLINE_VAR_P (code_pattern));
23309 else
23310 pattern_defined = ! DECL_EXTERNAL (code_pattern);
23313 /* We may be in the middle of deferred access check. Disable it now. */
23314 push_deferring_access_checks (dk_no_deferred);
23316 /* Unless an explicit instantiation directive has already determined
23317 the linkage of D, remember that a definition is available for
23318 this entity. */
23319 if (pattern_defined
23320 && !DECL_INTERFACE_KNOWN (d)
23321 && !DECL_NOT_REALLY_EXTERN (d))
23322 mark_definable (d);
23324 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
23325 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
23326 input_location = DECL_SOURCE_LOCATION (d);
23328 /* If D is a member of an explicitly instantiated class template,
23329 and no definition is available, treat it like an implicit
23330 instantiation. */
23331 if (!pattern_defined && expl_inst_class_mem_p
23332 && DECL_EXPLICIT_INSTANTIATION (d))
23334 /* Leave linkage flags alone on instantiations with anonymous
23335 visibility. */
23336 if (TREE_PUBLIC (d))
23338 DECL_NOT_REALLY_EXTERN (d) = 0;
23339 DECL_INTERFACE_KNOWN (d) = 0;
23341 SET_DECL_IMPLICIT_INSTANTIATION (d);
23344 /* Defer all other templates, unless we have been explicitly
23345 forbidden from doing so. */
23346 if (/* If there is no definition, we cannot instantiate the
23347 template. */
23348 ! pattern_defined
23349 /* If it's OK to postpone instantiation, do so. */
23350 || defer_ok
23351 /* If this is a static data member that will be defined
23352 elsewhere, we don't want to instantiate the entire data
23353 member, but we do want to instantiate the initializer so that
23354 we can substitute that elsewhere. */
23355 || (external_p && VAR_P (d))
23356 /* Handle here a deleted function too, avoid generating
23357 its body (c++/61080). */
23358 || deleted_p)
23360 /* The definition of the static data member is now required so
23361 we must substitute the initializer. */
23362 if (VAR_P (d)
23363 && !DECL_INITIAL (d)
23364 && DECL_INITIAL (code_pattern))
23366 tree ns;
23367 tree init;
23368 bool const_init = false;
23369 bool enter_context = DECL_CLASS_SCOPE_P (d);
23371 ns = decl_namespace_context (d);
23372 push_nested_namespace (ns);
23373 if (enter_context)
23374 push_nested_class (DECL_CONTEXT (d));
23375 init = tsubst_expr (DECL_INITIAL (code_pattern),
23376 args,
23377 tf_warning_or_error, NULL_TREE,
23378 /*integral_constant_expression_p=*/false);
23379 /* If instantiating the initializer involved instantiating this
23380 again, don't call cp_finish_decl twice. */
23381 if (!DECL_INITIAL (d))
23383 /* Make sure the initializer is still constant, in case of
23384 circular dependency (template/instantiate6.C). */
23385 const_init
23386 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23387 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
23388 /*asmspec_tree=*/NULL_TREE,
23389 LOOKUP_ONLYCONVERTING);
23391 if (enter_context)
23392 pop_nested_class ();
23393 pop_nested_namespace (ns);
23396 /* We restore the source position here because it's used by
23397 add_pending_template. */
23398 input_location = saved_loc;
23400 if (at_eof && !pattern_defined
23401 && DECL_EXPLICIT_INSTANTIATION (d)
23402 && DECL_NOT_REALLY_EXTERN (d))
23403 /* [temp.explicit]
23405 The definition of a non-exported function template, a
23406 non-exported member function template, or a non-exported
23407 member function or static data member of a class template
23408 shall be present in every translation unit in which it is
23409 explicitly instantiated. */
23410 permerror (input_location, "explicit instantiation of %qD "
23411 "but no definition available", d);
23413 /* If we're in unevaluated context, we just wanted to get the
23414 constant value; this isn't an odr use, so don't queue
23415 a full instantiation. */
23416 if (cp_unevaluated_operand != 0)
23417 goto out;
23418 /* ??? Historically, we have instantiated inline functions, even
23419 when marked as "extern template". */
23420 if (!(external_p && VAR_P (d)))
23421 add_pending_template (d);
23422 goto out;
23424 /* Tell the repository that D is available in this translation unit
23425 -- and see if it is supposed to be instantiated here. */
23426 if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
23428 /* In a PCH file, despite the fact that the repository hasn't
23429 requested instantiation in the PCH it is still possible that
23430 an instantiation will be required in a file that includes the
23431 PCH. */
23432 if (pch_file)
23433 add_pending_template (d);
23434 /* Instantiate inline functions so that the inliner can do its
23435 job, even though we'll not be emitting a copy of this
23436 function. */
23437 if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
23438 goto out;
23441 bool push_to_top, nested;
23442 tree fn_context;
23443 fn_context = decl_function_context (d);
23444 nested = current_function_decl != NULL_TREE;
23445 push_to_top = !(nested && fn_context == current_function_decl);
23447 vec<tree> omp_privatization_save;
23448 if (nested)
23449 save_omp_privatization_clauses (omp_privatization_save);
23451 if (push_to_top)
23452 push_to_top_level ();
23453 else
23455 push_function_context ();
23456 cp_unevaluated_operand = 0;
23457 c_inhibit_evaluation_warnings = 0;
23460 /* Mark D as instantiated so that recursive calls to
23461 instantiate_decl do not try to instantiate it again. */
23462 DECL_TEMPLATE_INSTANTIATED (d) = 1;
23464 /* Regenerate the declaration in case the template has been modified
23465 by a subsequent redeclaration. */
23466 regenerate_decl_from_template (d, td, args);
23468 /* We already set the file and line above. Reset them now in case
23469 they changed as a result of calling regenerate_decl_from_template. */
23470 input_location = DECL_SOURCE_LOCATION (d);
23472 if (VAR_P (d))
23474 tree init;
23475 bool const_init = false;
23477 /* Clear out DECL_RTL; whatever was there before may not be right
23478 since we've reset the type of the declaration. */
23479 SET_DECL_RTL (d, NULL);
23480 DECL_IN_AGGR_P (d) = 0;
23482 /* The initializer is placed in DECL_INITIAL by
23483 regenerate_decl_from_template so we don't need to
23484 push/pop_access_scope again here. Pull it out so that
23485 cp_finish_decl can process it. */
23486 init = DECL_INITIAL (d);
23487 DECL_INITIAL (d) = NULL_TREE;
23488 DECL_INITIALIZED_P (d) = 0;
23490 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
23491 initializer. That function will defer actual emission until
23492 we have a chance to determine linkage. */
23493 DECL_EXTERNAL (d) = 0;
23495 /* Enter the scope of D so that access-checking works correctly. */
23496 bool enter_context = DECL_CLASS_SCOPE_P (d);
23497 if (enter_context)
23498 push_nested_class (DECL_CONTEXT (d));
23500 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23501 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
23503 if (enter_context)
23504 pop_nested_class ();
23506 if (variable_template_p (gen_tmpl))
23507 note_variable_template_instantiation (d);
23509 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
23510 synthesize_method (d);
23511 else if (TREE_CODE (d) == FUNCTION_DECL)
23513 /* Set up the list of local specializations. */
23514 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
23515 tree block = NULL_TREE;
23517 /* Set up context. */
23518 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
23519 && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
23520 block = push_stmt_list ();
23521 else
23522 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
23524 /* Some typedefs referenced from within the template code need to be
23525 access checked at template instantiation time, i.e now. These
23526 types were added to the template at parsing time. Let's get those
23527 and perform the access checks then. */
23528 perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
23529 args);
23531 /* Create substitution entries for the parameters. */
23532 register_parameter_specializations (code_pattern, d);
23534 /* Substitute into the body of the function. */
23535 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
23536 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
23537 tf_warning_or_error, tmpl);
23538 else
23540 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
23541 tf_warning_or_error, tmpl,
23542 /*integral_constant_expression_p=*/false);
23544 /* Set the current input_location to the end of the function
23545 so that finish_function knows where we are. */
23546 input_location
23547 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
23549 /* Remember if we saw an infinite loop in the template. */
23550 current_function_infinite_loop
23551 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
23554 /* Finish the function. */
23555 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
23556 && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
23557 DECL_SAVED_TREE (d) = pop_stmt_list (block);
23558 else
23560 d = finish_function (/*inline_p=*/false);
23561 expand_or_defer_fn (d);
23564 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
23565 cp_check_omp_declare_reduction (d);
23568 /* We're not deferring instantiation any more. */
23569 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
23571 if (push_to_top)
23572 pop_from_top_level ();
23573 else
23574 pop_function_context ();
23576 if (nested)
23577 restore_omp_privatization_clauses (omp_privatization_save);
23579 out:
23580 pop_deferring_access_checks ();
23581 timevar_pop (TV_TEMPLATE_INST);
23582 pop_tinst_level ();
23583 input_location = saved_loc;
23584 cp_unevaluated_operand = saved_unevaluated_operand;
23585 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
23587 return d;
23590 /* Run through the list of templates that we wish we could
23591 instantiate, and instantiate any we can. RETRIES is the
23592 number of times we retry pending template instantiation. */
23594 void
23595 instantiate_pending_templates (int retries)
23597 int reconsider;
23598 location_t saved_loc = input_location;
23600 /* Instantiating templates may trigger vtable generation. This in turn
23601 may require further template instantiations. We place a limit here
23602 to avoid infinite loop. */
23603 if (pending_templates && retries >= max_tinst_depth)
23605 tree decl = pending_templates->tinst->decl;
23607 fatal_error (input_location,
23608 "template instantiation depth exceeds maximum of %d"
23609 " instantiating %q+D, possibly from virtual table generation"
23610 " (use -ftemplate-depth= to increase the maximum)",
23611 max_tinst_depth, decl);
23612 if (TREE_CODE (decl) == FUNCTION_DECL)
23613 /* Pretend that we defined it. */
23614 DECL_INITIAL (decl) = error_mark_node;
23615 return;
23620 struct pending_template **t = &pending_templates;
23621 struct pending_template *last = NULL;
23622 reconsider = 0;
23623 while (*t)
23625 tree instantiation = reopen_tinst_level ((*t)->tinst);
23626 bool complete = false;
23628 if (TYPE_P (instantiation))
23630 if (!COMPLETE_TYPE_P (instantiation))
23632 instantiate_class_template (instantiation);
23633 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
23634 for (tree fld = TYPE_FIELDS (instantiation);
23635 fld; fld = TREE_CHAIN (fld))
23636 if ((VAR_P (fld)
23637 || (TREE_CODE (fld) == FUNCTION_DECL
23638 && !DECL_ARTIFICIAL (fld)))
23639 && DECL_TEMPLATE_INSTANTIATION (fld))
23640 instantiate_decl (fld,
23641 /*defer_ok=*/false,
23642 /*expl_inst_class_mem_p=*/false);
23644 if (COMPLETE_TYPE_P (instantiation))
23645 reconsider = 1;
23648 complete = COMPLETE_TYPE_P (instantiation);
23650 else
23652 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
23653 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
23655 instantiation
23656 = instantiate_decl (instantiation,
23657 /*defer_ok=*/false,
23658 /*expl_inst_class_mem_p=*/false);
23659 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
23660 reconsider = 1;
23663 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
23664 || DECL_TEMPLATE_INSTANTIATED (instantiation));
23667 if (complete)
23668 /* If INSTANTIATION has been instantiated, then we don't
23669 need to consider it again in the future. */
23670 *t = (*t)->next;
23671 else
23673 last = *t;
23674 t = &(*t)->next;
23676 tinst_depth = 0;
23677 current_tinst_level = NULL;
23679 last_pending_template = last;
23681 while (reconsider);
23683 input_location = saved_loc;
23686 /* Substitute ARGVEC into T, which is a list of initializers for
23687 either base class or a non-static data member. The TREE_PURPOSEs
23688 are DECLs, and the TREE_VALUEs are the initializer values. Used by
23689 instantiate_decl. */
23691 static tree
23692 tsubst_initializer_list (tree t, tree argvec)
23694 tree inits = NULL_TREE;
23695 tree target_ctor = error_mark_node;
23697 for (; t; t = TREE_CHAIN (t))
23699 tree decl;
23700 tree init;
23701 tree expanded_bases = NULL_TREE;
23702 tree expanded_arguments = NULL_TREE;
23703 int i, len = 1;
23705 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
23707 tree expr;
23708 tree arg;
23710 /* Expand the base class expansion type into separate base
23711 classes. */
23712 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
23713 tf_warning_or_error,
23714 NULL_TREE);
23715 if (expanded_bases == error_mark_node)
23716 continue;
23718 /* We'll be building separate TREE_LISTs of arguments for
23719 each base. */
23720 len = TREE_VEC_LENGTH (expanded_bases);
23721 expanded_arguments = make_tree_vec (len);
23722 for (i = 0; i < len; i++)
23723 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
23725 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
23726 expand each argument in the TREE_VALUE of t. */
23727 expr = make_node (EXPR_PACK_EXPANSION);
23728 PACK_EXPANSION_LOCAL_P (expr) = true;
23729 PACK_EXPANSION_PARAMETER_PACKS (expr) =
23730 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
23732 if (TREE_VALUE (t) == void_type_node)
23733 /* VOID_TYPE_NODE is used to indicate
23734 value-initialization. */
23736 for (i = 0; i < len; i++)
23737 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
23739 else
23741 /* Substitute parameter packs into each argument in the
23742 TREE_LIST. */
23743 in_base_initializer = 1;
23744 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
23746 tree expanded_exprs;
23748 /* Expand the argument. */
23749 SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
23750 expanded_exprs
23751 = tsubst_pack_expansion (expr, argvec,
23752 tf_warning_or_error,
23753 NULL_TREE);
23754 if (expanded_exprs == error_mark_node)
23755 continue;
23757 /* Prepend each of the expanded expressions to the
23758 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
23759 for (i = 0; i < len; i++)
23761 TREE_VEC_ELT (expanded_arguments, i) =
23762 tree_cons (NULL_TREE,
23763 TREE_VEC_ELT (expanded_exprs, i),
23764 TREE_VEC_ELT (expanded_arguments, i));
23767 in_base_initializer = 0;
23769 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
23770 since we built them backwards. */
23771 for (i = 0; i < len; i++)
23773 TREE_VEC_ELT (expanded_arguments, i) =
23774 nreverse (TREE_VEC_ELT (expanded_arguments, i));
23779 for (i = 0; i < len; ++i)
23781 if (expanded_bases)
23783 decl = TREE_VEC_ELT (expanded_bases, i);
23784 decl = expand_member_init (decl);
23785 init = TREE_VEC_ELT (expanded_arguments, i);
23787 else
23789 tree tmp;
23790 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
23791 tf_warning_or_error, NULL_TREE);
23793 decl = expand_member_init (decl);
23794 if (decl && !DECL_P (decl))
23795 in_base_initializer = 1;
23797 init = TREE_VALUE (t);
23798 tmp = init;
23799 if (init != void_type_node)
23800 init = tsubst_expr (init, argvec,
23801 tf_warning_or_error, NULL_TREE,
23802 /*integral_constant_expression_p=*/false);
23803 if (init == NULL_TREE && tmp != NULL_TREE)
23804 /* If we had an initializer but it instantiated to nothing,
23805 value-initialize the object. This will only occur when
23806 the initializer was a pack expansion where the parameter
23807 packs used in that expansion were of length zero. */
23808 init = void_type_node;
23809 in_base_initializer = 0;
23812 if (target_ctor != error_mark_node
23813 && init != error_mark_node)
23815 error ("mem-initializer for %qD follows constructor delegation",
23816 decl);
23817 return inits;
23819 /* Look for a target constructor. */
23820 if (init != error_mark_node
23821 && decl && CLASS_TYPE_P (decl)
23822 && same_type_p (decl, current_class_type))
23824 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
23825 if (inits)
23827 error ("constructor delegation follows mem-initializer for %qD",
23828 TREE_PURPOSE (inits));
23829 continue;
23831 target_ctor = init;
23834 if (decl)
23836 init = build_tree_list (decl, init);
23837 TREE_CHAIN (init) = inits;
23838 inits = init;
23842 return inits;
23845 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL. */
23847 static void
23848 set_current_access_from_decl (tree decl)
23850 if (TREE_PRIVATE (decl))
23851 current_access_specifier = access_private_node;
23852 else if (TREE_PROTECTED (decl))
23853 current_access_specifier = access_protected_node;
23854 else
23855 current_access_specifier = access_public_node;
23858 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
23859 is the instantiation (which should have been created with
23860 start_enum) and ARGS are the template arguments to use. */
23862 static void
23863 tsubst_enum (tree tag, tree newtag, tree args)
23865 tree e;
23867 if (SCOPED_ENUM_P (newtag))
23868 begin_scope (sk_scoped_enum, newtag);
23870 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
23872 tree value;
23873 tree decl;
23875 decl = TREE_VALUE (e);
23876 /* Note that in a template enum, the TREE_VALUE is the
23877 CONST_DECL, not the corresponding INTEGER_CST. */
23878 value = tsubst_expr (DECL_INITIAL (decl),
23879 args, tf_warning_or_error, NULL_TREE,
23880 /*integral_constant_expression_p=*/true);
23882 /* Give this enumeration constant the correct access. */
23883 set_current_access_from_decl (decl);
23885 /* Actually build the enumerator itself. Here we're assuming that
23886 enumerators can't have dependent attributes. */
23887 build_enumerator (DECL_NAME (decl), value, newtag,
23888 DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
23891 if (SCOPED_ENUM_P (newtag))
23892 finish_scope ();
23894 finish_enum_value_list (newtag);
23895 finish_enum (newtag);
23897 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
23898 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
23901 /* DECL is a FUNCTION_DECL that is a template specialization. Return
23902 its type -- but without substituting the innermost set of template
23903 arguments. So, innermost set of template parameters will appear in
23904 the type. */
23906 tree
23907 get_mostly_instantiated_function_type (tree decl)
23909 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
23910 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
23913 /* Return truthvalue if we're processing a template different from
23914 the last one involved in diagnostics. */
23915 bool
23916 problematic_instantiation_changed (void)
23918 return current_tinst_level != last_error_tinst_level;
23921 /* Remember current template involved in diagnostics. */
23922 void
23923 record_last_problematic_instantiation (void)
23925 last_error_tinst_level = current_tinst_level;
23928 struct tinst_level *
23929 current_instantiation (void)
23931 return current_tinst_level;
23934 /* Return TRUE if current_function_decl is being instantiated, false
23935 otherwise. */
23937 bool
23938 instantiating_current_function_p (void)
23940 return (current_instantiation ()
23941 && current_instantiation ()->decl == current_function_decl);
23944 /* [temp.param] Check that template non-type parm TYPE is of an allowable
23945 type. Return false for ok, true for disallowed. Issue error and
23946 inform messages under control of COMPLAIN. */
23948 static bool
23949 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
23951 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
23952 return false;
23953 else if (POINTER_TYPE_P (type))
23954 return false;
23955 else if (TYPE_PTRMEM_P (type))
23956 return false;
23957 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
23958 return false;
23959 else if (TREE_CODE (type) == TYPENAME_TYPE)
23960 return false;
23961 else if (TREE_CODE (type) == DECLTYPE_TYPE)
23962 return false;
23963 else if (TREE_CODE (type) == NULLPTR_TYPE)
23964 return false;
23965 /* A bound template template parm could later be instantiated to have a valid
23966 nontype parm type via an alias template. */
23967 else if (cxx_dialect >= cxx11
23968 && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
23969 return false;
23971 if (complain & tf_error)
23973 if (type == error_mark_node)
23974 inform (input_location, "invalid template non-type parameter");
23975 else
23976 error ("%q#T is not a valid type for a template non-type parameter",
23977 type);
23979 return true;
23982 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
23983 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
23985 static bool
23986 dependent_type_p_r (tree type)
23988 tree scope;
23990 /* [temp.dep.type]
23992 A type is dependent if it is:
23994 -- a template parameter. Template template parameters are types
23995 for us (since TYPE_P holds true for them) so we handle
23996 them here. */
23997 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
23998 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
23999 return true;
24000 /* -- a qualified-id with a nested-name-specifier which contains a
24001 class-name that names a dependent type or whose unqualified-id
24002 names a dependent type. */
24003 if (TREE_CODE (type) == TYPENAME_TYPE)
24004 return true;
24006 /* An alias template specialization can be dependent even if the
24007 resulting type is not. */
24008 if (dependent_alias_template_spec_p (type))
24009 return true;
24011 /* -- a cv-qualified type where the cv-unqualified type is
24012 dependent.
24013 No code is necessary for this bullet; the code below handles
24014 cv-qualified types, and we don't want to strip aliases with
24015 TYPE_MAIN_VARIANT because of DR 1558. */
24016 /* -- a compound type constructed from any dependent type. */
24017 if (TYPE_PTRMEM_P (type))
24018 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
24019 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
24020 (type)));
24021 else if (TYPE_PTR_P (type)
24022 || TREE_CODE (type) == REFERENCE_TYPE)
24023 return dependent_type_p (TREE_TYPE (type));
24024 else if (TREE_CODE (type) == FUNCTION_TYPE
24025 || TREE_CODE (type) == METHOD_TYPE)
24027 tree arg_type;
24029 if (dependent_type_p (TREE_TYPE (type)))
24030 return true;
24031 for (arg_type = TYPE_ARG_TYPES (type);
24032 arg_type;
24033 arg_type = TREE_CHAIN (arg_type))
24034 if (dependent_type_p (TREE_VALUE (arg_type)))
24035 return true;
24036 if (cxx_dialect >= cxx17)
24037 /* A value-dependent noexcept-specifier makes the type dependent. */
24038 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
24039 if (tree noex = TREE_PURPOSE (spec))
24040 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
24041 affect overload resolution and treating it as dependent breaks
24042 things. */
24043 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
24044 && value_dependent_expression_p (noex))
24045 return true;
24046 return false;
24048 /* -- an array type constructed from any dependent type or whose
24049 size is specified by a constant expression that is
24050 value-dependent.
24052 We checked for type- and value-dependence of the bounds in
24053 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
24054 if (TREE_CODE (type) == ARRAY_TYPE)
24056 if (TYPE_DOMAIN (type)
24057 && dependent_type_p (TYPE_DOMAIN (type)))
24058 return true;
24059 return dependent_type_p (TREE_TYPE (type));
24062 /* -- a template-id in which either the template name is a template
24063 parameter ... */
24064 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24065 return true;
24066 /* ... or any of the template arguments is a dependent type or
24067 an expression that is type-dependent or value-dependent. */
24068 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
24069 && (any_dependent_template_arguments_p
24070 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
24071 return true;
24073 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
24074 dependent; if the argument of the `typeof' expression is not
24075 type-dependent, then it should already been have resolved. */
24076 if (TREE_CODE (type) == TYPEOF_TYPE
24077 || TREE_CODE (type) == DECLTYPE_TYPE
24078 || TREE_CODE (type) == UNDERLYING_TYPE)
24079 return true;
24081 /* A template argument pack is dependent if any of its packed
24082 arguments are. */
24083 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
24085 tree args = ARGUMENT_PACK_ARGS (type);
24086 int i, len = TREE_VEC_LENGTH (args);
24087 for (i = 0; i < len; ++i)
24088 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24089 return true;
24092 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
24093 be template parameters. */
24094 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
24095 return true;
24097 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
24098 return true;
24100 /* The standard does not specifically mention types that are local
24101 to template functions or local classes, but they should be
24102 considered dependent too. For example:
24104 template <int I> void f() {
24105 enum E { a = I };
24106 S<sizeof (E)> s;
24109 The size of `E' cannot be known until the value of `I' has been
24110 determined. Therefore, `E' must be considered dependent. */
24111 scope = TYPE_CONTEXT (type);
24112 if (scope && TYPE_P (scope))
24113 return dependent_type_p (scope);
24114 /* Don't use type_dependent_expression_p here, as it can lead
24115 to infinite recursion trying to determine whether a lambda
24116 nested in a lambda is dependent (c++/47687). */
24117 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
24118 && DECL_LANG_SPECIFIC (scope)
24119 && DECL_TEMPLATE_INFO (scope)
24120 && (any_dependent_template_arguments_p
24121 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
24122 return true;
24124 /* Other types are non-dependent. */
24125 return false;
24128 /* Returns TRUE if TYPE is dependent, in the sense of
24129 [temp.dep.type]. Note that a NULL type is considered dependent. */
24131 bool
24132 dependent_type_p (tree type)
24134 /* If there are no template parameters in scope, then there can't be
24135 any dependent types. */
24136 if (!processing_template_decl)
24138 /* If we are not processing a template, then nobody should be
24139 providing us with a dependent type. */
24140 gcc_assert (type);
24141 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
24142 return false;
24145 /* If the type is NULL, we have not computed a type for the entity
24146 in question; in that case, the type is dependent. */
24147 if (!type)
24148 return true;
24150 /* Erroneous types can be considered non-dependent. */
24151 if (type == error_mark_node)
24152 return false;
24154 /* Getting here with global_type_node means we improperly called this
24155 function on the TREE_TYPE of an IDENTIFIER_NODE. */
24156 gcc_checking_assert (type != global_type_node);
24158 /* If we have not already computed the appropriate value for TYPE,
24159 do so now. */
24160 if (!TYPE_DEPENDENT_P_VALID (type))
24162 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
24163 TYPE_DEPENDENT_P_VALID (type) = 1;
24166 return TYPE_DEPENDENT_P (type);
24169 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
24170 lookup. In other words, a dependent type that is not the current
24171 instantiation. */
24173 bool
24174 dependent_scope_p (tree scope)
24176 return (scope && TYPE_P (scope) && dependent_type_p (scope)
24177 && !currently_open_class (scope));
24180 /* T is a SCOPE_REF. Return whether it represents a non-static member of
24181 an unknown base of 'this' (and is therefore instantiation-dependent). */
24183 static bool
24184 unknown_base_ref_p (tree t)
24186 if (!current_class_ptr)
24187 return false;
24189 tree mem = TREE_OPERAND (t, 1);
24190 if (shared_member_p (mem))
24191 return false;
24193 tree cur = current_nonlambda_class_type ();
24194 if (!any_dependent_bases_p (cur))
24195 return false;
24197 tree ctx = TREE_OPERAND (t, 0);
24198 if (DERIVED_FROM_P (ctx, cur))
24199 return false;
24201 return true;
24204 /* T is a SCOPE_REF; return whether we need to consider it
24205 instantiation-dependent so that we can check access at instantiation
24206 time even though we know which member it resolves to. */
24208 static bool
24209 instantiation_dependent_scope_ref_p (tree t)
24211 if (DECL_P (TREE_OPERAND (t, 1))
24212 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
24213 && !unknown_base_ref_p (t)
24214 && accessible_in_template_p (TREE_OPERAND (t, 0),
24215 TREE_OPERAND (t, 1)))
24216 return false;
24217 else
24218 return true;
24221 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
24222 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
24223 expression. */
24225 /* Note that this predicate is not appropriate for general expressions;
24226 only constant expressions (that satisfy potential_constant_expression)
24227 can be tested for value dependence. */
24229 bool
24230 value_dependent_expression_p (tree expression)
24232 if (!processing_template_decl || expression == NULL_TREE)
24233 return false;
24235 /* A type-dependent expression is also value-dependent. */
24236 if (type_dependent_expression_p (expression))
24237 return true;
24239 switch (TREE_CODE (expression))
24241 case BASELINK:
24242 /* A dependent member function of the current instantiation. */
24243 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
24245 case FUNCTION_DECL:
24246 /* A dependent member function of the current instantiation. */
24247 if (DECL_CLASS_SCOPE_P (expression)
24248 && dependent_type_p (DECL_CONTEXT (expression)))
24249 return true;
24250 break;
24252 case IDENTIFIER_NODE:
24253 /* A name that has not been looked up -- must be dependent. */
24254 return true;
24256 case TEMPLATE_PARM_INDEX:
24257 /* A non-type template parm. */
24258 return true;
24260 case CONST_DECL:
24261 /* A non-type template parm. */
24262 if (DECL_TEMPLATE_PARM_P (expression))
24263 return true;
24264 return value_dependent_expression_p (DECL_INITIAL (expression));
24266 case VAR_DECL:
24267 /* A constant with literal type and is initialized
24268 with an expression that is value-dependent. */
24269 if (DECL_DEPENDENT_INIT_P (expression)
24270 /* FIXME cp_finish_decl doesn't fold reference initializers. */
24271 || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE)
24272 return true;
24273 if (DECL_HAS_VALUE_EXPR_P (expression))
24275 tree value_expr = DECL_VALUE_EXPR (expression);
24276 if (value_dependent_expression_p (value_expr))
24277 return true;
24279 return false;
24281 case DYNAMIC_CAST_EXPR:
24282 case STATIC_CAST_EXPR:
24283 case CONST_CAST_EXPR:
24284 case REINTERPRET_CAST_EXPR:
24285 case CAST_EXPR:
24286 case IMPLICIT_CONV_EXPR:
24287 /* These expressions are value-dependent if the type to which
24288 the cast occurs is dependent or the expression being casted
24289 is value-dependent. */
24291 tree type = TREE_TYPE (expression);
24293 if (dependent_type_p (type))
24294 return true;
24296 /* A functional cast has a list of operands. */
24297 expression = TREE_OPERAND (expression, 0);
24298 if (!expression)
24300 /* If there are no operands, it must be an expression such
24301 as "int()". This should not happen for aggregate types
24302 because it would form non-constant expressions. */
24303 gcc_assert (cxx_dialect >= cxx11
24304 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
24306 return false;
24309 if (TREE_CODE (expression) == TREE_LIST)
24310 return any_value_dependent_elements_p (expression);
24312 return value_dependent_expression_p (expression);
24315 case SIZEOF_EXPR:
24316 if (SIZEOF_EXPR_TYPE_P (expression))
24317 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
24318 /* FALLTHRU */
24319 case ALIGNOF_EXPR:
24320 case TYPEID_EXPR:
24321 /* A `sizeof' expression is value-dependent if the operand is
24322 type-dependent or is a pack expansion. */
24323 expression = TREE_OPERAND (expression, 0);
24324 if (PACK_EXPANSION_P (expression))
24325 return true;
24326 else if (TYPE_P (expression))
24327 return dependent_type_p (expression);
24328 return instantiation_dependent_uneval_expression_p (expression);
24330 case AT_ENCODE_EXPR:
24331 /* An 'encode' expression is value-dependent if the operand is
24332 type-dependent. */
24333 expression = TREE_OPERAND (expression, 0);
24334 return dependent_type_p (expression);
24336 case NOEXCEPT_EXPR:
24337 expression = TREE_OPERAND (expression, 0);
24338 return instantiation_dependent_uneval_expression_p (expression);
24340 case SCOPE_REF:
24341 /* All instantiation-dependent expressions should also be considered
24342 value-dependent. */
24343 return instantiation_dependent_scope_ref_p (expression);
24345 case COMPONENT_REF:
24346 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
24347 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
24349 case NONTYPE_ARGUMENT_PACK:
24350 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
24351 is value-dependent. */
24353 tree values = ARGUMENT_PACK_ARGS (expression);
24354 int i, len = TREE_VEC_LENGTH (values);
24356 for (i = 0; i < len; ++i)
24357 if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
24358 return true;
24360 return false;
24363 case TRAIT_EXPR:
24365 tree type2 = TRAIT_EXPR_TYPE2 (expression);
24367 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
24368 return true;
24370 if (!type2)
24371 return false;
24373 if (TREE_CODE (type2) != TREE_LIST)
24374 return dependent_type_p (type2);
24376 for (; type2; type2 = TREE_CHAIN (type2))
24377 if (dependent_type_p (TREE_VALUE (type2)))
24378 return true;
24380 return false;
24383 case MODOP_EXPR:
24384 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24385 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
24387 case ARRAY_REF:
24388 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24389 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
24391 case ADDR_EXPR:
24393 tree op = TREE_OPERAND (expression, 0);
24394 return (value_dependent_expression_p (op)
24395 || has_value_dependent_address (op));
24398 case REQUIRES_EXPR:
24399 /* Treat all requires-expressions as value-dependent so
24400 we don't try to fold them. */
24401 return true;
24403 case TYPE_REQ:
24404 return dependent_type_p (TREE_OPERAND (expression, 0));
24406 case CALL_EXPR:
24408 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
24409 return true;
24410 tree fn = get_callee_fndecl (expression);
24411 int i, nargs;
24412 nargs = call_expr_nargs (expression);
24413 for (i = 0; i < nargs; ++i)
24415 tree op = CALL_EXPR_ARG (expression, i);
24416 /* In a call to a constexpr member function, look through the
24417 implicit ADDR_EXPR on the object argument so that it doesn't
24418 cause the call to be considered value-dependent. We also
24419 look through it in potential_constant_expression. */
24420 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
24421 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
24422 && TREE_CODE (op) == ADDR_EXPR)
24423 op = TREE_OPERAND (op, 0);
24424 if (value_dependent_expression_p (op))
24425 return true;
24427 return false;
24430 case TEMPLATE_ID_EXPR:
24431 return variable_concept_p (TREE_OPERAND (expression, 0));
24433 case CONSTRUCTOR:
24435 unsigned ix;
24436 tree val;
24437 if (dependent_type_p (TREE_TYPE (expression)))
24438 return true;
24439 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
24440 if (value_dependent_expression_p (val))
24441 return true;
24442 return false;
24445 case STMT_EXPR:
24446 /* Treat a GNU statement expression as dependent to avoid crashing
24447 under instantiate_non_dependent_expr; it can't be constant. */
24448 return true;
24450 default:
24451 /* A constant expression is value-dependent if any subexpression is
24452 value-dependent. */
24453 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
24455 case tcc_reference:
24456 case tcc_unary:
24457 case tcc_comparison:
24458 case tcc_binary:
24459 case tcc_expression:
24460 case tcc_vl_exp:
24462 int i, len = cp_tree_operand_length (expression);
24464 for (i = 0; i < len; i++)
24466 tree t = TREE_OPERAND (expression, i);
24468 /* In some cases, some of the operands may be missing.
24469 (For example, in the case of PREDECREMENT_EXPR, the
24470 amount to increment by may be missing.) That doesn't
24471 make the expression dependent. */
24472 if (t && value_dependent_expression_p (t))
24473 return true;
24476 break;
24477 default:
24478 break;
24480 break;
24483 /* The expression is not value-dependent. */
24484 return false;
24487 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
24488 [temp.dep.expr]. Note that an expression with no type is
24489 considered dependent. Other parts of the compiler arrange for an
24490 expression with type-dependent subexpressions to have no type, so
24491 this function doesn't have to be fully recursive. */
24493 bool
24494 type_dependent_expression_p (tree expression)
24496 if (!processing_template_decl)
24497 return false;
24499 if (expression == NULL_TREE || expression == error_mark_node)
24500 return false;
24502 STRIP_ANY_LOCATION_WRAPPER (expression);
24504 /* An unresolved name is always dependent. */
24505 if (identifier_p (expression)
24506 || TREE_CODE (expression) == USING_DECL
24507 || TREE_CODE (expression) == WILDCARD_DECL)
24508 return true;
24510 /* A fold expression is type-dependent. */
24511 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
24512 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
24513 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
24514 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
24515 return true;
24517 /* Some expression forms are never type-dependent. */
24518 if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
24519 || TREE_CODE (expression) == SIZEOF_EXPR
24520 || TREE_CODE (expression) == ALIGNOF_EXPR
24521 || TREE_CODE (expression) == AT_ENCODE_EXPR
24522 || TREE_CODE (expression) == NOEXCEPT_EXPR
24523 || TREE_CODE (expression) == TRAIT_EXPR
24524 || TREE_CODE (expression) == TYPEID_EXPR
24525 || TREE_CODE (expression) == DELETE_EXPR
24526 || TREE_CODE (expression) == VEC_DELETE_EXPR
24527 || TREE_CODE (expression) == THROW_EXPR
24528 || TREE_CODE (expression) == REQUIRES_EXPR)
24529 return false;
24531 /* The types of these expressions depends only on the type to which
24532 the cast occurs. */
24533 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
24534 || TREE_CODE (expression) == STATIC_CAST_EXPR
24535 || TREE_CODE (expression) == CONST_CAST_EXPR
24536 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
24537 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
24538 || TREE_CODE (expression) == CAST_EXPR)
24539 return dependent_type_p (TREE_TYPE (expression));
24541 /* The types of these expressions depends only on the type created
24542 by the expression. */
24543 if (TREE_CODE (expression) == NEW_EXPR
24544 || TREE_CODE (expression) == VEC_NEW_EXPR)
24546 /* For NEW_EXPR tree nodes created inside a template, either
24547 the object type itself or a TREE_LIST may appear as the
24548 operand 1. */
24549 tree type = TREE_OPERAND (expression, 1);
24550 if (TREE_CODE (type) == TREE_LIST)
24551 /* This is an array type. We need to check array dimensions
24552 as well. */
24553 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
24554 || value_dependent_expression_p
24555 (TREE_OPERAND (TREE_VALUE (type), 1));
24556 else
24557 return dependent_type_p (type);
24560 if (TREE_CODE (expression) == SCOPE_REF)
24562 tree scope = TREE_OPERAND (expression, 0);
24563 tree name = TREE_OPERAND (expression, 1);
24565 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
24566 contains an identifier associated by name lookup with one or more
24567 declarations declared with a dependent type, or...a
24568 nested-name-specifier or qualified-id that names a member of an
24569 unknown specialization. */
24570 return (type_dependent_expression_p (name)
24571 || dependent_scope_p (scope));
24574 if (TREE_CODE (expression) == TEMPLATE_DECL
24575 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
24576 return uses_outer_template_parms (expression);
24578 if (TREE_CODE (expression) == STMT_EXPR)
24579 expression = stmt_expr_value_expr (expression);
24581 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
24583 tree elt;
24584 unsigned i;
24586 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
24588 if (type_dependent_expression_p (elt))
24589 return true;
24591 return false;
24594 /* A static data member of the current instantiation with incomplete
24595 array type is type-dependent, as the definition and specializations
24596 can have different bounds. */
24597 if (VAR_P (expression)
24598 && DECL_CLASS_SCOPE_P (expression)
24599 && dependent_type_p (DECL_CONTEXT (expression))
24600 && VAR_HAD_UNKNOWN_BOUND (expression))
24601 return true;
24603 /* An array of unknown bound depending on a variadic parameter, eg:
24605 template<typename... Args>
24606 void foo (Args... args)
24608 int arr[] = { args... };
24611 template<int... vals>
24612 void bar ()
24614 int arr[] = { vals... };
24617 If the array has no length and has an initializer, it must be that
24618 we couldn't determine its length in cp_complete_array_type because
24619 it is dependent. */
24620 if (VAR_P (expression)
24621 && TREE_TYPE (expression) != NULL_TREE
24622 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
24623 && !TYPE_DOMAIN (TREE_TYPE (expression))
24624 && DECL_INITIAL (expression))
24625 return true;
24627 /* A function or variable template-id is type-dependent if it has any
24628 dependent template arguments. */
24629 if (VAR_OR_FUNCTION_DECL_P (expression)
24630 && DECL_LANG_SPECIFIC (expression)
24631 && DECL_TEMPLATE_INFO (expression))
24633 /* Consider the innermost template arguments, since those are the ones
24634 that come from the template-id; the template arguments for the
24635 enclosing class do not make it type-dependent unless they are used in
24636 the type of the decl. */
24637 if (PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (expression))
24638 && (any_dependent_template_arguments_p
24639 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
24640 return true;
24643 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
24644 type-dependent. Checking this is important for functions with auto return
24645 type, which looks like a dependent type. */
24646 if (TREE_CODE (expression) == FUNCTION_DECL
24647 && !(DECL_CLASS_SCOPE_P (expression)
24648 && dependent_type_p (DECL_CONTEXT (expression)))
24649 && !(DECL_LANG_SPECIFIC (expression)
24650 && DECL_FRIEND_P (expression)
24651 && (!DECL_FRIEND_CONTEXT (expression)
24652 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
24653 && !DECL_LOCAL_FUNCTION_P (expression))
24655 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
24656 || undeduced_auto_decl (expression));
24657 return false;
24660 /* Always dependent, on the number of arguments if nothing else. */
24661 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
24662 return true;
24664 if (TREE_TYPE (expression) == unknown_type_node)
24666 if (TREE_CODE (expression) == ADDR_EXPR)
24667 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
24668 if (TREE_CODE (expression) == COMPONENT_REF
24669 || TREE_CODE (expression) == OFFSET_REF)
24671 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
24672 return true;
24673 expression = TREE_OPERAND (expression, 1);
24674 if (identifier_p (expression))
24675 return false;
24677 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
24678 if (TREE_CODE (expression) == SCOPE_REF)
24679 return false;
24681 if (BASELINK_P (expression))
24683 if (BASELINK_OPTYPE (expression)
24684 && dependent_type_p (BASELINK_OPTYPE (expression)))
24685 return true;
24686 expression = BASELINK_FUNCTIONS (expression);
24689 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
24691 if (any_dependent_template_arguments_p
24692 (TREE_OPERAND (expression, 1)))
24693 return true;
24694 expression = TREE_OPERAND (expression, 0);
24695 if (identifier_p (expression))
24696 return true;
24699 gcc_assert (TREE_CODE (expression) == OVERLOAD
24700 || TREE_CODE (expression) == FUNCTION_DECL);
24702 for (lkp_iterator iter (expression); iter; ++iter)
24703 if (type_dependent_expression_p (*iter))
24704 return true;
24706 return false;
24709 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
24711 /* Dependent type attributes might not have made it from the decl to
24712 the type yet. */
24713 if (DECL_P (expression)
24714 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
24715 return true;
24717 return (dependent_type_p (TREE_TYPE (expression)));
24720 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
24721 type-dependent if the expression refers to a member of the current
24722 instantiation and the type of the referenced member is dependent, or the
24723 class member access expression refers to a member of an unknown
24724 specialization.
24726 This function returns true if the OBJECT in such a class member access
24727 expression is of an unknown specialization. */
24729 bool
24730 type_dependent_object_expression_p (tree object)
24732 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
24733 dependent. */
24734 if (TREE_CODE (object) == IDENTIFIER_NODE)
24735 return true;
24736 tree scope = TREE_TYPE (object);
24737 return (!scope || dependent_scope_p (scope));
24740 /* walk_tree callback function for instantiation_dependent_expression_p,
24741 below. Returns non-zero if a dependent subexpression is found. */
24743 static tree
24744 instantiation_dependent_r (tree *tp, int *walk_subtrees,
24745 void * /*data*/)
24747 if (TYPE_P (*tp))
24749 /* We don't have to worry about decltype currently because decltype
24750 of an instantiation-dependent expr is a dependent type. This
24751 might change depending on the resolution of DR 1172. */
24752 *walk_subtrees = false;
24753 return NULL_TREE;
24755 enum tree_code code = TREE_CODE (*tp);
24756 switch (code)
24758 /* Don't treat an argument list as dependent just because it has no
24759 TREE_TYPE. */
24760 case TREE_LIST:
24761 case TREE_VEC:
24762 return NULL_TREE;
24764 case TEMPLATE_PARM_INDEX:
24765 return *tp;
24767 /* Handle expressions with type operands. */
24768 case SIZEOF_EXPR:
24769 case ALIGNOF_EXPR:
24770 case TYPEID_EXPR:
24771 case AT_ENCODE_EXPR:
24773 tree op = TREE_OPERAND (*tp, 0);
24774 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
24775 op = TREE_TYPE (op);
24776 if (TYPE_P (op))
24778 if (dependent_type_p (op))
24779 return *tp;
24780 else
24782 *walk_subtrees = false;
24783 return NULL_TREE;
24786 break;
24789 case COMPONENT_REF:
24790 if (identifier_p (TREE_OPERAND (*tp, 1)))
24791 /* In a template, finish_class_member_access_expr creates a
24792 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
24793 type-dependent, so that we can check access control at
24794 instantiation time (PR 42277). See also Core issue 1273. */
24795 return *tp;
24796 break;
24798 case SCOPE_REF:
24799 if (instantiation_dependent_scope_ref_p (*tp))
24800 return *tp;
24801 else
24802 break;
24804 /* Treat statement-expressions as dependent. */
24805 case BIND_EXPR:
24806 return *tp;
24808 /* Treat requires-expressions as dependent. */
24809 case REQUIRES_EXPR:
24810 return *tp;
24812 case CALL_EXPR:
24813 /* Treat calls to function concepts as dependent. */
24814 if (function_concept_check_p (*tp))
24815 return *tp;
24816 break;
24818 case TEMPLATE_ID_EXPR:
24819 /* And variable concepts. */
24820 if (variable_concept_p (TREE_OPERAND (*tp, 0)))
24821 return *tp;
24822 break;
24824 default:
24825 break;
24828 if (type_dependent_expression_p (*tp))
24829 return *tp;
24830 else
24831 return NULL_TREE;
24834 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
24835 sense defined by the ABI:
24837 "An expression is instantiation-dependent if it is type-dependent
24838 or value-dependent, or it has a subexpression that is type-dependent
24839 or value-dependent."
24841 Except don't actually check value-dependence for unevaluated expressions,
24842 because in sizeof(i) we don't care about the value of i. Checking
24843 type-dependence will in turn check value-dependence of array bounds/template
24844 arguments as needed. */
24846 bool
24847 instantiation_dependent_uneval_expression_p (tree expression)
24849 tree result;
24851 if (!processing_template_decl)
24852 return false;
24854 if (expression == error_mark_node)
24855 return false;
24857 result = cp_walk_tree_without_duplicates (&expression,
24858 instantiation_dependent_r, NULL);
24859 return result != NULL_TREE;
24862 /* As above, but also check value-dependence of the expression as a whole. */
24864 bool
24865 instantiation_dependent_expression_p (tree expression)
24867 return (instantiation_dependent_uneval_expression_p (expression)
24868 || value_dependent_expression_p (expression));
24871 /* Like type_dependent_expression_p, but it also works while not processing
24872 a template definition, i.e. during substitution or mangling. */
24874 bool
24875 type_dependent_expression_p_push (tree expr)
24877 bool b;
24878 ++processing_template_decl;
24879 b = type_dependent_expression_p (expr);
24880 --processing_template_decl;
24881 return b;
24884 /* Returns TRUE if ARGS contains a type-dependent expression. */
24886 bool
24887 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
24889 unsigned int i;
24890 tree arg;
24892 FOR_EACH_VEC_SAFE_ELT (args, i, arg)
24894 if (type_dependent_expression_p (arg))
24895 return true;
24897 return false;
24900 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
24901 expressions) contains any type-dependent expressions. */
24903 bool
24904 any_type_dependent_elements_p (const_tree list)
24906 for (; list; list = TREE_CHAIN (list))
24907 if (type_dependent_expression_p (TREE_VALUE (list)))
24908 return true;
24910 return false;
24913 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
24914 expressions) contains any value-dependent expressions. */
24916 bool
24917 any_value_dependent_elements_p (const_tree list)
24919 for (; list; list = TREE_CHAIN (list))
24920 if (value_dependent_expression_p (TREE_VALUE (list)))
24921 return true;
24923 return false;
24926 /* Returns TRUE if the ARG (a template argument) is dependent. */
24928 bool
24929 dependent_template_arg_p (tree arg)
24931 if (!processing_template_decl)
24932 return false;
24934 /* Assume a template argument that was wrongly written by the user
24935 is dependent. This is consistent with what
24936 any_dependent_template_arguments_p [that calls this function]
24937 does. */
24938 if (!arg || arg == error_mark_node)
24939 return true;
24941 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
24942 arg = argument_pack_select_arg (arg);
24944 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
24945 return true;
24946 if (TREE_CODE (arg) == TEMPLATE_DECL)
24948 if (DECL_TEMPLATE_PARM_P (arg))
24949 return true;
24950 /* A member template of a dependent class is not necessarily
24951 type-dependent, but it is a dependent template argument because it
24952 will be a member of an unknown specialization to that template. */
24953 tree scope = CP_DECL_CONTEXT (arg);
24954 return TYPE_P (scope) && dependent_type_p (scope);
24956 else if (ARGUMENT_PACK_P (arg))
24958 tree args = ARGUMENT_PACK_ARGS (arg);
24959 int i, len = TREE_VEC_LENGTH (args);
24960 for (i = 0; i < len; ++i)
24962 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24963 return true;
24966 return false;
24968 else if (TYPE_P (arg))
24969 return dependent_type_p (arg);
24970 else
24971 return (type_dependent_expression_p (arg)
24972 || value_dependent_expression_p (arg));
24975 /* Returns true if ARGS (a collection of template arguments) contains
24976 any types that require structural equality testing. */
24978 bool
24979 any_template_arguments_need_structural_equality_p (tree args)
24981 int i;
24982 int j;
24984 if (!args)
24985 return false;
24986 if (args == error_mark_node)
24987 return true;
24989 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
24991 tree level = TMPL_ARGS_LEVEL (args, i + 1);
24992 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
24994 tree arg = TREE_VEC_ELT (level, j);
24995 tree packed_args = NULL_TREE;
24996 int k, len = 1;
24998 if (ARGUMENT_PACK_P (arg))
25000 /* Look inside the argument pack. */
25001 packed_args = ARGUMENT_PACK_ARGS (arg);
25002 len = TREE_VEC_LENGTH (packed_args);
25005 for (k = 0; k < len; ++k)
25007 if (packed_args)
25008 arg = TREE_VEC_ELT (packed_args, k);
25010 if (error_operand_p (arg))
25011 return true;
25012 else if (TREE_CODE (arg) == TEMPLATE_DECL)
25013 continue;
25014 else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
25015 return true;
25016 else if (!TYPE_P (arg) && TREE_TYPE (arg)
25017 && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
25018 return true;
25023 return false;
25026 /* Returns true if ARGS (a collection of template arguments) contains
25027 any dependent arguments. */
25029 bool
25030 any_dependent_template_arguments_p (const_tree args)
25032 int i;
25033 int j;
25035 if (!args)
25036 return false;
25037 if (args == error_mark_node)
25038 return true;
25040 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25042 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25043 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25044 if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
25045 return true;
25048 return false;
25051 /* Returns TRUE if the template TMPL is type-dependent. */
25053 bool
25054 dependent_template_p (tree tmpl)
25056 if (TREE_CODE (tmpl) == OVERLOAD)
25058 for (lkp_iterator iter (tmpl); iter; ++iter)
25059 if (dependent_template_p (*iter))
25060 return true;
25061 return false;
25064 /* Template template parameters are dependent. */
25065 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
25066 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
25067 return true;
25068 /* So are names that have not been looked up. */
25069 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
25070 return true;
25071 return false;
25074 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
25076 bool
25077 dependent_template_id_p (tree tmpl, tree args)
25079 return (dependent_template_p (tmpl)
25080 || any_dependent_template_arguments_p (args));
25083 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
25084 are dependent. */
25086 bool
25087 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
25089 int i;
25091 if (!processing_template_decl)
25092 return false;
25094 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
25096 tree decl = TREE_VEC_ELT (declv, i);
25097 tree init = TREE_VEC_ELT (initv, i);
25098 tree cond = TREE_VEC_ELT (condv, i);
25099 tree incr = TREE_VEC_ELT (incrv, i);
25101 if (type_dependent_expression_p (decl)
25102 || TREE_CODE (decl) == SCOPE_REF)
25103 return true;
25105 if (init && type_dependent_expression_p (init))
25106 return true;
25108 if (type_dependent_expression_p (cond))
25109 return true;
25111 if (COMPARISON_CLASS_P (cond)
25112 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
25113 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
25114 return true;
25116 if (TREE_CODE (incr) == MODOP_EXPR)
25118 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
25119 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
25120 return true;
25122 else if (type_dependent_expression_p (incr))
25123 return true;
25124 else if (TREE_CODE (incr) == MODIFY_EXPR)
25126 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
25127 return true;
25128 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
25130 tree t = TREE_OPERAND (incr, 1);
25131 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
25132 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
25133 return true;
25138 return false;
25141 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
25142 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
25143 no such TYPE can be found. Note that this function peers inside
25144 uninstantiated templates and therefore should be used only in
25145 extremely limited situations. ONLY_CURRENT_P restricts this
25146 peering to the currently open classes hierarchy (which is required
25147 when comparing types). */
25149 tree
25150 resolve_typename_type (tree type, bool only_current_p)
25152 tree scope;
25153 tree name;
25154 tree decl;
25155 int quals;
25156 tree pushed_scope;
25157 tree result;
25159 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
25161 scope = TYPE_CONTEXT (type);
25162 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
25163 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
25164 a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
25165 the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
25166 identifier of the TYPENAME_TYPE anymore.
25167 So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
25168 TYPENAME_TYPE instead, we avoid messing up with a possible
25169 typedef variant case. */
25170 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
25172 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
25173 it first before we can figure out what NAME refers to. */
25174 if (TREE_CODE (scope) == TYPENAME_TYPE)
25176 if (TYPENAME_IS_RESOLVING_P (scope))
25177 /* Given a class template A with a dependent base with nested type C,
25178 typedef typename A::C::C C will land us here, as trying to resolve
25179 the initial A::C leads to the local C typedef, which leads back to
25180 A::C::C. So we break the recursion now. */
25181 return type;
25182 else
25183 scope = resolve_typename_type (scope, only_current_p);
25185 /* If we don't know what SCOPE refers to, then we cannot resolve the
25186 TYPENAME_TYPE. */
25187 if (!CLASS_TYPE_P (scope))
25188 return type;
25189 /* If this is a typedef, we don't want to look inside (c++/11987). */
25190 if (typedef_variant_p (type))
25191 return type;
25192 /* If SCOPE isn't the template itself, it will not have a valid
25193 TYPE_FIELDS list. */
25194 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
25195 /* scope is either the template itself or a compatible instantiation
25196 like X<T>, so look up the name in the original template. */
25197 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
25198 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
25199 gcc_checking_assert (uses_template_parms (scope));
25200 /* If scope has no fields, it can't be a current instantiation. Check this
25201 before currently_open_class to avoid infinite recursion (71515). */
25202 if (!TYPE_FIELDS (scope))
25203 return type;
25204 /* If the SCOPE is not the current instantiation, there's no reason
25205 to look inside it. */
25206 if (only_current_p && !currently_open_class (scope))
25207 return type;
25208 /* Enter the SCOPE so that name lookup will be resolved as if we
25209 were in the class definition. In particular, SCOPE will no
25210 longer be considered a dependent type. */
25211 pushed_scope = push_scope (scope);
25212 /* Look up the declaration. */
25213 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
25214 tf_warning_or_error);
25216 result = NULL_TREE;
25218 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
25219 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
25220 tree fullname = TYPENAME_TYPE_FULLNAME (type);
25221 if (!decl)
25222 /*nop*/;
25223 else if (identifier_p (fullname)
25224 && TREE_CODE (decl) == TYPE_DECL)
25226 result = TREE_TYPE (decl);
25227 if (result == error_mark_node)
25228 result = NULL_TREE;
25230 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
25231 && DECL_CLASS_TEMPLATE_P (decl))
25233 /* Obtain the template and the arguments. */
25234 tree tmpl = TREE_OPERAND (fullname, 0);
25235 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
25237 /* We get here with a plain identifier because a previous tentative
25238 parse of the nested-name-specifier as part of a ptr-operator saw
25239 ::template X<A>. The use of ::template is necessary in a
25240 ptr-operator, but wrong in a declarator-id.
25242 [temp.names]: In a qualified-id of a declarator-id, the keyword
25243 template shall not appear at the top level. */
25244 pedwarn (EXPR_LOC_OR_LOC (fullname, input_location), OPT_Wpedantic,
25245 "keyword %<template%> not allowed in declarator-id");
25246 tmpl = decl;
25248 tree args = TREE_OPERAND (fullname, 1);
25249 /* Instantiate the template. */
25250 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
25251 /*entering_scope=*/true,
25252 tf_error | tf_user);
25253 if (result == error_mark_node)
25254 result = NULL_TREE;
25257 /* Leave the SCOPE. */
25258 if (pushed_scope)
25259 pop_scope (pushed_scope);
25261 /* If we failed to resolve it, return the original typename. */
25262 if (!result)
25263 return type;
25265 /* If lookup found a typename type, resolve that too. */
25266 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
25268 /* Ill-formed programs can cause infinite recursion here, so we
25269 must catch that. */
25270 TYPENAME_IS_RESOLVING_P (result) = 1;
25271 result = resolve_typename_type (result, only_current_p);
25272 TYPENAME_IS_RESOLVING_P (result) = 0;
25275 /* Qualify the resulting type. */
25276 quals = cp_type_quals (type);
25277 if (quals)
25278 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
25280 return result;
25283 /* EXPR is an expression which is not type-dependent. Return a proxy
25284 for EXPR that can be used to compute the types of larger
25285 expressions containing EXPR. */
25287 tree
25288 build_non_dependent_expr (tree expr)
25290 tree orig_expr = expr;
25291 tree inner_expr;
25293 /* When checking, try to get a constant value for all non-dependent
25294 expressions in order to expose bugs in *_dependent_expression_p
25295 and constexpr. This can affect code generation, see PR70704, so
25296 only do this for -fchecking=2. */
25297 if (flag_checking > 1
25298 && cxx_dialect >= cxx11
25299 /* Don't do this during nsdmi parsing as it can lead to
25300 unexpected recursive instantiations. */
25301 && !parsing_nsdmi ()
25302 /* Don't do this during concept expansion either and for
25303 the same reason. */
25304 && !expanding_concept ())
25305 fold_non_dependent_expr (expr);
25307 STRIP_ANY_LOCATION_WRAPPER (expr);
25309 /* Preserve OVERLOADs; the functions must be available to resolve
25310 types. */
25311 inner_expr = expr;
25312 if (TREE_CODE (inner_expr) == STMT_EXPR)
25313 inner_expr = stmt_expr_value_expr (inner_expr);
25314 if (TREE_CODE (inner_expr) == ADDR_EXPR)
25315 inner_expr = TREE_OPERAND (inner_expr, 0);
25316 if (TREE_CODE (inner_expr) == COMPONENT_REF)
25317 inner_expr = TREE_OPERAND (inner_expr, 1);
25318 if (is_overloaded_fn (inner_expr)
25319 || TREE_CODE (inner_expr) == OFFSET_REF)
25320 return orig_expr;
25321 /* There is no need to return a proxy for a variable. */
25322 if (VAR_P (expr))
25323 return orig_expr;
25324 /* Preserve string constants; conversions from string constants to
25325 "char *" are allowed, even though normally a "const char *"
25326 cannot be used to initialize a "char *". */
25327 if (TREE_CODE (expr) == STRING_CST)
25328 return orig_expr;
25329 /* Preserve void and arithmetic constants, as an optimization -- there is no
25330 reason to create a new node. */
25331 if (TREE_CODE (expr) == VOID_CST
25332 || TREE_CODE (expr) == INTEGER_CST
25333 || TREE_CODE (expr) == REAL_CST)
25334 return orig_expr;
25335 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
25336 There is at least one place where we want to know that a
25337 particular expression is a throw-expression: when checking a ?:
25338 expression, there are special rules if the second or third
25339 argument is a throw-expression. */
25340 if (TREE_CODE (expr) == THROW_EXPR)
25341 return orig_expr;
25343 /* Don't wrap an initializer list, we need to be able to look inside. */
25344 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
25345 return orig_expr;
25347 /* Don't wrap a dummy object, we need to be able to test for it. */
25348 if (is_dummy_object (expr))
25349 return orig_expr;
25351 if (TREE_CODE (expr) == COND_EXPR)
25352 return build3 (COND_EXPR,
25353 TREE_TYPE (expr),
25354 TREE_OPERAND (expr, 0),
25355 (TREE_OPERAND (expr, 1)
25356 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
25357 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
25358 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
25359 if (TREE_CODE (expr) == COMPOUND_EXPR
25360 && !COMPOUND_EXPR_OVERLOADED (expr))
25361 return build2 (COMPOUND_EXPR,
25362 TREE_TYPE (expr),
25363 TREE_OPERAND (expr, 0),
25364 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
25366 /* If the type is unknown, it can't really be non-dependent */
25367 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
25369 /* Otherwise, build a NON_DEPENDENT_EXPR. */
25370 return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
25373 /* ARGS is a vector of expressions as arguments to a function call.
25374 Replace the arguments with equivalent non-dependent expressions.
25375 This modifies ARGS in place. */
25377 void
25378 make_args_non_dependent (vec<tree, va_gc> *args)
25380 unsigned int ix;
25381 tree arg;
25383 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
25385 tree newarg = build_non_dependent_expr (arg);
25386 if (newarg != arg)
25387 (*args)[ix] = newarg;
25391 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
25392 TEMPLATE_TYPE_PARM with a level one deeper than the actual template
25393 parms. If set_canonical is true, we set TYPE_CANONICAL on it. */
25395 static tree
25396 make_auto_1 (tree name, bool set_canonical)
25398 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
25399 TYPE_NAME (au) = build_decl (input_location,
25400 TYPE_DECL, name, au);
25401 TYPE_STUB_DECL (au) = TYPE_NAME (au);
25402 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
25403 (0, processing_template_decl + 1, processing_template_decl + 1,
25404 TYPE_NAME (au), NULL_TREE);
25405 if (set_canonical)
25406 TYPE_CANONICAL (au) = canonical_type_parameter (au);
25407 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
25408 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
25410 return au;
25413 tree
25414 make_decltype_auto (void)
25416 return make_auto_1 (decltype_auto_identifier, true);
25419 tree
25420 make_auto (void)
25422 return make_auto_1 (auto_identifier, true);
25425 /* Return a C++17 deduction placeholder for class template TMPL. */
25427 tree
25428 make_template_placeholder (tree tmpl)
25430 tree t = make_auto_1 (DECL_NAME (tmpl), true);
25431 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
25432 return t;
25435 /* True iff T is a C++17 class template deduction placeholder. */
25437 bool
25438 template_placeholder_p (tree t)
25440 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
25443 /* Make a "constrained auto" type-specifier. This is an
25444 auto type with constraints that must be associated after
25445 deduction. The constraint is formed from the given
25446 CONC and its optional sequence of arguments, which are
25447 non-null if written as partial-concept-id. */
25449 tree
25450 make_constrained_auto (tree con, tree args)
25452 tree type = make_auto_1 (auto_identifier, false);
25454 /* Build the constraint. */
25455 tree tmpl = DECL_TI_TEMPLATE (con);
25456 tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
25457 expr = build_concept_check (expr, type, args);
25459 tree constr = normalize_expression (expr);
25460 PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
25462 /* Our canonical type depends on the constraint. */
25463 TYPE_CANONICAL (type) = canonical_type_parameter (type);
25465 /* Attach the constraint to the type declaration. */
25466 tree decl = TYPE_NAME (type);
25467 return decl;
25470 /* Given type ARG, return std::initializer_list<ARG>. */
25472 static tree
25473 listify (tree arg)
25475 tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
25477 if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
25479 gcc_rich_location richloc (input_location);
25480 maybe_add_include_fixit (&richloc, "<initializer_list>");
25481 error_at (&richloc,
25482 "deducing from brace-enclosed initializer list"
25483 " requires %<#include <initializer_list>%>");
25485 return error_mark_node;
25487 tree argvec = make_tree_vec (1);
25488 TREE_VEC_ELT (argvec, 0) = arg;
25490 return lookup_template_class (std_init_list, argvec, NULL_TREE,
25491 NULL_TREE, 0, tf_warning_or_error);
25494 /* Replace auto in TYPE with std::initializer_list<auto>. */
25496 static tree
25497 listify_autos (tree type, tree auto_node)
25499 tree init_auto = listify (auto_node);
25500 tree argvec = make_tree_vec (1);
25501 TREE_VEC_ELT (argvec, 0) = init_auto;
25502 if (processing_template_decl)
25503 argvec = add_to_template_args (current_template_args (), argvec);
25504 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
25507 /* Hash traits for hashing possibly constrained 'auto'
25508 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
25510 struct auto_hash : default_hash_traits<tree>
25512 static inline hashval_t hash (tree);
25513 static inline bool equal (tree, tree);
25516 /* Hash the 'auto' T. */
25518 inline hashval_t
25519 auto_hash::hash (tree t)
25521 if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
25522 /* Matching constrained-type-specifiers denote the same template
25523 parameter, so hash the constraint. */
25524 return hash_placeholder_constraint (c);
25525 else
25526 /* But unconstrained autos are all separate, so just hash the pointer. */
25527 return iterative_hash_object (t, 0);
25530 /* Compare two 'auto's. */
25532 inline bool
25533 auto_hash::equal (tree t1, tree t2)
25535 if (t1 == t2)
25536 return true;
25538 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
25539 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
25541 /* Two unconstrained autos are distinct. */
25542 if (!c1 || !c2)
25543 return false;
25545 return equivalent_placeholder_constraints (c1, c2);
25548 /* for_each_template_parm callback for extract_autos: if t is a (possibly
25549 constrained) auto, add it to the vector. */
25551 static int
25552 extract_autos_r (tree t, void *data)
25554 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
25555 if (is_auto (t))
25557 /* All the autos were built with index 0; fix that up now. */
25558 tree *p = hash.find_slot (t, INSERT);
25559 unsigned idx;
25560 if (*p)
25561 /* If this is a repeated constrained-type-specifier, use the index we
25562 chose before. */
25563 idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
25564 else
25566 /* Otherwise this is new, so use the current count. */
25567 *p = t;
25568 idx = hash.elements () - 1;
25570 TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
25573 /* Always keep walking. */
25574 return 0;
25577 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
25578 says they can appear anywhere in the type. */
25580 static tree
25581 extract_autos (tree type)
25583 hash_set<tree> visited;
25584 hash_table<auto_hash> hash (2);
25586 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
25588 tree tree_vec = make_tree_vec (hash.elements());
25589 for (hash_table<auto_hash>::iterator iter = hash.begin();
25590 iter != hash.end(); ++iter)
25592 tree elt = *iter;
25593 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
25594 TREE_VEC_ELT (tree_vec, i)
25595 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
25598 return tree_vec;
25601 /* The stem for deduction guide names. */
25602 const char *const dguide_base = "__dguide_";
25604 /* Return the name for a deduction guide for class template TMPL. */
25606 tree
25607 dguide_name (tree tmpl)
25609 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
25610 tree tname = TYPE_IDENTIFIER (type);
25611 char *buf = (char *) alloca (1 + strlen (dguide_base)
25612 + IDENTIFIER_LENGTH (tname));
25613 memcpy (buf, dguide_base, strlen (dguide_base));
25614 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
25615 IDENTIFIER_LENGTH (tname) + 1);
25616 tree dname = get_identifier (buf);
25617 TREE_TYPE (dname) = type;
25618 return dname;
25621 /* True if NAME is the name of a deduction guide. */
25623 bool
25624 dguide_name_p (tree name)
25626 return (TREE_CODE (name) == IDENTIFIER_NODE
25627 && TREE_TYPE (name)
25628 && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
25629 strlen (dguide_base)));
25632 /* True if FN is a deduction guide. */
25634 bool
25635 deduction_guide_p (const_tree fn)
25637 if (DECL_P (fn))
25638 if (tree name = DECL_NAME (fn))
25639 return dguide_name_p (name);
25640 return false;
25643 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
25645 bool
25646 copy_guide_p (const_tree fn)
25648 gcc_assert (deduction_guide_p (fn));
25649 if (!DECL_ARTIFICIAL (fn))
25650 return false;
25651 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
25652 return (TREE_CHAIN (parms) == void_list_node
25653 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
25656 /* True if FN is a guide generated from a constructor template. */
25658 bool
25659 template_guide_p (const_tree fn)
25661 gcc_assert (deduction_guide_p (fn));
25662 if (!DECL_ARTIFICIAL (fn))
25663 return false;
25664 tree tmpl = DECL_TI_TEMPLATE (fn);
25665 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
25666 return PRIMARY_TEMPLATE_P (org);
25667 return false;
25670 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
25671 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
25672 template parameter types. Note that the handling of template template
25673 parameters relies on current_template_parms being set appropriately for the
25674 new template. */
25676 static tree
25677 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
25678 tree tsubst_args, tsubst_flags_t complain)
25680 tree oldidx = get_template_parm_index (olddecl);
25682 tree newtype;
25683 if (TREE_CODE (olddecl) == TYPE_DECL
25684 || TREE_CODE (olddecl) == TEMPLATE_DECL)
25686 tree oldtype = TREE_TYPE (olddecl);
25687 newtype = cxx_make_type (TREE_CODE (oldtype));
25688 TYPE_MAIN_VARIANT (newtype) = newtype;
25689 if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
25690 TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
25691 = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
25693 else
25694 newtype = tsubst (TREE_TYPE (olddecl), tsubst_args,
25695 complain, NULL_TREE);
25697 tree newdecl
25698 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
25699 DECL_NAME (olddecl), newtype);
25700 SET_DECL_TEMPLATE_PARM_P (newdecl);
25702 tree newidx;
25703 if (TREE_CODE (olddecl) == TYPE_DECL
25704 || TREE_CODE (olddecl) == TEMPLATE_DECL)
25706 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
25707 = build_template_parm_index (index, level, level,
25708 newdecl, newtype);
25709 TEMPLATE_PARM_PARAMETER_PACK (newidx)
25710 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
25711 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
25712 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
25714 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
25716 DECL_TEMPLATE_RESULT (newdecl)
25717 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
25718 DECL_NAME (olddecl), newtype);
25719 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
25720 // First create a copy (ttargs) of tsubst_args with an
25721 // additional level for the template template parameter's own
25722 // template parameters (ttparms).
25723 tree ttparms = (INNERMOST_TEMPLATE_PARMS
25724 (DECL_TEMPLATE_PARMS (olddecl)));
25725 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
25726 tree ttargs = make_tree_vec (depth + 1);
25727 for (int i = 0; i < depth; ++i)
25728 TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
25729 TREE_VEC_ELT (ttargs, depth)
25730 = template_parms_level_to_args (ttparms);
25731 // Substitute ttargs into ttparms to fix references to
25732 // other template parameters.
25733 ttparms = tsubst_template_parms_level (ttparms, ttargs,
25734 complain|tf_partial);
25735 // Now substitute again with args based on tparms, to reduce
25736 // the level of the ttparms.
25737 ttargs = current_template_args ();
25738 ttparms = tsubst_template_parms_level (ttparms, ttargs,
25739 complain);
25740 // Finally, tack the adjusted parms onto tparms.
25741 ttparms = tree_cons (size_int (depth), ttparms,
25742 current_template_parms);
25743 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
25746 else
25748 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
25749 tree newconst
25750 = build_decl (DECL_SOURCE_LOCATION (oldconst),
25751 TREE_CODE (oldconst),
25752 DECL_NAME (oldconst), newtype);
25753 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
25754 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
25755 SET_DECL_TEMPLATE_PARM_P (newconst);
25756 newidx = build_template_parm_index (index, level, level,
25757 newconst, newtype);
25758 TEMPLATE_PARM_PARAMETER_PACK (newidx)
25759 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
25760 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
25763 return newdecl;
25766 /* Returns a C++17 class deduction guide template based on the constructor
25767 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
25768 guide, or REFERENCE_TYPE for an implicit copy/move guide. */
25770 static tree
25771 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
25773 tree type, tparms, targs, fparms, fargs, ci;
25774 bool memtmpl = false;
25775 bool explicit_p;
25776 location_t loc;
25777 tree fn_tmpl = NULL_TREE;
25779 if (TYPE_P (ctor))
25781 type = ctor;
25782 bool copy_p = TREE_CODE (type) == REFERENCE_TYPE;
25783 if (copy_p)
25785 type = TREE_TYPE (type);
25786 fparms = tree_cons (NULL_TREE, type, void_list_node);
25788 else
25789 fparms = void_list_node;
25791 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
25792 tparms = DECL_TEMPLATE_PARMS (ctmpl);
25793 targs = CLASSTYPE_TI_ARGS (type);
25794 ci = NULL_TREE;
25795 fargs = NULL_TREE;
25796 loc = DECL_SOURCE_LOCATION (ctmpl);
25797 explicit_p = false;
25799 else
25801 ++processing_template_decl;
25803 fn_tmpl
25804 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
25805 : DECL_TI_TEMPLATE (ctor));
25806 if (outer_args)
25807 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
25808 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
25810 type = DECL_CONTEXT (ctor);
25812 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
25813 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
25814 fully specialized args for the enclosing class. Strip those off, as
25815 the deduction guide won't have those template parameters. */
25816 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
25817 TMPL_PARMS_DEPTH (tparms));
25818 /* Discard the 'this' parameter. */
25819 fparms = FUNCTION_ARG_CHAIN (ctor);
25820 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
25821 ci = get_constraints (ctor);
25822 loc = DECL_SOURCE_LOCATION (ctor);
25823 explicit_p = DECL_NONCONVERTING_P (ctor);
25825 if (PRIMARY_TEMPLATE_P (fn_tmpl))
25827 memtmpl = true;
25829 /* For a member template constructor, we need to flatten the two
25830 template parameter lists into one, and then adjust the function
25831 signature accordingly. This gets...complicated. */
25832 tree save_parms = current_template_parms;
25834 /* For a member template we should have two levels of parms/args, one
25835 for the class and one for the constructor. We stripped
25836 specialized args for further enclosing classes above. */
25837 const int depth = 2;
25838 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
25840 /* Template args for translating references to the two-level template
25841 parameters into references to the one-level template parameters we
25842 are creating. */
25843 tree tsubst_args = copy_node (targs);
25844 TMPL_ARGS_LEVEL (tsubst_args, depth)
25845 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
25847 /* Template parms for the constructor template. */
25848 tree ftparms = TREE_VALUE (tparms);
25849 unsigned flen = TREE_VEC_LENGTH (ftparms);
25850 /* Template parms for the class template. */
25851 tparms = TREE_CHAIN (tparms);
25852 tree ctparms = TREE_VALUE (tparms);
25853 unsigned clen = TREE_VEC_LENGTH (ctparms);
25854 /* Template parms for the deduction guide start as a copy of the
25855 template parms for the class. We set current_template_parms for
25856 lookup_template_class_1. */
25857 current_template_parms = tparms = copy_node (tparms);
25858 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
25859 for (unsigned i = 0; i < clen; ++i)
25860 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
25862 /* Now we need to rewrite the constructor parms to append them to the
25863 class parms. */
25864 for (unsigned i = 0; i < flen; ++i)
25866 unsigned index = i + clen;
25867 unsigned level = 1;
25868 tree oldelt = TREE_VEC_ELT (ftparms, i);
25869 tree olddecl = TREE_VALUE (oldelt);
25870 tree newdecl = rewrite_template_parm (olddecl, index, level,
25871 tsubst_args, complain);
25872 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
25873 tsubst_args, complain, ctor);
25874 tree list = build_tree_list (newdef, newdecl);
25875 TEMPLATE_PARM_CONSTRAINTS (list)
25876 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
25877 tsubst_args, complain, ctor);
25878 TREE_VEC_ELT (new_vec, index) = list;
25879 TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
25882 /* Now we have a final set of template parms to substitute into the
25883 function signature. */
25884 targs = template_parms_to_args (tparms);
25885 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
25886 complain, ctor);
25887 fargs = tsubst (fargs, tsubst_args, complain, ctor);
25888 if (ci)
25889 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
25891 current_template_parms = save_parms;
25893 --processing_template_decl;
25896 if (!memtmpl)
25898 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
25899 tparms = copy_node (tparms);
25900 INNERMOST_TEMPLATE_PARMS (tparms)
25901 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
25904 tree fntype = build_function_type (type, fparms);
25905 tree ded_fn = build_lang_decl_loc (loc,
25906 FUNCTION_DECL,
25907 dguide_name (type), fntype);
25908 DECL_ARGUMENTS (ded_fn) = fargs;
25909 DECL_ARTIFICIAL (ded_fn) = true;
25910 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
25911 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
25912 DECL_ARTIFICIAL (ded_tmpl) = true;
25913 DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
25914 TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
25915 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
25916 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
25917 if (DECL_P (ctor))
25918 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
25919 if (ci)
25920 set_constraints (ded_tmpl, ci);
25922 return ded_tmpl;
25925 /* Deduce template arguments for the class template placeholder PTYPE for
25926 template TMPL based on the initializer INIT, and return the resulting
25927 type. */
25929 static tree
25930 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
25931 tsubst_flags_t complain)
25933 if (!DECL_CLASS_TEMPLATE_P (tmpl))
25935 /* We should have handled this in the caller. */
25936 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
25937 return ptype;
25938 if (complain & tf_error)
25939 error ("non-class template %qT used without template arguments", tmpl);
25940 return error_mark_node;
25943 tree type = TREE_TYPE (tmpl);
25945 bool try_list_ctor = false;
25947 vec<tree,va_gc> *args;
25948 if (init == NULL_TREE
25949 || TREE_CODE (init) == TREE_LIST)
25950 args = make_tree_vector_from_list (init);
25951 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
25953 try_list_ctor = TYPE_HAS_LIST_CTOR (type);
25954 if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
25956 /* As an exception, the first phase in 16.3.1.7 (considering the
25957 initializer list as a single argument) is omitted if the
25958 initializer list consists of a single expression of type cv U,
25959 where U is a specialization of C or a class derived from a
25960 specialization of C. */
25961 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
25962 tree etype = TREE_TYPE (elt);
25964 tree tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
25965 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
25966 int err = unify (tparms, targs, type, etype,
25967 UNIFY_ALLOW_DERIVED, /*explain*/false);
25968 if (err == 0)
25969 try_list_ctor = false;
25970 ggc_free (targs);
25972 if (try_list_ctor || is_std_init_list (type))
25973 args = make_tree_vector_single (init);
25974 else
25975 args = make_tree_vector_from_ctor (init);
25977 else
25978 args = make_tree_vector_single (init);
25980 tree dname = dguide_name (tmpl);
25981 tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
25982 /*type*/false, /*complain*/false,
25983 /*hidden*/false);
25984 bool elided = false;
25985 if (cands == error_mark_node)
25986 cands = NULL_TREE;
25988 /* Prune explicit deduction guides in copy-initialization context. */
25989 if (flags & LOOKUP_ONLYCONVERTING)
25991 for (lkp_iterator iter (cands); !elided && iter; ++iter)
25992 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
25993 elided = true;
25995 if (elided)
25997 /* Found a nonconverting guide, prune the candidates. */
25998 tree pruned = NULL_TREE;
25999 for (lkp_iterator iter (cands); iter; ++iter)
26000 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26001 pruned = lookup_add (*iter, pruned);
26003 cands = pruned;
26007 tree outer_args = NULL_TREE;
26008 if (DECL_CLASS_SCOPE_P (tmpl)
26009 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (tmpl)))
26011 outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
26012 type = TREE_TYPE (most_general_template (tmpl));
26015 bool saw_ctor = false;
26016 // FIXME cache artificial deduction guides
26017 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
26019 tree guide = build_deduction_guide (*iter, outer_args, complain);
26020 if ((flags & LOOKUP_ONLYCONVERTING)
26021 && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
26022 elided = true;
26023 else
26024 cands = lookup_add (guide, cands);
26026 saw_ctor = true;
26029 tree call = error_mark_node;
26031 /* If this is list-initialization and the class has a list constructor, first
26032 try deducing from the list as a single argument, as [over.match.list]. */
26033 tree list_cands = NULL_TREE;
26034 if (try_list_ctor && cands)
26035 for (lkp_iterator iter (cands); iter; ++iter)
26037 tree dg = *iter;
26038 if (is_list_ctor (dg))
26039 list_cands = lookup_add (dg, list_cands);
26041 if (list_cands)
26043 ++cp_unevaluated_operand;
26044 call = build_new_function_call (list_cands, &args, tf_decltype);
26045 --cp_unevaluated_operand;
26047 if (call == error_mark_node)
26049 /* That didn't work, now try treating the list as a sequence of
26050 arguments. */
26051 release_tree_vector (args);
26052 args = make_tree_vector_from_ctor (init);
26056 /* Maybe generate an implicit deduction guide. */
26057 if (call == error_mark_node && args->length () < 2)
26059 tree gtype = NULL_TREE;
26061 if (args->length () == 1)
26062 /* Generate a copy guide. */
26063 gtype = build_reference_type (type);
26064 else if (!saw_ctor)
26065 /* Generate a default guide. */
26066 gtype = type;
26068 if (gtype)
26070 tree guide = build_deduction_guide (gtype, outer_args, complain);
26071 cands = lookup_add (guide, cands);
26075 if (elided && !cands)
26077 error ("cannot deduce template arguments for copy-initialization"
26078 " of %qT, as it has no non-explicit deduction guides or "
26079 "user-declared constructors", type);
26080 return error_mark_node;
26082 else if (!cands && call == error_mark_node)
26084 error ("cannot deduce template arguments of %qT, as it has no viable "
26085 "deduction guides", type);
26086 return error_mark_node;
26089 if (call == error_mark_node)
26091 ++cp_unevaluated_operand;
26092 call = build_new_function_call (cands, &args, tf_decltype);
26093 --cp_unevaluated_operand;
26096 if (call == error_mark_node && (complain & tf_warning_or_error))
26098 error ("class template argument deduction failed:");
26100 ++cp_unevaluated_operand;
26101 call = build_new_function_call (cands, &args, complain | tf_decltype);
26102 --cp_unevaluated_operand;
26104 if (elided)
26105 inform (input_location, "explicit deduction guides not considered "
26106 "for copy-initialization");
26109 release_tree_vector (args);
26111 return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
26114 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
26115 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
26116 The CONTEXT determines the context in which auto deduction is performed
26117 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
26118 OUTER_TARGS are used during template argument deduction
26119 (context == adc_unify) to properly substitute the result, and is ignored
26120 in other contexts.
26122 For partial-concept-ids, extra args may be appended to the list of deduced
26123 template arguments prior to determining constraint satisfaction. */
26125 tree
26126 do_auto_deduction (tree type, tree init, tree auto_node,
26127 tsubst_flags_t complain, auto_deduction_context context,
26128 tree outer_targs, int flags)
26130 tree targs;
26132 if (init == error_mark_node)
26133 return error_mark_node;
26135 if (init && type_dependent_expression_p (init)
26136 && context != adc_unify)
26137 /* Defining a subset of type-dependent expressions that we can deduce
26138 from ahead of time isn't worth the trouble. */
26139 return type;
26141 /* Similarly, we can't deduce from another undeduced decl. */
26142 if (init && undeduced_auto_decl (init))
26143 return type;
26145 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
26146 /* C++17 class template argument deduction. */
26147 return do_class_deduction (type, tmpl, init, flags, complain);
26149 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
26150 /* Nothing we can do with this, even in deduction context. */
26151 return type;
26153 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
26154 with either a new invented type template parameter U or, if the
26155 initializer is a braced-init-list (8.5.4), with
26156 std::initializer_list<U>. */
26157 if (BRACE_ENCLOSED_INITIALIZER_P (init))
26159 if (!DIRECT_LIST_INIT_P (init))
26160 type = listify_autos (type, auto_node);
26161 else if (CONSTRUCTOR_NELTS (init) == 1)
26162 init = CONSTRUCTOR_ELT (init, 0)->value;
26163 else
26165 if (complain & tf_warning_or_error)
26167 if (permerror (input_location, "direct-list-initialization of "
26168 "%<auto%> requires exactly one element"))
26169 inform (input_location,
26170 "for deduction to %<std::initializer_list%>, use copy-"
26171 "list-initialization (i.e. add %<=%> before the %<{%>)");
26173 type = listify_autos (type, auto_node);
26177 if (type == error_mark_node)
26178 return error_mark_node;
26180 init = resolve_nondeduced_context (init, complain);
26182 if (context == adc_decomp_type
26183 && auto_node == type
26184 && init != error_mark_node
26185 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
26186 /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
26187 and initializer has array type, deduce cv-qualified array type. */
26188 return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
26189 complain);
26190 else if (AUTO_IS_DECLTYPE (auto_node))
26192 bool id = (DECL_P (init)
26193 || ((TREE_CODE (init) == COMPONENT_REF
26194 || TREE_CODE (init) == SCOPE_REF)
26195 && !REF_PARENTHESIZED_P (init)));
26196 targs = make_tree_vec (1);
26197 TREE_VEC_ELT (targs, 0)
26198 = finish_decltype_type (init, id, tf_warning_or_error);
26199 if (type != auto_node)
26201 if (complain & tf_error)
26202 error ("%qT as type rather than plain %<decltype(auto)%>", type);
26203 return error_mark_node;
26206 else
26208 tree parms = build_tree_list (NULL_TREE, type);
26209 tree tparms;
26211 if (flag_concepts)
26212 tparms = extract_autos (type);
26213 else
26215 tparms = make_tree_vec (1);
26216 TREE_VEC_ELT (tparms, 0)
26217 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
26220 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26221 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
26222 DEDUCE_CALL, LOOKUP_NORMAL,
26223 NULL, /*explain_p=*/false);
26224 if (val > 0)
26226 if (processing_template_decl)
26227 /* Try again at instantiation time. */
26228 return type;
26229 if (type && type != error_mark_node
26230 && (complain & tf_error))
26231 /* If type is error_mark_node a diagnostic must have been
26232 emitted by now. Also, having a mention to '<type error>'
26233 in the diagnostic is not really useful to the user. */
26235 if (cfun && auto_node == current_function_auto_return_pattern
26236 && LAMBDA_FUNCTION_P (current_function_decl))
26237 error ("unable to deduce lambda return type from %qE", init);
26238 else
26239 error ("unable to deduce %qT from %qE", type, init);
26240 type_unification_real (tparms, targs, parms, &init, 1, 0,
26241 DEDUCE_CALL, LOOKUP_NORMAL,
26242 NULL, /*explain_p=*/true);
26244 return error_mark_node;
26248 /* Check any placeholder constraints against the deduced type. */
26249 if (flag_concepts && !processing_template_decl)
26250 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
26252 /* Use the deduced type to check the associated constraints. If we
26253 have a partial-concept-id, rebuild the argument list so that
26254 we check using the extra arguments. */
26255 gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
26256 tree cargs = CHECK_CONSTR_ARGS (constr);
26257 if (TREE_VEC_LENGTH (cargs) > 1)
26259 cargs = copy_node (cargs);
26260 TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
26262 else
26263 cargs = targs;
26264 if (!constraints_satisfied_p (constr, cargs))
26266 if (complain & tf_warning_or_error)
26268 switch (context)
26270 case adc_unspecified:
26271 case adc_unify:
26272 error("placeholder constraints not satisfied");
26273 break;
26274 case adc_variable_type:
26275 case adc_decomp_type:
26276 error ("deduced initializer does not satisfy "
26277 "placeholder constraints");
26278 break;
26279 case adc_return_type:
26280 error ("deduced return type does not satisfy "
26281 "placeholder constraints");
26282 break;
26283 case adc_requirement:
26284 error ("deduced expression type does not satisfy "
26285 "placeholder constraints");
26286 break;
26288 diagnose_constraints (input_location, constr, targs);
26290 return error_mark_node;
26294 if (processing_template_decl && context != adc_unify)
26295 outer_targs = current_template_args ();
26296 targs = add_to_template_args (outer_targs, targs);
26297 return tsubst (type, targs, complain, NULL_TREE);
26300 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
26301 result. */
26303 tree
26304 splice_late_return_type (tree type, tree late_return_type)
26306 if (is_auto (type))
26308 if (late_return_type)
26309 return late_return_type;
26311 tree idx = get_template_parm_index (type);
26312 if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
26313 /* In an abbreviated function template we didn't know we were dealing
26314 with a function template when we saw the auto return type, so update
26315 it to have the correct level. */
26316 return make_auto_1 (TYPE_IDENTIFIER (type), true);
26318 return type;
26321 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
26322 'decltype(auto)' or a deduced class template. */
26324 bool
26325 is_auto (const_tree type)
26327 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26328 && (TYPE_IDENTIFIER (type) == auto_identifier
26329 || TYPE_IDENTIFIER (type) == decltype_auto_identifier
26330 || CLASS_PLACEHOLDER_TEMPLATE (type)))
26331 return true;
26332 else
26333 return false;
26336 /* for_each_template_parm callback for type_uses_auto. */
26339 is_auto_r (tree tp, void */*data*/)
26341 return is_auto (tp);
26344 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
26345 a use of `auto'. Returns NULL_TREE otherwise. */
26347 tree
26348 type_uses_auto (tree type)
26350 if (type == NULL_TREE)
26351 return NULL_TREE;
26352 else if (flag_concepts)
26354 /* The Concepts TS allows multiple autos in one type-specifier; just
26355 return the first one we find, do_auto_deduction will collect all of
26356 them. */
26357 if (uses_template_parms (type))
26358 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
26359 /*visited*/NULL, /*nondeduced*/true);
26360 else
26361 return NULL_TREE;
26363 else
26364 return find_type_usage (type, is_auto);
26367 /* For a given template T, return the vector of typedefs referenced
26368 in T for which access check is needed at T instantiation time.
26369 T is either a FUNCTION_DECL or a RECORD_TYPE.
26370 Those typedefs were added to T by the function
26371 append_type_to_template_for_access_check. */
26373 vec<qualified_typedef_usage_t, va_gc> *
26374 get_types_needing_access_check (tree t)
26376 tree ti;
26377 vec<qualified_typedef_usage_t, va_gc> *result = NULL;
26379 if (!t || t == error_mark_node)
26380 return NULL;
26382 if (!(ti = get_template_info (t)))
26383 return NULL;
26385 if (CLASS_TYPE_P (t)
26386 || TREE_CODE (t) == FUNCTION_DECL)
26388 if (!TI_TEMPLATE (ti))
26389 return NULL;
26391 result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
26394 return result;
26397 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
26398 tied to T. That list of typedefs will be access checked at
26399 T instantiation time.
26400 T is either a FUNCTION_DECL or a RECORD_TYPE.
26401 TYPE_DECL is a TYPE_DECL node representing a typedef.
26402 SCOPE is the scope through which TYPE_DECL is accessed.
26403 LOCATION is the location of the usage point of TYPE_DECL.
26405 This function is a subroutine of
26406 append_type_to_template_for_access_check. */
26408 static void
26409 append_type_to_template_for_access_check_1 (tree t,
26410 tree type_decl,
26411 tree scope,
26412 location_t location)
26414 qualified_typedef_usage_t typedef_usage;
26415 tree ti;
26417 if (!t || t == error_mark_node)
26418 return;
26420 gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
26421 || CLASS_TYPE_P (t))
26422 && type_decl
26423 && TREE_CODE (type_decl) == TYPE_DECL
26424 && scope);
26426 if (!(ti = get_template_info (t)))
26427 return;
26429 gcc_assert (TI_TEMPLATE (ti));
26431 typedef_usage.typedef_decl = type_decl;
26432 typedef_usage.context = scope;
26433 typedef_usage.locus = location;
26435 vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
26438 /* Append TYPE_DECL to the template TEMPL.
26439 TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
26440 At TEMPL instanciation time, TYPE_DECL will be checked to see
26441 if it can be accessed through SCOPE.
26442 LOCATION is the location of the usage point of TYPE_DECL.
26444 e.g. consider the following code snippet:
26446 class C
26448 typedef int myint;
26451 template<class U> struct S
26453 C::myint mi; // <-- usage point of the typedef C::myint
26456 S<char> s;
26458 At S<char> instantiation time, we need to check the access of C::myint
26459 In other words, we need to check the access of the myint typedef through
26460 the C scope. For that purpose, this function will add the myint typedef
26461 and the scope C through which its being accessed to a list of typedefs
26462 tied to the template S. That list will be walked at template instantiation
26463 time and access check performed on each typedefs it contains.
26464 Note that this particular code snippet should yield an error because
26465 myint is private to C. */
26467 void
26468 append_type_to_template_for_access_check (tree templ,
26469 tree type_decl,
26470 tree scope,
26471 location_t location)
26473 qualified_typedef_usage_t *iter;
26474 unsigned i;
26476 gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
26478 /* Make sure we don't append the type to the template twice. */
26479 FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
26480 if (iter->typedef_decl == type_decl && scope == iter->context)
26481 return;
26483 append_type_to_template_for_access_check_1 (templ, type_decl,
26484 scope, location);
26487 /* Convert the generic type parameters in PARM that match the types given in the
26488 range [START_IDX, END_IDX) from the current_template_parms into generic type
26489 packs. */
26491 tree
26492 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
26494 tree current = current_template_parms;
26495 int depth = TMPL_PARMS_DEPTH (current);
26496 current = INNERMOST_TEMPLATE_PARMS (current);
26497 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
26499 for (int i = 0; i < start_idx; ++i)
26500 TREE_VEC_ELT (replacement, i)
26501 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
26503 for (int i = start_idx; i < end_idx; ++i)
26505 /* Create a distinct parameter pack type from the current parm and add it
26506 to the replacement args to tsubst below into the generic function
26507 parameter. */
26509 tree o = TREE_TYPE (TREE_VALUE
26510 (TREE_VEC_ELT (current, i)));
26511 tree t = copy_type (o);
26512 TEMPLATE_TYPE_PARM_INDEX (t)
26513 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
26514 o, 0, 0, tf_none);
26515 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
26516 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
26517 TYPE_MAIN_VARIANT (t) = t;
26518 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
26519 TYPE_CANONICAL (t) = canonical_type_parameter (t);
26520 TREE_VEC_ELT (replacement, i) = t;
26521 TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
26524 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
26525 TREE_VEC_ELT (replacement, i)
26526 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
26528 /* If there are more levels then build up the replacement with the outer
26529 template parms. */
26530 if (depth > 1)
26531 replacement = add_to_template_args (template_parms_to_args
26532 (TREE_CHAIN (current_template_parms)),
26533 replacement);
26535 return tsubst (parm, replacement, tf_none, NULL_TREE);
26538 /* Entries in the decl_constraint hash table. */
26539 struct GTY((for_user)) constr_entry
26541 tree decl;
26542 tree ci;
26545 /* Hashing function and equality for constraint entries. */
26546 struct constr_hasher : ggc_ptr_hash<constr_entry>
26548 static hashval_t hash (constr_entry *e)
26550 return (hashval_t)DECL_UID (e->decl);
26553 static bool equal (constr_entry *e1, constr_entry *e2)
26555 return e1->decl == e2->decl;
26559 /* A mapping from declarations to constraint information. Note that
26560 both templates and their underlying declarations are mapped to the
26561 same constraint information.
26563 FIXME: This is defined in pt.c because garbage collection
26564 code is not being generated for constraint.cc. */
26566 static GTY (()) hash_table<constr_hasher> *decl_constraints;
26568 /* Returns the template constraints of declaration T. If T is not
26569 constrained, return NULL_TREE. Note that T must be non-null. */
26571 tree
26572 get_constraints (tree t)
26574 if (!flag_concepts)
26575 return NULL_TREE;
26577 gcc_assert (DECL_P (t));
26578 if (TREE_CODE (t) == TEMPLATE_DECL)
26579 t = DECL_TEMPLATE_RESULT (t);
26580 constr_entry elt = { t, NULL_TREE };
26581 constr_entry* found = decl_constraints->find (&elt);
26582 if (found)
26583 return found->ci;
26584 else
26585 return NULL_TREE;
26588 /* Associate the given constraint information CI with the declaration
26589 T. If T is a template, then the constraints are associated with
26590 its underlying declaration. Don't build associations if CI is
26591 NULL_TREE. */
26593 void
26594 set_constraints (tree t, tree ci)
26596 if (!ci)
26597 return;
26598 gcc_assert (t && flag_concepts);
26599 if (TREE_CODE (t) == TEMPLATE_DECL)
26600 t = DECL_TEMPLATE_RESULT (t);
26601 gcc_assert (!get_constraints (t));
26602 constr_entry elt = {t, ci};
26603 constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
26604 constr_entry* entry = ggc_alloc<constr_entry> ();
26605 *entry = elt;
26606 *slot = entry;
26609 /* Remove the associated constraints of the declaration T. */
26611 void
26612 remove_constraints (tree t)
26614 gcc_assert (DECL_P (t));
26615 if (TREE_CODE (t) == TEMPLATE_DECL)
26616 t = DECL_TEMPLATE_RESULT (t);
26618 constr_entry elt = {t, NULL_TREE};
26619 constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
26620 if (slot)
26621 decl_constraints->clear_slot (slot);
26624 /* Memoized satisfaction results for declarations. This
26625 maps the pair (constraint_info, arguments) to the result computed
26626 by constraints_satisfied_p. */
26628 struct GTY((for_user)) constraint_sat_entry
26630 tree ci;
26631 tree args;
26632 tree result;
26635 /* Hashing function and equality for constraint entries. */
26637 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
26639 static hashval_t hash (constraint_sat_entry *e)
26641 hashval_t val = iterative_hash_object(e->ci, 0);
26642 return iterative_hash_template_arg (e->args, val);
26645 static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
26647 return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
26651 /* Memoized satisfaction results for concept checks. */
26653 struct GTY((for_user)) concept_spec_entry
26655 tree tmpl;
26656 tree args;
26657 tree result;
26660 /* Hashing function and equality for constraint entries. */
26662 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
26664 static hashval_t hash (concept_spec_entry *e)
26666 return hash_tmpl_and_args (e->tmpl, e->args);
26669 static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
26671 ++comparing_specializations;
26672 bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
26673 --comparing_specializations;
26674 return eq;
26678 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
26679 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
26681 /* Search for a memoized satisfaction result. Returns one of the
26682 truth value nodes if previously memoized, or NULL_TREE otherwise. */
26684 tree
26685 lookup_constraint_satisfaction (tree ci, tree args)
26687 constraint_sat_entry elt = { ci, args, NULL_TREE };
26688 constraint_sat_entry* found = constraint_memos->find (&elt);
26689 if (found)
26690 return found->result;
26691 else
26692 return NULL_TREE;
26695 /* Memoize the result of a satisfication test. Returns the saved result. */
26697 tree
26698 memoize_constraint_satisfaction (tree ci, tree args, tree result)
26700 constraint_sat_entry elt = {ci, args, result};
26701 constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
26702 constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
26703 *entry = elt;
26704 *slot = entry;
26705 return result;
26708 /* Search for a memoized satisfaction result for a concept. */
26710 tree
26711 lookup_concept_satisfaction (tree tmpl, tree args)
26713 concept_spec_entry elt = { tmpl, args, NULL_TREE };
26714 concept_spec_entry* found = concept_memos->find (&elt);
26715 if (found)
26716 return found->result;
26717 else
26718 return NULL_TREE;
26721 /* Memoize the result of a concept check. Returns the saved result. */
26723 tree
26724 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
26726 concept_spec_entry elt = {tmpl, args, result};
26727 concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
26728 concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
26729 *entry = elt;
26730 *slot = entry;
26731 return result;
26734 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
26736 /* Returns a prior concept specialization. This returns the substituted
26737 and normalized constraints defined by the concept. */
26739 tree
26740 get_concept_expansion (tree tmpl, tree args)
26742 concept_spec_entry elt = { tmpl, args, NULL_TREE };
26743 concept_spec_entry* found = concept_expansions->find (&elt);
26744 if (found)
26745 return found->result;
26746 else
26747 return NULL_TREE;
26750 /* Save a concept expansion for later. */
26752 tree
26753 save_concept_expansion (tree tmpl, tree args, tree def)
26755 concept_spec_entry elt = {tmpl, args, def};
26756 concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
26757 concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
26758 *entry = elt;
26759 *slot = entry;
26760 return def;
26763 static hashval_t
26764 hash_subsumption_args (tree t1, tree t2)
26766 gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
26767 gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
26768 int val = 0;
26769 val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
26770 val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
26771 val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
26772 val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
26773 return val;
26776 /* Compare the constraints of two subsumption entries. The LEFT1 and
26777 LEFT2 arguments comprise the first subsumption pair and the RIGHT1
26778 and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
26780 static bool
26781 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
26783 if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
26784 if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
26785 if (comp_template_args (CHECK_CONSTR_ARGS (left1),
26786 CHECK_CONSTR_ARGS (right1)))
26787 return comp_template_args (CHECK_CONSTR_ARGS (left2),
26788 CHECK_CONSTR_ARGS (right2));
26789 return false;
26792 /* Key/value pair for learning and memoizing subsumption results. This
26793 associates a pair of check constraints (including arguments) with
26794 a boolean value indicating the result. */
26796 struct GTY((for_user)) subsumption_entry
26798 tree t1;
26799 tree t2;
26800 bool result;
26803 /* Hashing function and equality for constraint entries. */
26805 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
26807 static hashval_t hash (subsumption_entry *e)
26809 return hash_subsumption_args (e->t1, e->t2);
26812 static bool equal (subsumption_entry *e1, subsumption_entry *e2)
26814 ++comparing_specializations;
26815 bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
26816 --comparing_specializations;
26817 return eq;
26821 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
26823 /* Search for a previously cached subsumption result. */
26825 bool*
26826 lookup_subsumption_result (tree t1, tree t2)
26828 subsumption_entry elt = { t1, t2, false };
26829 subsumption_entry* found = subsumption_table->find (&elt);
26830 if (found)
26831 return &found->result;
26832 else
26833 return 0;
26836 /* Save a subsumption result. */
26838 bool
26839 save_subsumption_result (tree t1, tree t2, bool result)
26841 subsumption_entry elt = {t1, t2, result};
26842 subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
26843 subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
26844 *entry = elt;
26845 *slot = entry;
26846 return result;
26849 /* Set up the hash table for constraint association. */
26851 void
26852 init_constraint_processing (void)
26854 if (!flag_concepts)
26855 return;
26857 decl_constraints = hash_table<constr_hasher>::create_ggc(37);
26858 constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
26859 concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
26860 concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
26861 subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
26864 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
26865 0..N-1. */
26867 void
26868 declare_integer_pack (void)
26870 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
26871 build_function_type_list (integer_type_node,
26872 integer_type_node,
26873 NULL_TREE),
26874 NULL_TREE, ECF_CONST);
26875 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
26876 DECL_BUILT_IN_CLASS (ipfn) = BUILT_IN_FRONTEND;
26879 /* Set up the hash tables for template instantiations. */
26881 void
26882 init_template_processing (void)
26884 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
26885 type_specializations = hash_table<spec_hasher>::create_ggc (37);
26887 if (cxx_dialect >= cxx11)
26888 declare_integer_pack ();
26891 /* Print stats about the template hash tables for -fstats. */
26893 void
26894 print_template_statistics (void)
26896 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
26897 "%f collisions\n", (long) decl_specializations->size (),
26898 (long) decl_specializations->elements (),
26899 decl_specializations->collisions ());
26900 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
26901 "%f collisions\n", (long) type_specializations->size (),
26902 (long) type_specializations->elements (),
26903 type_specializations->collisions ());
26906 #if CHECKING_P
26908 namespace selftest {
26910 /* Verify that build_non_dependent_expr () works, for various expressions,
26911 and that location wrappers don't affect the results. */
26913 static void
26914 test_build_non_dependent_expr ()
26916 location_t loc = BUILTINS_LOCATION;
26918 /* Verify constants, without and with location wrappers. */
26919 tree int_cst = build_int_cst (integer_type_node, 42);
26920 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
26922 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
26923 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
26924 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
26926 tree string_lit = build_string (4, "foo");
26927 TREE_TYPE (string_lit) = char_array_type_node;
26928 string_lit = fix_string_type (string_lit);
26929 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
26931 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
26932 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
26933 ASSERT_EQ (wrapped_string_lit,
26934 build_non_dependent_expr (wrapped_string_lit));
26937 /* Verify that type_dependent_expression_p () works correctly, even
26938 in the presence of location wrapper nodes. */
26940 static void
26941 test_type_dependent_expression_p ()
26943 location_t loc = BUILTINS_LOCATION;
26945 tree name = get_identifier ("foo");
26947 /* If no templates are involved, nothing is type-dependent. */
26948 gcc_assert (!processing_template_decl);
26949 ASSERT_FALSE (type_dependent_expression_p (name));
26951 ++processing_template_decl;
26953 /* Within a template, an unresolved name is always type-dependent. */
26954 ASSERT_TRUE (type_dependent_expression_p (name));
26956 /* Ensure it copes with NULL_TREE and errors. */
26957 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
26958 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
26960 /* A USING_DECL in a template should be type-dependent, even if wrapped
26961 with a location wrapper (PR c++/83799). */
26962 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
26963 TREE_TYPE (using_decl) = integer_type_node;
26964 ASSERT_TRUE (type_dependent_expression_p (using_decl));
26965 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
26966 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
26967 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
26969 --processing_template_decl;
26972 /* Run all of the selftests within this file. */
26974 void
26975 cp_pt_c_tests ()
26977 test_build_non_dependent_expr ();
26978 test_type_dependent_expression_p ();
26981 } // namespace selftest
26983 #endif /* #if CHECKING_P */
26985 #include "gt-cp-pt.h"