1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2021 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12 
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 /* Known bugs or deficiencies include:
23 
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".
26 
27      Fixed by: C++20 modules.  */
28 
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "cp-tree.h"
33 #include "timevar.h"
34 #include "stringpool.h"
35 #include "varasm.h"
36 #include "attribs.h"
37 #include "stor-layout.h"
38 #include "intl.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "toplev.h"
42 #include "tree-iterator.h"
43 #include "type-utils.h"
44 #include "gimplify.h"
45 #include "gcc-rich-location.h"
46 #include "selftest.h"
47 #include "target.h"
48 
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52 
53 /* The PENDING_TEMPLATES is a list of templates whose instantiations
54    have been deferred, either because their definitions were not yet
55    available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template
57 {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61 
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64 
65 int processing_template_parmlist;
66 static int template_header_count;
67 
68 static vec<int> inline_parm_levels;
69 
70 static GTY(()) struct tinst_level *current_tinst_level;
71 
72 static GTY(()) vec<tree, va_gc> *saved_access_scope;
73 
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78 
79 // -------------------------------------------------------------------------- //
80 // Local Specialization Stack
81 //
82 // Implementation of the RAII helper for creating new local
83 // specializations.
local_specialization_stack(lss_policy policy)84 local_specialization_stack::local_specialization_stack (lss_policy policy)
85   : saved (local_specializations)
86 {
87   if (policy == lss_nop)
88     ;
89   else if (policy == lss_blank || !saved)
90     local_specializations = new hash_map<tree, tree>;
91   else
92     local_specializations = new hash_map<tree, tree>(*saved);
93 }
94 
~local_specialization_stack()95 local_specialization_stack::~local_specialization_stack ()
96 {
97   if (local_specializations != saved)
98     {
99       delete local_specializations;
100       local_specializations = saved;
101     }
102 }
103 
104 /* True if we've recursed into fn_type_unification too many times.  */
105 static bool excessive_deduction_depth;
106 
107 struct spec_hasher : ggc_ptr_hash<spec_entry>
108 {
109   static hashval_t hash (spec_entry *);
110   static bool equal (spec_entry *, spec_entry *);
111 };
112 
113 /* The general template is not in these tables.  */
114 typedef hash_table<spec_hasher> spec_hash_table;
115 static GTY (()) spec_hash_table *decl_specializations;
116 static GTY (()) spec_hash_table *type_specializations;
117 
118 /* Contains canonical template parameter types. The vector is indexed by
119    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
120    TREE_LIST, whose TREE_VALUEs contain the canonical template
121    parameters of various types and levels.  */
122 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
123 
124 #define UNIFY_ALLOW_NONE 0
125 #define UNIFY_ALLOW_MORE_CV_QUAL 1
126 #define UNIFY_ALLOW_LESS_CV_QUAL 2
127 #define UNIFY_ALLOW_DERIVED 4
128 #define UNIFY_ALLOW_INTEGER 8
129 #define UNIFY_ALLOW_OUTER_LEVEL 16
130 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
131 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
132 
133 enum template_base_result {
134   tbr_incomplete_type,
135   tbr_ambiguous_baseclass,
136   tbr_success
137 };
138 
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 bool check_instantiated_args (tree, tree, tsubst_flags_t);
155 static int check_non_deducible_conversion (tree, tree, int, int,
156 					   struct conversion **, bool);
157 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
158 					     tree);
159 static int type_unification_real (tree, tree, tree, const tree *,
160 				  unsigned int, int, unification_kind_t,
161 				  vec<deferred_access_check, va_gc> **,
162 				  bool);
163 static void note_template_header (int);
164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166 static tree convert_template_argument (tree, tree, tree,
167 				       tsubst_flags_t, int, tree);
168 static tree for_each_template_parm (tree, tree_fn_t, void*,
169 				    hash_set<tree> *, bool, tree_fn_t = NULL);
170 static tree expand_template_argument_pack (tree);
171 static tree build_template_parm_index (int, int, int, tree, tree);
172 static bool inline_needs_template_parms (tree, bool);
173 static void push_inline_template_parms_recursive (tree, int);
174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175 static int mark_template_parm (tree, void *);
176 static int template_parm_this_level_p (tree, void *);
177 static tree tsubst_friend_function (tree, tree);
178 static tree tsubst_friend_class (tree, tree);
179 static int can_complete_type_without_circularity (tree);
180 static tree get_bindings (tree, tree, tree, bool);
181 static int template_decl_level (tree);
182 static int check_cv_quals_for_unify (int, tree, tree);
183 static int unify_pack_expansion (tree, tree, tree,
184 				 tree, unification_kind_t, bool, bool);
185 static tree copy_template_args (tree);
186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187 tree most_specialized_partial_spec (tree, tsubst_flags_t);
188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
191 static bool check_specialization_scope (void);
192 static tree process_partial_specialization (tree);
193 static enum template_base_result get_template_base (tree, tree, tree, tree,
194 						    bool , tree *);
195 static tree try_class_unification (tree, tree, tree, tree, bool);
196 static bool class_nttp_const_wrapper_p (tree t);
197 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
198 					   tree, tree);
199 static bool template_template_parm_bindings_ok_p (tree, tree);
200 static void tsubst_default_arguments (tree, tsubst_flags_t);
201 static tree for_each_template_parm_r (tree *, int *, void *);
202 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
203 static void copy_default_args_to_explicit_spec (tree);
204 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
205 static bool dependent_template_arg_p (tree);
206 static bool any_template_arguments_need_structural_equality_p (tree);
207 static bool dependent_type_p_r (tree);
208 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_decl (tree, tree, tsubst_flags_t);
210 static void perform_instantiation_time_access_checks (tree, tree);
211 static tree listify (tree);
212 static tree listify_autos (tree, tree);
213 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
214 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
215 static bool complex_alias_template_p (const_tree tmpl);
216 static tree get_underlying_template (tree);
217 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
218 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
219 static tree make_argument_pack (tree);
220 static void register_parameter_specializations (tree, tree);
221 static tree enclosing_instantiation_of (tree tctx);
222 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
223 
224 /* Make the current scope suitable for access checking when we are
225    processing T.  T can be FUNCTION_DECL for instantiated function
226    template, VAR_DECL for static member variable, or TYPE_DECL for
227    alias template (needed by instantiate_decl).  */
228 
229 void
push_access_scope(tree t)230 push_access_scope (tree t)
231 {
232   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
233 	      || TREE_CODE (t) == TYPE_DECL);
234 
235   if (DECL_FRIEND_CONTEXT (t))
236     push_nested_class (DECL_FRIEND_CONTEXT (t));
237   else if (DECL_CLASS_SCOPE_P (t))
238     push_nested_class (DECL_CONTEXT (t));
239   else
240     push_to_top_level ();
241 
242   if (TREE_CODE (t) == FUNCTION_DECL)
243     {
244       vec_safe_push (saved_access_scope, current_function_decl);
245       current_function_decl = t;
246     }
247 }
248 
249 /* Restore the scope set up by push_access_scope.  T is the node we
250    are processing.  */
251 
252 void
pop_access_scope(tree t)253 pop_access_scope (tree t)
254 {
255   if (TREE_CODE (t) == FUNCTION_DECL)
256     current_function_decl = saved_access_scope->pop();
257 
258   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
259     pop_nested_class ();
260   else
261     pop_from_top_level ();
262 }
263 
264 /* Do any processing required when DECL (a member template
265    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
266    to DECL, unless it is a specialization, in which case the DECL
267    itself is returned.  */
268 
269 tree
finish_member_template_decl(tree decl)270 finish_member_template_decl (tree decl)
271 {
272   if (decl == error_mark_node)
273     return error_mark_node;
274 
275   gcc_assert (DECL_P (decl));
276 
277   if (TREE_CODE (decl) == TYPE_DECL)
278     {
279       tree type;
280 
281       type = TREE_TYPE (decl);
282       if (type == error_mark_node)
283 	return error_mark_node;
284       if (MAYBE_CLASS_TYPE_P (type)
285 	  && CLASSTYPE_TEMPLATE_INFO (type)
286 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
287 	{
288 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
289 	  check_member_template (tmpl);
290 	  return tmpl;
291 	}
292       return NULL_TREE;
293     }
294   else if (TREE_CODE (decl) == FIELD_DECL)
295     error_at (DECL_SOURCE_LOCATION (decl),
296 	      "data member %qD cannot be a member template", decl);
297   else if (DECL_TEMPLATE_INFO (decl))
298     {
299       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
300 	{
301 	  check_member_template (DECL_TI_TEMPLATE (decl));
302 	  return DECL_TI_TEMPLATE (decl);
303 	}
304       else
305 	return decl;
306     }
307   else
308     error_at (DECL_SOURCE_LOCATION (decl),
309 	      "invalid member template declaration %qD", decl);
310 
311   return error_mark_node;
312 }
313 
314 /* Create a template info node.  */
315 
316 tree
build_template_info(tree template_decl,tree template_args)317 build_template_info (tree template_decl, tree template_args)
318 {
319   tree result = make_node (TEMPLATE_INFO);
320   TI_TEMPLATE (result) = template_decl;
321   TI_ARGS (result) = template_args;
322   return result;
323 }
324 
325 /* Return the template info node corresponding to T, whatever T is.  */
326 
327 tree
get_template_info(const_tree t)328 get_template_info (const_tree t)
329 {
330   tree tinfo = NULL_TREE;
331 
332   if (!t || t == error_mark_node)
333     return NULL;
334 
335   if (TREE_CODE (t) == NAMESPACE_DECL
336       || TREE_CODE (t) == PARM_DECL)
337     return NULL;
338 
339   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
340     tinfo = DECL_TEMPLATE_INFO (t);
341 
342   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
343     t = TREE_TYPE (t);
344 
345   if (OVERLOAD_TYPE_P (t))
346     tinfo = TYPE_TEMPLATE_INFO (t);
347   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
348     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
349 
350   return tinfo;
351 }
352 
353 /* Returns the template nesting level of the indicated class TYPE.
354 
355    For example, in:
356      template <class T>
357      struct A
358      {
359        template <class U>
360        struct B {};
361      };
362 
363    A<T>::B<U> has depth two, while A<T> has depth one.
364    Both A<T>::B<int> and A<int>::B<U> have depth one, if
365    they are instantiations, not specializations.
366 
367    This function is guaranteed to return 0 if passed NULL_TREE so
368    that, for example, `template_class_depth (current_class_type)' is
369    always safe.  */
370 
371 int
template_class_depth(tree type)372 template_class_depth (tree type)
373 {
374   int depth;
375 
376   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
377     {
378       tree tinfo = get_template_info (type);
379 
380       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
381 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
382 	++depth;
383 
384       if (DECL_P (type))
385 	{
386 	  if (tree fctx = DECL_FRIEND_CONTEXT (type))
387 	    type = fctx;
388 	  else
389 	    type = CP_DECL_CONTEXT (type);
390 	}
391       else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
392 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
393       else
394 	type = CP_TYPE_CONTEXT (type);
395     }
396 
397   return depth;
398 }
399 
400 /* Return TRUE if NODE instantiates a template that has arguments of
401    its own, be it directly a primary template or indirectly through a
402    partial specializations.  */
403 static bool
instantiates_primary_template_p(tree node)404 instantiates_primary_template_p (tree node)
405 {
406   tree tinfo = get_template_info (node);
407   if (!tinfo)
408     return false;
409 
410   tree tmpl = TI_TEMPLATE (tinfo);
411   if (PRIMARY_TEMPLATE_P (tmpl))
412     return true;
413 
414   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
415     return false;
416 
417   /* So now we know we have a specialization, but it could be a full
418      or a partial specialization.  To tell which, compare the depth of
419      its template arguments with those of its context.  */
420 
421   tree ctxt = DECL_CONTEXT (tmpl);
422   tree ctinfo = get_template_info (ctxt);
423   if (!ctinfo)
424     return true;
425 
426   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
427 	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
428 }
429 
430 /* Subroutine of maybe_begin_member_template_processing.
431    Returns true if processing DECL needs us to push template parms.  */
432 
433 static bool
inline_needs_template_parms(tree decl,bool nsdmi)434 inline_needs_template_parms (tree decl, bool nsdmi)
435 {
436   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
437     return false;
438 
439   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
440 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
441 }
442 
443 /* Subroutine of maybe_begin_member_template_processing.
444    Push the template parms in PARMS, starting from LEVELS steps into the
445    chain, and ending at the beginning, since template parms are listed
446    innermost first.  */
447 
448 static void
push_inline_template_parms_recursive(tree parmlist,int levels)449 push_inline_template_parms_recursive (tree parmlist, int levels)
450 {
451   tree parms = TREE_VALUE (parmlist);
452   int i;
453 
454   if (levels > 1)
455     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
456 
457   ++processing_template_decl;
458   current_template_parms
459     = tree_cons (size_int (processing_template_decl),
460 		 parms, current_template_parms);
461   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
462 
463   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
464 	       NULL);
465   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
466     {
467       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
468 
469       if (error_operand_p (parm))
470 	continue;
471 
472       gcc_assert (DECL_P (parm));
473 
474       switch (TREE_CODE (parm))
475 	{
476 	case TYPE_DECL:
477 	case TEMPLATE_DECL:
478 	  pushdecl (parm);
479 	  break;
480 
481 	case PARM_DECL:
482 	  /* Push the CONST_DECL.  */
483 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
484 	  break;
485 
486 	default:
487 	  gcc_unreachable ();
488 	}
489     }
490 }
491 
492 /* Restore the template parameter context for a member template, a
493    friend template defined in a class definition, or a non-template
494    member of template class.  */
495 
496 void
maybe_begin_member_template_processing(tree decl)497 maybe_begin_member_template_processing (tree decl)
498 {
499   tree parms;
500   int levels = 0;
501   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
502 
503   if (nsdmi)
504     {
505       tree ctx = DECL_CONTEXT (decl);
506       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
507 	      /* Disregard full specializations (c++/60999).  */
508 	      && uses_template_parms (ctx)
509 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
510     }
511 
512   if (inline_needs_template_parms (decl, nsdmi))
513     {
514       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
515       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
516 
517       if (DECL_TEMPLATE_SPECIALIZATION (decl))
518 	{
519 	  --levels;
520 	  parms = TREE_CHAIN (parms);
521 	}
522 
523       push_inline_template_parms_recursive (parms, levels);
524     }
525 
526   /* Remember how many levels of template parameters we pushed so that
527      we can pop them later.  */
528   inline_parm_levels.safe_push (levels);
529 }
530 
531 /* Undo the effects of maybe_begin_member_template_processing.  */
532 
533 void
maybe_end_member_template_processing(void)534 maybe_end_member_template_processing (void)
535 {
536   int i;
537   int last;
538 
539   if (inline_parm_levels.length () == 0)
540     return;
541 
542   last = inline_parm_levels.pop ();
543   for (i = 0; i < last; ++i)
544     {
545       --processing_template_decl;
546       current_template_parms = TREE_CHAIN (current_template_parms);
547       poplevel (0, 0, 0);
548     }
549 }
550 
551 /* Return a new template argument vector which contains all of ARGS,
552    but has as its innermost set of arguments the EXTRA_ARGS.  */
553 
554 tree
add_to_template_args(tree args,tree extra_args)555 add_to_template_args (tree args, tree extra_args)
556 {
557   tree new_args;
558   int extra_depth;
559   int i;
560   int j;
561 
562   if (args == NULL_TREE || extra_args == error_mark_node)
563     return extra_args;
564 
565   extra_depth = TMPL_ARGS_DEPTH (extra_args);
566   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
567 
568   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
569     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
570 
571   for (j = 1; j <= extra_depth; ++j, ++i)
572     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
573 
574   return new_args;
575 }
576 
577 /* Like add_to_template_args, but only the outermost ARGS are added to
578    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
579    (EXTRA_ARGS) levels are added.  This function is used to combine
580    the template arguments from a partial instantiation with the
581    template arguments used to attain the full instantiation from the
582    partial instantiation.
583 
584    If ARGS is a TEMPLATE_DECL, use its parameters as args.  */
585 
586 tree
add_outermost_template_args(tree args,tree extra_args)587 add_outermost_template_args (tree args, tree extra_args)
588 {
589   tree new_args;
590 
591   if (!args)
592     return extra_args;
593   if (TREE_CODE (args) == TEMPLATE_DECL)
594     {
595       tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
596       args = TI_ARGS (ti);
597     }
598 
599   /* If there are more levels of EXTRA_ARGS than there are ARGS,
600      something very fishy is going on.  */
601   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
602 
603   /* If *all* the new arguments will be the EXTRA_ARGS, just return
604      them.  */
605   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
606     return extra_args;
607 
608   /* For the moment, we make ARGS look like it contains fewer levels.  */
609   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
610 
611   new_args = add_to_template_args (args, extra_args);
612 
613   /* Now, we restore ARGS to its full dimensions.  */
614   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
615 
616   return new_args;
617 }
618 
619 /* Return the N levels of innermost template arguments from the ARGS.  */
620 
621 tree
get_innermost_template_args(tree args,int n)622 get_innermost_template_args (tree args, int n)
623 {
624   tree new_args;
625   int extra_levels;
626   int i;
627 
628   gcc_assert (n >= 0);
629 
630   /* If N is 1, just return the innermost set of template arguments.  */
631   if (n == 1)
632     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
633 
634   /* If we're not removing anything, just return the arguments we were
635      given.  */
636   extra_levels = TMPL_ARGS_DEPTH (args) - n;
637   gcc_assert (extra_levels >= 0);
638   if (extra_levels == 0)
639     return args;
640 
641   /* Make a new set of arguments, not containing the outer arguments.  */
642   new_args = make_tree_vec (n);
643   for (i = 1; i <= n; ++i)
644     SET_TMPL_ARGS_LEVEL (new_args, i,
645 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
646 
647   return new_args;
648 }
649 
650 /* The inverse of get_innermost_template_args: Return all but the innermost
651    EXTRA_LEVELS levels of template arguments from the ARGS.  */
652 
653 static tree
strip_innermost_template_args(tree args,int extra_levels)654 strip_innermost_template_args (tree args, int extra_levels)
655 {
656   tree new_args;
657   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
658   int i;
659 
660   gcc_assert (n >= 0);
661 
662   /* If N is 1, just return the outermost set of template arguments.  */
663   if (n == 1)
664     return TMPL_ARGS_LEVEL (args, 1);
665 
666   /* If we're not removing anything, just return the arguments we were
667      given.  */
668   gcc_assert (extra_levels >= 0);
669   if (extra_levels == 0)
670     return args;
671 
672   /* Make a new set of arguments, not containing the inner arguments.  */
673   new_args = make_tree_vec (n);
674   for (i = 1; i <= n; ++i)
675     SET_TMPL_ARGS_LEVEL (new_args, i,
676 			 TMPL_ARGS_LEVEL (args, i));
677 
678   return new_args;
679 }
680 
681 /* We've got a template header coming up; push to a new level for storing
682    the parms.  */
683 
684 void
begin_template_parm_list(void)685 begin_template_parm_list (void)
686 {
687   /* We use a non-tag-transparent scope here, which causes pushtag to
688      put tags in this scope, rather than in the enclosing class or
689      namespace scope.  This is the right thing, since we want
690      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
691      global template class, push_template_decl handles putting the
692      TEMPLATE_DECL into top-level scope.  For a nested template class,
693      e.g.:
694 
695        template <class T> struct S1 {
696 	 template <class T> struct S2 {};
697        };
698 
699      pushtag contains special code to insert the TEMPLATE_DECL for S2
700      at the right scope.  */
701   begin_scope (sk_template_parms, NULL);
702   ++processing_template_decl;
703   ++processing_template_parmlist;
704   note_template_header (0);
705 
706   /* Add a dummy parameter level while we process the parameter list.  */
707   current_template_parms
708     = tree_cons (size_int (processing_template_decl),
709 		 make_tree_vec (0),
710 		 current_template_parms);
711 }
712 
713 /* This routine is called when a specialization is declared.  If it is
714    invalid to declare a specialization here, an error is reported and
715    false is returned, otherwise this routine will return true.  */
716 
717 static bool
check_specialization_scope(void)718 check_specialization_scope (void)
719 {
720   tree scope = current_scope ();
721 
722   /* [temp.expl.spec]
723 
724      An explicit specialization shall be declared in the namespace of
725      which the template is a member, or, for member templates, in the
726      namespace of which the enclosing class or enclosing class
727      template is a member.  An explicit specialization of a member
728      function, member class or static data member of a class template
729      shall be declared in the namespace of which the class template
730      is a member.  */
731   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
732     {
733       error ("explicit specialization in non-namespace scope %qD", scope);
734       return false;
735     }
736 
737   /* [temp.expl.spec]
738 
739      In an explicit specialization declaration for a member of a class
740      template or a member template that appears in namespace scope,
741      the member template and some of its enclosing class templates may
742      remain unspecialized, except that the declaration shall not
743      explicitly specialize a class member template if its enclosing
744      class templates are not explicitly specialized as well.  */
745   if (current_template_parms)
746     {
747       error ("enclosing class templates are not explicitly specialized");
748       return false;
749     }
750 
751   return true;
752 }
753 
754 /* We've just seen template <>.  */
755 
756 bool
begin_specialization(void)757 begin_specialization (void)
758 {
759   begin_scope (sk_template_spec, NULL);
760   note_template_header (1);
761   return check_specialization_scope ();
762 }
763 
764 /* Called at then end of processing a declaration preceded by
765    template<>.  */
766 
767 void
end_specialization(void)768 end_specialization (void)
769 {
770   finish_scope ();
771   reset_specialization ();
772 }
773 
774 /* Any template <>'s that we have seen thus far are not referring to a
775    function specialization.  */
776 
777 void
reset_specialization(void)778 reset_specialization (void)
779 {
780   processing_specialization = 0;
781   template_header_count = 0;
782 }
783 
784 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
785    it was of the form template <>.  */
786 
787 static void
note_template_header(int specialization)788 note_template_header (int specialization)
789 {
790   processing_specialization = specialization;
791   template_header_count++;
792 }
793 
794 /* We're beginning an explicit instantiation.  */
795 
796 void
begin_explicit_instantiation(void)797 begin_explicit_instantiation (void)
798 {
799   gcc_assert (!processing_explicit_instantiation);
800   processing_explicit_instantiation = true;
801 }
802 
803 
804 void
end_explicit_instantiation(void)805 end_explicit_instantiation (void)
806 {
807   gcc_assert (processing_explicit_instantiation);
808   processing_explicit_instantiation = false;
809 }
810 
811 /* An explicit specialization or partial specialization of TMPL is being
812    declared.  Check that the namespace in which the specialization is
813    occurring is permissible.  Returns false iff it is invalid to
814    specialize TMPL in the current namespace.  */
815 
816 static bool
check_specialization_namespace(tree tmpl)817 check_specialization_namespace (tree tmpl)
818 {
819   tree tpl_ns = decl_namespace_context (tmpl);
820 
821   /* [tmpl.expl.spec]
822 
823      An explicit specialization shall be declared in a namespace enclosing the
824      specialized template. An explicit specialization whose declarator-id is
825      not qualified shall be declared in the nearest enclosing namespace of the
826      template, or, if the namespace is inline (7.3.1), any namespace from its
827      enclosing namespace set.  */
828   if (current_scope() != DECL_CONTEXT (tmpl)
829       && !at_namespace_scope_p ())
830     {
831       error ("specialization of %qD must appear at namespace scope", tmpl);
832       return false;
833     }
834 
835   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
836     /* Same or enclosing namespace.  */
837     return true;
838   else
839     {
840       auto_diagnostic_group d;
841       if (permerror (input_location,
842 		     "specialization of %qD in different namespace", tmpl))
843 	inform (DECL_SOURCE_LOCATION (tmpl),
844 		"  from definition of %q#D", tmpl);
845       return false;
846     }
847 }
848 
849 /* SPEC is an explicit instantiation.  Check that it is valid to
850    perform this explicit instantiation in the current namespace.  */
851 
852 static void
check_explicit_instantiation_namespace(tree spec)853 check_explicit_instantiation_namespace (tree spec)
854 {
855   tree ns;
856 
857   /* DR 275: An explicit instantiation shall appear in an enclosing
858      namespace of its template.  */
859   ns = decl_namespace_context (spec);
860   if (!is_nested_namespace (current_namespace, ns))
861     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
862 	       "(which does not enclose namespace %qD)",
863 	       spec, current_namespace, ns);
864 }
865 
866 /* Returns the type of a template specialization only if that
867    specialization needs to be defined. Otherwise (e.g., if the type has
868    already been defined), the function returns NULL_TREE.  */
869 
870 static tree
maybe_new_partial_specialization(tree type)871 maybe_new_partial_specialization (tree type)
872 {
873   /* An implicit instantiation of an incomplete type implies
874      the definition of a new class template.
875 
876 	template<typename T>
877 	  struct S;
878 
879 	template<typename T>
880 	  struct S<T*>;
881 
882      Here, S<T*> is an implicit instantiation of S whose type
883      is incomplete.  */
884   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
885     return type;
886 
887   /* It can also be the case that TYPE is a completed specialization.
888      Continuing the previous example, suppose we also declare:
889 
890 	template<typename T>
891 	  requires Integral<T>
892 	    struct S<T*>;
893 
894      Here, S<T*> refers to the specialization S<T*> defined
895      above. However, we need to differentiate definitions because
896      we intend to define a new partial specialization. In this case,
897      we rely on the fact that the constraints are different for
898      this declaration than that above.
899 
900      Note that we also get here for injected class names and
901      late-parsed template definitions. We must ensure that we
902      do not create new type declarations for those cases.  */
903   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
904     {
905       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
906       tree args = CLASSTYPE_TI_ARGS (type);
907 
908       /* If there are no template parameters, this cannot be a new
909 	 partial template specialization?  */
910       if (!current_template_parms)
911         return NULL_TREE;
912 
913       /* The injected-class-name is not a new partial specialization.  */
914       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
915 	return NULL_TREE;
916 
917       /* If the constraints are not the same as those of the primary
918 	 then, we can probably create a new specialization.  */
919       tree type_constr = current_template_constraints ();
920 
921       if (type == TREE_TYPE (tmpl))
922 	{
923 	  tree main_constr = get_constraints (tmpl);
924 	  if (equivalent_constraints (type_constr, main_constr))
925 	    return NULL_TREE;
926 	}
927 
928       /* Also, if there's a pre-existing specialization with matching
929 	 constraints, then this also isn't new.  */
930       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
931       while (specs)
932         {
933           tree spec_tmpl = TREE_VALUE (specs);
934           tree spec_args = TREE_PURPOSE (specs);
935           tree spec_constr = get_constraints (spec_tmpl);
936           if (comp_template_args (args, spec_args)
937 	      && equivalent_constraints (type_constr, spec_constr))
938             return NULL_TREE;
939           specs = TREE_CHAIN (specs);
940         }
941 
942       /* Create a new type node (and corresponding type decl)
943 	 for the newly declared specialization.  */
944       tree t = make_class_type (TREE_CODE (type));
945       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
946       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
947 
948       /* We only need a separate type node for storing the definition of this
949 	 partial specialization; uses of S<T*> are unconstrained, so all are
950 	 equivalent.  So keep TYPE_CANONICAL the same.  */
951       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
952 
953       /* Build the corresponding type decl.  */
954       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
955       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
956       DECL_SOURCE_LOCATION (d) = input_location;
957       TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
958       TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
959 
960       set_instantiating_module (d);
961       DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
962 
963       return t;
964     }
965 
966   return NULL_TREE;
967 }
968 
969 /* The TYPE is being declared.  If it is a template type, that means it
970    is a partial specialization.  Do appropriate error-checking.  */
971 
972 tree
maybe_process_partial_specialization(tree type)973 maybe_process_partial_specialization (tree type)
974 {
975   tree context;
976 
977   if (type == error_mark_node)
978     return error_mark_node;
979 
980   /* A lambda that appears in specialization context is not itself a
981      specialization.  */
982   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
983     return type;
984 
985   /* An injected-class-name is not a specialization.  */
986   if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
987     return type;
988 
989   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
990     {
991       error ("name of class shadows template template parameter %qD",
992 	     TYPE_NAME (type));
993       return error_mark_node;
994     }
995 
996   context = TYPE_CONTEXT (type);
997 
998   if (TYPE_ALIAS_P (type))
999     {
1000       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1001 
1002       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1003 	error ("specialization of alias template %qD",
1004 	       TI_TEMPLATE (tinfo));
1005       else
1006 	error ("explicit specialization of non-template %qT", type);
1007       return error_mark_node;
1008     }
1009   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1010     {
1011       /* This is for ordinary explicit specialization and partial
1012 	 specialization of a template class such as:
1013 
1014 	   template <> class C<int>;
1015 
1016 	 or:
1017 
1018 	   template <class T> class C<T*>;
1019 
1020 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1021 
1022       if (tree t = maybe_new_partial_specialization (type))
1023 	{
1024 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1025 	      && !at_namespace_scope_p ())
1026 	    return error_mark_node;
1027 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1028 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1029 	  if (processing_template_decl)
1030 	    {
1031 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1032 	      if (decl == error_mark_node)
1033 		return error_mark_node;
1034 	      return TREE_TYPE (decl);
1035 	    }
1036 	}
1037       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1038 	error ("specialization of %qT after instantiation", type);
1039       else if (errorcount && !processing_specialization
1040 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1041 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1042 	/* Trying to define a specialization either without a template<> header
1043 	   or in an inappropriate place.  We've already given an error, so just
1044 	   bail now so we don't actually define the specialization.  */
1045 	return error_mark_node;
1046     }
1047   else if (CLASS_TYPE_P (type)
1048 	   && !CLASSTYPE_USE_TEMPLATE (type)
1049 	   && CLASSTYPE_TEMPLATE_INFO (type)
1050 	   && context && CLASS_TYPE_P (context)
1051 	   && CLASSTYPE_TEMPLATE_INFO (context))
1052     {
1053       /* This is for an explicit specialization of member class
1054 	 template according to [temp.expl.spec/18]:
1055 
1056 	   template <> template <class U> class C<int>::D;
1057 
1058 	 The context `C<int>' must be an implicit instantiation.
1059 	 Otherwise this is just a member class template declared
1060 	 earlier like:
1061 
1062 	   template <> class C<int> { template <class U> class D; };
1063 	   template <> template <class U> class C<int>::D;
1064 
1065 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1066 	 while in the second case, `C<int>::D' is a primary template
1067 	 and `C<T>::D' may not exist.  */
1068 
1069       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1070 	  && !COMPLETE_TYPE_P (type))
1071 	{
1072 	  tree t;
1073 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1074 
1075 	  if (current_namespace
1076 	      != decl_namespace_context (tmpl))
1077 	    {
1078 	      if (permerror (input_location,
1079 			     "specialization of %qD in different namespace",
1080 			     type))
1081 		inform (DECL_SOURCE_LOCATION (tmpl),
1082 			"from definition of %q#D", tmpl);
1083 	    }
1084 
1085 	  /* Check for invalid specialization after instantiation:
1086 
1087 	       template <> template <> class C<int>::D<int>;
1088 	       template <> template <class U> class C<int>::D;  */
1089 
1090 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1091 	       t; t = TREE_CHAIN (t))
1092 	    {
1093 	      tree inst = TREE_VALUE (t);
1094 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1095 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1096 		{
1097 		  /* We already have a full specialization of this partial
1098 		     instantiation, or a full specialization has been
1099 		     looked up but not instantiated.  Reassign it to the
1100 		     new member specialization template.  */
1101 		  spec_entry elt;
1102 		  spec_entry *entry;
1103 
1104 		  elt.tmpl = most_general_template (tmpl);
1105 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1106 		  elt.spec = inst;
1107 
1108 		  type_specializations->remove_elt (&elt);
1109 
1110 		  elt.tmpl = tmpl;
1111 		  CLASSTYPE_TI_ARGS (inst)
1112 		    = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1113 
1114 		  spec_entry **slot
1115 		    = type_specializations->find_slot (&elt, INSERT);
1116 		  entry = ggc_alloc<spec_entry> ();
1117 		  *entry = elt;
1118 		  *slot = entry;
1119 		}
1120 	      else
1121 		/* But if we've had an implicit instantiation, that's a
1122 		   problem ([temp.expl.spec]/6).  */
1123 		error ("specialization %qT after instantiation %qT",
1124 		       type, inst);
1125 	    }
1126 
1127 	  /* Mark TYPE as a specialization.  And as a result, we only
1128 	     have one level of template argument for the innermost
1129 	     class template.  */
1130 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1131 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1132 	  CLASSTYPE_TI_ARGS (type)
1133 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1134 	}
1135     }
1136   else if (processing_specialization)
1137     {
1138        /* Someday C++0x may allow for enum template specialization.  */
1139       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1140 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1141 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1142 		 "of %qD not allowed by ISO C++", type);
1143       else
1144 	{
1145 	  error ("explicit specialization of non-template %qT", type);
1146 	  return error_mark_node;
1147 	}
1148     }
1149 
1150   return type;
1151 }
1152 
1153 /* Returns nonzero if we can optimize the retrieval of specializations
1154    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1155    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1156 
1157 static inline bool
optimize_specialization_lookup_p(tree tmpl)1158 optimize_specialization_lookup_p (tree tmpl)
1159 {
1160   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1161 	  && DECL_CLASS_SCOPE_P (tmpl)
1162 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1163 	     parameter.  */
1164 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1165 	  /* The optimized lookup depends on the fact that the
1166 	     template arguments for the member function template apply
1167 	     purely to the containing class, which is not true if the
1168 	     containing class is an explicit or partial
1169 	     specialization.  */
1170 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1171 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1172 	  && !DECL_CONV_FN_P (tmpl)
1173 	  /* It is possible to have a template that is not a member
1174 	     template and is not a member of a template class:
1175 
1176 	     template <typename T>
1177 	     struct S { friend A::f(); };
1178 
1179 	     Here, the friend function is a template, but the context does
1180 	     not have template information.  The optimized lookup relies
1181 	     on having ARGS be the template arguments for both the class
1182 	     and the function template.  */
1183 	  && !DECL_UNIQUE_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1184 }
1185 
1186 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1187    gone through coerce_template_parms by now.  */
1188 
1189 static void
verify_unstripped_args_1(tree inner)1190 verify_unstripped_args_1 (tree inner)
1191 {
1192   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1193     {
1194       tree arg = TREE_VEC_ELT (inner, i);
1195       if (TREE_CODE (arg) == TEMPLATE_DECL)
1196 	/* OK */;
1197       else if (TYPE_P (arg))
1198 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1199       else if (ARGUMENT_PACK_P (arg))
1200 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1201       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1202 	/* Allow typedefs on the type of a non-type argument, since a
1203 	   parameter can have them.  */;
1204       else
1205 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1206     }
1207 }
1208 
1209 static void
verify_unstripped_args(tree args)1210 verify_unstripped_args (tree args)
1211 {
1212   ++processing_template_decl;
1213   if (!any_dependent_template_arguments_p (args))
1214     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1215   --processing_template_decl;
1216 }
1217 
1218 /* Retrieve the specialization (in the sense of [temp.spec] - a
1219    specialization is either an instantiation or an explicit
1220    specialization) of TMPL for the given template ARGS.  If there is
1221    no such specialization, return NULL_TREE.  The ARGS are a vector of
1222    arguments, or a vector of vectors of arguments, in the case of
1223    templates with more than one level of parameters.
1224 
1225    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1226    then we search for a partial specialization matching ARGS.  This
1227    parameter is ignored if TMPL is not a class template.
1228 
1229    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1230    result is a NONTYPE_ARGUMENT_PACK.  */
1231 
1232 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1233 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1234 {
1235   if (tmpl == NULL_TREE)
1236     return NULL_TREE;
1237 
1238   if (args == error_mark_node)
1239     return NULL_TREE;
1240 
1241   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1242 	      || TREE_CODE (tmpl) == FIELD_DECL);
1243 
1244   /* There should be as many levels of arguments as there are
1245      levels of parameters.  */
1246   gcc_assert (TMPL_ARGS_DEPTH (args)
1247 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1248 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1249 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1250 
1251   if (flag_checking)
1252     verify_unstripped_args (args);
1253 
1254   /* Lambda functions in templates aren't instantiated normally, but through
1255      tsubst_lambda_expr.  */
1256   if (lambda_fn_in_template_p (tmpl))
1257     return NULL_TREE;
1258 
1259   if (optimize_specialization_lookup_p (tmpl))
1260     {
1261       /* The template arguments actually apply to the containing
1262 	 class.  Find the class specialization with those
1263 	 arguments.  */
1264       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1265       tree class_specialization
1266 	= retrieve_specialization (class_template, args, 0);
1267       if (!class_specialization)
1268 	return NULL_TREE;
1269 
1270       /* Find the instance of TMPL.  */
1271       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1272       for (ovl_iterator iter (fns); iter; ++iter)
1273 	{
1274 	  tree fn = *iter;
1275 	  if (tree ti = get_template_info (fn))
1276 	    if (TI_TEMPLATE (ti) == tmpl
1277 		/* using-declarations can bring in a different
1278 		   instantiation of tmpl as a member of a different
1279 		   instantiation of tmpl's class.  We don't want those
1280 		   here.  */
1281 		&& DECL_CONTEXT (fn) == class_specialization)
1282 	      return fn;
1283 	}
1284       return NULL_TREE;
1285     }
1286   else
1287     {
1288       spec_entry *found;
1289       spec_entry elt;
1290       spec_hash_table *specializations;
1291 
1292       elt.tmpl = tmpl;
1293       elt.args = args;
1294       elt.spec = NULL_TREE;
1295 
1296       if (DECL_CLASS_TEMPLATE_P (tmpl))
1297 	specializations = type_specializations;
1298       else
1299 	specializations = decl_specializations;
1300 
1301       if (hash == 0)
1302 	hash = spec_hasher::hash (&elt);
1303       found = specializations->find_with_hash (&elt, hash);
1304       if (found)
1305 	return found->spec;
1306     }
1307 
1308   return NULL_TREE;
1309 }
1310 
1311 /* Like retrieve_specialization, but for local declarations.  */
1312 
1313 tree
retrieve_local_specialization(tree tmpl)1314 retrieve_local_specialization (tree tmpl)
1315 {
1316   if (local_specializations == NULL)
1317     return NULL_TREE;
1318 
1319   tree *slot = local_specializations->get (tmpl);
1320   return slot ? *slot : NULL_TREE;
1321 }
1322 
1323 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1324 
1325 int
is_specialization_of(tree decl,tree tmpl)1326 is_specialization_of (tree decl, tree tmpl)
1327 {
1328   tree t;
1329 
1330   if (TREE_CODE (decl) == FUNCTION_DECL)
1331     {
1332       for (t = decl;
1333 	   t != NULL_TREE;
1334 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1335 	if (t == tmpl)
1336 	  return 1;
1337     }
1338   else
1339     {
1340       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1341 
1342       for (t = TREE_TYPE (decl);
1343 	   t != NULL_TREE;
1344 	   t = CLASSTYPE_USE_TEMPLATE (t)
1345 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1346 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1347 	  return 1;
1348     }
1349 
1350   return 0;
1351 }
1352 
1353 /* Returns nonzero iff DECL is a specialization of friend declaration
1354    FRIEND_DECL according to [temp.friend].  */
1355 
1356 bool
is_specialization_of_friend(tree decl,tree friend_decl)1357 is_specialization_of_friend (tree decl, tree friend_decl)
1358 {
1359   bool need_template = true;
1360   int template_depth;
1361 
1362   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1363 	      || TREE_CODE (decl) == TYPE_DECL);
1364 
1365   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1366      of a template class, we want to check if DECL is a specialization
1367      if this.  */
1368   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1369       && DECL_TEMPLATE_INFO (friend_decl)
1370       && !DECL_USE_TEMPLATE (friend_decl))
1371     {
1372       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1373       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1374       need_template = false;
1375     }
1376   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1377 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1378     need_template = false;
1379 
1380   /* There is nothing to do if this is not a template friend.  */
1381   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1382     return false;
1383 
1384   if (is_specialization_of (decl, friend_decl))
1385     return true;
1386 
1387   /* [temp.friend/6]
1388      A member of a class template may be declared to be a friend of a
1389      non-template class.  In this case, the corresponding member of
1390      every specialization of the class template is a friend of the
1391      class granting friendship.
1392 
1393      For example, given a template friend declaration
1394 
1395        template <class T> friend void A<T>::f();
1396 
1397      the member function below is considered a friend
1398 
1399        template <> struct A<int> {
1400 	 void f();
1401        };
1402 
1403      For this type of template friend, TEMPLATE_DEPTH below will be
1404      nonzero.  To determine if DECL is a friend of FRIEND, we first
1405      check if the enclosing class is a specialization of another.  */
1406 
1407   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1408   if (template_depth
1409       && DECL_CLASS_SCOPE_P (decl)
1410       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1411 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1412     {
1413       /* Next, we check the members themselves.  In order to handle
1414 	 a few tricky cases, such as when FRIEND_DECL's are
1415 
1416 	   template <class T> friend void A<T>::g(T t);
1417 	   template <class T> template <T t> friend void A<T>::h();
1418 
1419 	 and DECL's are
1420 
1421 	   void A<int>::g(int);
1422 	   template <int> void A<int>::h();
1423 
1424 	 we need to figure out ARGS, the template arguments from
1425 	 the context of DECL.  This is required for template substitution
1426 	 of `T' in the function parameter of `g' and template parameter
1427 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1428 
1429       tree context = DECL_CONTEXT (decl);
1430       tree args = NULL_TREE;
1431       int current_depth = 0;
1432 
1433       while (current_depth < template_depth)
1434 	{
1435 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1436 	    {
1437 	      if (current_depth == 0)
1438 		args = TYPE_TI_ARGS (context);
1439 	      else
1440 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1441 	      current_depth++;
1442 	    }
1443 	  context = TYPE_CONTEXT (context);
1444 	}
1445 
1446       if (TREE_CODE (decl) == FUNCTION_DECL)
1447 	{
1448 	  bool is_template;
1449 	  tree friend_type;
1450 	  tree decl_type;
1451 	  tree friend_args_type;
1452 	  tree decl_args_type;
1453 
1454 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1455 	     non-templates.  */
1456 	  is_template = DECL_TEMPLATE_INFO (decl)
1457 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1458 	  if (need_template ^ is_template)
1459 	    return false;
1460 	  else if (is_template)
1461 	    {
1462 	      /* If both are templates, check template parameter list.  */
1463 	      tree friend_parms
1464 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1465 					 args, tf_none);
1466 	      if (!comp_template_parms
1467 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1468 		      friend_parms))
1469 		return false;
1470 
1471 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1472 	    }
1473 	  else
1474 	    decl_type = TREE_TYPE (decl);
1475 
1476 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1477 					      tf_none, NULL_TREE);
1478 	  if (friend_type == error_mark_node)
1479 	    return false;
1480 
1481 	  /* Check if return types match.  */
1482 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1483 	    return false;
1484 
1485 	  /* Check if function parameter types match, ignoring the
1486 	     `this' parameter.  */
1487 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1488 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1489 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1490 	    friend_args_type = TREE_CHAIN (friend_args_type);
1491 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1492 	    decl_args_type = TREE_CHAIN (decl_args_type);
1493 
1494 	  return compparms (decl_args_type, friend_args_type);
1495 	}
1496       else
1497 	{
1498 	  /* DECL is a TYPE_DECL */
1499 	  bool is_template;
1500 	  tree decl_type = TREE_TYPE (decl);
1501 
1502 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1503 	     non-templates.  */
1504 	  is_template
1505 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1506 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1507 
1508 	  if (need_template ^ is_template)
1509 	    return false;
1510 	  else if (is_template)
1511 	    {
1512 	      tree friend_parms;
1513 	      /* If both are templates, check the name of the two
1514 		 TEMPLATE_DECL's first because is_friend didn't.  */
1515 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1516 		  != DECL_NAME (friend_decl))
1517 		return false;
1518 
1519 	      /* Now check template parameter list.  */
1520 	      friend_parms
1521 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1522 					 args, tf_none);
1523 	      return comp_template_parms
1524 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1525 		 friend_parms);
1526 	    }
1527 	  else
1528 	    return (DECL_NAME (decl)
1529 		    == DECL_NAME (friend_decl));
1530 	}
1531     }
1532   return false;
1533 }
1534 
1535 /* Register the specialization SPEC as a specialization of TMPL with
1536    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1537    is actually just a friend declaration.  ATTRLIST is the list of
1538    attributes that the specialization is declared with or NULL when
1539    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1540    available.
1541 
1542    We also store instantiations of field packs in the hash table, even
1543    though they are not themselves templates, to make lookup easier.  */
1544 
1545 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1546 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1547 			 hashval_t hash)
1548 {
1549   tree fn;
1550   spec_entry **slot = NULL;
1551   spec_entry elt;
1552 
1553   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1554 	      || (TREE_CODE (tmpl) == FIELD_DECL
1555 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1556 
1557   if (TREE_CODE (spec) == FUNCTION_DECL
1558       && uses_template_parms (DECL_TI_ARGS (spec)))
1559     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1560        register it; we want the corresponding TEMPLATE_DECL instead.
1561        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1562        the more obvious `uses_template_parms (spec)' to avoid problems
1563        with default function arguments.  In particular, given
1564        something like this:
1565 
1566 	  template <class T> void f(T t1, T t = T())
1567 
1568        the default argument expression is not substituted for in an
1569        instantiation unless and until it is actually needed.  */
1570     return spec;
1571 
1572   if (optimize_specialization_lookup_p (tmpl))
1573     /* We don't put these specializations in the hash table, but we might
1574        want to give an error about a mismatch.  */
1575     fn = retrieve_specialization (tmpl, args, 0);
1576   else
1577     {
1578       elt.tmpl = tmpl;
1579       elt.args = args;
1580       elt.spec = spec;
1581 
1582       if (hash == 0)
1583 	hash = spec_hasher::hash (&elt);
1584 
1585       slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1586       if (*slot)
1587 	fn = (*slot)->spec;
1588       else
1589 	fn = NULL_TREE;
1590     }
1591 
1592   /* We can sometimes try to re-register a specialization that we've
1593      already got.  In particular, regenerate_decl_from_template calls
1594      duplicate_decls which will update the specialization list.  But,
1595      we'll still get called again here anyhow.  It's more convenient
1596      to simply allow this than to try to prevent it.  */
1597   if (fn == spec)
1598     return spec;
1599   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1600     {
1601       if (DECL_TEMPLATE_INSTANTIATION (fn))
1602 	{
1603 	  if (DECL_ODR_USED (fn)
1604 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1605 	    {
1606 	      error ("specialization of %qD after instantiation",
1607 		     fn);
1608 	      return error_mark_node;
1609 	    }
1610 	  else
1611 	    {
1612 	      tree clone;
1613 	      /* This situation should occur only if the first
1614 		 specialization is an implicit instantiation, the
1615 		 second is an explicit specialization, and the
1616 		 implicit instantiation has not yet been used.  That
1617 		 situation can occur if we have implicitly
1618 		 instantiated a member function and then specialized
1619 		 it later.
1620 
1621 		 We can also wind up here if a friend declaration that
1622 		 looked like an instantiation turns out to be a
1623 		 specialization:
1624 
1625 		   template <class T> void foo(T);
1626 		   class S { friend void foo<>(int) };
1627 		   template <> void foo(int);
1628 
1629 		 We transform the existing DECL in place so that any
1630 		 pointers to it become pointers to the updated
1631 		 declaration.
1632 
1633 		 If there was a definition for the template, but not
1634 		 for the specialization, we want this to look as if
1635 		 there were no definition, and vice versa.  */
1636 	      DECL_INITIAL (fn) = NULL_TREE;
1637 	      duplicate_decls (spec, fn, /*hiding=*/is_friend);
1638 	      /* The call to duplicate_decls will have applied
1639 		 [temp.expl.spec]:
1640 
1641 		   An explicit specialization of a function template
1642 		   is inline only if it is explicitly declared to be,
1643 		   and independently of whether its function template
1644 		   is.
1645 
1646 		to the primary function; now copy the inline bits to
1647 		the various clones.  */
1648 	      FOR_EACH_CLONE (clone, fn)
1649 		{
1650 		  DECL_DECLARED_INLINE_P (clone)
1651 		    = DECL_DECLARED_INLINE_P (fn);
1652 		  DECL_SOURCE_LOCATION (clone)
1653 		    = DECL_SOURCE_LOCATION (fn);
1654 		  DECL_DELETED_FN (clone)
1655 		    = DECL_DELETED_FN (fn);
1656 		}
1657 	      check_specialization_namespace (tmpl);
1658 
1659 	      return fn;
1660 	    }
1661 	}
1662       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1663 	{
1664 	  tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1665 	  if (dd == error_mark_node)
1666 	    /* We've already complained in duplicate_decls.  */
1667 	    return error_mark_node;
1668 
1669 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1670 	    /* Dup decl failed, but this is a new definition. Set the
1671 	       line number so any errors match this new
1672 	       definition.  */
1673 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1674 
1675 	  return fn;
1676 	}
1677     }
1678   else if (fn)
1679     return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1680 
1681   /* A specialization must be declared in the same namespace as the
1682      template it is specializing.  */
1683   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1684       && !check_specialization_namespace (tmpl))
1685     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1686 
1687   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1688     {
1689       spec_entry *entry = ggc_alloc<spec_entry> ();
1690       gcc_assert (tmpl && args && spec);
1691       *entry = elt;
1692       *slot = entry;
1693       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1694 	   && PRIMARY_TEMPLATE_P (tmpl)
1695 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1696 	  || variable_template_p (tmpl))
1697 	/* If TMPL is a forward declaration of a template function, keep a list
1698 	   of all specializations in case we need to reassign them to a friend
1699 	   template later in tsubst_friend_function.
1700 
1701 	   Also keep a list of all variable template instantiations so that
1702 	   process_partial_specialization can check whether a later partial
1703 	   specialization would have used it.  */
1704 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1705 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1706     }
1707 
1708   return spec;
1709 }
1710 
1711 /* Restricts tree and type comparisons.  */
1712 int comparing_specializations;
1713 int comparing_dependent_aliases;
1714 
1715 /* Returns true iff two spec_entry nodes are equivalent.  */
1716 
1717 bool
equal(spec_entry * e1,spec_entry * e2)1718 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1719 {
1720   int equal;
1721 
1722   ++comparing_specializations;
1723   ++comparing_dependent_aliases;
1724   ++processing_template_decl;
1725   equal = (e1->tmpl == e2->tmpl
1726 	   && comp_template_args (e1->args, e2->args));
1727   if (equal && flag_concepts
1728       /* tmpl could be a FIELD_DECL for a capture pack.  */
1729       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1730       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1731       && uses_template_parms (e1->args))
1732     {
1733       /* Partial specializations of a variable template can be distinguished by
1734 	 constraints.  */
1735       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1736       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1737       equal = equivalent_constraints (c1, c2);
1738     }
1739   --processing_template_decl;
1740   --comparing_dependent_aliases;
1741   --comparing_specializations;
1742 
1743   return equal;
1744 }
1745 
1746 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1747 
1748 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1749 hash_tmpl_and_args (tree tmpl, tree args)
1750 {
1751   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1752   return iterative_hash_template_arg (args, val);
1753 }
1754 
1755 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1756    ignoring SPEC.  */
1757 
1758 hashval_t
hash(spec_entry * e)1759 spec_hasher::hash (spec_entry *e)
1760 {
1761   return hash_tmpl_and_args (e->tmpl, e->args);
1762 }
1763 
1764 /* Recursively calculate a hash value for a template argument ARG, for use
1765    in the hash tables of template specializations.   We must be
1766    careful to (at least) skip the same entities template_args_equal
1767    does.  */
1768 
1769 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1770 iterative_hash_template_arg (tree arg, hashval_t val)
1771 {
1772   if (arg == NULL_TREE)
1773     return iterative_hash_object (arg, val);
1774 
1775   if (!TYPE_P (arg))
1776     /* Strip nop-like things, but not the same as STRIP_NOPS.  */
1777     while (CONVERT_EXPR_P (arg)
1778 	   || TREE_CODE (arg) == NON_LVALUE_EXPR
1779 	   || class_nttp_const_wrapper_p (arg))
1780       arg = TREE_OPERAND (arg, 0);
1781 
1782   enum tree_code code = TREE_CODE (arg);
1783 
1784   val = iterative_hash_object (code, val);
1785 
1786   switch (code)
1787     {
1788     case ARGUMENT_PACK_SELECT:
1789       gcc_unreachable ();
1790 
1791     case ERROR_MARK:
1792       return val;
1793 
1794     case IDENTIFIER_NODE:
1795       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1796 
1797     case TREE_VEC:
1798       for (int i = 0, len = TREE_VEC_LENGTH (arg); i < len; ++i)
1799 	val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1800       return val;
1801 
1802     case TYPE_PACK_EXPANSION:
1803     case EXPR_PACK_EXPANSION:
1804       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1805       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1806 
1807     case TYPE_ARGUMENT_PACK:
1808     case NONTYPE_ARGUMENT_PACK:
1809       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1810 
1811     case TREE_LIST:
1812       for (; arg; arg = TREE_CHAIN (arg))
1813 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1814       return val;
1815 
1816     case OVERLOAD:
1817       for (lkp_iterator iter (arg); iter; ++iter)
1818 	val = iterative_hash_template_arg (*iter, val);
1819       return val;
1820 
1821     case CONSTRUCTOR:
1822       {
1823 	tree field, value;
1824 	unsigned i;
1825 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1826 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1827 	  {
1828 	    val = iterative_hash_template_arg (field, val);
1829 	    val = iterative_hash_template_arg (value, val);
1830 	  }
1831 	return val;
1832       }
1833 
1834     case PARM_DECL:
1835       if (!DECL_ARTIFICIAL (arg))
1836 	{
1837 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1838 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1839 	}
1840       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1841 
1842     case TARGET_EXPR:
1843       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1844 
1845     case PTRMEM_CST:
1846       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1847       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1848 
1849     case TEMPLATE_PARM_INDEX:
1850       val = iterative_hash_template_arg
1851 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1852       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1853       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1854 
1855     case TRAIT_EXPR:
1856       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1857       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1858       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1859 
1860     case BASELINK:
1861       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1862 					 val);
1863       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1864 					  val);
1865 
1866     case MODOP_EXPR:
1867       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1868       code = TREE_CODE (TREE_OPERAND (arg, 1));
1869       val = iterative_hash_object (code, val);
1870       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1871 
1872     case LAMBDA_EXPR:
1873       /* [temp.over.link] Two lambda-expressions are never considered
1874 	 equivalent.
1875 
1876          So just hash the closure type.  */
1877       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1878 
1879     case CAST_EXPR:
1880     case IMPLICIT_CONV_EXPR:
1881     case STATIC_CAST_EXPR:
1882     case REINTERPRET_CAST_EXPR:
1883     case CONST_CAST_EXPR:
1884     case DYNAMIC_CAST_EXPR:
1885     case NEW_EXPR:
1886       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1887       /* Now hash operands as usual.  */
1888       break;
1889 
1890     case CALL_EXPR:
1891       {
1892 	tree fn = CALL_EXPR_FN (arg);
1893 	if (tree name = dependent_name (fn))
1894 	  {
1895 	    if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1896 	      val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1897 	    fn = name;
1898 	  }
1899 	val = iterative_hash_template_arg (fn, val);
1900 	call_expr_arg_iterator ai;
1901 	for (tree x = first_call_expr_arg (arg, &ai); x;
1902 	     x = next_call_expr_arg (&ai))
1903 	  val = iterative_hash_template_arg (x, val);
1904 	return val;
1905       }
1906 
1907     default:
1908       break;
1909     }
1910 
1911   char tclass = TREE_CODE_CLASS (code);
1912   switch (tclass)
1913     {
1914     case tcc_type:
1915       if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1916 	{
1917 	  // We want an alias specialization that survived strip_typedefs
1918 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1919 	  // collisions that compare as different in template_args_equal.
1920 	  // These could be dependent specializations that strip_typedefs
1921 	  // left alone, or untouched specializations because
1922 	  // coerce_template_parms returns the unconverted template
1923 	  // arguments if it sees incomplete argument packs.
1924 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1925 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1926 	}
1927 
1928       switch (TREE_CODE (arg))
1929 	{
1930 	case TEMPLATE_TEMPLATE_PARM:
1931 	  {
1932 	    tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1933 
1934 	    /* Do not recurse with TPI directly, as that is unbounded
1935 	       recursion.  */
1936 	    val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1937 	    val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1938 	  }
1939 	  break;
1940 
1941 	case  DECLTYPE_TYPE:
1942 	  val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1943 	  break;
1944 
1945 	default:
1946 	  if (tree canonical = TYPE_CANONICAL (arg))
1947 	    val = iterative_hash_object (TYPE_HASH (canonical), val);
1948 	  break;
1949 	}
1950 
1951       return val;
1952 
1953     case tcc_declaration:
1954     case tcc_constant:
1955       return iterative_hash_expr (arg, val);
1956 
1957     default:
1958       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1959       for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1960 	val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1961       return val;
1962     }
1963 
1964   gcc_unreachable ();
1965   return 0;
1966 }
1967 
1968 /* Unregister the specialization SPEC as a specialization of TMPL.
1969    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1970    if the SPEC was listed as a specialization of TMPL.
1971 
1972    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1973 
1974 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1975 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1976 {
1977   spec_entry *entry;
1978   spec_entry elt;
1979 
1980   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1981   elt.args = TI_ARGS (tinfo);
1982   elt.spec = NULL_TREE;
1983 
1984   entry = decl_specializations->find (&elt);
1985   if (entry != NULL)
1986     {
1987       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1988       gcc_assert (new_spec != NULL_TREE);
1989       entry->spec = new_spec;
1990       return 1;
1991     }
1992 
1993   return 0;
1994 }
1995 
1996 /* Like register_specialization, but for local declarations.  We are
1997    registering SPEC, an instantiation of TMPL.  */
1998 
1999 void
register_local_specialization(tree spec,tree tmpl)2000 register_local_specialization (tree spec, tree tmpl)
2001 {
2002   gcc_assert (tmpl != spec);
2003   local_specializations->put (tmpl, spec);
2004 }
2005 
2006 /* TYPE is a class type.  Returns true if TYPE is an explicitly
2007    specialized class.  */
2008 
2009 bool
explicit_class_specialization_p(tree type)2010 explicit_class_specialization_p (tree type)
2011 {
2012   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2013     return false;
2014   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2015 }
2016 
2017 /* Print the list of functions at FNS, going through all the overloads
2018    for each element of the list.  Alternatively, FNS cannot be a
2019    TREE_LIST, in which case it will be printed together with all the
2020    overloads.
2021 
2022    MORE and *STR should respectively be FALSE and NULL when the function
2023    is called from the outside.  They are used internally on recursive
2024    calls.  print_candidates manages the two parameters and leaves NULL
2025    in *STR when it ends.  */
2026 
2027 static void
2028 print_candidates_1 (tree fns, char **str, bool more = false)
2029 {
2030   if (TREE_CODE (fns) == TREE_LIST)
2031     for (; fns; fns = TREE_CHAIN (fns))
2032       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2033   else
2034     for (lkp_iterator iter (fns); iter;)
2035       {
2036 	tree cand = *iter;
2037 	++iter;
2038 
2039 	const char *pfx = *str;
2040 	if (!pfx)
2041 	  {
2042 	    if (more || iter)
2043 	      pfx = _("candidates are:");
2044 	    else
2045 	      pfx = _("candidate is:");
2046 	    *str = get_spaces (pfx);
2047 	  }
2048 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2049       }
2050 }
2051 
2052 /* Print the list of candidate FNS in an error message.  FNS can also
2053    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2054 
2055 void
print_candidates(tree fns)2056 print_candidates (tree fns)
2057 {
2058   char *str = NULL;
2059   print_candidates_1 (fns, &str);
2060   free (str);
2061 }
2062 
2063 /* Get a (possibly) constrained template declaration for the
2064    purpose of ordering candidates.  */
2065 static tree
get_template_for_ordering(tree list)2066 get_template_for_ordering (tree list)
2067 {
2068   gcc_assert (TREE_CODE (list) == TREE_LIST);
2069   tree f = TREE_VALUE (list);
2070   if (tree ti = DECL_TEMPLATE_INFO (f))
2071     return TI_TEMPLATE (ti);
2072   return f;
2073 }
2074 
2075 /* Among candidates having the same signature, return the
2076    most constrained or NULL_TREE if there is no best candidate.
2077    If the signatures of candidates vary (e.g., template
2078    specialization vs. member function), then there can be no
2079    most constrained.
2080 
2081    Note that we don't compare constraints on the functions
2082    themselves, but rather those of their templates. */
2083 static tree
most_constrained_function(tree candidates)2084 most_constrained_function (tree candidates)
2085 {
2086   // Try to find the best candidate in a first pass.
2087   tree champ = candidates;
2088   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2089     {
2090       int winner = more_constrained (get_template_for_ordering (champ),
2091                                      get_template_for_ordering (c));
2092       if (winner == -1)
2093         champ = c; // The candidate is more constrained
2094       else if (winner == 0)
2095         return NULL_TREE; // Neither is more constrained
2096     }
2097 
2098   // Verify that the champ is better than previous candidates.
2099   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2100     if (!more_constrained (get_template_for_ordering (champ),
2101                            get_template_for_ordering (c)))
2102       return NULL_TREE;
2103   }
2104 
2105   return champ;
2106 }
2107 
2108 
2109 /* Returns the template (one of the functions given by TEMPLATE_ID)
2110    which can be specialized to match the indicated DECL with the
2111    explicit template args given in TEMPLATE_ID.  The DECL may be
2112    NULL_TREE if none is available.  In that case, the functions in
2113    TEMPLATE_ID are non-members.
2114 
2115    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2116    specialization of a member template.
2117 
2118    The TEMPLATE_COUNT is the number of references to qualifying
2119    template classes that appeared in the name of the function. See
2120    check_explicit_specialization for a more accurate description.
2121 
2122    TSK indicates what kind of template declaration (if any) is being
2123    declared.  TSK_TEMPLATE indicates that the declaration given by
2124    DECL, though a FUNCTION_DECL, has template parameters, and is
2125    therefore a template function.
2126 
2127    The template args (those explicitly specified and those deduced)
2128    are output in a newly created vector *TARGS_OUT.
2129 
2130    If it is impossible to determine the result, an error message is
2131    issued.  The error_mark_node is returned to indicate failure.  */
2132 
2133 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2134 determine_specialization (tree template_id,
2135 			  tree decl,
2136 			  tree* targs_out,
2137 			  int need_member_template,
2138 			  int template_count,
2139 			  tmpl_spec_kind tsk)
2140 {
2141   tree fns;
2142   tree targs;
2143   tree explicit_targs;
2144   tree candidates = NULL_TREE;
2145 
2146   /* A TREE_LIST of templates of which DECL may be a specialization.
2147      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2148      corresponding TREE_PURPOSE is the set of template arguments that,
2149      when used to instantiate the template, would produce a function
2150      with the signature of DECL.  */
2151   tree templates = NULL_TREE;
2152   int header_count;
2153   cp_binding_level *b;
2154 
2155   *targs_out = NULL_TREE;
2156 
2157   if (template_id == error_mark_node || decl == error_mark_node)
2158     return error_mark_node;
2159 
2160   /* We shouldn't be specializing a member template of an
2161      unspecialized class template; we already gave an error in
2162      check_specialization_scope, now avoid crashing.  */
2163   if (!VAR_P (decl)
2164       && template_count && DECL_CLASS_SCOPE_P (decl)
2165       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2166     {
2167       gcc_assert (errorcount);
2168       return error_mark_node;
2169     }
2170 
2171   fns = TREE_OPERAND (template_id, 0);
2172   explicit_targs = TREE_OPERAND (template_id, 1);
2173 
2174   if (fns == error_mark_node)
2175     return error_mark_node;
2176 
2177   /* Check for baselinks.  */
2178   if (BASELINK_P (fns))
2179     fns = BASELINK_FUNCTIONS (fns);
2180 
2181   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2182     {
2183       error_at (DECL_SOURCE_LOCATION (decl),
2184 		"%qD is not a function template", fns);
2185       return error_mark_node;
2186     }
2187   else if (VAR_P (decl) && !variable_template_p (fns))
2188     {
2189       error ("%qD is not a variable template", fns);
2190       return error_mark_node;
2191     }
2192 
2193   /* Count the number of template headers specified for this
2194      specialization.  */
2195   header_count = 0;
2196   for (b = current_binding_level;
2197        b->kind == sk_template_parms;
2198        b = b->level_chain)
2199     ++header_count;
2200 
2201   tree orig_fns = fns;
2202   bool header_mismatch = false;
2203 
2204   if (variable_template_p (fns))
2205     {
2206       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2207       targs = coerce_template_parms (parms, explicit_targs, fns,
2208 				     tf_warning_or_error,
2209 				     /*req_all*/true, /*use_defarg*/true);
2210       if (targs != error_mark_node
2211 	  && constraints_satisfied_p (fns, targs))
2212         templates = tree_cons (targs, fns, templates);
2213     }
2214   else for (lkp_iterator iter (fns); iter; ++iter)
2215     {
2216       tree fn = *iter;
2217 
2218       if (TREE_CODE (fn) == TEMPLATE_DECL)
2219 	{
2220 	  tree decl_arg_types;
2221 	  tree fn_arg_types;
2222 	  tree insttype;
2223 
2224 	  /* In case of explicit specialization, we need to check if
2225 	     the number of template headers appearing in the specialization
2226 	     is correct. This is usually done in check_explicit_specialization,
2227 	     but the check done there cannot be exhaustive when specializing
2228 	     member functions. Consider the following code:
2229 
2230 	     template <> void A<int>::f(int);
2231 	     template <> template <> void A<int>::f(int);
2232 
2233 	     Assuming that A<int> is not itself an explicit specialization
2234 	     already, the first line specializes "f" which is a non-template
2235 	     member function, whilst the second line specializes "f" which
2236 	     is a template member function. So both lines are syntactically
2237 	     correct, and check_explicit_specialization does not reject
2238 	     them.
2239 
2240 	     Here, we can do better, as we are matching the specialization
2241 	     against the declarations. We count the number of template
2242 	     headers, and we check if they match TEMPLATE_COUNT + 1
2243 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2244 	     plus there must be another header for the member template
2245 	     itself).
2246 
2247 	     Notice that if header_count is zero, this is not a
2248 	     specialization but rather a template instantiation, so there
2249 	     is no check we can perform here.  */
2250 	  if (header_count && header_count != template_count + 1)
2251 	    {
2252 	      header_mismatch = true;
2253 	      continue;
2254 	    }
2255 
2256 	  /* Check that the number of template arguments at the
2257 	     innermost level for DECL is the same as for FN.  */
2258 	  if (current_binding_level->kind == sk_template_parms
2259 	      && !current_binding_level->explicit_spec_p
2260 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2261 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2262 				      (current_template_parms))))
2263 	    continue;
2264 
2265 	  /* DECL might be a specialization of FN.  */
2266 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2267 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2268 
2269 	  /* For a non-static member function, we need to make sure
2270 	     that the const qualification is the same.  Since
2271 	     get_bindings does not try to merge the "this" parameter,
2272 	     we must do the comparison explicitly.  */
2273 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2274 	    {
2275 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2276 				TREE_VALUE (decl_arg_types)))
2277 		continue;
2278 
2279 	      /* And the ref-qualification.  */
2280 	      if (type_memfn_rqual (TREE_TYPE (decl))
2281 		  != type_memfn_rqual (TREE_TYPE (fn)))
2282 		continue;
2283 	    }
2284 
2285 	  /* Skip the "this" parameter and, for constructors of
2286 	     classes with virtual bases, the VTT parameter.  A
2287 	     full specialization of a constructor will have a VTT
2288 	     parameter, but a template never will.  */
2289 	  decl_arg_types
2290 	    = skip_artificial_parms_for (decl, decl_arg_types);
2291 	  fn_arg_types
2292 	    = skip_artificial_parms_for (fn, fn_arg_types);
2293 
2294 	  /* Function templates cannot be specializations; there are
2295 	     no partial specializations of functions.  Therefore, if
2296 	     the type of DECL does not match FN, there is no
2297 	     match.
2298 
2299              Note that it should never be the case that we have both
2300              candidates added here, and for regular member functions
2301              below. */
2302 	  if (tsk == tsk_template)
2303 	    {
2304 	      if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2305 					current_template_parms))
2306 		continue;
2307 	      if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2308 				TREE_TYPE (TREE_TYPE (fn))))
2309 		continue;
2310 	      if (!compparms (fn_arg_types, decl_arg_types))
2311 		continue;
2312 
2313 	      tree freq = get_trailing_function_requirements (fn);
2314 	      tree dreq = get_trailing_function_requirements (decl);
2315 	      if (!freq != !dreq)
2316 		continue;
2317 	      if (freq)
2318 		{
2319 		  tree fargs = DECL_TI_ARGS (fn);
2320 		  tsubst_flags_t complain = tf_none;
2321 		  freq = tsubst_constraint (freq, fargs, complain, fn);
2322 		  if (!cp_tree_equal (freq, dreq))
2323 		    continue;
2324 		}
2325 
2326 	      candidates = tree_cons (NULL_TREE, fn, candidates);
2327 	      continue;
2328 	    }
2329 
2330 	  /* See whether this function might be a specialization of this
2331 	     template.  Suppress access control because we might be trying
2332 	     to make this specialization a friend, and we have already done
2333 	     access control for the declaration of the specialization.  */
2334 	  push_deferring_access_checks (dk_no_check);
2335 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2336 	  pop_deferring_access_checks ();
2337 
2338 	  if (!targs)
2339 	    /* We cannot deduce template arguments that when used to
2340 	       specialize TMPL will produce DECL.  */
2341 	    continue;
2342 
2343 	  if (uses_template_parms (targs))
2344 	    /* We deduced something involving 'auto', which isn't a valid
2345 	       template argument.  */
2346 	    continue;
2347 
2348           /* Remove, from the set of candidates, all those functions
2349              whose constraints are not satisfied. */
2350           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2351             continue;
2352 
2353           // Then, try to form the new function type.
2354 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2355 	  if (insttype == error_mark_node)
2356 	    continue;
2357 	  fn_arg_types
2358 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2359 	  if (!compparms (fn_arg_types, decl_arg_types))
2360 	    continue;
2361 
2362 	  /* Save this template, and the arguments deduced.  */
2363 	  templates = tree_cons (targs, fn, templates);
2364 	}
2365       else if (need_member_template)
2366 	/* FN is an ordinary member function, and we need a
2367 	   specialization of a member template.  */
2368 	;
2369       else if (TREE_CODE (fn) != FUNCTION_DECL)
2370 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2371 	   cases.  */
2372 	;
2373       else if (!DECL_FUNCTION_MEMBER_P (fn))
2374 	/* This is just an ordinary non-member function.  Nothing can
2375 	   be a specialization of that.  */
2376 	;
2377       else if (DECL_ARTIFICIAL (fn))
2378 	/* Cannot specialize functions that are created implicitly.  */
2379 	;
2380       else
2381 	{
2382 	  tree decl_arg_types;
2383 
2384 	  /* This is an ordinary member function.  However, since
2385 	     we're here, we can assume its enclosing class is a
2386 	     template class.  For example,
2387 
2388 	       template <typename T> struct S { void f(); };
2389 	       template <> void S<int>::f() {}
2390 
2391 	     Here, S<int>::f is a non-template, but S<int> is a
2392 	     template class.  If FN has the same type as DECL, we
2393 	     might be in business.  */
2394 
2395 	  if (!DECL_TEMPLATE_INFO (fn))
2396 	    /* Its enclosing class is an explicit specialization
2397 	       of a template class.  This is not a candidate.  */
2398 	    continue;
2399 
2400 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2401 			    TREE_TYPE (TREE_TYPE (fn))))
2402 	    /* The return types differ.  */
2403 	    continue;
2404 
2405 	  /* Adjust the type of DECL in case FN is a static member.  */
2406 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2407 	  if (DECL_STATIC_FUNCTION_P (fn)
2408 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2409 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2410 
2411 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2412 			 decl_arg_types))
2413             continue;
2414 
2415 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2416 	      && (type_memfn_rqual (TREE_TYPE (decl))
2417 		  != type_memfn_rqual (TREE_TYPE (fn))))
2418 	    continue;
2419 
2420           // If the deduced arguments do not satisfy the constraints,
2421           // this is not a candidate.
2422           if (flag_concepts && !constraints_satisfied_p (fn))
2423             continue;
2424 
2425           // Add the candidate.
2426           candidates = tree_cons (NULL_TREE, fn, candidates);
2427 	}
2428     }
2429 
2430   if (templates && TREE_CHAIN (templates))
2431     {
2432       /* We have:
2433 
2434 	   [temp.expl.spec]
2435 
2436 	   It is possible for a specialization with a given function
2437 	   signature to be instantiated from more than one function
2438 	   template.  In such cases, explicit specification of the
2439 	   template arguments must be used to uniquely identify the
2440 	   function template specialization being specialized.
2441 
2442 	 Note that here, there's no suggestion that we're supposed to
2443 	 determine which of the candidate templates is most
2444 	 specialized.  However, we, also have:
2445 
2446 	   [temp.func.order]
2447 
2448 	   Partial ordering of overloaded function template
2449 	   declarations is used in the following contexts to select
2450 	   the function template to which a function template
2451 	   specialization refers:
2452 
2453 	   -- when an explicit specialization refers to a function
2454 	      template.
2455 
2456 	 So, we do use the partial ordering rules, at least for now.
2457 	 This extension can only serve to make invalid programs valid,
2458 	 so it's safe.  And, there is strong anecdotal evidence that
2459 	 the committee intended the partial ordering rules to apply;
2460 	 the EDG front end has that behavior, and John Spicer claims
2461 	 that the committee simply forgot to delete the wording in
2462 	 [temp.expl.spec].  */
2463       tree tmpl = most_specialized_instantiation (templates);
2464       if (tmpl != error_mark_node)
2465 	{
2466 	  templates = tmpl;
2467 	  TREE_CHAIN (templates) = NULL_TREE;
2468 	}
2469     }
2470 
2471   // Concepts allows multiple declarations of member functions
2472   // with the same signature. Like above, we need to rely on
2473   // on the partial ordering of those candidates to determine which
2474   // is the best.
2475   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2476     {
2477       if (tree cand = most_constrained_function (candidates))
2478         {
2479           candidates = cand;
2480           TREE_CHAIN (cand) = NULL_TREE;
2481         }
2482     }
2483 
2484   if (templates == NULL_TREE && candidates == NULL_TREE)
2485     {
2486       error ("template-id %qD for %q+D does not match any template "
2487 	     "declaration", template_id, decl);
2488       if (header_mismatch)
2489 	inform (DECL_SOURCE_LOCATION (decl),
2490 		"saw %d %<template<>%>, need %d for "
2491 		"specializing a member function template",
2492 		header_count, template_count + 1);
2493       print_candidates (orig_fns);
2494       return error_mark_node;
2495     }
2496   else if ((templates && TREE_CHAIN (templates))
2497 	   || (candidates && TREE_CHAIN (candidates))
2498 	   || (templates && candidates))
2499     {
2500       error ("ambiguous template specialization %qD for %q+D",
2501 	     template_id, decl);
2502       candidates = chainon (candidates, templates);
2503       print_candidates (candidates);
2504       return error_mark_node;
2505     }
2506 
2507   /* We have one, and exactly one, match.  */
2508   if (candidates)
2509     {
2510       tree fn = TREE_VALUE (candidates);
2511       *targs_out = copy_node (DECL_TI_ARGS (fn));
2512 
2513       /* Propagate the candidate's constraints to the declaration.  */
2514       if (tsk != tsk_template)
2515 	set_constraints (decl, get_constraints (fn));
2516 
2517       /* DECL is a re-declaration or partial instantiation of a template
2518 	 function.  */
2519       if (TREE_CODE (fn) == TEMPLATE_DECL)
2520 	return fn;
2521       /* It was a specialization of an ordinary member function in a
2522 	 template class.  */
2523       return DECL_TI_TEMPLATE (fn);
2524     }
2525 
2526   /* It was a specialization of a template.  */
2527   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2528   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2529     {
2530       *targs_out = copy_node (targs);
2531       SET_TMPL_ARGS_LEVEL (*targs_out,
2532 			   TMPL_ARGS_DEPTH (*targs_out),
2533 			   TREE_PURPOSE (templates));
2534     }
2535   else
2536     *targs_out = TREE_PURPOSE (templates);
2537   return TREE_VALUE (templates);
2538 }
2539 
2540 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2541    but with the default argument values filled in from those in the
2542    TMPL_TYPES.  */
2543 
2544 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2545 copy_default_args_to_explicit_spec_1 (tree spec_types,
2546 				      tree tmpl_types)
2547 {
2548   tree new_spec_types;
2549 
2550   if (!spec_types)
2551     return NULL_TREE;
2552 
2553   if (spec_types == void_list_node)
2554     return void_list_node;
2555 
2556   /* Substitute into the rest of the list.  */
2557   new_spec_types =
2558     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2559 					  TREE_CHAIN (tmpl_types));
2560 
2561   /* Add the default argument for this parameter.  */
2562   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2563 			 TREE_VALUE (spec_types),
2564 			 new_spec_types);
2565 }
2566 
2567 /* DECL is an explicit specialization.  Replicate default arguments
2568    from the template it specializes.  (That way, code like:
2569 
2570      template <class T> void f(T = 3);
2571      template <> void f(double);
2572      void g () { f (); }
2573 
2574    works, as required.)  An alternative approach would be to look up
2575    the correct default arguments at the call-site, but this approach
2576    is consistent with how implicit instantiations are handled.  */
2577 
2578 static void
copy_default_args_to_explicit_spec(tree decl)2579 copy_default_args_to_explicit_spec (tree decl)
2580 {
2581   tree tmpl;
2582   tree spec_types;
2583   tree tmpl_types;
2584   tree new_spec_types;
2585   tree old_type;
2586   tree new_type;
2587   tree t;
2588   tree object_type = NULL_TREE;
2589   tree in_charge = NULL_TREE;
2590   tree vtt = NULL_TREE;
2591 
2592   /* See if there's anything we need to do.  */
2593   tmpl = DECL_TI_TEMPLATE (decl);
2594   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2595   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2596     if (TREE_PURPOSE (t))
2597       break;
2598   if (!t)
2599     return;
2600 
2601   old_type = TREE_TYPE (decl);
2602   spec_types = TYPE_ARG_TYPES (old_type);
2603 
2604   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2605     {
2606       /* Remove the this pointer, but remember the object's type for
2607 	 CV quals.  */
2608       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2609       spec_types = TREE_CHAIN (spec_types);
2610       tmpl_types = TREE_CHAIN (tmpl_types);
2611 
2612       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2613 	{
2614 	  /* DECL may contain more parameters than TMPL due to the extra
2615 	     in-charge parameter in constructors and destructors.  */
2616 	  in_charge = spec_types;
2617 	  spec_types = TREE_CHAIN (spec_types);
2618 	}
2619       if (DECL_HAS_VTT_PARM_P (decl))
2620 	{
2621 	  vtt = spec_types;
2622 	  spec_types = TREE_CHAIN (spec_types);
2623 	}
2624     }
2625 
2626   /* Compute the merged default arguments.  */
2627   new_spec_types =
2628     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2629 
2630   /* Compute the new FUNCTION_TYPE.  */
2631   if (object_type)
2632     {
2633       if (vtt)
2634 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2635 					 TREE_VALUE (vtt),
2636 					 new_spec_types);
2637 
2638       if (in_charge)
2639 	/* Put the in-charge parameter back.  */
2640 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2641 					 TREE_VALUE (in_charge),
2642 					 new_spec_types);
2643 
2644       new_type = build_method_type_directly (object_type,
2645 					     TREE_TYPE (old_type),
2646 					     new_spec_types);
2647     }
2648   else
2649     new_type = build_function_type (TREE_TYPE (old_type),
2650 				    new_spec_types);
2651   new_type = cp_build_type_attribute_variant (new_type,
2652 					      TYPE_ATTRIBUTES (old_type));
2653   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2654 
2655   TREE_TYPE (decl) = new_type;
2656 }
2657 
2658 /* Return the number of template headers we expect to see for a definition
2659    or specialization of CTYPE or one of its non-template members.  */
2660 
2661 int
num_template_headers_for_class(tree ctype)2662 num_template_headers_for_class (tree ctype)
2663 {
2664   int num_templates = 0;
2665 
2666   while (ctype && CLASS_TYPE_P (ctype))
2667     {
2668       /* You're supposed to have one `template <...>' for every
2669 	 template class, but you don't need one for a full
2670 	 specialization.  For example:
2671 
2672 	 template <class T> struct S{};
2673 	 template <> struct S<int> { void f(); };
2674 	 void S<int>::f () {}
2675 
2676 	 is correct; there shouldn't be a `template <>' for the
2677 	 definition of `S<int>::f'.  */
2678       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2679 	/* If CTYPE does not have template information of any
2680 	   kind,  then it is not a template, nor is it nested
2681 	   within a template.  */
2682 	break;
2683       if (explicit_class_specialization_p (ctype))
2684 	break;
2685       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2686 	++num_templates;
2687 
2688       ctype = TYPE_CONTEXT (ctype);
2689     }
2690 
2691   return num_templates;
2692 }
2693 
2694 /* Do a simple sanity check on the template headers that precede the
2695    variable declaration DECL.  */
2696 
2697 void
check_template_variable(tree decl)2698 check_template_variable (tree decl)
2699 {
2700   tree ctx = CP_DECL_CONTEXT (decl);
2701   int wanted = num_template_headers_for_class (ctx);
2702   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2703       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2704     {
2705       if (cxx_dialect < cxx14)
2706         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2707 		 "variable templates only available with "
2708 		 "%<-std=c++14%> or %<-std=gnu++14%>");
2709 
2710       // Namespace-scope variable templates should have a template header.
2711       ++wanted;
2712     }
2713   if (template_header_count > wanted)
2714     {
2715       auto_diagnostic_group d;
2716       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2717 			     "too many template headers for %qD "
2718 	                     "(should be %d)",
2719 			     decl, wanted);
2720       if (warned && CLASS_TYPE_P (ctx)
2721 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2722 	inform (DECL_SOURCE_LOCATION (decl),
2723 		"members of an explicitly specialized class are defined "
2724 		"without a template header");
2725     }
2726 }
2727 
2728 /* An explicit specialization whose declarator-id or class-head-name is not
2729    qualified shall be declared in the nearest enclosing namespace of the
2730    template, or, if the namespace is inline (7.3.1), any namespace from its
2731    enclosing namespace set.
2732 
2733    If the name declared in the explicit instantiation is an unqualified name,
2734    the explicit instantiation shall appear in the namespace where its template
2735    is declared or, if that namespace is inline (7.3.1), any namespace from its
2736    enclosing namespace set.  */
2737 
2738 void
check_unqualified_spec_or_inst(tree t,location_t loc)2739 check_unqualified_spec_or_inst (tree t, location_t loc)
2740 {
2741   tree tmpl = most_general_template (t);
2742   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2743       && !is_nested_namespace (current_namespace,
2744 			       CP_DECL_CONTEXT (tmpl), true))
2745     {
2746       if (processing_specialization)
2747 	permerror (loc, "explicit specialization of %qD outside its "
2748 		   "namespace must use a nested-name-specifier", tmpl);
2749       else if (processing_explicit_instantiation
2750 	       && cxx_dialect >= cxx11)
2751 	/* This was allowed in C++98, so only pedwarn.  */
2752 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2753 		 "outside its namespace must use a nested-name-"
2754 		 "specifier", tmpl);
2755     }
2756 }
2757 
2758 /* Warn for a template specialization SPEC that is missing some of a set
2759    of function or type attributes that the template TEMPL is declared with.
2760    ATTRLIST is a list of additional attributes that SPEC should be taken
2761    to ultimately be declared with.  */
2762 
2763 static void
warn_spec_missing_attributes(tree tmpl,tree spec,tree attrlist)2764 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2765 {
2766   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2767     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2768 
2769   /* Avoid warning if the difference between the primary and
2770      the specialization is not in one of the attributes below.  */
2771   const char* const blacklist[] = {
2772     "alloc_align", "alloc_size", "assume_aligned", "format",
2773     "format_arg", "malloc", "nonnull", NULL
2774   };
2775 
2776   /* Put together a list of the black listed attributes that the primary
2777      template is declared with that the specialization is not, in case
2778      it's not apparent from the most recent declaration of the primary.  */
2779   pretty_printer str;
2780   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2781 						 blacklist, &str);
2782 
2783   if (!nattrs)
2784     return;
2785 
2786   auto_diagnostic_group d;
2787   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2788 		  "explicit specialization %q#D may be missing attributes",
2789 		  spec))
2790     inform (DECL_SOURCE_LOCATION (tmpl),
2791 	    nattrs > 1
2792 	    ? G_("missing primary template attributes %s")
2793 	    : G_("missing primary template attribute %s"),
2794 	    pp_formatted_text (&str));
2795 }
2796 
2797 /* Check to see if the function just declared, as indicated in
2798    DECLARATOR, and in DECL, is a specialization of a function
2799    template.  We may also discover that the declaration is an explicit
2800    instantiation at this point.
2801 
2802    Returns DECL, or an equivalent declaration that should be used
2803    instead if all goes well.  Issues an error message if something is
2804    amiss.  Returns error_mark_node if the error is not easily
2805    recoverable.
2806 
2807    FLAGS is a bitmask consisting of the following flags:
2808 
2809    2: The function has a definition.
2810    4: The function is a friend.
2811 
2812    The TEMPLATE_COUNT is the number of references to qualifying
2813    template classes that appeared in the name of the function.  For
2814    example, in
2815 
2816      template <class T> struct S { void f(); };
2817      void S<int>::f();
2818 
2819    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2820    classes are not counted in the TEMPLATE_COUNT, so that in
2821 
2822      template <class T> struct S {};
2823      template <> struct S<int> { void f(); }
2824      template <> void S<int>::f();
2825 
2826    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2827    invalid; there should be no template <>.)
2828 
2829    If the function is a specialization, it is marked as such via
2830    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2831    is set up correctly, and it is added to the list of specializations
2832    for that template.  */
2833 
2834 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags,tree attrlist)2835 check_explicit_specialization (tree declarator,
2836 			       tree decl,
2837 			       int template_count,
2838 			       int flags,
2839 			       tree attrlist)
2840 {
2841   int have_def = flags & 2;
2842   int is_friend = flags & 4;
2843   bool is_concept = flags & 8;
2844   int specialization = 0;
2845   int explicit_instantiation = 0;
2846   int member_specialization = 0;
2847   tree ctype = DECL_CLASS_CONTEXT (decl);
2848   tree dname = DECL_NAME (decl);
2849   tmpl_spec_kind tsk;
2850 
2851   if (is_friend)
2852     {
2853       if (!processing_specialization)
2854 	tsk = tsk_none;
2855       else
2856 	tsk = tsk_excessive_parms;
2857     }
2858   else
2859     tsk = current_tmpl_spec_kind (template_count);
2860 
2861   switch (tsk)
2862     {
2863     case tsk_none:
2864       if (processing_specialization && !VAR_P (decl))
2865 	{
2866 	  specialization = 1;
2867 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2868 	}
2869       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2870 	{
2871 	  if (is_friend)
2872 	    /* This could be something like:
2873 
2874 	       template <class T> void f(T);
2875 	       class S { friend void f<>(int); }  */
2876 	    specialization = 1;
2877 	  else
2878 	    {
2879 	      /* This case handles bogus declarations like template <>
2880 		 template <class T> void f<int>(); */
2881 
2882 	      error_at (cp_expr_loc_or_input_loc (declarator),
2883 			"template-id %qE in declaration of primary template",
2884 			declarator);
2885 	      return decl;
2886 	    }
2887 	}
2888       break;
2889 
2890     case tsk_invalid_member_spec:
2891       /* The error has already been reported in
2892 	 check_specialization_scope.  */
2893       return error_mark_node;
2894 
2895     case tsk_invalid_expl_inst:
2896       error ("template parameter list used in explicit instantiation");
2897 
2898       /* Fall through.  */
2899 
2900     case tsk_expl_inst:
2901       if (have_def)
2902 	error ("definition provided for explicit instantiation");
2903 
2904       explicit_instantiation = 1;
2905       break;
2906 
2907     case tsk_excessive_parms:
2908     case tsk_insufficient_parms:
2909       if (tsk == tsk_excessive_parms)
2910 	error ("too many template parameter lists in declaration of %qD",
2911 	       decl);
2912       else if (template_header_count)
2913 	error("too few template parameter lists in declaration of %qD", decl);
2914       else
2915 	error("explicit specialization of %qD must be introduced by "
2916 	      "%<template <>%>", decl);
2917 
2918       /* Fall through.  */
2919     case tsk_expl_spec:
2920       if (is_concept)
2921         error ("explicit specialization declared %<concept%>");
2922 
2923       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2924 	/* In cases like template<> constexpr bool v = true;
2925 	   We'll give an error in check_template_variable.  */
2926 	break;
2927 
2928       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2929       if (ctype)
2930 	member_specialization = 1;
2931       else
2932 	specialization = 1;
2933       break;
2934 
2935     case tsk_template:
2936       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2937 	{
2938 	  /* This case handles bogus declarations like template <>
2939 	     template <class T> void f<int>(); */
2940 
2941 	  if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2942 	    error_at (cp_expr_loc_or_input_loc (declarator),
2943 		      "template-id %qE in declaration of primary template",
2944 		      declarator);
2945 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2946 	    {
2947 	      /* Partial specialization of variable template.  */
2948 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2949 	      specialization = 1;
2950 	      goto ok;
2951 	    }
2952 	  else if (cxx_dialect < cxx14)
2953 	    error_at (cp_expr_loc_or_input_loc (declarator),
2954 		      "non-type partial specialization %qE "
2955 		      "is not allowed", declarator);
2956 	  else
2957 	    error_at (cp_expr_loc_or_input_loc (declarator),
2958 		      "non-class, non-variable partial specialization %qE "
2959 		      "is not allowed", declarator);
2960 	  return decl;
2961 	ok:;
2962 	}
2963 
2964       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2965 	/* This is a specialization of a member template, without
2966 	   specialization the containing class.  Something like:
2967 
2968 	     template <class T> struct S {
2969 	       template <class U> void f (U);
2970 	     };
2971 	     template <> template <class U> void S<int>::f(U) {}
2972 
2973 	   That's a specialization -- but of the entire template.  */
2974 	specialization = 1;
2975       break;
2976 
2977     default:
2978       gcc_unreachable ();
2979     }
2980 
2981   if ((specialization || member_specialization)
2982       /* This doesn't apply to variable templates.  */
2983       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2984     {
2985       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2986       for (; t; t = TREE_CHAIN (t))
2987 	if (TREE_PURPOSE (t))
2988 	  {
2989 	    permerror (input_location,
2990 		       "default argument specified in explicit specialization");
2991 	    break;
2992 	  }
2993     }
2994 
2995   if (specialization || member_specialization || explicit_instantiation)
2996     {
2997       tree tmpl = NULL_TREE;
2998       tree targs = NULL_TREE;
2999       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
3000       bool found_hidden = false;
3001 
3002       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
3003       if (!was_template_id)
3004 	{
3005 	  tree fns;
3006 
3007 	  gcc_assert (identifier_p (declarator));
3008 	  if (ctype)
3009 	    fns = dname;
3010 	  else
3011 	    {
3012 	      /* If there is no class context, the explicit instantiation
3013 		 must be at namespace scope.  */
3014 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
3015 
3016 	      /* Find the namespace binding, using the declaration
3017 		 context.  */
3018 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3019 					   LOOK_want::NORMAL, true);
3020 	      if (fns == error_mark_node)
3021 		{
3022 		  /* If lookup fails, look for a friend declaration so we can
3023 		     give a better diagnostic.  */
3024 		  fns = (lookup_qualified_name
3025 			 (CP_DECL_CONTEXT (decl), dname,
3026 			  LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3027 			  /*complain*/true));
3028 		  found_hidden = true;
3029 		}
3030 
3031 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
3032 		{
3033 		  error ("%qD is not a template function", dname);
3034 		  fns = error_mark_node;
3035 		}
3036 	    }
3037 
3038 	  declarator = lookup_template_function (fns, NULL_TREE);
3039 	}
3040 
3041       if (declarator == error_mark_node)
3042 	return error_mark_node;
3043 
3044       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3045 	{
3046 	  if (!explicit_instantiation)
3047 	    /* A specialization in class scope.  This is invalid,
3048 	       but the error will already have been flagged by
3049 	       check_specialization_scope.  */
3050 	    return error_mark_node;
3051 	  else
3052 	    {
3053 	      /* It's not valid to write an explicit instantiation in
3054 		 class scope, e.g.:
3055 
3056 		   class C { template void f(); }
3057 
3058 		   This case is caught by the parser.  However, on
3059 		   something like:
3060 
3061 		   template class C { void f(); };
3062 
3063 		   (which is invalid) we can get here.  The error will be
3064 		   issued later.  */
3065 	      ;
3066 	    }
3067 
3068 	  return decl;
3069 	}
3070       else if (ctype != NULL_TREE
3071 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3072 	{
3073 	  // We'll match variable templates in start_decl.
3074 	  if (VAR_P (decl))
3075 	    return decl;
3076 
3077 	  /* Find the list of functions in ctype that have the same
3078 	     name as the declared function.  */
3079 	  tree name = TREE_OPERAND (declarator, 0);
3080 
3081 	  if (constructor_name_p (name, ctype))
3082 	    {
3083 	      if (DECL_CONSTRUCTOR_P (decl)
3084 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3085 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3086 		{
3087 		  /* From [temp.expl.spec]:
3088 
3089 		     If such an explicit specialization for the member
3090 		     of a class template names an implicitly-declared
3091 		     special member function (clause _special_), the
3092 		     program is ill-formed.
3093 
3094 		     Similar language is found in [temp.explicit].  */
3095 		  error ("specialization of implicitly-declared special member function");
3096 		  return error_mark_node;
3097 		}
3098 
3099 	      name = DECL_NAME (decl);
3100 	    }
3101 
3102 	  /* For a type-conversion operator, We might be looking for
3103 	     `operator int' which will be a specialization of
3104 	     `operator T'.  Grab all the conversion operators, and
3105 	     then select from them.  */
3106 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3107 					? conv_op_identifier : name);
3108 
3109 	  if (fns == NULL_TREE)
3110 	    {
3111 	      error ("no member function %qD declared in %qT", name, ctype);
3112 	      return error_mark_node;
3113 	    }
3114 	  else
3115 	    TREE_OPERAND (declarator, 0) = fns;
3116 	}
3117 
3118       /* Figure out what exactly is being specialized at this point.
3119 	 Note that for an explicit instantiation, even one for a
3120 	 member function, we cannot tell a priori whether the
3121 	 instantiation is for a member template, or just a member
3122 	 function of a template class.  Even if a member template is
3123 	 being instantiated, the member template arguments may be
3124 	 elided if they can be deduced from the rest of the
3125 	 declaration.  */
3126       tmpl = determine_specialization (declarator, decl,
3127 				       &targs,
3128 				       member_specialization,
3129 				       template_count,
3130 				       tsk);
3131 
3132       if (!tmpl || tmpl == error_mark_node)
3133 	/* We couldn't figure out what this declaration was
3134 	   specializing.  */
3135 	return error_mark_node;
3136       else
3137 	{
3138 	  if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3139 	    {
3140 	      auto_diagnostic_group d;
3141 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3142 			   "friend declaration %qD is not visible to "
3143 			   "explicit specialization", tmpl))
3144 		inform (DECL_SOURCE_LOCATION (tmpl),
3145 			"friend declaration here");
3146 	    }
3147 
3148 	  if (!ctype && !is_friend
3149 	      && CP_DECL_CONTEXT (decl) == current_namespace)
3150 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3151 
3152 	  tree gen_tmpl = most_general_template (tmpl);
3153 
3154 	  if (explicit_instantiation)
3155 	    {
3156 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3157 		 is done by do_decl_instantiation later.  */
3158 
3159 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3160 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3161 
3162 	      if (arg_depth > parm_depth)
3163 		{
3164 		  /* If TMPL is not the most general template (for
3165 		     example, if TMPL is a friend template that is
3166 		     injected into namespace scope), then there will
3167 		     be too many levels of TARGS.  Remove some of them
3168 		     here.  */
3169 		  int i;
3170 		  tree new_targs;
3171 
3172 		  new_targs = make_tree_vec (parm_depth);
3173 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3174 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3175 		      = TREE_VEC_ELT (targs, i);
3176 		  targs = new_targs;
3177 		}
3178 
3179 	      return instantiate_template (tmpl, targs, tf_error);
3180 	    }
3181 
3182 	  /* If we thought that the DECL was a member function, but it
3183 	     turns out to be specializing a static member function,
3184 	     make DECL a static member function as well.  */
3185 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3186 	      && DECL_STATIC_FUNCTION_P (tmpl)
3187 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3188 	    revert_static_member_fn (decl);
3189 
3190 	  /* If this is a specialization of a member template of a
3191 	     template class, we want to return the TEMPLATE_DECL, not
3192 	     the specialization of it.  */
3193 	  if (tsk == tsk_template && !was_template_id)
3194 	    {
3195 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3196 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3197 	      DECL_INITIAL (result) = NULL_TREE;
3198 	      if (have_def)
3199 		{
3200 		  tree parm;
3201 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3202 		  DECL_SOURCE_LOCATION (result)
3203 		    = DECL_SOURCE_LOCATION (decl);
3204 		  /* We want to use the argument list specified in the
3205 		     definition, not in the original declaration.  */
3206 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3207 		  for (parm = DECL_ARGUMENTS (result); parm;
3208 		       parm = DECL_CHAIN (parm))
3209 		    DECL_CONTEXT (parm) = result;
3210 		}
3211 	      return register_specialization (tmpl, gen_tmpl, targs,
3212 					      is_friend, 0);
3213 	    }
3214 
3215 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3216 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3217 
3218 	  if (was_template_id)
3219 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3220 
3221 	  /* Inherit default function arguments from the template
3222 	     DECL is specializing.  */
3223 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3224 	    copy_default_args_to_explicit_spec (decl);
3225 
3226 	  /* This specialization has the same protection as the
3227 	     template it specializes.  */
3228 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3229 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3230 
3231           /* 7.1.1-1 [dcl.stc]
3232 
3233              A storage-class-specifier shall not be specified in an
3234              explicit specialization...
3235 
3236              The parser rejects these, so unless action is taken here,
3237              explicit function specializations will always appear with
3238              global linkage.
3239 
3240              The action recommended by the C++ CWG in response to C++
3241              defect report 605 is to make the storage class and linkage
3242              of the explicit specialization match the templated function:
3243 
3244              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3245            */
3246           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3247             {
3248               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3249               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3250 
3251               /* A concept cannot be specialized.  */
3252               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3253                 {
3254                   error ("explicit specialization of function concept %qD",
3255                          gen_tmpl);
3256                   return error_mark_node;
3257                 }
3258 
3259               /* This specialization has the same linkage and visibility as
3260                  the function template it specializes.  */
3261               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3262 	      if (! TREE_PUBLIC (decl))
3263 		{
3264 		  DECL_INTERFACE_KNOWN (decl) = 1;
3265 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3266 		}
3267               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3268               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3269                 {
3270                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3271                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3272                 }
3273             }
3274 
3275 	  /* If DECL is a friend declaration, declared using an
3276 	     unqualified name, the namespace associated with DECL may
3277 	     have been set incorrectly.  For example, in:
3278 
3279 	       template <typename T> void f(T);
3280 	       namespace N {
3281 		 struct S { friend void f<int>(int); }
3282 	       }
3283 
3284 	     we will have set the DECL_CONTEXT for the friend
3285 	     declaration to N, rather than to the global namespace.  */
3286 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3287 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3288 
3289 	  if (is_friend && !have_def)
3290 	    /* This is not really a declaration of a specialization.
3291 	       It's just the name of an instantiation.  But, it's not
3292 	       a request for an instantiation, either.  */
3293 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3294 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3295 	    /* A specialization is not necessarily COMDAT.  */
3296 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3297 				  && DECL_DECLARED_INLINE_P (decl));
3298 	  else if (VAR_P (decl))
3299 	    DECL_COMDAT (decl) = false;
3300 
3301 	  /* If this is a full specialization, register it so that we can find
3302 	     it again.  Partial specializations will be registered in
3303 	     process_partial_specialization.  */
3304 	  if (!processing_template_decl)
3305 	    {
3306 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3307 
3308 	      decl = register_specialization (decl, gen_tmpl, targs,
3309 					      is_friend, 0);
3310 	    }
3311 
3312 
3313 	  /* A 'structor should already have clones.  */
3314 	  gcc_assert (decl == error_mark_node
3315 		      || variable_template_p (tmpl)
3316 		      || !(DECL_CONSTRUCTOR_P (decl)
3317 			   || DECL_DESTRUCTOR_P (decl))
3318 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3319 	}
3320     }
3321 
3322   return decl;
3323 }
3324 
3325 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3326    parameters.  These are represented in the same format used for
3327    DECL_TEMPLATE_PARMS.  */
3328 
3329 int
comp_template_parms(const_tree parms1,const_tree parms2)3330 comp_template_parms (const_tree parms1, const_tree parms2)
3331 {
3332   const_tree p1;
3333   const_tree p2;
3334 
3335   if (parms1 == parms2)
3336     return 1;
3337 
3338   for (p1 = parms1, p2 = parms2;
3339        p1 != NULL_TREE && p2 != NULL_TREE;
3340        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3341     {
3342       tree t1 = TREE_VALUE (p1);
3343       tree t2 = TREE_VALUE (p2);
3344       int i;
3345 
3346       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3347       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3348 
3349       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3350 	return 0;
3351 
3352       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3353 	{
3354           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3355           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3356 
3357           /* If either of the template parameters are invalid, assume
3358              they match for the sake of error recovery. */
3359           if (error_operand_p (parm1) || error_operand_p (parm2))
3360             return 1;
3361 
3362 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3363 	    return 0;
3364 
3365 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3366               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3367                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3368 	    continue;
3369 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3370 	    return 0;
3371 	}
3372     }
3373 
3374   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3375     /* One set of parameters has more parameters lists than the
3376        other.  */
3377     return 0;
3378 
3379   return 1;
3380 }
3381 
3382 /* Returns true if two template parameters are declared with
3383    equivalent constraints.  */
3384 
3385 static bool
template_parameter_constraints_equivalent_p(const_tree parm1,const_tree parm2)3386 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3387 {
3388   tree req1 = TREE_TYPE (parm1);
3389   tree req2 = TREE_TYPE (parm2);
3390   if (!req1 != !req2)
3391     return false;
3392   if (req1)
3393     return cp_tree_equal (req1, req2);
3394   return true;
3395 }
3396 
3397 /* Returns true when two template parameters are equivalent.  */
3398 
3399 static bool
template_parameters_equivalent_p(const_tree parm1,const_tree parm2)3400 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3401 {
3402   tree decl1 = TREE_VALUE (parm1);
3403   tree decl2 = TREE_VALUE (parm2);
3404 
3405   /* If either of the template parameters are invalid, assume
3406      they match for the sake of error recovery. */
3407   if (error_operand_p (decl1) || error_operand_p (decl2))
3408     return true;
3409 
3410   /* ... they declare parameters of the same kind.  */
3411   if (TREE_CODE (decl1) != TREE_CODE (decl2))
3412     return false;
3413 
3414   /* ... one parameter was introduced by a parameter declaration, then
3415      both are. This case arises as a result of eagerly rewriting declarations
3416      during parsing.  */
3417   if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3418     return false;
3419 
3420   /* ... if either declares a pack, they both do.  */
3421   if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3422     return false;
3423 
3424   if (TREE_CODE (decl1) == PARM_DECL)
3425     {
3426       /* ... if they declare non-type parameters, the types are equivalent.  */
3427       if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3428 	return false;
3429     }
3430   else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3431     {
3432       /* ... if they declare template template parameters, their template
3433 	 parameter lists are equivalent.  */
3434       if (!template_heads_equivalent_p (decl1, decl2))
3435 	return false;
3436     }
3437 
3438   /* ... if they are declared with a qualified-concept name, they both
3439      are, and those names are equivalent.  */
3440   return template_parameter_constraints_equivalent_p (parm1, parm2);
3441 }
3442 
3443 /* Returns true if two template parameters lists are equivalent.
3444    Two template parameter lists are equivalent if they have the
3445    same length and their corresponding parameters are equivalent.
3446 
3447    PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3448    data structure returned by DECL_TEMPLATE_PARMS.
3449 
3450    This is generally the same implementation as comp_template_parms
3451    except that it also the concept names and arguments used to
3452    introduce parameters.  */
3453 
3454 static bool
template_parameter_lists_equivalent_p(const_tree parms1,const_tree parms2)3455 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3456 {
3457   if (parms1 == parms2)
3458     return true;
3459 
3460   const_tree p1 = parms1;
3461   const_tree p2 = parms2;
3462   while (p1 != NULL_TREE && p2 != NULL_TREE)
3463     {
3464       tree list1 = TREE_VALUE (p1);
3465       tree list2 = TREE_VALUE (p2);
3466 
3467       if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3468 	return 0;
3469 
3470       for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3471 	{
3472 	  tree parm1 = TREE_VEC_ELT (list1, i);
3473 	  tree parm2 = TREE_VEC_ELT (list2, i);
3474 	  if (!template_parameters_equivalent_p (parm1, parm2))
3475 	    return false;
3476 	}
3477 
3478       p1 = TREE_CHAIN (p1);
3479       p2 = TREE_CHAIN (p2);
3480     }
3481 
3482   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3483     return false;
3484 
3485   return true;
3486 }
3487 
3488 /* Return true if the requires-clause of the template parameter lists are
3489    equivalent and false otherwise.  */
3490 static bool
template_requirements_equivalent_p(const_tree parms1,const_tree parms2)3491 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3492 {
3493   tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3494   tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3495   if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3496     return false;
3497   if (!cp_tree_equal (req1, req2))
3498     return false;
3499   return true;
3500 }
3501 
3502 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3503    Two template heads are equivalent if their template parameter
3504    lists are equivalent and their requires clauses are equivalent.
3505 
3506    In pre-C++20, this is equivalent to calling comp_template_parms
3507    for the template parameters of TMPL1 and TMPL2.  */
3508 
3509 bool
template_heads_equivalent_p(const_tree tmpl1,const_tree tmpl2)3510 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3511 {
3512   tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3513   tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3514 
3515   /* Don't change the matching rules for pre-C++20.  */
3516   if (cxx_dialect < cxx20)
3517     return comp_template_parms (parms1, parms2);
3518 
3519   /* ... have the same number of template parameters, and their
3520      corresponding parameters are equivalent.  */
3521   if (!template_parameter_lists_equivalent_p (parms1, parms2))
3522     return false;
3523 
3524   /* ... if either has a requires-clause, they both do and their
3525      corresponding constraint-expressions are equivalent.  */
3526   return template_requirements_equivalent_p (parms1, parms2);
3527 }
3528 
3529 /* Determine whether PARM is a parameter pack.  */
3530 
3531 bool
template_parameter_pack_p(const_tree parm)3532 template_parameter_pack_p (const_tree parm)
3533 {
3534   /* Determine if we have a non-type template parameter pack.  */
3535   if (TREE_CODE (parm) == PARM_DECL)
3536     return (DECL_TEMPLATE_PARM_P (parm)
3537             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3538   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3539     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3540 
3541   /* If this is a list of template parameters, we could get a
3542      TYPE_DECL or a TEMPLATE_DECL.  */
3543   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3544     parm = TREE_TYPE (parm);
3545 
3546   /* Otherwise it must be a type template parameter.  */
3547   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3548 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3549 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3550 }
3551 
3552 /* Determine if T is a function parameter pack.  */
3553 
3554 bool
function_parameter_pack_p(const_tree t)3555 function_parameter_pack_p (const_tree t)
3556 {
3557   if (t && TREE_CODE (t) == PARM_DECL)
3558     return DECL_PACK_P (t);
3559   return false;
3560 }
3561 
3562 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3563    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3564 
3565 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3566 get_function_template_decl (const_tree primary_func_tmpl_inst)
3567 {
3568   if (! primary_func_tmpl_inst
3569       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3570       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3571     return NULL;
3572 
3573   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3574 }
3575 
3576 /* Return true iff the function parameter PARAM_DECL was expanded
3577    from the function parameter pack PACK.  */
3578 
3579 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3580 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3581 {
3582   if (DECL_ARTIFICIAL (param_decl)
3583       || !function_parameter_pack_p (pack))
3584     return false;
3585 
3586   /* The parameter pack and its pack arguments have the same
3587      DECL_PARM_INDEX.  */
3588   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3589 }
3590 
3591 /* Determine whether ARGS describes a variadic template args list,
3592    i.e., one that is terminated by a template argument pack.  */
3593 
3594 static bool
template_args_variadic_p(tree args)3595 template_args_variadic_p (tree args)
3596 {
3597   int nargs;
3598   tree last_parm;
3599 
3600   if (args == NULL_TREE)
3601     return false;
3602 
3603   args = INNERMOST_TEMPLATE_ARGS (args);
3604   nargs = TREE_VEC_LENGTH (args);
3605 
3606   if (nargs == 0)
3607     return false;
3608 
3609   last_parm = TREE_VEC_ELT (args, nargs - 1);
3610 
3611   return ARGUMENT_PACK_P (last_parm);
3612 }
3613 
3614 /* Generate a new name for the parameter pack name NAME (an
3615    IDENTIFIER_NODE) that incorporates its */
3616 
3617 static tree
make_ith_pack_parameter_name(tree name,int i)3618 make_ith_pack_parameter_name (tree name, int i)
3619 {
3620   /* Munge the name to include the parameter index.  */
3621 #define NUMBUF_LEN 128
3622   char numbuf[NUMBUF_LEN];
3623   char* newname;
3624   int newname_len;
3625 
3626   if (name == NULL_TREE)
3627     return name;
3628   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3629   newname_len = IDENTIFIER_LENGTH (name)
3630 	        + strlen (numbuf) + 2;
3631   newname = (char*)alloca (newname_len);
3632   snprintf (newname, newname_len,
3633 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3634   return get_identifier (newname);
3635 }
3636 
3637 /* Return true if T is a primary function, class or alias template
3638    specialization, not including the template pattern.  */
3639 
3640 bool
primary_template_specialization_p(const_tree t)3641 primary_template_specialization_p (const_tree t)
3642 {
3643   if (!t)
3644     return false;
3645 
3646   if (VAR_OR_FUNCTION_DECL_P (t))
3647     return (DECL_LANG_SPECIFIC (t)
3648 	    && DECL_USE_TEMPLATE (t)
3649 	    && DECL_TEMPLATE_INFO (t)
3650 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3651   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3652     return (CLASSTYPE_TEMPLATE_INFO (t)
3653 	    && CLASSTYPE_USE_TEMPLATE (t)
3654 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3655   else if (alias_template_specialization_p (t, nt_transparent))
3656     return true;
3657   return false;
3658 }
3659 
3660 /* Return true if PARM is a template template parameter.  */
3661 
3662 bool
template_template_parameter_p(const_tree parm)3663 template_template_parameter_p (const_tree parm)
3664 {
3665   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3666 }
3667 
3668 /* Return true iff PARM is a DECL representing a type template
3669    parameter.  */
3670 
3671 bool
template_type_parameter_p(const_tree parm)3672 template_type_parameter_p (const_tree parm)
3673 {
3674   return (parm
3675 	  && (TREE_CODE (parm) == TYPE_DECL
3676 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3677 	  && DECL_TEMPLATE_PARM_P (parm));
3678 }
3679 
3680 /* Return the template parameters of T if T is a
3681    primary template instantiation, NULL otherwise.  */
3682 
3683 tree
get_primary_template_innermost_parameters(const_tree t)3684 get_primary_template_innermost_parameters (const_tree t)
3685 {
3686   tree parms = NULL, template_info = NULL;
3687 
3688   if ((template_info = get_template_info (t))
3689       && primary_template_specialization_p (t))
3690     parms = INNERMOST_TEMPLATE_PARMS
3691 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3692 
3693   return parms;
3694 }
3695 
3696 /* Return the template parameters of the LEVELth level from the full list
3697    of template parameters PARMS.  */
3698 
3699 tree
get_template_parms_at_level(tree parms,int level)3700 get_template_parms_at_level (tree parms, int level)
3701 {
3702   tree p;
3703   if (!parms
3704       || TREE_CODE (parms) != TREE_LIST
3705       || level > TMPL_PARMS_DEPTH (parms))
3706     return NULL_TREE;
3707 
3708   for (p = parms; p; p = TREE_CHAIN (p))
3709     if (TMPL_PARMS_DEPTH (p) == level)
3710       return p;
3711 
3712   return NULL_TREE;
3713 }
3714 
3715 /* Returns the template arguments of T if T is a template instantiation,
3716    NULL otherwise.  */
3717 
3718 tree
get_template_innermost_arguments(const_tree t)3719 get_template_innermost_arguments (const_tree t)
3720 {
3721   tree args = NULL, template_info = NULL;
3722 
3723   if ((template_info = get_template_info (t))
3724       && TI_ARGS (template_info))
3725     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3726 
3727   return args;
3728 }
3729 
3730 /* Return the argument pack elements of T if T is a template argument pack,
3731    NULL otherwise.  */
3732 
3733 tree
get_template_argument_pack_elems(const_tree t)3734 get_template_argument_pack_elems (const_tree t)
3735 {
3736   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3737       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3738     return NULL;
3739 
3740   return ARGUMENT_PACK_ARGS (t);
3741 }
3742 
3743 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3744    ARGUMENT_PACK_SELECT represents. */
3745 
3746 static tree
argument_pack_select_arg(tree t)3747 argument_pack_select_arg (tree t)
3748 {
3749   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3750   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3751 
3752   /* If the selected argument is an expansion E, that most likely means we were
3753      called from gen_elem_of_pack_expansion_instantiation during the
3754      substituting of an argument pack (of which the Ith element is a pack
3755      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3756      In this case, the Ith element resulting from this substituting is going to
3757      be a pack expansion, which pattern is the pattern of E.  Let's return the
3758      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3759      resulting pack expansion from it.  */
3760   if (PACK_EXPANSION_P (arg))
3761     {
3762       /* Make sure we aren't throwing away arg info.  */
3763       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3764       arg = PACK_EXPANSION_PATTERN (arg);
3765     }
3766 
3767   return arg;
3768 }
3769 
3770 
3771 /* True iff FN is a function representing a built-in variadic parameter
3772    pack.  */
3773 
3774 bool
builtin_pack_fn_p(tree fn)3775 builtin_pack_fn_p (tree fn)
3776 {
3777   if (!fn
3778       || TREE_CODE (fn) != FUNCTION_DECL
3779       || !DECL_IS_UNDECLARED_BUILTIN (fn))
3780     return false;
3781 
3782   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3783     return true;
3784 
3785   return false;
3786 }
3787 
3788 /* True iff CALL is a call to a function representing a built-in variadic
3789    parameter pack.  */
3790 
3791 static bool
builtin_pack_call_p(tree call)3792 builtin_pack_call_p (tree call)
3793 {
3794   if (TREE_CODE (call) != CALL_EXPR)
3795     return false;
3796   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3797 }
3798 
3799 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3800 
3801 static tree
expand_integer_pack(tree call,tree args,tsubst_flags_t complain,tree in_decl)3802 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3803 		     tree in_decl)
3804 {
3805   tree ohi = CALL_EXPR_ARG (call, 0);
3806   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3807 				   false/*fn*/, true/*int_cst*/);
3808 
3809   if (value_dependent_expression_p (hi))
3810     {
3811       if (hi != ohi)
3812 	{
3813 	  call = copy_node (call);
3814 	  CALL_EXPR_ARG (call, 0) = hi;
3815 	}
3816       tree ex = make_pack_expansion (call, complain);
3817       tree vec = make_tree_vec (1);
3818       TREE_VEC_ELT (vec, 0) = ex;
3819       return vec;
3820     }
3821   else
3822     {
3823       hi = cxx_constant_value (hi);
3824       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3825 
3826       /* Calculate the largest value of len that won't make the size of the vec
3827 	 overflow an int.  The compiler will exceed resource limits long before
3828 	 this, but it seems a decent place to diagnose.  */
3829       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3830 
3831       if (len < 0 || len > max)
3832 	{
3833 	  if ((complain & tf_error)
3834 	      && hi != error_mark_node)
3835 	    error ("argument to %<__integer_pack%> must be between 0 and %d",
3836 		   max);
3837 	  return error_mark_node;
3838 	}
3839 
3840       tree vec = make_tree_vec (len);
3841 
3842       for (int i = 0; i < len; ++i)
3843 	TREE_VEC_ELT (vec, i) = size_int (i);
3844 
3845       return vec;
3846     }
3847 }
3848 
3849 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3850    CALL.  */
3851 
3852 static tree
expand_builtin_pack_call(tree call,tree args,tsubst_flags_t complain,tree in_decl)3853 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3854 			  tree in_decl)
3855 {
3856   if (!builtin_pack_call_p (call))
3857     return NULL_TREE;
3858 
3859   tree fn = CALL_EXPR_FN (call);
3860 
3861   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3862     return expand_integer_pack (call, args, complain, in_decl);
3863 
3864   return NULL_TREE;
3865 }
3866 
3867 /* Structure used to track the progress of find_parameter_packs_r.  */
3868 struct find_parameter_pack_data
3869 {
3870   /* TREE_LIST that will contain all of the parameter packs found by
3871      the traversal.  */
3872   tree* parameter_packs;
3873 
3874   /* Set of AST nodes that have been visited by the traversal.  */
3875   hash_set<tree> *visited;
3876 
3877   /* True iff we're making a type pack expansion.  */
3878   bool type_pack_expansion_p;
3879 };
3880 
3881 /* Identifies all of the argument packs that occur in a template
3882    argument and appends them to the TREE_LIST inside DATA, which is a
3883    find_parameter_pack_data structure. This is a subroutine of
3884    make_pack_expansion and uses_parameter_packs.  */
3885 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3886 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3887 {
3888   tree t = *tp;
3889   struct find_parameter_pack_data* ppd =
3890     (struct find_parameter_pack_data*)data;
3891   bool parameter_pack_p = false;
3892 
3893 #define WALK_SUBTREE(NODE)				\
3894   cp_walk_tree (&(NODE), &find_parameter_packs_r,	\
3895 		ppd, ppd->visited)			\
3896 
3897   /* Don't look through typedefs; we are interested in whether a
3898      parameter pack is actually written in the expression/type we're
3899      looking at, not the target type.  */
3900   if (TYPE_P (t) && typedef_variant_p (t))
3901     {
3902       /* But do look at arguments for an alias template.  */
3903       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3904 	cp_walk_tree (&TI_ARGS (tinfo),
3905 		      &find_parameter_packs_r,
3906 		      ppd, ppd->visited);
3907       *walk_subtrees = 0;
3908       return NULL_TREE;
3909     }
3910 
3911   /* Identify whether this is a parameter pack or not.  */
3912   switch (TREE_CODE (t))
3913     {
3914     case TEMPLATE_PARM_INDEX:
3915       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3916         parameter_pack_p = true;
3917       break;
3918 
3919     case TEMPLATE_TYPE_PARM:
3920       t = TYPE_MAIN_VARIANT (t);
3921       /* FALLTHRU */
3922     case TEMPLATE_TEMPLATE_PARM:
3923       /* If the placeholder appears in the decl-specifier-seq of a function
3924 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3925 	 is a pack expansion, the invented template parameter is a template
3926 	 parameter pack.  */
3927       if (ppd->type_pack_expansion_p && is_auto (t))
3928 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3929       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3930         parameter_pack_p = true;
3931       break;
3932 
3933     case FIELD_DECL:
3934     case PARM_DECL:
3935       if (DECL_PACK_P (t))
3936         {
3937           /* We don't want to walk into the type of a PARM_DECL,
3938              because we don't want to see the type parameter pack.  */
3939           *walk_subtrees = 0;
3940 	  parameter_pack_p = true;
3941         }
3942       break;
3943 
3944     case VAR_DECL:
3945       if (DECL_PACK_P (t))
3946         {
3947           /* We don't want to walk into the type of a variadic capture proxy,
3948              because we don't want to see the type parameter pack.  */
3949           *walk_subtrees = 0;
3950 	  parameter_pack_p = true;
3951         }
3952       else if (variable_template_specialization_p (t))
3953 	{
3954 	  cp_walk_tree (&DECL_TI_ARGS (t),
3955 			find_parameter_packs_r,
3956 			ppd, ppd->visited);
3957 	  *walk_subtrees = 0;
3958 	}
3959       break;
3960 
3961     case CALL_EXPR:
3962       if (builtin_pack_call_p (t))
3963 	parameter_pack_p = true;
3964       break;
3965 
3966     case BASES:
3967       parameter_pack_p = true;
3968       break;
3969     default:
3970       /* Not a parameter pack.  */
3971       break;
3972     }
3973 
3974   if (parameter_pack_p)
3975     {
3976       /* Add this parameter pack to the list.  */
3977       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3978     }
3979 
3980   if (TYPE_P (t))
3981     cp_walk_tree (&TYPE_CONTEXT (t),
3982 		  &find_parameter_packs_r, ppd, ppd->visited);
3983 
3984   /* This switch statement will return immediately if we don't find a
3985      parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
3986   switch (TREE_CODE (t))
3987     {
3988     case BOUND_TEMPLATE_TEMPLATE_PARM:
3989       /* Check the template itself.  */
3990       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3991 		    &find_parameter_packs_r, ppd, ppd->visited);
3992       return NULL_TREE;
3993 
3994     case DECL_EXPR:
3995       {
3996 	tree decl = DECL_EXPR_DECL (t);
3997 	/* Ignore the declaration of a capture proxy for a parameter pack.  */
3998 	if (is_capture_proxy (decl))
3999 	  *walk_subtrees = 0;
4000 	if (is_typedef_decl (decl))
4001 	  /* Since we stop at typedefs above, we need to look through them at
4002 	     the point of the DECL_EXPR.  */
4003 	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4004 			&find_parameter_packs_r, ppd, ppd->visited);
4005 	return NULL_TREE;
4006       }
4007 
4008     case TEMPLATE_DECL:
4009       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4010 	return NULL_TREE;
4011       cp_walk_tree (&TREE_TYPE (t),
4012 		    &find_parameter_packs_r, ppd, ppd->visited);
4013       return NULL_TREE;
4014 
4015     case TYPE_PACK_EXPANSION:
4016     case EXPR_PACK_EXPANSION:
4017       *walk_subtrees = 0;
4018       return NULL_TREE;
4019 
4020     case INTEGER_TYPE:
4021       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4022 		    ppd, ppd->visited);
4023       *walk_subtrees = 0;
4024       return NULL_TREE;
4025 
4026     case IDENTIFIER_NODE:
4027       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4028 		    ppd->visited);
4029       *walk_subtrees = 0;
4030       return NULL_TREE;
4031 
4032     case LAMBDA_EXPR:
4033       {
4034 	/* Since we defer implicit capture, look in the parms and body.  */
4035 	tree fn = lambda_function (t);
4036 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4037 		      ppd->visited);
4038 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4039 		      ppd->visited);
4040 	return NULL_TREE;
4041       }
4042 
4043     case DECLTYPE_TYPE:
4044       {
4045 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4046 	   type_pack_expansion_p to false so that any placeholders
4047 	   within the expression don't get marked as parameter packs.  */
4048 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4049 	ppd->type_pack_expansion_p = false;
4050 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4051 		      ppd, ppd->visited);
4052 	ppd->type_pack_expansion_p = type_pack_expansion_p;
4053 	*walk_subtrees = 0;
4054 	return NULL_TREE;
4055       }
4056 
4057     case IF_STMT:
4058       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4059 		    ppd, ppd->visited);
4060       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4061 		    ppd, ppd->visited);
4062       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4063 		    ppd, ppd->visited);
4064       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
4065       *walk_subtrees = 0;
4066       return NULL_TREE;
4067 
4068     case TAG_DEFN:
4069       /* Local class, need to look through the whole definition.  */
4070       t = TREE_TYPE (t);
4071       if (CLASS_TYPE_P (t))
4072 	for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4073 	  cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4074 			ppd, ppd->visited);
4075       return NULL_TREE;
4076 
4077     case FUNCTION_TYPE:
4078     case METHOD_TYPE:
4079       WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4080       break;
4081 
4082     default:
4083       return NULL_TREE;
4084     }
4085 
4086 #undef WALK_SUBTREE
4087 
4088   return NULL_TREE;
4089 }
4090 
4091 /* Determines if the expression or type T uses any parameter packs.  */
4092 tree
uses_parameter_packs(tree t)4093 uses_parameter_packs (tree t)
4094 {
4095   tree parameter_packs = NULL_TREE;
4096   struct find_parameter_pack_data ppd;
4097   ppd.parameter_packs = &parameter_packs;
4098   ppd.visited = new hash_set<tree>;
4099   ppd.type_pack_expansion_p = false;
4100   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4101   delete ppd.visited;
4102   return parameter_packs;
4103 }
4104 
4105 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4106    representation a base-class initializer into a parameter pack
4107    expansion. If all goes well, the resulting node will be an
4108    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4109    respectively.  */
4110 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)4111 make_pack_expansion (tree arg, tsubst_flags_t complain)
4112 {
4113   tree result;
4114   tree parameter_packs = NULL_TREE;
4115   bool for_types = false;
4116   struct find_parameter_pack_data ppd;
4117 
4118   if (!arg || arg == error_mark_node)
4119     return arg;
4120 
4121   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4122     {
4123       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4124          class initializer.  In this case, the TREE_PURPOSE will be a
4125          _TYPE node (representing the base class expansion we're
4126          initializing) and the TREE_VALUE will be a TREE_LIST
4127          containing the initialization arguments.
4128 
4129          The resulting expansion looks somewhat different from most
4130          expansions. Rather than returning just one _EXPANSION, we
4131          return a TREE_LIST whose TREE_PURPOSE is a
4132          TYPE_PACK_EXPANSION containing the bases that will be
4133          initialized.  The TREE_VALUE will be identical to the
4134          original TREE_VALUE, which is a list of arguments that will
4135          be passed to each base.  We do not introduce any new pack
4136          expansion nodes into the TREE_VALUE (although it is possible
4137          that some already exist), because the TREE_PURPOSE and
4138          TREE_VALUE all need to be expanded together with the same
4139          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
4140          resulting TREE_PURPOSE will mention the parameter packs in
4141          both the bases and the arguments to the bases.  */
4142       tree purpose;
4143       tree value;
4144       tree parameter_packs = NULL_TREE;
4145 
4146       /* Determine which parameter packs will be used by the base
4147          class expansion.  */
4148       ppd.visited = new hash_set<tree>;
4149       ppd.parameter_packs = &parameter_packs;
4150       ppd.type_pack_expansion_p = false;
4151       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4152       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4153                     &ppd, ppd.visited);
4154 
4155       if (parameter_packs == NULL_TREE)
4156         {
4157 	  if (complain & tf_error)
4158 	    error ("base initializer expansion %qT contains no parameter packs",
4159 		   arg);
4160           delete ppd.visited;
4161           return error_mark_node;
4162         }
4163 
4164       if (TREE_VALUE (arg) != void_type_node)
4165         {
4166           /* Collect the sets of parameter packs used in each of the
4167              initialization arguments.  */
4168           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4169             {
4170               /* Determine which parameter packs will be expanded in this
4171                  argument.  */
4172               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4173                             &ppd, ppd.visited);
4174             }
4175         }
4176 
4177       delete ppd.visited;
4178 
4179       /* Create the pack expansion type for the base type.  */
4180       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4181       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4182       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4183       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4184 
4185       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4186 	 they will rarely be compared to anything.  */
4187       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4188 
4189       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4190     }
4191 
4192   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4193     for_types = true;
4194 
4195   /* Build the PACK_EXPANSION_* node.  */
4196   result = for_types
4197      ? cxx_make_type (TYPE_PACK_EXPANSION)
4198      : make_node (EXPR_PACK_EXPANSION);
4199   SET_PACK_EXPANSION_PATTERN (result, arg);
4200   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4201     {
4202       /* Propagate type and const-expression information.  */
4203       TREE_TYPE (result) = TREE_TYPE (arg);
4204       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4205       /* Mark this read now, since the expansion might be length 0.  */
4206       mark_exp_read (arg);
4207     }
4208   else
4209     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4210        they will rarely be compared to anything.  */
4211     SET_TYPE_STRUCTURAL_EQUALITY (result);
4212 
4213   /* Determine which parameter packs will be expanded.  */
4214   ppd.parameter_packs = &parameter_packs;
4215   ppd.visited = new hash_set<tree>;
4216   ppd.type_pack_expansion_p = TYPE_P (arg);
4217   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4218   delete ppd.visited;
4219 
4220   /* Make sure we found some parameter packs.  */
4221   if (parameter_packs == NULL_TREE)
4222     {
4223       if (complain & tf_error)
4224 	{
4225 	  if (TYPE_P (arg))
4226 	    error ("expansion pattern %qT contains no parameter packs", arg);
4227 	  else
4228 	    error ("expansion pattern %qE contains no parameter packs", arg);
4229 	}
4230       return error_mark_node;
4231     }
4232   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4233 
4234   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4235 
4236   return result;
4237 }
4238 
4239 /* Checks T for any "bare" parameter packs, which have not yet been
4240    expanded, and issues an error if any are found. This operation can
4241    only be done on full expressions or types (e.g., an expression
4242    statement, "if" condition, etc.), because we could have expressions like:
4243 
4244      foo(f(g(h(args)))...)
4245 
4246    where "args" is a parameter pack. check_for_bare_parameter_packs
4247    should not be called for the subexpressions args, h(args),
4248    g(h(args)), or f(g(h(args))), because we would produce erroneous
4249    error messages.
4250 
4251    Returns TRUE and emits an error if there were bare parameter packs,
4252    returns FALSE otherwise.  */
4253 bool
check_for_bare_parameter_packs(tree t,location_t loc)4254 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4255 {
4256   tree parameter_packs = NULL_TREE;
4257   struct find_parameter_pack_data ppd;
4258 
4259   if (!processing_template_decl || !t || t == error_mark_node)
4260     return false;
4261 
4262   if (TREE_CODE (t) == TYPE_DECL)
4263     t = TREE_TYPE (t);
4264 
4265   ppd.parameter_packs = &parameter_packs;
4266   ppd.visited = new hash_set<tree>;
4267   ppd.type_pack_expansion_p = false;
4268   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4269   delete ppd.visited;
4270 
4271   /* It's OK for a lambda to have an unexpanded parameter pack from the
4272      containing context, but do complain about unexpanded capture packs.  */
4273   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4274       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4275     for (; parameter_packs;
4276 	 parameter_packs = TREE_CHAIN (parameter_packs))
4277       {
4278 	tree pack = TREE_VALUE (parameter_packs);
4279 	if (is_capture_proxy (pack))
4280 	  break;
4281       }
4282 
4283   if (parameter_packs)
4284     {
4285       if (loc == UNKNOWN_LOCATION)
4286 	loc = cp_expr_loc_or_input_loc (t);
4287       error_at (loc, "parameter packs not expanded with %<...%>:");
4288       while (parameter_packs)
4289         {
4290           tree pack = TREE_VALUE (parameter_packs);
4291           tree name = NULL_TREE;
4292 
4293           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4294               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4295             name = TYPE_NAME (pack);
4296           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4297             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4298 	  else if (TREE_CODE (pack) == CALL_EXPR)
4299 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4300           else
4301             name = DECL_NAME (pack);
4302 
4303 	  if (name)
4304 	    inform (loc, "        %qD", name);
4305 	  else
4306 	    inform (loc, "        %s", "<anonymous>");
4307 
4308           parameter_packs = TREE_CHAIN (parameter_packs);
4309         }
4310 
4311       return true;
4312     }
4313 
4314   return false;
4315 }
4316 
4317 /* Expand any parameter packs that occur in the template arguments in
4318    ARGS.  */
4319 tree
expand_template_argument_pack(tree args)4320 expand_template_argument_pack (tree args)
4321 {
4322   if (args == error_mark_node)
4323     return error_mark_node;
4324 
4325   tree result_args = NULL_TREE;
4326   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4327   int num_result_args = -1;
4328   int non_default_args_count = -1;
4329 
4330   /* First, determine if we need to expand anything, and the number of
4331      slots we'll need.  */
4332   for (in_arg = 0; in_arg < nargs; ++in_arg)
4333     {
4334       tree arg = TREE_VEC_ELT (args, in_arg);
4335       if (arg == NULL_TREE)
4336 	return args;
4337       if (ARGUMENT_PACK_P (arg))
4338         {
4339           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4340           if (num_result_args < 0)
4341             num_result_args = in_arg + num_packed;
4342           else
4343             num_result_args += num_packed;
4344         }
4345       else
4346         {
4347           if (num_result_args >= 0)
4348             num_result_args++;
4349         }
4350     }
4351 
4352   /* If no expansion is necessary, we're done.  */
4353   if (num_result_args < 0)
4354     return args;
4355 
4356   /* Expand arguments.  */
4357   result_args = make_tree_vec (num_result_args);
4358   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4359     non_default_args_count =
4360       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4361   for (in_arg = 0; in_arg < nargs; ++in_arg)
4362     {
4363       tree arg = TREE_VEC_ELT (args, in_arg);
4364       if (ARGUMENT_PACK_P (arg))
4365         {
4366           tree packed = ARGUMENT_PACK_ARGS (arg);
4367           int i, num_packed = TREE_VEC_LENGTH (packed);
4368           for (i = 0; i < num_packed; ++i, ++out_arg)
4369             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4370 	  if (non_default_args_count > 0)
4371 	    non_default_args_count += num_packed - 1;
4372         }
4373       else
4374         {
4375           TREE_VEC_ELT (result_args, out_arg) = arg;
4376           ++out_arg;
4377         }
4378     }
4379   if (non_default_args_count >= 0)
4380     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4381   return result_args;
4382 }
4383 
4384 /* Checks if DECL shadows a template parameter.
4385 
4386    [temp.local]: A template-parameter shall not be redeclared within its
4387    scope (including nested scopes).
4388 
4389    Emits an error and returns TRUE if the DECL shadows a parameter,
4390    returns FALSE otherwise.  */
4391 
4392 bool
check_template_shadow(tree decl)4393 check_template_shadow (tree decl)
4394 {
4395   tree olddecl;
4396 
4397   /* If we're not in a template, we can't possibly shadow a template
4398      parameter.  */
4399   if (!current_template_parms)
4400     return true;
4401 
4402   /* Figure out what we're shadowing.  */
4403   decl = OVL_FIRST (decl);
4404   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4405 
4406   /* If there's no previous binding for this name, we're not shadowing
4407      anything, let alone a template parameter.  */
4408   if (!olddecl)
4409     return true;
4410 
4411   /* If we're not shadowing a template parameter, we're done.  Note
4412      that OLDDECL might be an OVERLOAD (or perhaps even an
4413      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4414      node.  */
4415   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4416     return true;
4417 
4418   /* We check for decl != olddecl to avoid bogus errors for using a
4419      name inside a class.  We check TPFI to avoid duplicate errors for
4420      inline member templates.  */
4421   if (decl == olddecl
4422       || (DECL_TEMPLATE_PARM_P (decl)
4423 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4424     return true;
4425 
4426   /* Don't complain about the injected class name, as we've already
4427      complained about the class itself.  */
4428   if (DECL_SELF_REFERENCE_P (decl))
4429     return false;
4430 
4431   if (DECL_TEMPLATE_PARM_P (decl))
4432     error ("declaration of template parameter %q+D shadows "
4433 	   "template parameter", decl);
4434   else
4435     error ("declaration of %q+#D shadows template parameter", decl);
4436   inform (DECL_SOURCE_LOCATION (olddecl),
4437 	  "template parameter %qD declared here", olddecl);
4438   return false;
4439 }
4440 
4441 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4442    ORIG_LEVEL, DECL, and TYPE.  */
4443 
4444 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4445 build_template_parm_index (int index,
4446 			   int level,
4447 			   int orig_level,
4448 			   tree decl,
4449 			   tree type)
4450 {
4451   tree t = make_node (TEMPLATE_PARM_INDEX);
4452   TEMPLATE_PARM_IDX (t) = index;
4453   TEMPLATE_PARM_LEVEL (t) = level;
4454   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4455   TEMPLATE_PARM_DECL (t) = decl;
4456   TREE_TYPE (t) = type;
4457   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4458   TREE_READONLY (t) = TREE_READONLY (decl);
4459 
4460   return t;
4461 }
4462 
4463 /* Find the canonical type parameter for the given template type
4464    parameter.  Returns the canonical type parameter, which may be TYPE
4465    if no such parameter existed.  */
4466 
4467 tree
canonical_type_parameter(tree type)4468 canonical_type_parameter (tree type)
4469 {
4470   int idx = TEMPLATE_TYPE_IDX (type);
4471 
4472   gcc_assert (TREE_CODE (type) != TEMPLATE_TEMPLATE_PARM);
4473 
4474   if (vec_safe_length (canonical_template_parms) <= (unsigned) idx)
4475     vec_safe_grow_cleared (canonical_template_parms, idx + 1, true);
4476 
4477   for (tree list = (*canonical_template_parms)[idx];
4478        list; list = TREE_CHAIN (list))
4479     if (comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4480       return TREE_VALUE (list);
4481 
4482   (*canonical_template_parms)[idx]
4483     = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4484   return type;
4485 }
4486 
4487 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4488    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4489    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4490    new one is created.  */
4491 
4492 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4493 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4494 			    tsubst_flags_t complain)
4495 {
4496   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4497       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4498 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4499       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4500     {
4501       tree orig_decl = TEMPLATE_PARM_DECL (index);
4502 
4503       tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4504 			      TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4505 			      type);
4506       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4507       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4508       DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4509       DECL_ARTIFICIAL (decl) = 1;
4510       SET_DECL_TEMPLATE_PARM_P (decl);
4511 
4512       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4513 					    TEMPLATE_PARM_LEVEL (index) - levels,
4514 					    TEMPLATE_PARM_ORIG_LEVEL (index),
4515 					    decl, type);
4516       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4517       TEMPLATE_PARM_PARAMETER_PACK (tpi)
4518 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4519 
4520       /* Template template parameters need this.  */
4521       tree inner = decl;
4522       if (TREE_CODE (decl) == TEMPLATE_DECL)
4523 	{
4524 	  inner = build_decl (DECL_SOURCE_LOCATION (decl),
4525 			      TYPE_DECL, DECL_NAME (decl), type);
4526 	  DECL_TEMPLATE_RESULT (decl) = inner;
4527 	  DECL_ARTIFICIAL (inner) = true;
4528 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4529 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4530 	}
4531 
4532       /* Attach the TPI to the decl.  */
4533       if (TREE_CODE (inner) == TYPE_DECL)
4534 	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4535       else
4536 	DECL_INITIAL (decl) = tpi;
4537     }
4538 
4539   return TEMPLATE_PARM_DESCENDANTS (index);
4540 }
4541 
4542 /* Process information from new template parameter PARM and append it
4543    to the LIST being built.  This new parameter is a non-type
4544    parameter iff IS_NON_TYPE is true. This new parameter is a
4545    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4546    is in PARM_LOC.  */
4547 
4548 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4549 process_template_parm (tree list, location_t parm_loc, tree parm,
4550 		       bool is_non_type, bool is_parameter_pack)
4551 {
4552   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4553   tree prev = NULL_TREE;
4554   int idx = 0;
4555 
4556   if (list)
4557     {
4558       prev = tree_last (list);
4559 
4560       tree p = TREE_VALUE (prev);
4561       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4562 	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4563       else if (TREE_CODE (p) == PARM_DECL)
4564 	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4565 
4566       ++idx;
4567     }
4568 
4569   tree decl = NULL_TREE;
4570   tree defval = TREE_PURPOSE (parm);
4571   tree constr = TREE_TYPE (parm);
4572 
4573   if (is_non_type)
4574     {
4575       parm = TREE_VALUE (parm);
4576 
4577       SET_DECL_TEMPLATE_PARM_P (parm);
4578 
4579       if (TREE_TYPE (parm) != error_mark_node)
4580 	{
4581 	  /* [temp.param]
4582 
4583 	     The top-level cv-qualifiers on the template-parameter are
4584 	     ignored when determining its type.  */
4585 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4586 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4587 	    TREE_TYPE (parm) = error_mark_node;
4588 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4589 		   && !is_parameter_pack
4590 		   /* If we're in a nested template parameter list, the template
4591 		      template parameter could be a parameter pack.  */
4592 		   && processing_template_parmlist == 1)
4593 	    {
4594 	      /* This template parameter is not a parameter pack, but it
4595 		 should be. Complain about "bare" parameter packs.  */
4596 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4597 
4598 	      /* Recover by calling this a parameter pack.  */
4599 	      is_parameter_pack = true;
4600 	    }
4601 	}
4602 
4603       /* A template parameter is not modifiable.  */
4604       TREE_CONSTANT (parm) = 1;
4605       TREE_READONLY (parm) = 1;
4606       decl = build_decl (parm_loc,
4607 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4608       TREE_CONSTANT (decl) = 1;
4609       TREE_READONLY (decl) = 1;
4610       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4611 	= build_template_parm_index (idx, processing_template_decl,
4612 				     processing_template_decl,
4613 				     decl, TREE_TYPE (parm));
4614 
4615       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4616 	= is_parameter_pack;
4617     }
4618   else
4619     {
4620       tree t;
4621       parm = TREE_VALUE (TREE_VALUE (parm));
4622 
4623       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4624 	{
4625 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4626 	  /* This is for distinguishing between real templates and template
4627 	     template parameters */
4628 	  TREE_TYPE (parm) = t;
4629 
4630 	  /* any_template_parm_r expects to be able to get the targs of a
4631 	     DECL_TEMPLATE_RESULT.  */
4632 	  tree result = DECL_TEMPLATE_RESULT (parm);
4633 	  TREE_TYPE (result) = t;
4634 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4635 	  tree tinfo = build_template_info (parm, args);
4636 	  retrofit_lang_decl (result);
4637 	  DECL_TEMPLATE_INFO (result) = tinfo;
4638 
4639 	  decl = parm;
4640 	}
4641       else
4642 	{
4643 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4644 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4645 	  decl = build_decl (parm_loc,
4646 			     TYPE_DECL, parm, t);
4647 	}
4648 
4649       TYPE_NAME (t) = decl;
4650       TYPE_STUB_DECL (t) = decl;
4651       parm = decl;
4652       TEMPLATE_TYPE_PARM_INDEX (t)
4653 	= build_template_parm_index (idx, processing_template_decl,
4654 				     processing_template_decl,
4655 				     decl, TREE_TYPE (parm));
4656       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4657       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4658 	SET_TYPE_STRUCTURAL_EQUALITY (t);
4659       else
4660 	TYPE_CANONICAL (t) = canonical_type_parameter (t);
4661     }
4662   DECL_ARTIFICIAL (decl) = 1;
4663   SET_DECL_TEMPLATE_PARM_P (decl);
4664 
4665   /* Build requirements for the type/template parameter.
4666      This must be done after SET_DECL_TEMPLATE_PARM_P or
4667      process_template_parm could fail. */
4668   tree reqs = finish_shorthand_constraint (parm, constr);
4669 
4670   decl = pushdecl (decl);
4671   if (!is_non_type)
4672     parm = decl;
4673 
4674   /* Build the parameter node linking the parameter declaration,
4675      its default argument (if any), and its constraints (if any). */
4676   parm = build_tree_list (defval, parm);
4677   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4678 
4679   if (prev)
4680     TREE_CHAIN (prev) = parm;
4681   else
4682     list = parm;
4683 
4684   return list;
4685 }
4686 
4687 /* The end of a template parameter list has been reached.  Process the
4688    tree list into a parameter vector, converting each parameter into a more
4689    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4690    as PARM_DECLs.  */
4691 
4692 tree
end_template_parm_list(tree parms)4693 end_template_parm_list (tree parms)
4694 {
4695   tree saved_parmlist = make_tree_vec (list_length (parms));
4696 
4697   /* Pop the dummy parameter level and add the real one.  We do not
4698      morph the dummy parameter in place, as it might have been
4699      captured by a (nested) template-template-parm.  */
4700   current_template_parms = TREE_CHAIN (current_template_parms);
4701 
4702   current_template_parms
4703     = tree_cons (size_int (processing_template_decl),
4704 		 saved_parmlist, current_template_parms);
4705 
4706   for (unsigned ix = 0; parms; ix++)
4707     {
4708       tree parm = parms;
4709       parms = TREE_CHAIN (parms);
4710       TREE_CHAIN (parm) = NULL_TREE;
4711 
4712       TREE_VEC_ELT (saved_parmlist, ix) = parm;
4713     }
4714 
4715   --processing_template_parmlist;
4716 
4717   return saved_parmlist;
4718 }
4719 
4720 // Explicitly indicate the end of the template parameter list. We assume
4721 // that the current template parameters have been constructed and/or
4722 // managed explicitly, as when creating new template template parameters
4723 // from a shorthand constraint.
4724 void
end_template_parm_list()4725 end_template_parm_list ()
4726 {
4727   --processing_template_parmlist;
4728 }
4729 
4730 /* end_template_decl is called after a template declaration is seen.  */
4731 
4732 void
end_template_decl(void)4733 end_template_decl (void)
4734 {
4735   reset_specialization ();
4736 
4737   if (! processing_template_decl)
4738     return;
4739 
4740   /* This matches the pushlevel in begin_template_parm_list.  */
4741   finish_scope ();
4742 
4743   --processing_template_decl;
4744   current_template_parms = TREE_CHAIN (current_template_parms);
4745 }
4746 
4747 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4748    thereof, and converts it into an argument suitable to be passed to
4749    the type substitution functions.  Note that if the TREE_LIST contains
4750    an error_mark node, the returned argument is error_mark_node.  */
4751 
4752 tree
template_parm_to_arg(tree t)4753 template_parm_to_arg (tree t)
4754 {
4755   if (!t)
4756     return NULL_TREE;
4757 
4758   if (TREE_CODE (t) == TREE_LIST)
4759     t = TREE_VALUE (t);
4760 
4761   if (error_operand_p (t))
4762     return error_mark_node;
4763 
4764   if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4765     {
4766       if (TREE_CODE (t) == TYPE_DECL
4767 	  || TREE_CODE (t) == TEMPLATE_DECL)
4768 	t = TREE_TYPE (t);
4769       else
4770 	t = DECL_INITIAL (t);
4771     }
4772 
4773   gcc_assert (TEMPLATE_PARM_P (t));
4774 
4775   if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4776       || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4777     {
4778       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4779 	{
4780 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4781 	     with a single element, which expands T.  */
4782 	  tree vec = make_tree_vec (1);
4783 	  if (CHECKING_P)
4784 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4785 
4786 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4787 
4788 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4789 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4790 	}
4791     }
4792   else
4793     {
4794       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4795 	{
4796 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4797 	     with a single element, which expands T.  */
4798 	  tree vec = make_tree_vec (1);
4799 	  if (CHECKING_P)
4800 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4801 
4802 	  t = convert_from_reference (t);
4803 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4804 
4805 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4806 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4807 	}
4808       else
4809 	t = convert_from_reference (t);
4810     }
4811   return t;
4812 }
4813 
4814 /* Given a single level of template parameters (a TREE_VEC), return it
4815    as a set of template arguments.  */
4816 
4817 tree
template_parms_level_to_args(tree parms)4818 template_parms_level_to_args (tree parms)
4819 {
4820   tree a = copy_node (parms);
4821   TREE_TYPE (a) = NULL_TREE;
4822   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4823     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4824 
4825   if (CHECKING_P)
4826     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4827 
4828   return a;
4829 }
4830 
4831 /* Given a set of template parameters, return them as a set of template
4832    arguments.  The template parameters are represented as a TREE_VEC, in
4833    the form documented in cp-tree.h for template arguments.  */
4834 
4835 tree
template_parms_to_args(tree parms)4836 template_parms_to_args (tree parms)
4837 {
4838   tree header;
4839   tree args = NULL_TREE;
4840   int length = TMPL_PARMS_DEPTH (parms);
4841   int l = length;
4842 
4843   /* If there is only one level of template parameters, we do not
4844      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4845      TREE_VEC containing the arguments.  */
4846   if (length > 1)
4847     args = make_tree_vec (length);
4848 
4849   for (header = parms; header; header = TREE_CHAIN (header))
4850     {
4851       tree a = template_parms_level_to_args (TREE_VALUE (header));
4852 
4853       if (length > 1)
4854 	TREE_VEC_ELT (args, --l) = a;
4855       else
4856 	args = a;
4857     }
4858 
4859   return args;
4860 }
4861 
4862 /* Within the declaration of a template, return the currently active
4863    template parameters as an argument TREE_VEC.  */
4864 
4865 static tree
current_template_args(void)4866 current_template_args (void)
4867 {
4868   return template_parms_to_args (current_template_parms);
4869 }
4870 
4871 /* Return the fully generic arguments for of TMPL, i.e. what
4872    current_template_args would be while parsing it.  */
4873 
4874 tree
generic_targs_for(tree tmpl)4875 generic_targs_for (tree tmpl)
4876 {
4877   if (tmpl == NULL_TREE)
4878     return NULL_TREE;
4879   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4880       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4881     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4882        template parameter, it has no TEMPLATE_INFO; for a partial
4883        specialization, it has the arguments for the primary template, and we
4884        want the arguments for the partial specialization.  */;
4885   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4886     if (tree ti = get_template_info (result))
4887       return TI_ARGS (ti);
4888   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4889 }
4890 
4891 /* Update the declared TYPE by doing any lookups which were thought to be
4892    dependent, but are not now that we know the SCOPE of the declarator.  */
4893 
4894 tree
maybe_update_decl_type(tree orig_type,tree scope)4895 maybe_update_decl_type (tree orig_type, tree scope)
4896 {
4897   tree type = orig_type;
4898 
4899   if (type == NULL_TREE)
4900     return type;
4901 
4902   if (TREE_CODE (orig_type) == TYPE_DECL)
4903     type = TREE_TYPE (type);
4904 
4905   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4906       && dependent_type_p (type)
4907       /* Don't bother building up the args in this case.  */
4908       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4909     {
4910       /* tsubst in the args corresponding to the template parameters,
4911 	 including auto if present.  Most things will be unchanged, but
4912 	 make_typename_type and tsubst_qualified_id will resolve
4913 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4914       tree args = current_template_args ();
4915       tree auto_node = type_uses_auto (type);
4916       tree pushed;
4917       if (auto_node)
4918 	{
4919 	  tree auto_vec = make_tree_vec (1);
4920 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4921 	  args = add_to_template_args (args, auto_vec);
4922 	}
4923       pushed = push_scope (scope);
4924       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4925       if (pushed)
4926 	pop_scope (scope);
4927     }
4928 
4929   if (type == error_mark_node)
4930     return orig_type;
4931 
4932   if (TREE_CODE (orig_type) == TYPE_DECL)
4933     {
4934       if (same_type_p (type, TREE_TYPE (orig_type)))
4935 	type = orig_type;
4936       else
4937 	type = TYPE_NAME (type);
4938     }
4939   return type;
4940 }
4941 
4942 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4943    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4944    the new  template is a member template. */
4945 
4946 static tree
build_template_decl(tree decl,tree parms,bool member_template_p)4947 build_template_decl (tree decl, tree parms, bool member_template_p)
4948 {
4949   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4950   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4951   DECL_TEMPLATE_PARMS (tmpl) = parms;
4952   DECL_TEMPLATE_RESULT (tmpl) = decl;
4953   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4954   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4955   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4956   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4957 
4958   /* Propagate module information from the decl.  */
4959   DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
4960 
4961   return tmpl;
4962 }
4963 
4964 struct template_parm_data
4965 {
4966   /* The level of the template parameters we are currently
4967      processing.  */
4968   int level;
4969 
4970   /* The index of the specialization argument we are currently
4971      processing.  */
4972   int current_arg;
4973 
4974   /* An array whose size is the number of template parameters.  The
4975      elements are nonzero if the parameter has been used in any one
4976      of the arguments processed so far.  */
4977   int* parms;
4978 
4979   /* An array whose size is the number of template arguments.  The
4980      elements are nonzero if the argument makes use of template
4981      parameters of this level.  */
4982   int* arg_uses_template_parms;
4983 };
4984 
4985 /* Subroutine of push_template_decl used to see if each template
4986    parameter in a partial specialization is used in the explicit
4987    argument list.  If T is of the LEVEL given in DATA (which is
4988    treated as a template_parm_data*), then DATA->PARMS is marked
4989    appropriately.  */
4990 
4991 static int
mark_template_parm(tree t,void * data)4992 mark_template_parm (tree t, void* data)
4993 {
4994   int level;
4995   int idx;
4996   struct template_parm_data* tpd = (struct template_parm_data*) data;
4997 
4998   template_parm_level_and_index (t, &level, &idx);
4999 
5000   if (level == tpd->level)
5001     {
5002       tpd->parms[idx] = 1;
5003       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5004     }
5005 
5006   /* In C++17 the type of a non-type argument is a deduced context.  */
5007   if (cxx_dialect >= cxx17
5008       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5009     for_each_template_parm (TREE_TYPE (t),
5010 			    &mark_template_parm,
5011 			    data,
5012 			    NULL,
5013 			    /*include_nondeduced_p=*/false);
5014 
5015   /* Return zero so that for_each_template_parm will continue the
5016      traversal of the tree; we want to mark *every* template parm.  */
5017   return 0;
5018 }
5019 
5020 /* Process the partial specialization DECL.  */
5021 
5022 static tree
process_partial_specialization(tree decl)5023 process_partial_specialization (tree decl)
5024 {
5025   tree type = TREE_TYPE (decl);
5026   tree tinfo = get_template_info (decl);
5027   tree maintmpl = TI_TEMPLATE (tinfo);
5028   tree specargs = TI_ARGS (tinfo);
5029   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5030   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5031   tree inner_parms;
5032   tree inst;
5033   int nargs = TREE_VEC_LENGTH (inner_args);
5034   int ntparms;
5035   int  i;
5036   bool did_error_intro = false;
5037   struct template_parm_data tpd;
5038   struct template_parm_data tpd2;
5039 
5040   gcc_assert (current_template_parms);
5041 
5042   /* A concept cannot be specialized.  */
5043   if (flag_concepts && variable_concept_p (maintmpl))
5044     {
5045       error ("specialization of variable concept %q#D", maintmpl);
5046       return error_mark_node;
5047     }
5048 
5049   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5050   ntparms = TREE_VEC_LENGTH (inner_parms);
5051 
5052   /* We check that each of the template parameters given in the
5053      partial specialization is used in the argument list to the
5054      specialization.  For example:
5055 
5056        template <class T> struct S;
5057        template <class T> struct S<T*>;
5058 
5059      The second declaration is OK because `T*' uses the template
5060      parameter T, whereas
5061 
5062        template <class T> struct S<int>;
5063 
5064      is no good.  Even trickier is:
5065 
5066        template <class T>
5067        struct S1
5068        {
5069 	  template <class U>
5070 	  struct S2;
5071 	  template <class U>
5072 	  struct S2<T>;
5073        };
5074 
5075      The S2<T> declaration is actually invalid; it is a
5076      full-specialization.  Of course,
5077 
5078 	  template <class U>
5079 	  struct S2<T (*)(U)>;
5080 
5081      or some such would have been OK.  */
5082   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5083   tpd.parms = XALLOCAVEC (int, ntparms);
5084   memset (tpd.parms, 0, sizeof (int) * ntparms);
5085 
5086   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5087   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5088   for (i = 0; i < nargs; ++i)
5089     {
5090       tpd.current_arg = i;
5091       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5092 			      &mark_template_parm,
5093 			      &tpd,
5094 			      NULL,
5095 			      /*include_nondeduced_p=*/false);
5096     }
5097   for (i = 0; i < ntparms; ++i)
5098     if (tpd.parms[i] == 0)
5099       {
5100 	/* One of the template parms was not used in a deduced context in the
5101 	   specialization.  */
5102 	if (!did_error_intro)
5103 	  {
5104 	    error ("template parameters not deducible in "
5105 		   "partial specialization:");
5106 	    did_error_intro = true;
5107 	  }
5108 
5109 	inform (input_location, "        %qD",
5110 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5111       }
5112 
5113   if (did_error_intro)
5114     return error_mark_node;
5115 
5116   /* [temp.class.spec]
5117 
5118      The argument list of the specialization shall not be identical to
5119      the implicit argument list of the primary template.  */
5120   tree main_args
5121     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5122   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5123       && (!flag_concepts
5124 	  || !strictly_subsumes (current_template_constraints (), maintmpl)))
5125     {
5126       if (!flag_concepts)
5127         error ("partial specialization %q+D does not specialize "
5128 	       "any template arguments; to define the primary template, "
5129 	       "remove the template argument list", decl);
5130       else
5131         error ("partial specialization %q+D does not specialize any "
5132 	       "template arguments and is not more constrained than "
5133 	       "the primary template; to define the primary template, "
5134 	       "remove the template argument list", decl);
5135       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5136     }
5137 
5138   /* A partial specialization that replaces multiple parameters of the
5139      primary template with a pack expansion is less specialized for those
5140      parameters.  */
5141   if (nargs < DECL_NTPARMS (maintmpl))
5142     {
5143       error ("partial specialization is not more specialized than the "
5144 	     "primary template because it replaces multiple parameters "
5145 	     "with a pack expansion");
5146       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5147       /* Avoid crash in process_partial_specialization.  */
5148       return decl;
5149     }
5150 
5151   else if (nargs > DECL_NTPARMS (maintmpl))
5152     {
5153       error ("too many arguments for partial specialization %qT", type);
5154       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5155       /* Avoid crash below.  */
5156       return decl;
5157     }
5158 
5159   /* If we aren't in a dependent class, we can actually try deduction.  */
5160   else if (tpd.level == 1
5161 	   /* FIXME we should be able to handle a partial specialization of a
5162 	      partial instantiation, but currently we can't (c++/41727).  */
5163 	   && TMPL_ARGS_DEPTH (specargs) == 1
5164 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5165     {
5166       auto_diagnostic_group d;
5167       if (permerror (input_location, "partial specialization %qD is not "
5168 		     "more specialized than", decl))
5169 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5170 		maintmpl);
5171     }
5172 
5173   /* [temp.class.spec]
5174 
5175      A partially specialized non-type argument expression shall not
5176      involve template parameters of the partial specialization except
5177      when the argument expression is a simple identifier.
5178 
5179      The type of a template parameter corresponding to a specialized
5180      non-type argument shall not be dependent on a parameter of the
5181      specialization.
5182 
5183      Also, we verify that pack expansions only occur at the
5184      end of the argument list.  */
5185   tpd2.parms = 0;
5186   for (i = 0; i < nargs; ++i)
5187     {
5188       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5189       tree arg = TREE_VEC_ELT (inner_args, i);
5190       tree packed_args = NULL_TREE;
5191       int j, len = 1;
5192 
5193       if (ARGUMENT_PACK_P (arg))
5194         {
5195           /* Extract the arguments from the argument pack. We'll be
5196              iterating over these in the following loop.  */
5197           packed_args = ARGUMENT_PACK_ARGS (arg);
5198           len = TREE_VEC_LENGTH (packed_args);
5199         }
5200 
5201       for (j = 0; j < len; j++)
5202         {
5203           if (packed_args)
5204             /* Get the Jth argument in the parameter pack.  */
5205             arg = TREE_VEC_ELT (packed_args, j);
5206 
5207           if (PACK_EXPANSION_P (arg))
5208             {
5209               /* Pack expansions must come at the end of the
5210                  argument list.  */
5211               if ((packed_args && j < len - 1)
5212                   || (!packed_args && i < nargs - 1))
5213                 {
5214                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5215                     error ("parameter pack argument %qE must be at the "
5216 			   "end of the template argument list", arg);
5217                   else
5218                     error ("parameter pack argument %qT must be at the "
5219 			   "end of the template argument list", arg);
5220                 }
5221             }
5222 
5223           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5224             /* We only care about the pattern.  */
5225             arg = PACK_EXPANSION_PATTERN (arg);
5226 
5227           if (/* These first two lines are the `non-type' bit.  */
5228               !TYPE_P (arg)
5229               && TREE_CODE (arg) != TEMPLATE_DECL
5230               /* This next two lines are the `argument expression is not just a
5231                  simple identifier' condition and also the `specialized
5232                  non-type argument' bit.  */
5233               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5234 	      && !((REFERENCE_REF_P (arg)
5235 		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5236 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5237             {
5238               if ((!packed_args && tpd.arg_uses_template_parms[i])
5239                   || (packed_args && uses_template_parms (arg)))
5240 		error_at (cp_expr_loc_or_input_loc (arg),
5241 			  "template argument %qE involves template "
5242 			  "parameter(s)", arg);
5243               else
5244                 {
5245                   /* Look at the corresponding template parameter,
5246                      marking which template parameters its type depends
5247                      upon.  */
5248                   tree type = TREE_TYPE (parm);
5249 
5250                   if (!tpd2.parms)
5251                     {
5252                       /* We haven't yet initialized TPD2.  Do so now.  */
5253                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5254                       /* The number of parameters here is the number in the
5255                          main template, which, as checked in the assertion
5256                          above, is NARGS.  */
5257                       tpd2.parms = XALLOCAVEC (int, nargs);
5258                       tpd2.level =
5259                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5260                     }
5261 
5262                   /* Mark the template parameters.  But this time, we're
5263                      looking for the template parameters of the main
5264                      template, not in the specialization.  */
5265                   tpd2.current_arg = i;
5266                   tpd2.arg_uses_template_parms[i] = 0;
5267                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5268                   for_each_template_parm (type,
5269                                           &mark_template_parm,
5270                                           &tpd2,
5271                                           NULL,
5272 					  /*include_nondeduced_p=*/false);
5273 
5274                   if (tpd2.arg_uses_template_parms [i])
5275                     {
5276                       /* The type depended on some template parameters.
5277                          If they are fully specialized in the
5278                          specialization, that's OK.  */
5279                       int j;
5280                       int count = 0;
5281                       for (j = 0; j < nargs; ++j)
5282                         if (tpd2.parms[j] != 0
5283                             && tpd.arg_uses_template_parms [j])
5284                           ++count;
5285                       if (count != 0)
5286                         error_n (input_location, count,
5287                                  "type %qT of template argument %qE depends "
5288                                  "on a template parameter",
5289                                  "type %qT of template argument %qE depends "
5290                                  "on template parameters",
5291                                  type,
5292                                  arg);
5293                     }
5294                 }
5295             }
5296         }
5297     }
5298 
5299   /* We should only get here once.  */
5300   if (TREE_CODE (decl) == TYPE_DECL)
5301     gcc_assert (!COMPLETE_TYPE_P (type));
5302 
5303   // Build the template decl.
5304   tree tmpl = build_template_decl (decl, current_template_parms,
5305 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5306   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5307   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5308   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5309 
5310   /* Give template template parms a DECL_CONTEXT of the template
5311      for which they are a parameter.  */
5312   for (i = 0; i < ntparms; ++i)
5313     {
5314       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5315       if (TREE_CODE (parm) == TEMPLATE_DECL)
5316 	DECL_CONTEXT (parm) = tmpl;
5317     }
5318 
5319   if (VAR_P (decl))
5320     /* We didn't register this in check_explicit_specialization so we could
5321        wait until the constraints were set.  */
5322     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5323   else
5324     associate_classtype_constraints (type);
5325 
5326   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5327     = tree_cons (specargs, tmpl,
5328                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5329   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5330 
5331   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5332        inst = TREE_CHAIN (inst))
5333     {
5334       tree instance = TREE_VALUE (inst);
5335       if (TYPE_P (instance)
5336 	  ? (COMPLETE_TYPE_P (instance)
5337 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5338 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5339 	{
5340 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5341 	  tree inst_decl = (DECL_P (instance)
5342 			    ? instance : TYPE_NAME (instance));
5343 	  if (!spec)
5344 	    /* OK */;
5345 	  else if (spec == error_mark_node)
5346 	    permerror (input_location,
5347 		       "declaration of %qD ambiguates earlier template "
5348 		       "instantiation for %qD", decl, inst_decl);
5349 	  else if (TREE_VALUE (spec) == tmpl)
5350 	    permerror (input_location,
5351 		       "partial specialization of %qD after instantiation "
5352 		       "of %qD", decl, inst_decl);
5353 	}
5354     }
5355 
5356   return decl;
5357 }
5358 
5359 /* PARM is a template parameter of some form; return the corresponding
5360    TEMPLATE_PARM_INDEX.  */
5361 
5362 static tree
get_template_parm_index(tree parm)5363 get_template_parm_index (tree parm)
5364 {
5365   if (TREE_CODE (parm) == PARM_DECL
5366       || TREE_CODE (parm) == CONST_DECL)
5367     parm = DECL_INITIAL (parm);
5368   else if (TREE_CODE (parm) == TYPE_DECL
5369 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5370     parm = TREE_TYPE (parm);
5371   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5372       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5373       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5374     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5375   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5376   return parm;
5377 }
5378 
5379 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5380    parameter packs used by the template parameter PARM.  */
5381 
5382 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5383 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5384 {
5385   /* A type parm can't refer to another parm.  */
5386   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5387     return;
5388   else if (TREE_CODE (parm) == PARM_DECL)
5389     {
5390       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5391 		    ppd, ppd->visited);
5392       return;
5393     }
5394 
5395   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5396 
5397   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5398   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5399     {
5400       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5401       if (template_parameter_pack_p (p))
5402 	/* Any packs in the type are expanded by this parameter.  */;
5403       else
5404 	fixed_parameter_pack_p_1 (p, ppd);
5405     }
5406 }
5407 
5408 /* PARM is a template parameter pack.  Return any parameter packs used in
5409    its type or the type of any of its template parameters.  If there are
5410    any such packs, it will be instantiated into a fixed template parameter
5411    list by partial instantiation rather than be fully deduced.  */
5412 
5413 tree
fixed_parameter_pack_p(tree parm)5414 fixed_parameter_pack_p (tree parm)
5415 {
5416   /* This can only be true in a member template.  */
5417   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5418     return NULL_TREE;
5419   /* This can only be true for a parameter pack.  */
5420   if (!template_parameter_pack_p (parm))
5421     return NULL_TREE;
5422   /* A type parm can't refer to another parm.  */
5423   if (TREE_CODE (parm) == TYPE_DECL)
5424     return NULL_TREE;
5425 
5426   tree parameter_packs = NULL_TREE;
5427   struct find_parameter_pack_data ppd;
5428   ppd.parameter_packs = &parameter_packs;
5429   ppd.visited = new hash_set<tree>;
5430   ppd.type_pack_expansion_p = false;
5431 
5432   fixed_parameter_pack_p_1 (parm, &ppd);
5433 
5434   delete ppd.visited;
5435   return parameter_packs;
5436 }
5437 
5438 /* Check that a template declaration's use of default arguments and
5439    parameter packs is not invalid.  Here, PARMS are the template
5440    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5441    a primary template.  IS_PARTIAL is true if DECL is a partial
5442    specialization.
5443 
5444    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5445    function template declaration or a friend class template
5446    declaration.  In the function case, 1 indicates a declaration, 2
5447    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5448    emitted for extraneous default arguments.
5449 
5450    Returns TRUE if there were no errors found, FALSE otherwise. */
5451 
5452 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5453 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5454                          bool is_partial, int is_friend_decl)
5455 {
5456   const char *msg;
5457   int last_level_to_check;
5458   tree parm_level;
5459   bool no_errors = true;
5460 
5461   /* [temp.param]
5462 
5463      A default template-argument shall not be specified in a
5464      function template declaration or a function template definition, nor
5465      in the template-parameter-list of the definition of a member of a
5466      class template.  */
5467 
5468   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5469       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5470     /* You can't have a function template declaration in a local
5471        scope, nor you can you define a member of a class template in a
5472        local scope.  */
5473     return true;
5474 
5475   if ((TREE_CODE (decl) == TYPE_DECL
5476        && TREE_TYPE (decl)
5477        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5478       || (TREE_CODE (decl) == FUNCTION_DECL
5479 	  && LAMBDA_FUNCTION_P (decl)))
5480     /* A lambda doesn't have an explicit declaration; don't complain
5481        about the parms of the enclosing class.  */
5482     return true;
5483 
5484   if (current_class_type
5485       && !TYPE_BEING_DEFINED (current_class_type)
5486       && DECL_LANG_SPECIFIC (decl)
5487       && DECL_DECLARES_FUNCTION_P (decl)
5488       /* If this is either a friend defined in the scope of the class
5489 	 or a member function.  */
5490       && (DECL_FUNCTION_MEMBER_P (decl)
5491 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5492 	  : DECL_FRIEND_CONTEXT (decl)
5493 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5494 	  : false)
5495       /* And, if it was a member function, it really was defined in
5496 	 the scope of the class.  */
5497       && (!DECL_FUNCTION_MEMBER_P (decl)
5498 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5499     /* We already checked these parameters when the template was
5500        declared, so there's no need to do it again now.  This function
5501        was defined in class scope, but we're processing its body now
5502        that the class is complete.  */
5503     return true;
5504 
5505   /* Core issue 226 (C++0x only): the following only applies to class
5506      templates.  */
5507   if (is_primary
5508       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5509     {
5510       /* [temp.param]
5511 
5512          If a template-parameter has a default template-argument, all
5513          subsequent template-parameters shall have a default
5514          template-argument supplied.  */
5515       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5516         {
5517           tree inner_parms = TREE_VALUE (parm_level);
5518           int ntparms = TREE_VEC_LENGTH (inner_parms);
5519           int seen_def_arg_p = 0;
5520           int i;
5521 
5522           for (i = 0; i < ntparms; ++i)
5523             {
5524               tree parm = TREE_VEC_ELT (inner_parms, i);
5525 
5526               if (parm == error_mark_node)
5527                 continue;
5528 
5529               if (TREE_PURPOSE (parm))
5530                 seen_def_arg_p = 1;
5531               else if (seen_def_arg_p
5532 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5533                 {
5534                   error ("no default argument for %qD", TREE_VALUE (parm));
5535                   /* For better subsequent error-recovery, we indicate that
5536                      there should have been a default argument.  */
5537                   TREE_PURPOSE (parm) = error_mark_node;
5538                   no_errors = false;
5539                 }
5540 	      else if (!is_partial
5541 		       && !is_friend_decl
5542 		       /* Don't complain about an enclosing partial
5543 			  specialization.  */
5544 		       && parm_level == parms
5545 		       && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5546 		       && i < ntparms - 1
5547 		       && template_parameter_pack_p (TREE_VALUE (parm))
5548 		       /* A fixed parameter pack will be partially
5549 			  instantiated into a fixed length list.  */
5550 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5551 		{
5552 		  /* A primary class template, primary variable template
5553 		     (DR 2032), or alias template can only have one
5554 		     parameter pack, at the end of the template
5555 		     parameter list.  */
5556 
5557 		  error ("parameter pack %q+D must be at the end of the"
5558 			 " template parameter list", TREE_VALUE (parm));
5559 
5560 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5561 		    = error_mark_node;
5562 		  no_errors = false;
5563 		}
5564             }
5565         }
5566     }
5567 
5568   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5569       || is_partial
5570       || !is_primary
5571       || is_friend_decl)
5572     /* For an ordinary class template, default template arguments are
5573        allowed at the innermost level, e.g.:
5574 	 template <class T = int>
5575 	 struct S {};
5576        but, in a partial specialization, they're not allowed even
5577        there, as we have in [temp.class.spec]:
5578 
5579 	 The template parameter list of a specialization shall not
5580 	 contain default template argument values.
5581 
5582        So, for a partial specialization, or for a function template
5583        (in C++98/C++03), we look at all of them.  */
5584     ;
5585   else
5586     /* But, for a primary class template that is not a partial
5587        specialization we look at all template parameters except the
5588        innermost ones.  */
5589     parms = TREE_CHAIN (parms);
5590 
5591   /* Figure out what error message to issue.  */
5592   if (is_friend_decl == 2)
5593     msg = G_("default template arguments may not be used in function template "
5594 	     "friend re-declaration");
5595   else if (is_friend_decl)
5596     msg = G_("default template arguments may not be used in template "
5597 	     "friend declarations");
5598   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5599     msg = G_("default template arguments may not be used in function templates "
5600 	     "without %<-std=c++11%> or %<-std=gnu++11%>");
5601   else if (is_partial)
5602     msg = G_("default template arguments may not be used in "
5603 	     "partial specializations");
5604   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5605     msg = G_("default argument for template parameter for class enclosing %qD");
5606   else
5607     /* Per [temp.param]/9, "A default template-argument shall not be
5608        specified in the template-parameter-lists of the definition of
5609        a member of a class template that appears outside of the member's
5610        class.", thus if we aren't handling a member of a class template
5611        there is no need to examine the parameters.  */
5612     return true;
5613 
5614   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5615     /* If we're inside a class definition, there's no need to
5616        examine the parameters to the class itself.  On the one
5617        hand, they will be checked when the class is defined, and,
5618        on the other, default arguments are valid in things like:
5619 	 template <class T = double>
5620 	 struct S { template <class U> void f(U); };
5621        Here the default argument for `S' has no bearing on the
5622        declaration of `f'.  */
5623     last_level_to_check = template_class_depth (current_class_type) + 1;
5624   else
5625     /* Check everything.  */
5626     last_level_to_check = 0;
5627 
5628   for (parm_level = parms;
5629        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5630        parm_level = TREE_CHAIN (parm_level))
5631     {
5632       tree inner_parms = TREE_VALUE (parm_level);
5633       int i;
5634       int ntparms;
5635 
5636       ntparms = TREE_VEC_LENGTH (inner_parms);
5637       for (i = 0; i < ntparms; ++i)
5638         {
5639           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5640             continue;
5641 
5642 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5643 	    {
5644 	      if (msg)
5645 	        {
5646                   no_errors = false;
5647                   if (is_friend_decl == 2)
5648                     return no_errors;
5649 
5650 		  error (msg, decl);
5651 		  msg = 0;
5652 	        }
5653 
5654 	      /* Clear out the default argument so that we are not
5655 	         confused later.  */
5656 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5657 	    }
5658         }
5659 
5660       /* At this point, if we're still interested in issuing messages,
5661 	 they must apply to classes surrounding the object declared.  */
5662       if (msg)
5663 	msg = G_("default argument for template parameter for class "
5664 		 "enclosing %qD");
5665     }
5666 
5667   return no_errors;
5668 }
5669 
5670 /* Worker for push_template_decl_real, called via
5671    for_each_template_parm.  DATA is really an int, indicating the
5672    level of the parameters we are interested in.  If T is a template
5673    parameter of that level, return nonzero.  */
5674 
5675 static int
template_parm_this_level_p(tree t,void * data)5676 template_parm_this_level_p (tree t, void* data)
5677 {
5678   int this_level = *(int *)data;
5679   int level;
5680 
5681   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5682     level = TEMPLATE_PARM_LEVEL (t);
5683   else
5684     level = TEMPLATE_TYPE_LEVEL (t);
5685   return level == this_level;
5686 }
5687 
5688 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5689    DATA is really an int, indicating the innermost outer level of parameters.
5690    If T is a template parameter of that level or further out, return
5691    nonzero.  */
5692 
5693 static int
template_parm_outer_level(tree t,void * data)5694 template_parm_outer_level (tree t, void *data)
5695 {
5696   int this_level = *(int *)data;
5697   int level;
5698 
5699   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5700     level = TEMPLATE_PARM_LEVEL (t);
5701   else
5702     level = TEMPLATE_TYPE_LEVEL (t);
5703   return level <= this_level;
5704 }
5705 
5706 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5707    parameters given by current_template_args, or reuses a
5708    previously existing one, if appropriate.  Returns the DECL, or an
5709    equivalent one, if it is replaced via a call to duplicate_decls.
5710 
5711    If IS_FRIEND is true, DECL is a friend declaration.  */
5712 
5713 tree
push_template_decl(tree decl,bool is_friend)5714 push_template_decl (tree decl, bool is_friend)
5715 {
5716   if (decl == error_mark_node || !current_template_parms)
5717     return error_mark_node;
5718 
5719   /* See if this is a partial specialization.  */
5720   bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5721 		      && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5722 		      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5723 		     || (VAR_P (decl)
5724 			 && DECL_LANG_SPECIFIC (decl)
5725 			 && DECL_TEMPLATE_SPECIALIZATION (decl)
5726 			 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5727 
5728   /* No surprising friend functions.  */
5729   gcc_checking_assert (is_friend
5730 		       || !(TREE_CODE (decl) == FUNCTION_DECL
5731 			    && DECL_UNIQUE_FRIEND_P (decl)));
5732 
5733   tree ctx;
5734   if (is_friend)
5735     /* For a friend, we want the context of the friend, not
5736        the type of which it is a friend.  */
5737     ctx = CP_DECL_CONTEXT (decl);
5738   else if (CP_DECL_CONTEXT (decl)
5739 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5740     /* In the case of a virtual function, we want the class in which
5741        it is defined.  */
5742     ctx = CP_DECL_CONTEXT (decl);
5743   else
5744     /* Otherwise, if we're currently defining some class, the DECL
5745        is assumed to be a member of the class.  */
5746     ctx = current_scope ();
5747 
5748   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5749     ctx = NULL_TREE;
5750 
5751   if (!DECL_CONTEXT (decl))
5752     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5753 
5754   /* See if this is a primary template.  */
5755   bool is_primary = false;
5756   if (is_friend && ctx
5757       && uses_template_parms_level (ctx, processing_template_decl))
5758     /* A friend template that specifies a class context, i.e.
5759          template <typename T> friend void A<T>::f();
5760        is not primary.  */
5761     ;
5762   else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5763     /* Lambdas are not primary.  */
5764     ;
5765   else
5766     is_primary = template_parm_scope_p ();
5767 
5768   /* True if the template is a member template, in the sense of
5769      [temp.mem].  */
5770   bool member_template_p = false;
5771 
5772   if (is_primary)
5773     {
5774       warning (OPT_Wtemplates, "template %qD declared", decl);
5775 
5776       if (DECL_CLASS_SCOPE_P (decl))
5777 	member_template_p = true;
5778 
5779       if (TREE_CODE (decl) == TYPE_DECL
5780 	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5781 	{
5782 	  error ("template class without a name");
5783 	  return error_mark_node;
5784 	}
5785       else if (TREE_CODE (decl) == FUNCTION_DECL)
5786 	{
5787 	  if (member_template_p)
5788 	    {
5789 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5790 		error ("member template %qD may not have virt-specifiers", decl);
5791 	    }
5792 	  if (DECL_DESTRUCTOR_P (decl))
5793 	    {
5794 	      /* [temp.mem]
5795 
5796 		 A destructor shall not be a member template.  */
5797 	      error_at (DECL_SOURCE_LOCATION (decl),
5798 			"destructor %qD declared as member template", decl);
5799 	      return error_mark_node;
5800 	    }
5801 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5802 	      && (!prototype_p (TREE_TYPE (decl))
5803 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5804 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5805 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5806 		      == void_list_node)))
5807 	    {
5808 	      /* [basic.stc.dynamic.allocation]
5809 
5810 		 An allocation function can be a function
5811 		 template. ... Template allocation functions shall
5812 		 have two or more parameters.  */
5813 	      error ("invalid template declaration of %qD", decl);
5814 	      return error_mark_node;
5815 	    }
5816 	}
5817       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5818 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5819 	{
5820 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5821 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5822 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5823 	    {
5824 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5825 	      if (TREE_CODE (t) == TYPE_DECL)
5826 		t = TREE_TYPE (t);
5827 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5828 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5829 	    }
5830 	}
5831       else if (TREE_CODE (decl) == TYPE_DECL
5832 	       && TYPE_DECL_ALIAS_P (decl))
5833 	/* alias-declaration */
5834 	gcc_assert (!DECL_ARTIFICIAL (decl));
5835       else if (VAR_P (decl))
5836 	/* C++14 variable template. */;
5837       else if (TREE_CODE (decl) == CONCEPT_DECL)
5838 	/* C++20 concept definitions.  */;
5839       else
5840 	{
5841 	  error ("template declaration of %q#D", decl);
5842 	  return error_mark_node;
5843 	}
5844     }
5845 
5846   bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5847 		  && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5848 		      || (VAR_OR_FUNCTION_DECL_P (decl)
5849 			  && DECL_LOCAL_DECL_P (decl))));
5850 
5851   /* Check to see that the rules regarding the use of default
5852      arguments are not being violated.  We check args for a friend
5853      functions when we know whether it's a definition, introducing
5854      declaration or re-declaration.  */
5855   if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5856     check_default_tmpl_args (decl, current_template_parms,
5857 			     is_primary, is_partial, is_friend);
5858 
5859   /* Ensure that there are no parameter packs in the type of this
5860      declaration that have not been expanded.  */
5861   if (TREE_CODE (decl) == FUNCTION_DECL)
5862     {
5863       /* Check each of the arguments individually to see if there are
5864          any bare parameter packs.  */
5865       tree type = TREE_TYPE (decl);
5866       tree arg = DECL_ARGUMENTS (decl);
5867       tree argtype = TYPE_ARG_TYPES (type);
5868 
5869       while (arg && argtype)
5870         {
5871           if (!DECL_PACK_P (arg)
5872               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5873             {
5874             /* This is a PARM_DECL that contains unexpanded parameter
5875                packs. We have already complained about this in the
5876                check_for_bare_parameter_packs call, so just replace
5877                these types with ERROR_MARK_NODE.  */
5878               TREE_TYPE (arg) = error_mark_node;
5879               TREE_VALUE (argtype) = error_mark_node;
5880             }
5881 
5882           arg = DECL_CHAIN (arg);
5883           argtype = TREE_CHAIN (argtype);
5884         }
5885 
5886       /* Check for bare parameter packs in the return type and the
5887          exception specifiers.  */
5888       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5889 	/* Errors were already issued, set return type to int
5890 	   as the frontend doesn't expect error_mark_node as
5891 	   the return type.  */
5892 	TREE_TYPE (type) = integer_type_node;
5893       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5894 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5895     }
5896   else if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5897 					   ? DECL_ORIGINAL_TYPE (decl)
5898 					   : TREE_TYPE (decl)))
5899     {
5900       TREE_TYPE (decl) = error_mark_node;
5901       return error_mark_node;
5902     }
5903 
5904   if (is_partial)
5905     return process_partial_specialization (decl);
5906 
5907   tree args = current_template_args ();
5908   tree tmpl = NULL_TREE;
5909   bool new_template_p = false;
5910   if (local_p)
5911     {
5912       /* Does not get a template head.  */
5913       tmpl = NULL_TREE;
5914       gcc_checking_assert (!is_primary);
5915     }
5916   else if (!ctx
5917 	   || TREE_CODE (ctx) == FUNCTION_DECL
5918 	   || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5919 	   || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5920 	   || (is_friend && !(DECL_LANG_SPECIFIC (decl)
5921 			      && DECL_TEMPLATE_INFO (decl))))
5922     {
5923       if (DECL_LANG_SPECIFIC (decl)
5924 	  && DECL_TEMPLATE_INFO (decl)
5925 	  && DECL_TI_TEMPLATE (decl))
5926 	tmpl = DECL_TI_TEMPLATE (decl);
5927       /* If DECL is a TYPE_DECL for a class-template, then there won't
5928 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5929 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5930       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5931 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5932 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5933 	{
5934 	  /* Since a template declaration already existed for this
5935 	     class-type, we must be redeclaring it here.  Make sure
5936 	     that the redeclaration is valid.  */
5937 	  redeclare_class_template (TREE_TYPE (decl),
5938 				    current_template_parms,
5939 				    current_template_constraints ());
5940 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5941 	     one we already had.  */
5942 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5943 	}
5944       else
5945 	{
5946 	  tmpl = build_template_decl (decl, current_template_parms,
5947 				      member_template_p);
5948 	  new_template_p = true;
5949 
5950 	  if (DECL_LANG_SPECIFIC (decl)
5951 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5952 	    {
5953 	      /* A specialization of a member template of a template
5954 		 class.  */
5955 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5956 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5957 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5958 	    }
5959 	}
5960     }
5961   else
5962     {
5963       tree a, t, current, parms;
5964       int i;
5965       tree tinfo = get_template_info (decl);
5966 
5967       if (!tinfo)
5968 	{
5969 	  error ("template definition of non-template %q#D", decl);
5970 	  return error_mark_node;
5971 	}
5972 
5973       tmpl = TI_TEMPLATE (tinfo);
5974 
5975       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5976 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5977 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5978 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5979 	{
5980 	  /* The declaration is a specialization of a member
5981 	     template, declared outside the class.  Therefore, the
5982 	     innermost template arguments will be NULL, so we
5983 	     replace them with the arguments determined by the
5984 	     earlier call to check_explicit_specialization.  */
5985 	  args = DECL_TI_ARGS (decl);
5986 
5987 	  tree new_tmpl
5988 	    = build_template_decl (decl, current_template_parms,
5989 				   member_template_p);
5990 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5991 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5992 	  DECL_TEMPLATE_INFO (new_tmpl)
5993 	    = build_template_info (tmpl, args);
5994 
5995 	  register_specialization (new_tmpl,
5996 				   most_general_template (tmpl),
5997 				   args,
5998 				   is_friend, 0);
5999 	  return decl;
6000 	}
6001 
6002       /* Make sure the template headers we got make sense.  */
6003 
6004       parms = DECL_TEMPLATE_PARMS (tmpl);
6005       i = TMPL_PARMS_DEPTH (parms);
6006       if (TMPL_ARGS_DEPTH (args) != i)
6007 	{
6008 	  error ("expected %d levels of template parms for %q#D, got %d",
6009 		 i, decl, TMPL_ARGS_DEPTH (args));
6010 	  DECL_INTERFACE_KNOWN (decl) = 1;
6011 	  return error_mark_node;
6012 	}
6013       else
6014 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6015 	  {
6016 	    a = TMPL_ARGS_LEVEL (args, i);
6017 	    t = INNERMOST_TEMPLATE_PARMS (parms);
6018 
6019 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6020 	      {
6021 		if (current == decl)
6022 		  error ("got %d template parameters for %q#D",
6023 			 TREE_VEC_LENGTH (a), decl);
6024 		else
6025 		  error ("got %d template parameters for %q#T",
6026 			 TREE_VEC_LENGTH (a), current);
6027 		error ("  but %d required", TREE_VEC_LENGTH (t));
6028 		/* Avoid crash in import_export_decl.  */
6029 		DECL_INTERFACE_KNOWN (decl) = 1;
6030 		return error_mark_node;
6031 	      }
6032 
6033 	    if (current == decl)
6034 	      current = ctx;
6035 	    else if (current == NULL_TREE)
6036 	      /* Can happen in erroneous input.  */
6037 	      break;
6038 	    else
6039 	      current = get_containing_scope (current);
6040 	  }
6041 
6042       /* Check that the parms are used in the appropriate qualifying scopes
6043 	 in the declarator.  */
6044       if (!comp_template_args
6045 	  (TI_ARGS (tinfo),
6046 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6047 	{
6048 	  error ("template arguments to %qD do not match original "
6049 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6050 	  if (!uses_template_parms (TI_ARGS (tinfo)))
6051 	    inform (input_location, "use %<template<>%> for"
6052 		    " an explicit specialization");
6053 	  /* Avoid crash in import_export_decl.  */
6054 	  DECL_INTERFACE_KNOWN (decl) = 1;
6055 	  return error_mark_node;
6056 	}
6057     }
6058 
6059   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6060 
6061   if (new_template_p)
6062     {
6063       /* Push template declarations for global functions and types.
6064 	 Note that we do not try to push a global template friend
6065 	 declared in a template class; such a thing may well depend on
6066 	 the template parameters of the class and we'll push it when
6067 	 instantiating the befriending class.  */
6068       if (!ctx
6069 	  && !(is_friend && template_class_depth (current_class_type) > 0))
6070 	{
6071 	  tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6072 	  if (pushed == error_mark_node)
6073 	    return error_mark_node;
6074 
6075 	  /* pushdecl may have found an existing template.  */
6076 	  if (pushed != tmpl)
6077 	    {
6078 	      decl = DECL_TEMPLATE_RESULT (pushed);
6079 	      tmpl = NULL_TREE;
6080 	    }
6081 	}
6082       else if (is_friend)
6083 	{
6084 	  /* Record this decl as belonging to the current class.  It's
6085 	     not chained onto anything else.  */
6086 	  DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6087 	  gcc_checking_assert (!DECL_CHAIN (tmpl));
6088 	  DECL_CHAIN (tmpl) = current_scope ();
6089 	}
6090     }
6091   else if (tmpl)
6092     /* The type may have been completed, or (erroneously) changed.  */
6093     TREE_TYPE (tmpl) = TREE_TYPE (decl);
6094 
6095   if (tmpl)
6096     {
6097       if (is_primary)
6098 	{
6099 	  tree parms = DECL_TEMPLATE_PARMS (tmpl);
6100 
6101 	  DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6102 
6103 	  /* Give template template parms a DECL_CONTEXT of the template
6104 	     for which they are a parameter.  */
6105 	  parms = INNERMOST_TEMPLATE_PARMS (parms);
6106 	  for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6107 	    {
6108 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6109 	      if (TREE_CODE (parm) == TEMPLATE_DECL)
6110 		DECL_CONTEXT (parm) = tmpl;
6111 	    }
6112 
6113 	  if (TREE_CODE (decl) == TYPE_DECL
6114 	      && TYPE_DECL_ALIAS_P (decl))
6115 	    {
6116 	      if (tree constr
6117 		  = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6118 		{
6119 		  /* ??? Why don't we do this here for all templates?  */
6120 		  constr = build_constraints (constr, NULL_TREE);
6121 		  set_constraints (decl, constr);
6122 		}
6123 	      if (complex_alias_template_p (tmpl))
6124 		TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6125 	    }
6126 	}
6127 
6128       /* The DECL_TI_ARGS of DECL contains full set of arguments
6129 	 referring wback to its most general template.  If TMPL is a
6130 	 specialization, ARGS may only have the innermost set of
6131 	 arguments.  Add the missing argument levels if necessary.  */
6132       if (DECL_TEMPLATE_INFO (tmpl))
6133 	args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6134 
6135       tree info = build_template_info (tmpl, args);
6136 
6137       if (DECL_IMPLICIT_TYPEDEF_P (decl))
6138 	SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6139       else
6140 	{
6141 	  retrofit_lang_decl (decl);
6142 	  DECL_TEMPLATE_INFO (decl) = info;
6143 	}
6144     }
6145 
6146   if (flag_implicit_templates
6147       && !is_friend
6148       && TREE_PUBLIC (decl)
6149       && VAR_OR_FUNCTION_DECL_P (decl))
6150     /* Set DECL_COMDAT on template instantiations; if we force
6151        them to be emitted by explicit instantiation,
6152        mark_needed will tell cgraph to do the right thing.  */
6153     DECL_COMDAT (decl) = true;
6154 
6155   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6156 
6157   return decl;
6158 }
6159 
6160 /* FN is an inheriting constructor that inherits from the constructor
6161    template INHERITED; turn FN into a constructor template with a matching
6162    template header.  */
6163 
6164 tree
add_inherited_template_parms(tree fn,tree inherited)6165 add_inherited_template_parms (tree fn, tree inherited)
6166 {
6167   tree inner_parms
6168     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6169   inner_parms = copy_node (inner_parms);
6170   tree parms
6171     = tree_cons (size_int (processing_template_decl + 1),
6172 		 inner_parms, current_template_parms);
6173   tree tmpl = build_template_decl (fn, parms, /*member*/true);
6174   tree args = template_parms_to_args (parms);
6175   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6176   DECL_ARTIFICIAL (tmpl) = true;
6177   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6178   return tmpl;
6179 }
6180 
6181 /* Called when a class template TYPE is redeclared with the indicated
6182    template PARMS, e.g.:
6183 
6184      template <class T> struct S;
6185      template <class T> struct S {};  */
6186 
6187 bool
redeclare_class_template(tree type,tree parms,tree cons)6188 redeclare_class_template (tree type, tree parms, tree cons)
6189 {
6190   tree tmpl;
6191   tree tmpl_parms;
6192   int i;
6193 
6194   if (!TYPE_TEMPLATE_INFO (type))
6195     {
6196       error ("%qT is not a template type", type);
6197       return false;
6198     }
6199 
6200   tmpl = TYPE_TI_TEMPLATE (type);
6201   if (!PRIMARY_TEMPLATE_P (tmpl))
6202     /* The type is nested in some template class.  Nothing to worry
6203        about here; there are no new template parameters for the nested
6204        type.  */
6205     return true;
6206 
6207   if (!parms)
6208     {
6209       error ("template specifiers not specified in declaration of %qD",
6210 	     tmpl);
6211       return false;
6212     }
6213 
6214   parms = INNERMOST_TEMPLATE_PARMS (parms);
6215   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6216 
6217   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6218     {
6219       error_n (input_location, TREE_VEC_LENGTH (parms),
6220                "redeclared with %d template parameter",
6221                "redeclared with %d template parameters",
6222                TREE_VEC_LENGTH (parms));
6223       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6224                 "previous declaration %qD used %d template parameter",
6225                 "previous declaration %qD used %d template parameters",
6226                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6227       return false;
6228     }
6229 
6230   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6231     {
6232       tree tmpl_parm;
6233       tree parm;
6234       tree tmpl_default;
6235       tree parm_default;
6236 
6237       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6238           || TREE_VEC_ELT (parms, i) == error_mark_node)
6239         continue;
6240 
6241       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6242       if (error_operand_p (tmpl_parm))
6243 	return false;
6244 
6245       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6246       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
6247       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
6248 
6249       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6250 	 TEMPLATE_DECL.  */
6251       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6252 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
6253 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6254 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6255 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6256 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6257 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6258 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6259 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6260 	{
6261 	  auto_diagnostic_group d;
6262 	  error ("template parameter %q+#D", tmpl_parm);
6263 	  inform (input_location, "redeclared here as %q#D", parm);
6264 	  return false;
6265 	}
6266 
6267       /* The parameters can be declared to introduce different
6268 	 constraints.  */
6269       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6270       tree p2 = TREE_VEC_ELT (parms, i);
6271       if (!template_parameter_constraints_equivalent_p (p1, p2))
6272 	{
6273 	  auto_diagnostic_group d;
6274 	  error ("declaration of template parameter %q+#D with different "
6275 		 "constraints", parm);
6276 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6277 		  "original declaration appeared here");
6278 	  return false;
6279 	}
6280 
6281       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6282 	{
6283 	  /* We have in [temp.param]:
6284 
6285 	     A template-parameter may not be given default arguments
6286 	     by two different declarations in the same scope.  */
6287 	  auto_diagnostic_group d;
6288 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
6289 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6290 		  "original definition appeared here");
6291 	  return false;
6292 	}
6293 
6294       if (parm_default != NULL_TREE)
6295 	/* Update the previous template parameters (which are the ones
6296 	   that will really count) with the new default value.  */
6297 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6298       else if (tmpl_default != NULL_TREE)
6299 	/* Update the new parameters, too; they'll be used as the
6300 	   parameters for any members.  */
6301 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6302 
6303       /* Give each template template parm in this redeclaration a
6304 	 DECL_CONTEXT of the template for which they are a parameter.  */
6305       if (TREE_CODE (parm) == TEMPLATE_DECL)
6306 	{
6307 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6308 	  DECL_CONTEXT (parm) = tmpl;
6309 	}
6310 
6311       if (TREE_CODE (parm) == TYPE_DECL)
6312 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6313     }
6314 
6315   tree ci = get_constraints (tmpl);
6316   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6317   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6318 
6319   /* Two classes with different constraints declare different entities.  */
6320   if (!cp_tree_equal (req1, req2))
6321     {
6322       auto_diagnostic_group d;
6323       error_at (input_location, "redeclaration %q#D with different "
6324                                 "constraints", tmpl);
6325       inform (DECL_SOURCE_LOCATION (tmpl),
6326               "original declaration appeared here");
6327       return false;
6328     }
6329 
6330     return true;
6331 }
6332 
6333 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6334    to be used when the caller has already checked
6335    (processing_template_decl
6336     && !instantiation_dependent_expression_p (expr)
6337     && potential_constant_expression (expr))
6338    and cleared processing_template_decl.  */
6339 
6340 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6341 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6342 {
6343   return tsubst_copy_and_build (expr,
6344 				/*args=*/NULL_TREE,
6345 				complain,
6346 				/*in_decl=*/NULL_TREE,
6347 				/*function_p=*/false,
6348 				/*integral_constant_expression_p=*/true);
6349 }
6350 
6351 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6352    (possibly simplified) expression.  */
6353 
6354 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6355 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6356 {
6357   if (expr == NULL_TREE)
6358     return NULL_TREE;
6359 
6360   /* If we're in a template, but EXPR isn't value dependent, simplify
6361      it.  We're supposed to treat:
6362 
6363        template <typename T> void f(T[1 + 1]);
6364        template <typename T> void f(T[2]);
6365 
6366      as two declarations of the same function, for example.  */
6367   if (processing_template_decl
6368       && is_nondependent_constant_expression (expr))
6369     {
6370       processing_template_decl_sentinel s;
6371       expr = instantiate_non_dependent_expr_internal (expr, complain);
6372     }
6373   return expr;
6374 }
6375 
6376 tree
instantiate_non_dependent_expr(tree expr)6377 instantiate_non_dependent_expr (tree expr)
6378 {
6379   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6380 }
6381 
6382 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6383    an uninstantiated expression.  */
6384 
6385 tree
instantiate_non_dependent_or_null(tree expr)6386 instantiate_non_dependent_or_null (tree expr)
6387 {
6388   if (expr == NULL_TREE)
6389     return NULL_TREE;
6390   if (processing_template_decl)
6391     {
6392       if (!is_nondependent_constant_expression (expr))
6393 	expr = NULL_TREE;
6394       else
6395 	{
6396 	  processing_template_decl_sentinel s;
6397 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6398 	}
6399     }
6400   return expr;
6401 }
6402 
6403 /* True iff T is a specialization of a variable template.  */
6404 
6405 bool
variable_template_specialization_p(tree t)6406 variable_template_specialization_p (tree t)
6407 {
6408   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6409     return false;
6410   tree tmpl = DECL_TI_TEMPLATE (t);
6411   return variable_template_p (tmpl);
6412 }
6413 
6414 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6415    template declaration, or a TYPE_DECL for an alias declaration.  */
6416 
6417 bool
alias_type_or_template_p(tree t)6418 alias_type_or_template_p (tree t)
6419 {
6420   if (t == NULL_TREE)
6421     return false;
6422   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6423 	  || (TYPE_P (t)
6424 	      && TYPE_NAME (t)
6425 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6426 	  || DECL_ALIAS_TEMPLATE_P (t));
6427 }
6428 
6429 /* If T is a specialization of an alias template, return it; otherwise return
6430    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6431 
6432 tree
alias_template_specialization_p(const_tree t,bool transparent_typedefs)6433 alias_template_specialization_p (const_tree t,
6434 				 bool transparent_typedefs)
6435 {
6436   if (!TYPE_P (t))
6437     return NULL_TREE;
6438 
6439   /* It's an alias template specialization if it's an alias and its
6440      TYPE_NAME is a specialization of a primary template.  */
6441   if (typedef_variant_p (t))
6442     {
6443       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6444 	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6445 	  return CONST_CAST_TREE (t);
6446       if (transparent_typedefs)
6447 	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6448 						(TYPE_NAME (t)),
6449 						transparent_typedefs);
6450     }
6451 
6452   return NULL_TREE;
6453 }
6454 
6455 /* An alias template is complex from a SFINAE perspective if a template-id
6456    using that alias can be ill-formed when the expansion is not, as with
6457    the void_t template.  We determine this by checking whether the
6458    expansion for the alias template uses all its template parameters.  */
6459 
6460 struct uses_all_template_parms_data
6461 {
6462   int level;
6463   bool *seen;
6464 };
6465 
6466 static int
uses_all_template_parms_r(tree t,void * data_)6467 uses_all_template_parms_r (tree t, void *data_)
6468 {
6469   struct uses_all_template_parms_data &data
6470     = *(struct uses_all_template_parms_data*)data_;
6471   tree idx = get_template_parm_index (t);
6472 
6473   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6474     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6475   return 0;
6476 }
6477 
6478 /* for_each_template_parm any_fn callback for complex_alias_template_p.  */
6479 
6480 static int
complex_pack_expansion_r(tree t,void * data_)6481 complex_pack_expansion_r (tree t, void *data_)
6482 {
6483   /* An alias template with a pack expansion that expands a pack from the
6484      enclosing class needs to be considered complex, to avoid confusion with
6485      the same pack being used as an argument to the alias's own template
6486      parameter (91966).  */
6487   if (!PACK_EXPANSION_P (t))
6488     return 0;
6489   struct uses_all_template_parms_data &data
6490     = *(struct uses_all_template_parms_data*)data_;
6491   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6492        pack = TREE_CHAIN (pack))
6493     {
6494       tree parm_pack = TREE_VALUE (pack);
6495       if (!TEMPLATE_PARM_P (parm_pack))
6496 	continue;
6497       int idx, level;
6498       template_parm_level_and_index (parm_pack, &level, &idx);
6499       if (level < data.level)
6500 	return 1;
6501     }
6502   return 0;
6503 }
6504 
6505 static bool
complex_alias_template_p(const_tree tmpl)6506 complex_alias_template_p (const_tree tmpl)
6507 {
6508   /* A renaming alias isn't complex.  */
6509   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6510     return false;
6511 
6512   /* Any other constrained alias is complex.  */
6513   if (get_constraints (tmpl))
6514     return true;
6515 
6516   struct uses_all_template_parms_data data;
6517   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6518   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6519   data.level = TMPL_PARMS_DEPTH (parms);
6520   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6521   data.seen = XALLOCAVEC (bool, len);
6522   for (int i = 0; i < len; ++i)
6523     data.seen[i] = false;
6524 
6525   if (for_each_template_parm (pat, uses_all_template_parms_r, &data,
6526 			      NULL, true, complex_pack_expansion_r))
6527     return true;
6528   for (int i = 0; i < len; ++i)
6529     if (!data.seen[i])
6530       return true;
6531   return false;
6532 }
6533 
6534 /* If T is a specialization of a complex alias template with dependent
6535    template-arguments, return it; otherwise return NULL_TREE.  If T is a
6536    typedef to such a specialization, return the specialization.  */
6537 
6538 tree
dependent_alias_template_spec_p(const_tree t,bool transparent_typedefs)6539 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6540 {
6541   if (t == error_mark_node)
6542     return NULL_TREE;
6543   gcc_assert (TYPE_P (t));
6544 
6545   if (!typedef_variant_p (t))
6546     return NULL_TREE;
6547 
6548   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6549   if (tinfo
6550       && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6551       && (any_dependent_template_arguments_p
6552 	  (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6553     return CONST_CAST_TREE (t);
6554 
6555   if (transparent_typedefs)
6556     {
6557       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6558       return dependent_alias_template_spec_p (utype, transparent_typedefs);
6559     }
6560 
6561   return NULL_TREE;
6562 }
6563 
6564 /* Return the number of innermost template parameters in TMPL.  */
6565 
6566 static int
num_innermost_template_parms(const_tree tmpl)6567 num_innermost_template_parms (const_tree tmpl)
6568 {
6569   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6570   return TREE_VEC_LENGTH (parms);
6571 }
6572 
6573 /* Return either TMPL or another template that it is equivalent to under DR
6574    1286: An alias that just changes the name of a template is equivalent to
6575    the other template.  */
6576 
6577 static tree
get_underlying_template(tree tmpl)6578 get_underlying_template (tree tmpl)
6579 {
6580   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6581   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6582     {
6583       /* Determine if the alias is equivalent to an underlying template.  */
6584       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6585       /* The underlying type may have been ill-formed. Don't proceed.  */
6586       if (!orig_type)
6587 	break;
6588       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6589       if (!tinfo)
6590 	break;
6591 
6592       tree underlying = TI_TEMPLATE (tinfo);
6593       if (!PRIMARY_TEMPLATE_P (underlying)
6594 	  || (num_innermost_template_parms (tmpl)
6595 	      != num_innermost_template_parms (underlying)))
6596 	break;
6597 
6598       /* Does the alias add cv-quals?  */
6599       if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6600 	break;
6601 
6602       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6603       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6604 	break;
6605 
6606       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6607 	 it's appropriate to treat a less-constrained alias as equivalent.  */
6608       if (!at_least_as_constrained (underlying, tmpl))
6609 	break;
6610 
6611       /* Alias is equivalent.  Strip it and repeat.  */
6612       tmpl = underlying;
6613     }
6614 
6615   return tmpl;
6616 }
6617 
6618 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6619    must be a reference-to-function or a pointer-to-function type, as specified
6620    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6621    and check that the resulting function has external linkage.  */
6622 
6623 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6624 convert_nontype_argument_function (tree type, tree expr,
6625 				   tsubst_flags_t complain)
6626 {
6627   tree fns = expr;
6628   tree fn, fn_no_ptr;
6629   linkage_kind linkage;
6630 
6631   fn = instantiate_type (type, fns, tf_none);
6632   if (fn == error_mark_node)
6633     return error_mark_node;
6634 
6635   if (value_dependent_expression_p (fn))
6636     goto accept;
6637 
6638   fn_no_ptr = fn;
6639   if (REFERENCE_REF_P (fn_no_ptr))
6640     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6641   fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6642   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6643     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6644   if (BASELINK_P (fn_no_ptr))
6645     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6646 
6647   /* [temp.arg.nontype]/1
6648 
6649      A template-argument for a non-type, non-template template-parameter
6650      shall be one of:
6651      [...]
6652      -- the address of an object or function with external [C++11: or
6653         internal] linkage.  */
6654 
6655   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6656   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6657     {
6658       if (complain & tf_error)
6659 	{
6660 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6661 	  error_at (loc, "%qE is not a valid template argument for type %qT",
6662 		    expr, type);
6663 	  if (TYPE_PTR_P (type))
6664 	    inform (loc, "it must be the address of a function "
6665 		    "with external linkage");
6666 	  else
6667 	    inform (loc, "it must be the name of a function with "
6668 		    "external linkage");
6669 	}
6670       return NULL_TREE;
6671     }
6672 
6673   linkage = decl_linkage (fn_no_ptr);
6674   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6675     {
6676       if (complain & tf_error)
6677 	{
6678 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6679 	  if (cxx_dialect >= cxx11)
6680 	    error_at (loc, "%qE is not a valid template argument for type "
6681 		      "%qT because %qD has no linkage",
6682 		      expr, type, fn_no_ptr);
6683 	  else
6684 	    error_at (loc, "%qE is not a valid template argument for type "
6685 		      "%qT because %qD does not have external linkage",
6686 		      expr, type, fn_no_ptr);
6687 	}
6688       return NULL_TREE;
6689     }
6690 
6691  accept:
6692   if (TYPE_REF_P (type))
6693     {
6694       if (REFERENCE_REF_P (fn))
6695 	fn = TREE_OPERAND (fn, 0);
6696       else
6697 	fn = build_address (fn);
6698     }
6699   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6700     fn = build_nop (type, fn);
6701 
6702   return fn;
6703 }
6704 
6705 /* Subroutine of convert_nontype_argument.
6706    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6707    Emit an error otherwise.  */
6708 
6709 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6710 check_valid_ptrmem_cst_expr (tree type, tree expr,
6711 			     tsubst_flags_t complain)
6712 {
6713   tree orig_expr = expr;
6714   STRIP_NOPS (expr);
6715   if (null_ptr_cst_p (expr))
6716     return true;
6717   if (TREE_CODE (expr) == PTRMEM_CST
6718       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6719 		      PTRMEM_CST_CLASS (expr)))
6720     return true;
6721   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6722     return true;
6723   if (processing_template_decl
6724       && TREE_CODE (expr) == ADDR_EXPR
6725       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6726     return true;
6727   if (complain & tf_error)
6728     {
6729       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6730       error_at (loc, "%qE is not a valid template argument for type %qT",
6731 		orig_expr, type);
6732       if (TREE_CODE (expr) != PTRMEM_CST)
6733 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6734       else
6735 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6736     }
6737   return false;
6738 }
6739 
6740 /* Returns TRUE iff the address of OP is value-dependent.
6741 
6742    14.6.2.4 [temp.dep.temp]:
6743    A non-integral non-type template-argument is dependent if its type is
6744    dependent or it has either of the following forms
6745      qualified-id
6746      & qualified-id
6747    and contains a nested-name-specifier which specifies a class-name that
6748    names a dependent type.
6749 
6750    We generalize this to just say that the address of a member of a
6751    dependent class is value-dependent; the above doesn't cover the
6752    address of a static data member named with an unqualified-id.  */
6753 
6754 static bool
has_value_dependent_address(tree op)6755 has_value_dependent_address (tree op)
6756 {
6757   STRIP_ANY_LOCATION_WRAPPER (op);
6758 
6759   /* We could use get_inner_reference here, but there's no need;
6760      this is only relevant for template non-type arguments, which
6761      can only be expressed as &id-expression.  */
6762   if (DECL_P (op))
6763     {
6764       tree ctx = CP_DECL_CONTEXT (op);
6765       if (TYPE_P (ctx) && dependent_type_p (ctx))
6766 	return true;
6767     }
6768 
6769   return false;
6770 }
6771 
6772 /* The next set of functions are used for providing helpful explanatory
6773    diagnostics for failed overload resolution.  Their messages should be
6774    indented by two spaces for consistency with the messages in
6775    call.c  */
6776 
6777 static int
unify_success(bool)6778 unify_success (bool /*explain_p*/)
6779 {
6780   return 0;
6781 }
6782 
6783 /* Other failure functions should call this one, to provide a single function
6784    for setting a breakpoint on.  */
6785 
6786 static int
unify_invalid(bool)6787 unify_invalid (bool /*explain_p*/)
6788 {
6789   return 1;
6790 }
6791 
6792 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6793 unify_parameter_deduction_failure (bool explain_p, tree parm)
6794 {
6795   if (explain_p)
6796     inform (input_location,
6797 	    "  couldn%'t deduce template parameter %qD", parm);
6798   return unify_invalid (explain_p);
6799 }
6800 
6801 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6802 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6803 {
6804   if (explain_p)
6805     inform (input_location,
6806 	    "  types %qT and %qT have incompatible cv-qualifiers",
6807 	    parm, arg);
6808   return unify_invalid (explain_p);
6809 }
6810 
6811 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6812 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6813 {
6814   if (explain_p)
6815     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6816   return unify_invalid (explain_p);
6817 }
6818 
6819 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6820 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6821 {
6822   if (explain_p)
6823     inform (input_location,
6824 	    "  template parameter %qD is not a parameter pack, but "
6825 	    "argument %qD is",
6826 	    parm, arg);
6827   return unify_invalid (explain_p);
6828 }
6829 
6830 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6831 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6832 {
6833   if (explain_p)
6834     inform (input_location,
6835 	    "  template argument %qE does not match "
6836 	    "pointer-to-member constant %qE",
6837 	    arg, parm);
6838   return unify_invalid (explain_p);
6839 }
6840 
6841 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6842 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6843 {
6844   if (explain_p)
6845     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6846   return unify_invalid (explain_p);
6847 }
6848 
6849 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6850 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6851 {
6852   if (explain_p)
6853     inform (input_location,
6854 	    "  inconsistent parameter pack deduction with %qT and %qT",
6855 	    old_arg, new_arg);
6856   return unify_invalid (explain_p);
6857 }
6858 
6859 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6860 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6861 {
6862   if (explain_p)
6863     {
6864       if (TYPE_P (parm))
6865 	inform (input_location,
6866 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6867 		parm, first, second);
6868       else
6869 	inform (input_location,
6870 		"  deduced conflicting values for non-type parameter "
6871 		"%qE (%qE and %qE)", parm, first, second);
6872     }
6873   return unify_invalid (explain_p);
6874 }
6875 
6876 static int
unify_vla_arg(bool explain_p,tree arg)6877 unify_vla_arg (bool explain_p, tree arg)
6878 {
6879   if (explain_p)
6880     inform (input_location,
6881 	    "  variable-sized array type %qT is not "
6882 	    "a valid template argument",
6883 	    arg);
6884   return unify_invalid (explain_p);
6885 }
6886 
6887 static int
unify_method_type_error(bool explain_p,tree arg)6888 unify_method_type_error (bool explain_p, tree arg)
6889 {
6890   if (explain_p)
6891     inform (input_location,
6892 	    "  member function type %qT is not a valid template argument",
6893 	    arg);
6894   return unify_invalid (explain_p);
6895 }
6896 
6897 static int
6898 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6899 {
6900   if (explain_p)
6901     {
6902       if (least_p)
6903 	inform_n (input_location, wanted,
6904 		  "  candidate expects at least %d argument, %d provided",
6905 		  "  candidate expects at least %d arguments, %d provided",
6906 		  wanted, have);
6907       else
6908 	inform_n (input_location, wanted,
6909 		  "  candidate expects %d argument, %d provided",
6910 		  "  candidate expects %d arguments, %d provided",
6911 		  wanted, have);
6912     }
6913   return unify_invalid (explain_p);
6914 }
6915 
6916 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6917 unify_too_many_arguments (bool explain_p, int have, int wanted)
6918 {
6919   return unify_arity (explain_p, have, wanted);
6920 }
6921 
6922 static int
6923 unify_too_few_arguments (bool explain_p, int have, int wanted,
6924 			 bool least_p = false)
6925 {
6926   return unify_arity (explain_p, have, wanted, least_p);
6927 }
6928 
6929 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6930 unify_arg_conversion (bool explain_p, tree to_type,
6931 		      tree from_type, tree arg)
6932 {
6933   if (explain_p)
6934     inform (cp_expr_loc_or_input_loc (arg),
6935 	    "  cannot convert %qE (type %qT) to type %qT",
6936 	    arg, from_type, to_type);
6937   return unify_invalid (explain_p);
6938 }
6939 
6940 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6941 unify_no_common_base (bool explain_p, enum template_base_result r,
6942 		      tree parm, tree arg)
6943 {
6944   if (explain_p)
6945     switch (r)
6946       {
6947       case tbr_ambiguous_baseclass:
6948 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6949 		parm, arg);
6950 	break;
6951       default:
6952 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6953 	break;
6954       }
6955   return unify_invalid (explain_p);
6956 }
6957 
6958 static int
unify_inconsistent_template_template_parameters(bool explain_p)6959 unify_inconsistent_template_template_parameters (bool explain_p)
6960 {
6961   if (explain_p)
6962     inform (input_location,
6963 	    "  template parameters of a template template argument are "
6964 	    "inconsistent with other deduced template arguments");
6965   return unify_invalid (explain_p);
6966 }
6967 
6968 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6969 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6970 {
6971   if (explain_p)
6972     inform (input_location,
6973 	    "  cannot deduce a template for %qT from non-template type %qT",
6974 	    parm, arg);
6975   return unify_invalid (explain_p);
6976 }
6977 
6978 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6979 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6980 {
6981   if (explain_p)
6982     inform (input_location,
6983 	    "  template argument %qE does not match %qE", arg, parm);
6984   return unify_invalid (explain_p);
6985 }
6986 
6987 /* True if T is a C++20 template parameter object to store the argument for a
6988    template parameter of class type.  */
6989 
6990 bool
template_parm_object_p(const_tree t)6991 template_parm_object_p (const_tree t)
6992 {
6993   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6994 	  && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6995 }
6996 
6997 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
6998    argument for TYPE, points to an unsuitable object.
6999 
7000    Also adjust the type of the index in C++20 array subobject references.  */
7001 
7002 static bool
invalid_tparm_referent_p(tree type,tree expr,tsubst_flags_t complain)7003 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7004 {
7005   switch (TREE_CODE (expr))
7006     {
7007     CASE_CONVERT:
7008       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7009 				       complain);
7010 
7011     case TARGET_EXPR:
7012       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7013 				       complain);
7014 
7015     case CONSTRUCTOR:
7016       {
7017 	unsigned i; tree elt;
7018 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
7019 	  if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
7020 	    return true;
7021       }
7022       break;
7023 
7024     case ADDR_EXPR:
7025       {
7026 	tree decl = TREE_OPERAND (expr, 0);
7027 
7028 	if (cxx_dialect >= cxx20)
7029 	  while (TREE_CODE (decl) == COMPONENT_REF
7030 		 || TREE_CODE (decl) == ARRAY_REF)
7031 	    {
7032 	      tree &op = TREE_OPERAND (decl, 1);
7033 	      if (TREE_CODE (decl) == ARRAY_REF
7034 		  && TREE_CODE (op) == INTEGER_CST)
7035 		/* Canonicalize array offsets to ptrdiff_t; how they were
7036 		   written doesn't matter for subobject identity.  */
7037 		op = fold_convert (ptrdiff_type_node, op);
7038 	      decl = TREE_OPERAND (decl, 0);
7039 	    }
7040 
7041 	if (!VAR_P (decl))
7042 	  {
7043 	    if (complain & tf_error)
7044 	      error_at (cp_expr_loc_or_input_loc (expr),
7045 			"%qE is not a valid template argument of type %qT "
7046 			"because %qE is not a variable", expr, type, decl);
7047 	    return true;
7048 	  }
7049 	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7050 	  {
7051 	    if (complain & tf_error)
7052 	      error_at (cp_expr_loc_or_input_loc (expr),
7053 			"%qE is not a valid template argument of type %qT "
7054 			"in C++98 because %qD does not have external linkage",
7055 			expr, type, decl);
7056 	    return true;
7057 	  }
7058 	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7059 		 && decl_linkage (decl) == lk_none)
7060 	  {
7061 	    if (complain & tf_error)
7062 	      error_at (cp_expr_loc_or_input_loc (expr),
7063 			"%qE is not a valid template argument of type %qT "
7064 			"because %qD has no linkage", expr, type, decl);
7065 	    return true;
7066 	  }
7067 	/* C++17: For a non-type template-parameter of reference or pointer
7068 	   type, the value of the constant expression shall not refer to (or
7069 	   for a pointer type, shall not be the address of):
7070 	   * a subobject (4.5),
7071 	   * a temporary object (15.2),
7072 	   * a string literal (5.13.5),
7073 	   * the result of a typeid expression (8.2.8), or
7074 	   * a predefined __func__ variable (11.4.1).  */
7075 	else if (DECL_ARTIFICIAL (decl))
7076 	  {
7077 	    if (complain & tf_error)
7078 	      error ("the address of %qD is not a valid template argument",
7079 		     decl);
7080 	    return true;
7081 	  }
7082 	else if (cxx_dialect < cxx20
7083 		 && !(same_type_ignoring_top_level_qualifiers_p
7084 		      (strip_array_types (TREE_TYPE (type)),
7085 		       strip_array_types (TREE_TYPE (decl)))))
7086 	  {
7087 	    if (complain & tf_error)
7088 	      error ("the address of the %qT subobject of %qD is not a "
7089 		     "valid template argument", TREE_TYPE (type), decl);
7090 	    return true;
7091 	  }
7092 	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7093 	  {
7094 	    if (complain & tf_error)
7095 	      error ("the address of %qD is not a valid template argument "
7096 		     "because it does not have static storage duration",
7097 		     decl);
7098 	    return true;
7099 	  }
7100       }
7101       break;
7102 
7103     default:
7104       if (!INDIRECT_TYPE_P (type))
7105 	/* We're only concerned about pointers and references here.  */;
7106       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7107 	/* Null pointer values are OK in C++11.  */;
7108       else
7109 	{
7110 	  if (VAR_P (expr))
7111 	    {
7112 	      if (complain & tf_error)
7113 		error ("%qD is not a valid template argument "
7114 		       "because %qD is a variable, not the address of "
7115 		       "a variable", expr, expr);
7116 	      return true;
7117 	    }
7118 	  else
7119 	    {
7120 	      if (complain & tf_error)
7121 		error ("%qE is not a valid template argument for %qT "
7122 		       "because it is not the address of a variable",
7123 		       expr, type);
7124 	      return true;
7125 	    }
7126 	}
7127     }
7128   return false;
7129 
7130 }
7131 
7132 /* The template arguments corresponding to template parameter objects of types
7133    that contain pointers to members.  */
7134 
7135 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7136 
7137 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7138    template argument EXPR.  */
7139 
7140 static tree
get_template_parm_object(tree expr,tsubst_flags_t complain)7141 get_template_parm_object (tree expr, tsubst_flags_t complain)
7142 {
7143   if (TREE_CODE (expr) == TARGET_EXPR)
7144     expr = TARGET_EXPR_INITIAL (expr);
7145 
7146   if (!TREE_CONSTANT (expr))
7147     {
7148       if ((complain & tf_error)
7149 	  && require_rvalue_constant_expression (expr))
7150 	cxx_constant_value (expr);
7151       return error_mark_node;
7152     }
7153   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7154     return error_mark_node;
7155 
7156   /* This is no longer a compound literal.  */
7157   TREE_HAS_CONSTRUCTOR (expr) = 0;
7158 
7159   tree name = mangle_template_parm_object (expr);
7160   tree decl = get_global_binding (name);
7161   if (decl)
7162     return decl;
7163 
7164   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7165   decl = create_temporary_var (type);
7166   DECL_CONTEXT (decl) = NULL_TREE;
7167   TREE_STATIC (decl) = true;
7168   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7169   TREE_READONLY (decl) = true;
7170   DECL_NAME (decl) = name;
7171   SET_DECL_ASSEMBLER_NAME (decl, name);
7172   comdat_linkage (decl);
7173 
7174   if (!zero_init_p (type))
7175     {
7176       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7177 	 lower_var_init before we're done mangling.  So store the original
7178 	 value elsewhere.  */
7179       tree copy = unshare_constructor (expr);
7180       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7181     }
7182 
7183   pushdecl_top_level_and_finish (decl, expr);
7184 
7185   return decl;
7186 }
7187 
7188 /* Return the actual template argument corresponding to template parameter
7189    object VAR.  */
7190 
7191 tree
tparm_object_argument(tree var)7192 tparm_object_argument (tree var)
7193 {
7194   if (zero_init_p (TREE_TYPE (var)))
7195     return DECL_INITIAL (var);
7196   return *(tparm_obj_values->get (var));
7197 }
7198 
7199 /* Attempt to convert the non-type template parameter EXPR to the
7200    indicated TYPE.  If the conversion is successful, return the
7201    converted value.  If the conversion is unsuccessful, return
7202    NULL_TREE if we issued an error message, or error_mark_node if we
7203    did not.  We issue error messages for out-and-out bad template
7204    parameters, but not simply because the conversion failed, since we
7205    might be just trying to do argument deduction.  Both TYPE and EXPR
7206    must be non-dependent.
7207 
7208    The conversion follows the special rules described in
7209    [temp.arg.nontype], and it is much more strict than an implicit
7210    conversion.
7211 
7212    This function is called twice for each template argument (see
7213    lookup_template_class for a more accurate description of this
7214    problem). This means that we need to handle expressions which
7215    are not valid in a C++ source, but can be created from the
7216    first call (for instance, casts to perform conversions). These
7217    hacks can go away after we fix the double coercion problem.  */
7218 
7219 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)7220 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7221 {
7222   tree expr_type;
7223   location_t loc = cp_expr_loc_or_input_loc (expr);
7224 
7225   /* Detect immediately string literals as invalid non-type argument.
7226      This special-case is not needed for correctness (we would easily
7227      catch this later), but only to provide better diagnostic for this
7228      common user mistake. As suggested by DR 100, we do not mention
7229      linkage issues in the diagnostic as this is not the point.  */
7230   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7231     {
7232       if (complain & tf_error)
7233 	error ("%qE is not a valid template argument for type %qT "
7234 	       "because string literals can never be used in this context",
7235 	       expr, type);
7236       return NULL_TREE;
7237     }
7238 
7239   /* Add the ADDR_EXPR now for the benefit of
7240      value_dependent_expression_p.  */
7241   if (TYPE_PTROBV_P (type)
7242       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7243     {
7244       expr = decay_conversion (expr, complain);
7245       if (expr == error_mark_node)
7246 	return error_mark_node;
7247     }
7248 
7249   /* If we are in a template, EXPR may be non-dependent, but still
7250      have a syntactic, rather than semantic, form.  For example, EXPR
7251      might be a SCOPE_REF, rather than the VAR_DECL to which the
7252      SCOPE_REF refers.  Preserving the qualifying scope is necessary
7253      so that access checking can be performed when the template is
7254      instantiated -- but here we need the resolved form so that we can
7255      convert the argument.  */
7256   bool non_dep = false;
7257   if (TYPE_REF_OBJ_P (type)
7258       && has_value_dependent_address (expr))
7259     /* If we want the address and it's value-dependent, don't fold.  */;
7260   else if (processing_template_decl
7261 	   && is_nondependent_constant_expression (expr))
7262     non_dep = true;
7263   if (error_operand_p (expr))
7264     return error_mark_node;
7265   expr_type = TREE_TYPE (expr);
7266 
7267   /* If the argument is non-dependent, perform any conversions in
7268      non-dependent context as well.  */
7269   processing_template_decl_sentinel s (non_dep);
7270   if (non_dep)
7271     expr = instantiate_non_dependent_expr_internal (expr, complain);
7272 
7273   const bool val_dep_p = value_dependent_expression_p (expr);
7274   if (val_dep_p)
7275     expr = canonicalize_expr_argument (expr, complain);
7276 
7277   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7278      to a non-type argument of "nullptr".  */
7279   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7280     expr = fold_simple (convert (type, expr));
7281 
7282   /* In C++11, integral or enumeration non-type template arguments can be
7283      arbitrary constant expressions.  Pointer and pointer to
7284      member arguments can be general constant expressions that evaluate
7285      to a null value, but otherwise still need to be of a specific form.  */
7286   if (cxx_dialect >= cxx11)
7287     {
7288       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7289 	/* A PTRMEM_CST is already constant, and a valid template
7290 	   argument for a parameter of pointer to member type, we just want
7291 	   to leave it in that form rather than lower it to a
7292 	   CONSTRUCTOR.  */;
7293       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7294 	       || cxx_dialect >= cxx17)
7295 	{
7296 	  /* C++17: A template-argument for a non-type template-parameter shall
7297 	     be a converted constant expression (8.20) of the type of the
7298 	     template-parameter.  */
7299 	  expr = build_converted_constant_expr (type, expr, complain);
7300 	  if (expr == error_mark_node)
7301 	    /* Make sure we return NULL_TREE only if we have really issued
7302 	       an error, as described above.  */
7303 	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
7304 	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7305 	    {
7306 	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7307 	      return expr;
7308 	    }
7309 	  expr = maybe_constant_value (expr, NULL_TREE,
7310 				       /*manifestly_const_eval=*/true);
7311 	  expr = convert_from_reference (expr);
7312 	}
7313       else if (TYPE_PTR_OR_PTRMEM_P (type))
7314 	{
7315 	  tree folded = maybe_constant_value (expr, NULL_TREE,
7316 					      /*manifestly_const_eval=*/true);
7317 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
7318 	      : null_member_pointer_value_p (folded))
7319 	    expr = folded;
7320 	}
7321     }
7322 
7323   if (TYPE_REF_P (type))
7324     expr = mark_lvalue_use (expr);
7325   else
7326     expr = mark_rvalue_use (expr);
7327 
7328   /* HACK: Due to double coercion, we can get a
7329      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7330      which is the tree that we built on the first call (see
7331      below when coercing to reference to object or to reference to
7332      function). We just strip everything and get to the arg.
7333      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7334      for examples.  */
7335   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7336     {
7337       tree probe_type, probe = expr;
7338       if (REFERENCE_REF_P (probe))
7339 	probe = TREE_OPERAND (probe, 0);
7340       probe_type = TREE_TYPE (probe);
7341       if (TREE_CODE (probe) == NOP_EXPR)
7342 	{
7343 	  /* ??? Maybe we could use convert_from_reference here, but we
7344 	     would need to relax its constraints because the NOP_EXPR
7345 	     could actually change the type to something more cv-qualified,
7346 	     and this is not folded by convert_from_reference.  */
7347 	  tree addr = TREE_OPERAND (probe, 0);
7348 	  if (TYPE_REF_P (probe_type)
7349 	      && TREE_CODE (addr) == ADDR_EXPR
7350 	      && TYPE_PTR_P (TREE_TYPE (addr))
7351 	      && (same_type_ignoring_top_level_qualifiers_p
7352 		  (TREE_TYPE (probe_type),
7353 		   TREE_TYPE (TREE_TYPE (addr)))))
7354 	    {
7355 	      expr = TREE_OPERAND (addr, 0);
7356 	      expr_type = TREE_TYPE (probe_type);
7357 	    }
7358 	}
7359     }
7360 
7361   /* [temp.arg.nontype]/5, bullet 1
7362 
7363      For a non-type template-parameter of integral or enumeration type,
7364      integral promotions (_conv.prom_) and integral conversions
7365      (_conv.integral_) are applied.  */
7366   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7367       || TREE_CODE (type) == REAL_TYPE)
7368     {
7369       if (cxx_dialect < cxx11)
7370 	{
7371 	  tree t = build_converted_constant_expr (type, expr, complain);
7372 	  t = maybe_constant_value (t);
7373 	  if (t != error_mark_node)
7374 	    expr = t;
7375 	}
7376 
7377       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7378 	return error_mark_node;
7379 
7380       /* Notice that there are constant expressions like '4 % 0' which
7381 	 do not fold into integer constants.  */
7382       if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7383 	{
7384 	  if (complain & tf_error)
7385 	    {
7386 	      int errs = errorcount, warns = warningcount + werrorcount;
7387 	      if (!require_potential_constant_expression (expr))
7388 		expr = error_mark_node;
7389 	      else
7390 		expr = cxx_constant_value (expr);
7391 	      if (errorcount > errs || warningcount + werrorcount > warns)
7392 		inform (loc, "in template argument for type %qT", type);
7393 	      if (expr == error_mark_node)
7394 		return NULL_TREE;
7395 	      /* else cxx_constant_value complained but gave us
7396 		 a real constant, so go ahead.  */
7397 	      if (!CONSTANT_CLASS_P (expr))
7398 		{
7399 		  /* Some assemble time constant expressions like
7400 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7401 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7402 		     as we can emit them into .rodata initializers of
7403 		     variables, yet they can't fold into an INTEGER_CST at
7404 		     compile time.  Refuse them here.  */
7405 		  gcc_checking_assert (reduced_constant_expression_p (expr));
7406 		  error_at (loc, "template argument %qE for type %qT not "
7407 				 "a compile-time constant", expr, type);
7408 		  return NULL_TREE;
7409 		}
7410 	    }
7411 	  else
7412 	    return NULL_TREE;
7413 	}
7414 
7415       /* Avoid typedef problems.  */
7416       if (TREE_TYPE (expr) != type)
7417 	expr = fold_convert (type, expr);
7418     }
7419   /* [temp.arg.nontype]/5, bullet 2
7420 
7421      For a non-type template-parameter of type pointer to object,
7422      qualification conversions (_conv.qual_) and the array-to-pointer
7423      conversion (_conv.array_) are applied.  */
7424   else if (TYPE_PTROBV_P (type))
7425     {
7426       tree decayed = expr;
7427 
7428       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7429 	 decay_conversion or an explicit cast.  If it's a problematic cast,
7430 	 we'll complain about it below.  */
7431       if (TREE_CODE (expr) == NOP_EXPR)
7432 	{
7433 	  tree probe = expr;
7434 	  STRIP_NOPS (probe);
7435 	  if (TREE_CODE (probe) == ADDR_EXPR
7436 	      && TYPE_PTR_P (TREE_TYPE (probe)))
7437 	    {
7438 	      expr = probe;
7439 	      expr_type = TREE_TYPE (expr);
7440 	    }
7441 	}
7442 
7443       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7444 
7445 	 A template-argument for a non-type, non-template template-parameter
7446 	 shall be one of: [...]
7447 
7448 	 -- the name of a non-type template-parameter;
7449 	 -- the address of an object or function with external linkage, [...]
7450 	    expressed as "& id-expression" where the & is optional if the name
7451 	    refers to a function or array, or if the corresponding
7452 	    template-parameter is a reference.
7453 
7454 	Here, we do not care about functions, as they are invalid anyway
7455 	for a parameter of type pointer-to-object.  */
7456 
7457       if (val_dep_p)
7458 	/* Non-type template parameters are OK.  */
7459 	;
7460       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7461 	/* Null pointer values are OK in C++11.  */;
7462       else if (TREE_CODE (expr) != ADDR_EXPR
7463 	       && !INDIRECT_TYPE_P (expr_type))
7464 	/* Other values, like integer constants, might be valid
7465 	   non-type arguments of some other type.  */
7466 	return error_mark_node;
7467       else if (invalid_tparm_referent_p (type, expr, complain))
7468 	return NULL_TREE;
7469 
7470       expr = decayed;
7471 
7472       expr = perform_qualification_conversions (type, expr);
7473       if (expr == error_mark_node)
7474 	return error_mark_node;
7475     }
7476   /* [temp.arg.nontype]/5, bullet 3
7477 
7478      For a non-type template-parameter of type reference to object, no
7479      conversions apply. The type referred to by the reference may be more
7480      cv-qualified than the (otherwise identical) type of the
7481      template-argument. The template-parameter is bound directly to the
7482      template-argument, which must be an lvalue.  */
7483   else if (TYPE_REF_OBJ_P (type))
7484     {
7485       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7486 						      expr_type))
7487 	return error_mark_node;
7488 
7489       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7490 	{
7491 	  if (complain & tf_error)
7492 	    error ("%qE is not a valid template argument for type %qT "
7493 		   "because of conflicts in cv-qualification", expr, type);
7494 	  return NULL_TREE;
7495 	}
7496 
7497       if (!lvalue_p (expr))
7498 	{
7499 	  if (complain & tf_error)
7500 	    error ("%qE is not a valid template argument for type %qT "
7501 		   "because it is not an lvalue", expr, type);
7502 	  return NULL_TREE;
7503 	}
7504 
7505       /* [temp.arg.nontype]/1
7506 
7507 	 A template-argument for a non-type, non-template template-parameter
7508 	 shall be one of: [...]
7509 
7510 	 -- the address of an object or function with external linkage.  */
7511       if (INDIRECT_REF_P (expr)
7512 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7513 	{
7514 	  expr = TREE_OPERAND (expr, 0);
7515 	  if (DECL_P (expr))
7516 	    {
7517 	      if (complain & tf_error)
7518 		error ("%q#D is not a valid template argument for type %qT "
7519 		       "because a reference variable does not have a constant "
7520 		       "address", expr, type);
7521 	      return NULL_TREE;
7522 	    }
7523 	}
7524 
7525       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7526 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7527 	   itself value-dependent, since what we want here is its address.  */;
7528       else
7529 	{
7530 	  expr = build_address (expr);
7531 
7532 	  if (invalid_tparm_referent_p (type, expr, complain))
7533 	    return NULL_TREE;
7534 	}
7535 
7536       if (!same_type_p (type, TREE_TYPE (expr)))
7537 	expr = build_nop (type, expr);
7538     }
7539   /* [temp.arg.nontype]/5, bullet 4
7540 
7541      For a non-type template-parameter of type pointer to function, only
7542      the function-to-pointer conversion (_conv.func_) is applied. If the
7543      template-argument represents a set of overloaded functions (or a
7544      pointer to such), the matching function is selected from the set
7545      (_over.over_).  */
7546   else if (TYPE_PTRFN_P (type))
7547     {
7548       /* If the argument is a template-id, we might not have enough
7549 	 context information to decay the pointer.  */
7550       if (!type_unknown_p (expr_type))
7551 	{
7552 	  expr = decay_conversion (expr, complain);
7553 	  if (expr == error_mark_node)
7554 	    return error_mark_node;
7555 	}
7556 
7557       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7558 	/* Null pointer values are OK in C++11.  */
7559 	return perform_qualification_conversions (type, expr);
7560 
7561       expr = convert_nontype_argument_function (type, expr, complain);
7562       if (!expr || expr == error_mark_node)
7563 	return expr;
7564     }
7565   /* [temp.arg.nontype]/5, bullet 5
7566 
7567      For a non-type template-parameter of type reference to function, no
7568      conversions apply. If the template-argument represents a set of
7569      overloaded functions, the matching function is selected from the set
7570      (_over.over_).  */
7571   else if (TYPE_REFFN_P (type))
7572     {
7573       if (TREE_CODE (expr) == ADDR_EXPR)
7574 	{
7575 	  if (complain & tf_error)
7576 	    {
7577 	      error ("%qE is not a valid template argument for type %qT "
7578 		     "because it is a pointer", expr, type);
7579 	      inform (input_location, "try using %qE instead",
7580 		      TREE_OPERAND (expr, 0));
7581 	    }
7582 	  return NULL_TREE;
7583 	}
7584 
7585       expr = convert_nontype_argument_function (type, expr, complain);
7586       if (!expr || expr == error_mark_node)
7587 	return expr;
7588     }
7589   /* [temp.arg.nontype]/5, bullet 6
7590 
7591      For a non-type template-parameter of type pointer to member function,
7592      no conversions apply. If the template-argument represents a set of
7593      overloaded member functions, the matching member function is selected
7594      from the set (_over.over_).  */
7595   else if (TYPE_PTRMEMFUNC_P (type))
7596     {
7597       expr = instantiate_type (type, expr, tf_none);
7598       if (expr == error_mark_node)
7599 	return error_mark_node;
7600 
7601       /* [temp.arg.nontype] bullet 1 says the pointer to member
7602          expression must be a pointer-to-member constant.  */
7603       if (!val_dep_p
7604 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7605 	return NULL_TREE;
7606 
7607       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7608 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7609       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7610 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7611     }
7612   /* [temp.arg.nontype]/5, bullet 7
7613 
7614      For a non-type template-parameter of type pointer to data member,
7615      qualification conversions (_conv.qual_) are applied.  */
7616   else if (TYPE_PTRDATAMEM_P (type))
7617     {
7618       /* [temp.arg.nontype] bullet 1 says the pointer to member
7619          expression must be a pointer-to-member constant.  */
7620       if (!val_dep_p
7621 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7622 	return NULL_TREE;
7623 
7624       expr = perform_qualification_conversions (type, expr);
7625       if (expr == error_mark_node)
7626 	return expr;
7627     }
7628   else if (NULLPTR_TYPE_P (type))
7629     {
7630       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7631 	{
7632 	  if (complain & tf_error)
7633 	    error ("%qE is not a valid template argument for type %qT "
7634 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7635 	  return NULL_TREE;
7636 	}
7637       return expr;
7638     }
7639   else if (CLASS_TYPE_P (type))
7640     {
7641       /* Replace the argument with a reference to the corresponding template
7642 	 parameter object.  */
7643       if (!val_dep_p)
7644 	expr = get_template_parm_object (expr, complain);
7645       if (expr == error_mark_node)
7646 	return NULL_TREE;
7647     }
7648   /* A template non-type parameter must be one of the above.  */
7649   else
7650     gcc_unreachable ();
7651 
7652   /* Sanity check: did we actually convert the argument to the
7653      right type?  */
7654   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7655 	      (type, TREE_TYPE (expr)));
7656   return convert_from_reference (expr);
7657 }
7658 
7659 /* Subroutine of coerce_template_template_parms, which returns 1 if
7660    PARM_PARM and ARG_PARM match using the rule for the template
7661    parameters of template template parameters. Both PARM and ARG are
7662    template parameters; the rest of the arguments are the same as for
7663    coerce_template_template_parms.
7664  */
7665 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7666 coerce_template_template_parm (tree parm,
7667                               tree arg,
7668                               tsubst_flags_t complain,
7669                               tree in_decl,
7670                               tree outer_args)
7671 {
7672   if (arg == NULL_TREE || error_operand_p (arg)
7673       || parm == NULL_TREE || error_operand_p (parm))
7674     return 0;
7675 
7676   if (TREE_CODE (arg) != TREE_CODE (parm))
7677     return 0;
7678 
7679   switch (TREE_CODE (parm))
7680     {
7681     case TEMPLATE_DECL:
7682       /* We encounter instantiations of templates like
7683 	 template <template <template <class> class> class TT>
7684 	 class C;  */
7685       {
7686 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7687 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7688 
7689 	if (!coerce_template_template_parms
7690 	    (parmparm, argparm, complain, in_decl, outer_args))
7691 	  return 0;
7692       }
7693       /* Fall through.  */
7694 
7695     case TYPE_DECL:
7696       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7697 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7698 	/* Argument is a parameter pack but parameter is not.  */
7699 	return 0;
7700       break;
7701 
7702     case PARM_DECL:
7703       /* The tsubst call is used to handle cases such as
7704 
7705            template <int> class C {};
7706 	   template <class T, template <T> class TT> class D {};
7707 	   D<int, C> d;
7708 
7709 	 i.e. the parameter list of TT depends on earlier parameters.  */
7710       if (!uses_template_parms (TREE_TYPE (arg)))
7711 	{
7712 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7713 	  if (!uses_template_parms (t)
7714 	      && !same_type_p (t, TREE_TYPE (arg)))
7715 	    return 0;
7716 	}
7717 
7718       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7719 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7720 	/* Argument is a parameter pack but parameter is not.  */
7721 	return 0;
7722 
7723       break;
7724 
7725     default:
7726       gcc_unreachable ();
7727     }
7728 
7729   return 1;
7730 }
7731 
7732 /* Coerce template argument list ARGLIST for use with template
7733    template-parameter TEMPL.  */
7734 
7735 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7736 coerce_template_args_for_ttp (tree templ, tree arglist,
7737 			      tsubst_flags_t complain)
7738 {
7739   /* Consider an example where a template template parameter declared as
7740 
7741      template <class T, class U = std::allocator<T> > class TT
7742 
7743      The template parameter level of T and U are one level larger than
7744      of TT.  To proper process the default argument of U, say when an
7745      instantiation `TT<int>' is seen, we need to build the full
7746      arguments containing {int} as the innermost level.  Outer levels,
7747      available when not appearing as default template argument, can be
7748      obtained from the arguments of the enclosing template.
7749 
7750      Suppose that TT is later substituted with std::vector.  The above
7751      instantiation is `TT<int, std::allocator<T> >' with TT at
7752      level 1, and T at level 2, while the template arguments at level 1
7753      becomes {std::vector} and the inner level 2 is {int}.  */
7754 
7755   tree outer = DECL_CONTEXT (templ);
7756   if (outer)
7757     outer = generic_targs_for (outer);
7758   else if (current_template_parms)
7759     {
7760       /* This is an argument of the current template, so we haven't set
7761 	 DECL_CONTEXT yet.  */
7762       tree relevant_template_parms;
7763 
7764       /* Parameter levels that are greater than the level of the given
7765 	 template template parm are irrelevant.  */
7766       relevant_template_parms = current_template_parms;
7767       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7768 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7769 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7770 
7771       outer = template_parms_to_args (relevant_template_parms);
7772     }
7773 
7774   if (outer)
7775     arglist = add_to_template_args (outer, arglist);
7776 
7777   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7778   return coerce_template_parms (parmlist, arglist, templ,
7779 				complain,
7780 				/*require_all_args=*/true,
7781 				/*use_default_args=*/true);
7782 }
7783 
7784 /* A cache of template template parameters with match-all default
7785    arguments.  */
7786 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7787 
7788 /* T is a bound template template-parameter.  Copy its arguments into default
7789    arguments of the template template-parameter's template parameters.  */
7790 
7791 static tree
add_defaults_to_ttp(tree otmpl)7792 add_defaults_to_ttp (tree otmpl)
7793 {
7794   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7795     return *c;
7796 
7797   tree ntmpl = copy_node (otmpl);
7798 
7799   tree ntype = copy_node (TREE_TYPE (otmpl));
7800   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7801   TYPE_MAIN_VARIANT (ntype) = ntype;
7802   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7803   TYPE_NAME (ntype) = ntmpl;
7804   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7805 
7806   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7807     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7808   TEMPLATE_PARM_DECL (idx) = ntmpl;
7809   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7810 
7811   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7812   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7813   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7814   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7815   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7816     {
7817       tree o = TREE_VEC_ELT (vec, i);
7818       if (!template_parameter_pack_p (TREE_VALUE (o)))
7819 	{
7820 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7821 	  TREE_PURPOSE (n) = any_targ_node;
7822 	}
7823     }
7824 
7825   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7826   return ntmpl;
7827 }
7828 
7829 /* ARG is a bound potential template template-argument, and PARGS is a list
7830    of arguments for the corresponding template template-parameter.  Adjust
7831    PARGS as appropriate for application to ARG's template, and if ARG is a
7832    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7833    arguments to the template template parameter.  */
7834 
7835 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7836 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7837 {
7838   ++processing_template_decl;
7839   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7840   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7841     {
7842       /* When comparing two template template-parameters in partial ordering,
7843 	 rewrite the one currently being used as an argument to have default
7844 	 arguments for all parameters.  */
7845       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7846       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7847       if (pargs != error_mark_node)
7848 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7849 					   TYPE_TI_ARGS (arg));
7850     }
7851   else
7852     {
7853       tree aparms
7854 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7855       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7856 				       /*require_all*/true,
7857 				       /*use_default*/true);
7858     }
7859   --processing_template_decl;
7860   return pargs;
7861 }
7862 
7863 /* Subroutine of unify for the case when PARM is a
7864    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7865 
7866 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7867 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7868 		      bool explain_p)
7869 {
7870   tree parmvec = TYPE_TI_ARGS (parm);
7871   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7872 
7873   /* The template template parm might be variadic and the argument
7874      not, so flatten both argument lists.  */
7875   parmvec = expand_template_argument_pack (parmvec);
7876   argvec = expand_template_argument_pack (argvec);
7877 
7878   if (flag_new_ttp)
7879     {
7880       /* In keeping with P0522R0, adjust P's template arguments
7881 	 to apply to A's template; then flatten it again.  */
7882       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7883       nparmvec = expand_template_argument_pack (nparmvec);
7884 
7885       if (unify (tparms, targs, nparmvec, argvec,
7886 		 UNIFY_ALLOW_NONE, explain_p))
7887 	return 1;
7888 
7889       /* If the P0522 adjustment eliminated a pack expansion, deduce
7890 	 empty packs.  */
7891       if (flag_new_ttp
7892 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7893 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7894 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7895 	return 1;
7896     }
7897   else
7898     {
7899       /* Deduce arguments T, i from TT<T> or TT<i>.
7900 	 We check each element of PARMVEC and ARGVEC individually
7901 	 rather than the whole TREE_VEC since they can have
7902 	 different number of elements, which is allowed under N2555.  */
7903 
7904       int len = TREE_VEC_LENGTH (parmvec);
7905 
7906       /* Check if the parameters end in a pack, making them
7907 	 variadic.  */
7908       int parm_variadic_p = 0;
7909       if (len > 0
7910 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7911 	parm_variadic_p = 1;
7912 
7913       for (int i = 0; i < len - parm_variadic_p; ++i)
7914 	/* If the template argument list of P contains a pack
7915 	   expansion that is not the last template argument, the
7916 	   entire template argument list is a non-deduced
7917 	   context.  */
7918 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7919 	  return unify_success (explain_p);
7920 
7921       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7922 	return unify_too_few_arguments (explain_p,
7923 					TREE_VEC_LENGTH (argvec), len);
7924 
7925       for (int i = 0; i < len - parm_variadic_p; ++i)
7926 	if (unify (tparms, targs,
7927 		   TREE_VEC_ELT (parmvec, i),
7928 		   TREE_VEC_ELT (argvec, i),
7929 		   UNIFY_ALLOW_NONE, explain_p))
7930 	  return 1;
7931 
7932       if (parm_variadic_p
7933 	  && unify_pack_expansion (tparms, targs,
7934 				   parmvec, argvec,
7935 				   DEDUCE_EXACT,
7936 				   /*subr=*/true, explain_p))
7937 	return 1;
7938     }
7939 
7940   return 0;
7941 }
7942 
7943 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7944    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7945    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7946    or PARM_DECL.
7947 
7948    Consider the example:
7949      template <class T> class A;
7950      template<template <class U> class TT> class B;
7951 
7952    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7953    the parameters to A, and OUTER_ARGS contains A.  */
7954 
7955 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7956 coerce_template_template_parms (tree parm_parms,
7957 				tree arg_parms,
7958 				tsubst_flags_t complain,
7959 				tree in_decl,
7960 				tree outer_args)
7961 {
7962   int nparms, nargs, i;
7963   tree parm, arg;
7964   int variadic_p = 0;
7965 
7966   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7967   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7968 
7969   nparms = TREE_VEC_LENGTH (parm_parms);
7970   nargs = TREE_VEC_LENGTH (arg_parms);
7971 
7972   if (flag_new_ttp)
7973     {
7974       /* P0522R0: A template template-parameter P is at least as specialized as
7975 	 a template template-argument A if, given the following rewrite to two
7976 	 function templates, the function template corresponding to P is at
7977 	 least as specialized as the function template corresponding to A
7978 	 according to the partial ordering rules for function templates
7979 	 ([temp.func.order]). Given an invented class template X with the
7980 	 template parameter list of A (including default arguments):
7981 
7982 	 * Each of the two function templates has the same template parameters,
7983 	 respectively, as P or A.
7984 
7985 	 * Each function template has a single function parameter whose type is
7986 	 a specialization of X with template arguments corresponding to the
7987 	 template parameters from the respective function template where, for
7988 	 each template parameter PP in the template parameter list of the
7989 	 function template, a corresponding template argument AA is formed. If
7990 	 PP declares a parameter pack, then AA is the pack expansion
7991 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7992 
7993 	 If the rewrite produces an invalid type, then P is not at least as
7994 	 specialized as A.  */
7995 
7996       /* So coerce P's args to apply to A's parms, and then deduce between A's
7997 	 args and the converted args.  If that succeeds, A is at least as
7998 	 specialized as P, so they match.*/
7999       tree pargs = template_parms_level_to_args (parm_parms);
8000       pargs = add_outermost_template_args (outer_args, pargs);
8001       ++processing_template_decl;
8002       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
8003 				     /*require_all*/true, /*use_default*/true);
8004       --processing_template_decl;
8005       if (pargs != error_mark_node)
8006 	{
8007 	  tree targs = make_tree_vec (nargs);
8008 	  tree aargs = template_parms_level_to_args (arg_parms);
8009 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8010 		      /*explain*/false))
8011 	    return 1;
8012 	}
8013     }
8014 
8015   /* Determine whether we have a parameter pack at the end of the
8016      template template parameter's template parameter list.  */
8017   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8018     {
8019       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8020 
8021       if (error_operand_p (parm))
8022 	return 0;
8023 
8024       switch (TREE_CODE (parm))
8025         {
8026         case TEMPLATE_DECL:
8027         case TYPE_DECL:
8028           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8029             variadic_p = 1;
8030           break;
8031 
8032         case PARM_DECL:
8033           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8034             variadic_p = 1;
8035           break;
8036 
8037         default:
8038           gcc_unreachable ();
8039         }
8040     }
8041 
8042   if (nargs != nparms
8043       && !(variadic_p && nargs >= nparms - 1))
8044     return 0;
8045 
8046   /* Check all of the template parameters except the parameter pack at
8047      the end (if any).  */
8048   for (i = 0; i < nparms - variadic_p; ++i)
8049     {
8050       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8051           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8052         continue;
8053 
8054       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8055       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8056 
8057       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8058                                           outer_args))
8059 	return 0;
8060 
8061     }
8062 
8063   if (variadic_p)
8064     {
8065       /* Check each of the template parameters in the template
8066 	 argument against the template parameter pack at the end of
8067 	 the template template parameter.  */
8068       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8069 	return 0;
8070 
8071       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8072 
8073       for (; i < nargs; ++i)
8074         {
8075           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8076             continue;
8077 
8078           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8079 
8080           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8081                                               outer_args))
8082             return 0;
8083         }
8084     }
8085 
8086   return 1;
8087 }
8088 
8089 /* Verifies that the deduced template arguments (in TARGS) for the
8090    template template parameters (in TPARMS) represent valid bindings,
8091    by comparing the template parameter list of each template argument
8092    to the template parameter list of its corresponding template
8093    template parameter, in accordance with DR150. This
8094    routine can only be called after all template arguments have been
8095    deduced. It will return TRUE if all of the template template
8096    parameter bindings are okay, FALSE otherwise.  */
8097 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)8098 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8099 {
8100   int i, ntparms = TREE_VEC_LENGTH (tparms);
8101   bool ret = true;
8102 
8103   /* We're dealing with template parms in this process.  */
8104   ++processing_template_decl;
8105 
8106   targs = INNERMOST_TEMPLATE_ARGS (targs);
8107 
8108   for (i = 0; i < ntparms; ++i)
8109     {
8110       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8111       tree targ = TREE_VEC_ELT (targs, i);
8112 
8113       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8114 	{
8115 	  tree packed_args = NULL_TREE;
8116 	  int idx, len = 1;
8117 
8118 	  if (ARGUMENT_PACK_P (targ))
8119 	    {
8120 	      /* Look inside the argument pack.  */
8121 	      packed_args = ARGUMENT_PACK_ARGS (targ);
8122 	      len = TREE_VEC_LENGTH (packed_args);
8123 	    }
8124 
8125 	  for (idx = 0; idx < len; ++idx)
8126 	    {
8127 	      tree targ_parms = NULL_TREE;
8128 
8129 	      if (packed_args)
8130 		/* Extract the next argument from the argument
8131 		   pack.  */
8132 		targ = TREE_VEC_ELT (packed_args, idx);
8133 
8134 	      if (PACK_EXPANSION_P (targ))
8135 		/* Look at the pattern of the pack expansion.  */
8136 		targ = PACK_EXPANSION_PATTERN (targ);
8137 
8138 	      /* Extract the template parameters from the template
8139 		 argument.  */
8140 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
8141 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
8142 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8143 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
8144 
8145 	      /* Verify that we can coerce the template template
8146 		 parameters from the template argument to the template
8147 		 parameter.  This requires an exact match.  */
8148 	      if (targ_parms
8149 		  && !coerce_template_template_parms
8150 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
8151 			targ_parms,
8152 			tf_none,
8153 			tparm,
8154 			targs))
8155 		{
8156 		  ret = false;
8157 		  goto out;
8158 		}
8159 	    }
8160 	}
8161     }
8162 
8163  out:
8164 
8165   --processing_template_decl;
8166   return ret;
8167 }
8168 
8169 /* Since type attributes aren't mangled, we need to strip them from
8170    template type arguments.  */
8171 
8172 tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)8173 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8174 {
8175   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8176     return arg;
8177   bool removed_attributes = false;
8178   tree canon = strip_typedefs (arg, &removed_attributes);
8179   if (removed_attributes
8180       && (complain & tf_warning))
8181     warning (OPT_Wignored_attributes,
8182 	     "ignoring attributes on template argument %qT", arg);
8183   return canon;
8184 }
8185 
8186 /* And from inside dependent non-type arguments like sizeof(Type).  */
8187 
8188 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)8189 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8190 {
8191   if (!arg || arg == error_mark_node)
8192     return arg;
8193   bool removed_attributes = false;
8194   tree canon = strip_typedefs_expr (arg, &removed_attributes);
8195   if (removed_attributes
8196       && (complain & tf_warning))
8197     warning (OPT_Wignored_attributes,
8198 	     "ignoring attributes in template argument %qE", arg);
8199   return canon;
8200 }
8201 
8202 /* A template declaration can be substituted for a constrained
8203    template template parameter only when the argument is no more
8204    constrained than the parameter.  */
8205 
8206 static bool
is_compatible_template_arg(tree parm,tree arg)8207 is_compatible_template_arg (tree parm, tree arg)
8208 {
8209   tree parm_cons = get_constraints (parm);
8210 
8211   /* For now, allow constrained template template arguments
8212      and unconstrained template template parameters.  */
8213   if (parm_cons == NULL_TREE)
8214     return true;
8215 
8216   /* If the template parameter is constrained, we need to rewrite its
8217      constraints in terms of the ARG's template parameters. This ensures
8218      that all of the template parameter types will have the same depth.
8219 
8220      Note that this is only valid when coerce_template_template_parm is
8221      true for the innermost template parameters of PARM and ARG. In other
8222      words, because coercion is successful, this conversion will be valid.  */
8223   tree new_args = NULL_TREE;
8224   if (parm_cons)
8225     {
8226       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8227       new_args = template_parms_level_to_args (aparms);
8228       ++processing_template_decl;
8229       parm_cons = tsubst_constraint_info (parm_cons, new_args,
8230 					  tf_none, NULL_TREE);
8231       --processing_template_decl;
8232       if (parm_cons == error_mark_node)
8233         return false;
8234     }
8235 
8236   return weakly_subsumes (parm_cons, arg);
8237 }
8238 
8239 // Convert a placeholder argument into a binding to the original
8240 // parameter. The original parameter is saved as the TREE_TYPE of
8241 // ARG.
8242 static inline tree
convert_wildcard_argument(tree parm,tree arg)8243 convert_wildcard_argument (tree parm, tree arg)
8244 {
8245   TREE_TYPE (arg) = parm;
8246   return arg;
8247 }
8248 
8249 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8250    because one of them is dependent.  But we need to represent the
8251    conversion for the benefit of cp_tree_equal.  */
8252 
8253 static tree
maybe_convert_nontype_argument(tree type,tree arg)8254 maybe_convert_nontype_argument (tree type, tree arg)
8255 {
8256   /* Auto parms get no conversion.  */
8257   if (type_uses_auto (type))
8258     return arg;
8259   /* We don't need or want to add this conversion now if we're going to use the
8260      argument for deduction.  */
8261   if (value_dependent_expression_p (arg))
8262     return arg;
8263 
8264   type = cv_unqualified (type);
8265   tree argtype = TREE_TYPE (arg);
8266   if (same_type_p (type, argtype))
8267     return arg;
8268 
8269   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8270   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8271   return arg;
8272 }
8273 
8274 /* Convert the indicated template ARG as necessary to match the
8275    indicated template PARM.  Returns the converted ARG, or
8276    error_mark_node if the conversion was unsuccessful.  Error and
8277    warning messages are issued under control of COMPLAIN.  This
8278    conversion is for the Ith parameter in the parameter list.  ARGS is
8279    the full set of template arguments deduced so far.  */
8280 
8281 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)8282 convert_template_argument (tree parm,
8283 			   tree arg,
8284 			   tree args,
8285 			   tsubst_flags_t complain,
8286 			   int i,
8287 			   tree in_decl)
8288 {
8289   tree orig_arg;
8290   tree val;
8291   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8292 
8293   if (parm == error_mark_node || error_operand_p (arg))
8294     return error_mark_node;
8295 
8296   /* Trivially convert placeholders. */
8297   if (TREE_CODE (arg) == WILDCARD_DECL)
8298     return convert_wildcard_argument (parm, arg);
8299 
8300   if (arg == any_targ_node)
8301     return arg;
8302 
8303   if (TREE_CODE (arg) == TREE_LIST
8304       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8305     {
8306       /* The template argument was the name of some
8307 	 member function.  That's usually
8308 	 invalid, but static members are OK.  In any
8309 	 case, grab the underlying fields/functions
8310 	 and issue an error later if required.  */
8311       TREE_TYPE (arg) = unknown_type_node;
8312     }
8313 
8314   orig_arg = arg;
8315 
8316   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8317   requires_type = (TREE_CODE (parm) == TYPE_DECL
8318 		   || requires_tmpl_type);
8319 
8320   /* When determining whether an argument pack expansion is a template,
8321      look at the pattern.  */
8322   if (PACK_EXPANSION_P (arg))
8323     arg = PACK_EXPANSION_PATTERN (arg);
8324 
8325   /* Deal with an injected-class-name used as a template template arg.  */
8326   if (requires_tmpl_type && CLASS_TYPE_P (arg))
8327     {
8328       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8329       if (TREE_CODE (t) == TEMPLATE_DECL)
8330 	{
8331 	  if (cxx_dialect >= cxx11)
8332 	    /* OK under DR 1004.  */;
8333 	  else if (complain & tf_warning_or_error)
8334 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8335 		     " used as template template argument", TYPE_NAME (arg));
8336 	  else if (flag_pedantic_errors)
8337 	    t = arg;
8338 
8339 	  arg = t;
8340 	}
8341     }
8342 
8343   is_tmpl_type =
8344     ((TREE_CODE (arg) == TEMPLATE_DECL
8345       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8346      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8347      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8348      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8349 
8350   if (is_tmpl_type
8351       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8352 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8353     arg = TYPE_STUB_DECL (arg);
8354 
8355   is_type = TYPE_P (arg) || is_tmpl_type;
8356 
8357   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8358       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8359     {
8360       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8361 	{
8362 	  if (complain & tf_error)
8363 	    error ("invalid use of destructor %qE as a type", orig_arg);
8364 	  return error_mark_node;
8365 	}
8366 
8367       permerror (input_location,
8368 		 "to refer to a type member of a template parameter, "
8369 		 "use %<typename %E%>", orig_arg);
8370 
8371       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8372 				     TREE_OPERAND (arg, 1),
8373 				     typename_type,
8374 				     complain);
8375       arg = orig_arg;
8376       is_type = 1;
8377     }
8378   if (is_type != requires_type)
8379     {
8380       if (in_decl)
8381 	{
8382 	  if (complain & tf_error)
8383 	    {
8384 	      error ("type/value mismatch at argument %d in template "
8385 		     "parameter list for %qD",
8386 		     i + 1, in_decl);
8387 	      if (is_type)
8388 		{
8389 		  /* The template argument is a type, but we're expecting
8390 		     an expression.  */
8391 		  inform (input_location,
8392 			  "  expected a constant of type %qT, got %qT",
8393 			  TREE_TYPE (parm),
8394 			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8395 		  /* [temp.arg]/2: "In a template-argument, an ambiguity
8396 		     between a type-id and an expression is resolved to a
8397 		     type-id, regardless of the form of the corresponding
8398 		     template-parameter."  So give the user a clue.  */
8399 		  if (TREE_CODE (arg) == FUNCTION_TYPE)
8400 		    inform (input_location, "  ambiguous template argument "
8401 			    "for non-type template parameter is treated as "
8402 			    "function type");
8403 		}
8404 	      else if (requires_tmpl_type)
8405 		inform (input_location,
8406 			"  expected a class template, got %qE", orig_arg);
8407 	      else
8408 		inform (input_location,
8409 			"  expected a type, got %qE", orig_arg);
8410 	    }
8411 	}
8412       return error_mark_node;
8413     }
8414   if (is_tmpl_type ^ requires_tmpl_type)
8415     {
8416       if (in_decl && (complain & tf_error))
8417 	{
8418 	  error ("type/value mismatch at argument %d in template "
8419 		 "parameter list for %qD",
8420 		 i + 1, in_decl);
8421 	  if (is_tmpl_type)
8422 	    inform (input_location,
8423 		    "  expected a type, got %qT", DECL_NAME (arg));
8424 	  else
8425 	    inform (input_location,
8426 		    "  expected a class template, got %qT", orig_arg);
8427 	}
8428       return error_mark_node;
8429     }
8430 
8431   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8432     /* We already did the appropriate conversion when packing args.  */
8433     val = orig_arg;
8434   else if (is_type)
8435     {
8436       if (requires_tmpl_type)
8437 	{
8438 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8439 	    /* The number of argument required is not known yet.
8440 	       Just accept it for now.  */
8441 	    val = orig_arg;
8442 	  else
8443 	    {
8444 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8445 	      tree argparm;
8446 
8447 	      /* Strip alias templates that are equivalent to another
8448 		 template.  */
8449 	      arg = get_underlying_template (arg);
8450               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8451 
8452 	      if (coerce_template_template_parms (parmparm, argparm,
8453 						  complain, in_decl,
8454 						  args))
8455 		{
8456 		  val = arg;
8457 
8458 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8459 		     TEMPLATE_DECL.  */
8460 		  if (val != error_mark_node)
8461                     {
8462                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8463                         val = TREE_TYPE (val);
8464 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8465 			val = make_pack_expansion (val, complain);
8466                     }
8467 		}
8468 	      else
8469 		{
8470 		  if (in_decl && (complain & tf_error))
8471 		    {
8472 		      error ("type/value mismatch at argument %d in "
8473 			     "template parameter list for %qD",
8474 			     i + 1, in_decl);
8475 		      inform (input_location,
8476 			      "  expected a template of type %qD, got %qT",
8477 			      parm, orig_arg);
8478 		    }
8479 
8480 		  val = error_mark_node;
8481 		}
8482 
8483               // Check that the constraints are compatible before allowing the
8484               // substitution.
8485               if (val != error_mark_node)
8486                 if (!is_compatible_template_arg (parm, arg))
8487                   {
8488 		    if (in_decl && (complain & tf_error))
8489                       {
8490                         error ("constraint mismatch at argument %d in "
8491                                "template parameter list for %qD",
8492                                i + 1, in_decl);
8493                         inform (input_location, "  expected %qD but got %qD",
8494                                 parm, arg);
8495                       }
8496 		    val = error_mark_node;
8497                   }
8498 	    }
8499 	}
8500       else
8501 	val = orig_arg;
8502       /* We only form one instance of each template specialization.
8503 	 Therefore, if we use a non-canonical variant (i.e., a
8504 	 typedef), any future messages referring to the type will use
8505 	 the typedef, which is confusing if those future uses do not
8506 	 themselves also use the typedef.  */
8507       if (TYPE_P (val))
8508 	val = canonicalize_type_argument (val, complain);
8509     }
8510   else
8511     {
8512       tree t = TREE_TYPE (parm);
8513 
8514       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8515 	  > TMPL_ARGS_DEPTH (args))
8516 	/* We don't have enough levels of args to do any substitution.  This
8517 	   can happen in the context of -fnew-ttp-matching.  */;
8518       else if (tree a = type_uses_auto (t))
8519 	{
8520 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8521 				 LOOKUP_IMPLICIT);
8522 	  if (t == error_mark_node)
8523 	    return error_mark_node;
8524 	}
8525       else
8526 	t = tsubst (t, args, complain, in_decl);
8527 
8528       if (invalid_nontype_parm_type_p (t, complain))
8529 	return error_mark_node;
8530 
8531       if (t != TREE_TYPE (parm))
8532 	t = canonicalize_type_argument (t, complain);
8533 
8534       if (!type_dependent_expression_p (orig_arg)
8535 	  && !uses_template_parms (t))
8536 	/* We used to call digest_init here.  However, digest_init
8537 	   will report errors, which we don't want when complain
8538 	   is zero.  More importantly, digest_init will try too
8539 	   hard to convert things: for example, `0' should not be
8540 	   converted to pointer type at this point according to
8541 	   the standard.  Accepting this is not merely an
8542 	   extension, since deciding whether or not these
8543 	   conversions can occur is part of determining which
8544 	   function template to call, or whether a given explicit
8545 	   argument specification is valid.  */
8546 	val = convert_nontype_argument (t, orig_arg, complain);
8547       else
8548 	{
8549 	  val = canonicalize_expr_argument (orig_arg, complain);
8550 	  val = maybe_convert_nontype_argument (t, val);
8551 	}
8552 
8553 
8554       if (val == NULL_TREE)
8555 	val = error_mark_node;
8556       else if (val == error_mark_node && (complain & tf_error))
8557 	error_at (cp_expr_loc_or_input_loc (orig_arg),
8558 		  "could not convert template argument %qE from %qT to %qT",
8559 		  orig_arg, TREE_TYPE (orig_arg), t);
8560 
8561       if (INDIRECT_REF_P (val))
8562         {
8563           /* Reject template arguments that are references to built-in
8564              functions with no library fallbacks.  */
8565           const_tree inner = TREE_OPERAND (val, 0);
8566 	  const_tree innertype = TREE_TYPE (inner);
8567 	  if (innertype
8568 	      && TYPE_REF_P (innertype)
8569 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8570 	      && TREE_OPERAND_LENGTH (inner) > 0
8571               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8572               return error_mark_node;
8573         }
8574 
8575       if (TREE_CODE (val) == SCOPE_REF)
8576 	{
8577 	  /* Strip typedefs from the SCOPE_REF.  */
8578 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8579 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8580 						   complain);
8581 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8582 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8583 	}
8584     }
8585 
8586   return val;
8587 }
8588 
8589 /* Coerces the remaining template arguments in INNER_ARGS (from
8590    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8591    Returns the coerced argument pack. PARM_IDX is the position of this
8592    parameter in the template parameter list. ARGS is the original
8593    template argument list.  */
8594 static tree
coerce_template_parameter_pack(tree parms,int parm_idx,tree args,tree inner_args,int arg_idx,tree new_args,int * lost,tree in_decl,tsubst_flags_t complain)8595 coerce_template_parameter_pack (tree parms,
8596                                 int parm_idx,
8597                                 tree args,
8598                                 tree inner_args,
8599                                 int arg_idx,
8600                                 tree new_args,
8601                                 int* lost,
8602                                 tree in_decl,
8603                                 tsubst_flags_t complain)
8604 {
8605   tree parm = TREE_VEC_ELT (parms, parm_idx);
8606   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8607   tree packed_args;
8608   tree argument_pack;
8609   tree packed_parms = NULL_TREE;
8610 
8611   if (arg_idx > nargs)
8612     arg_idx = nargs;
8613 
8614   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8615     {
8616       /* When the template parameter is a non-type template parameter pack
8617          or template template parameter pack whose type or template
8618          parameters use parameter packs, we know exactly how many arguments
8619          we are looking for.  Build a vector of the instantiated decls for
8620          these template parameters in PACKED_PARMS.  */
8621       /* We can't use make_pack_expansion here because it would interpret a
8622 	 _DECL as a use rather than a declaration.  */
8623       tree decl = TREE_VALUE (parm);
8624       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8625       SET_PACK_EXPANSION_PATTERN (exp, decl);
8626       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8627       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8628 
8629       TREE_VEC_LENGTH (args)--;
8630       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8631       TREE_VEC_LENGTH (args)++;
8632 
8633       if (packed_parms == error_mark_node)
8634         return error_mark_node;
8635 
8636       /* If we're doing a partial instantiation of a member template,
8637          verify that all of the types used for the non-type
8638          template parameter pack are, in fact, valid for non-type
8639          template parameters.  */
8640       if (arg_idx < nargs
8641           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8642         {
8643           int j, len = TREE_VEC_LENGTH (packed_parms);
8644           for (j = 0; j < len; ++j)
8645             {
8646               tree t = TREE_VEC_ELT (packed_parms, j);
8647               if (TREE_CODE (t) == PARM_DECL
8648 		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8649                 return error_mark_node;
8650             }
8651 	  /* We don't know how many args we have yet, just
8652 	     use the unconverted ones for now.  */
8653 	  return NULL_TREE;
8654         }
8655 
8656       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8657     }
8658   /* Check if we have a placeholder pack, which indicates we're
8659      in the context of a introduction list.  In that case we want
8660      to match this pack to the single placeholder.  */
8661   else if (arg_idx < nargs
8662            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8663            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8664     {
8665       nargs = arg_idx + 1;
8666       packed_args = make_tree_vec (1);
8667     }
8668   else
8669     packed_args = make_tree_vec (nargs - arg_idx);
8670 
8671   /* Convert the remaining arguments, which will be a part of the
8672      parameter pack "parm".  */
8673   int first_pack_arg = arg_idx;
8674   for (; arg_idx < nargs; ++arg_idx)
8675     {
8676       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8677       tree actual_parm = TREE_VALUE (parm);
8678       int pack_idx = arg_idx - first_pack_arg;
8679 
8680       if (packed_parms)
8681         {
8682 	  /* Once we've packed as many args as we have types, stop.  */
8683 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8684 	    break;
8685 	  else if (PACK_EXPANSION_P (arg))
8686 	    /* We don't know how many args we have yet, just
8687 	       use the unconverted ones for now.  */
8688 	    return NULL_TREE;
8689 	  else
8690 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8691         }
8692 
8693       if (arg == error_mark_node)
8694 	{
8695 	  if (complain & tf_error)
8696 	    error ("template argument %d is invalid", arg_idx + 1);
8697 	}
8698       else
8699 	arg = convert_template_argument (actual_parm,
8700 					 arg, new_args, complain, parm_idx,
8701 					 in_decl);
8702       if (arg == error_mark_node)
8703         (*lost)++;
8704       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8705     }
8706 
8707   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8708       && TREE_VEC_LENGTH (packed_args) > 0)
8709     {
8710       if (complain & tf_error)
8711 	error ("wrong number of template arguments (%d, should be %d)",
8712 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8713       return error_mark_node;
8714     }
8715 
8716   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8717       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8718     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8719   else
8720     {
8721       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8722       TREE_CONSTANT (argument_pack) = 1;
8723     }
8724 
8725   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8726   if (CHECKING_P)
8727     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8728 					 TREE_VEC_LENGTH (packed_args));
8729   return argument_pack;
8730 }
8731 
8732 /* Returns the number of pack expansions in the template argument vector
8733    ARGS.  */
8734 
8735 static int
pack_expansion_args_count(tree args)8736 pack_expansion_args_count (tree args)
8737 {
8738   int i;
8739   int count = 0;
8740   if (args)
8741     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8742       {
8743 	tree elt = TREE_VEC_ELT (args, i);
8744 	if (elt && PACK_EXPANSION_P (elt))
8745 	  ++count;
8746       }
8747   return count;
8748 }
8749 
8750 /* Convert all template arguments to their appropriate types, and
8751    return a vector containing the innermost resulting template
8752    arguments.  If any error occurs, return error_mark_node. Error and
8753    warning messages are issued under control of COMPLAIN.
8754 
8755    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8756    for arguments not specified in ARGS.  Otherwise, if
8757    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8758    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8759    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8760    ARGS.  */
8761 
8762 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8763 coerce_template_parms (tree parms,
8764 		       tree args,
8765 		       tree in_decl,
8766 		       tsubst_flags_t complain,
8767 		       bool require_all_args,
8768 		       bool use_default_args)
8769 {
8770   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8771   tree orig_inner_args;
8772   tree inner_args;
8773   tree new_args;
8774   tree new_inner_args;
8775 
8776   /* When used as a boolean value, indicates whether this is a
8777      variadic template parameter list. Since it's an int, we can also
8778      subtract it from nparms to get the number of non-variadic
8779      parameters.  */
8780   int variadic_p = 0;
8781   int variadic_args_p = 0;
8782   int post_variadic_parms = 0;
8783 
8784   /* Adjustment to nparms for fixed parameter packs.  */
8785   int fixed_pack_adjust = 0;
8786   int fixed_packs = 0;
8787   int missing = 0;
8788 
8789   /* Likewise for parameters with default arguments.  */
8790   int default_p = 0;
8791 
8792   if (args == error_mark_node)
8793     return error_mark_node;
8794 
8795   nparms = TREE_VEC_LENGTH (parms);
8796 
8797   /* Determine if there are any parameter packs or default arguments.  */
8798   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8799     {
8800       tree parm = TREE_VEC_ELT (parms, parm_idx);
8801       if (variadic_p)
8802 	++post_variadic_parms;
8803       if (template_parameter_pack_p (TREE_VALUE (parm)))
8804 	++variadic_p;
8805       if (TREE_PURPOSE (parm))
8806 	++default_p;
8807     }
8808 
8809   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8810   /* If there are no parameters that follow a parameter pack, we need to
8811      expand any argument packs so that we can deduce a parameter pack from
8812      some non-packed args followed by an argument pack, as in variadic85.C.
8813      If there are such parameters, we need to leave argument packs intact
8814      so the arguments are assigned properly.  This can happen when dealing
8815      with a nested class inside a partial specialization of a class
8816      template, as in variadic92.C, or when deducing a template parameter pack
8817      from a sub-declarator, as in variadic114.C.  */
8818   if (!post_variadic_parms)
8819     inner_args = expand_template_argument_pack (inner_args);
8820 
8821   /* Count any pack expansion args.  */
8822   variadic_args_p = pack_expansion_args_count (inner_args);
8823 
8824   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8825   if ((nargs - variadic_args_p > nparms && !variadic_p)
8826       || (nargs < nparms - variadic_p
8827 	  && require_all_args
8828 	  && !variadic_args_p
8829 	  && (!use_default_args
8830 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8831                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8832     {
8833     bad_nargs:
8834       if (complain & tf_error)
8835 	{
8836           if (variadic_p || default_p)
8837             {
8838               nparms -= variadic_p + default_p;
8839 	      error ("wrong number of template arguments "
8840 		     "(%d, should be at least %d)", nargs, nparms);
8841             }
8842 	  else
8843 	     error ("wrong number of template arguments "
8844 		    "(%d, should be %d)", nargs, nparms);
8845 
8846 	  if (in_decl)
8847 	    inform (DECL_SOURCE_LOCATION (in_decl),
8848 		    "provided for %qD", in_decl);
8849 	}
8850 
8851       return error_mark_node;
8852     }
8853   /* We can't pass a pack expansion to a non-pack parameter of an alias
8854      template (DR 1430).  */
8855   else if (in_decl
8856 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8857 	       || concept_definition_p (in_decl))
8858 	   && variadic_args_p
8859 	   && nargs - variadic_args_p < nparms - variadic_p)
8860     {
8861       if (complain & tf_error)
8862 	{
8863 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8864 	    {
8865 	      tree arg = TREE_VEC_ELT (inner_args, i);
8866 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8867 
8868 	      if (PACK_EXPANSION_P (arg)
8869 		  && !template_parameter_pack_p (parm))
8870 		{
8871 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8872 		    error_at (location_of (arg),
8873 			      "pack expansion argument for non-pack parameter "
8874 			      "%qD of alias template %qD", parm, in_decl);
8875 		  else
8876 		    error_at (location_of (arg),
8877 			      "pack expansion argument for non-pack parameter "
8878 			      "%qD of concept %qD", parm, in_decl);
8879 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8880 		  goto found;
8881 		}
8882 	    }
8883 	  gcc_unreachable ();
8884 	found:;
8885 	}
8886       return error_mark_node;
8887     }
8888 
8889   /* We need to evaluate the template arguments, even though this
8890      template-id may be nested within a "sizeof".  */
8891   cp_evaluated ev;
8892 
8893   new_inner_args = make_tree_vec (nparms);
8894   new_args = add_outermost_template_args (args, new_inner_args);
8895   int pack_adjust = 0;
8896   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8897     {
8898       tree arg;
8899       tree parm;
8900 
8901       /* Get the Ith template parameter.  */
8902       parm = TREE_VEC_ELT (parms, parm_idx);
8903 
8904       if (parm == error_mark_node)
8905 	{
8906 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8907 	  continue;
8908 	}
8909 
8910       /* Calculate the next argument.  */
8911       if (arg_idx < nargs)
8912 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8913       else
8914 	arg = NULL_TREE;
8915 
8916       if (template_parameter_pack_p (TREE_VALUE (parm))
8917 	  && (arg || require_all_args || !(complain & tf_partial))
8918 	  && !(arg && ARGUMENT_PACK_P (arg)))
8919         {
8920 	  /* Some arguments will be placed in the
8921 	     template parameter pack PARM.  */
8922 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8923 						inner_args, arg_idx,
8924 						new_args, &lost,
8925 						in_decl, complain);
8926 
8927 	  if (arg == NULL_TREE)
8928 	    {
8929 	      /* We don't know how many args we have yet, just use the
8930 		 unconverted (and still packed) ones for now.  */
8931 	      new_inner_args = orig_inner_args;
8932 	      arg_idx = nargs;
8933 	      break;
8934 	    }
8935 
8936           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8937 
8938           /* Store this argument.  */
8939           if (arg == error_mark_node)
8940 	    {
8941 	      lost++;
8942 	      /* We are done with all of the arguments.  */
8943 	      arg_idx = nargs;
8944 	      break;
8945 	    }
8946 	  else
8947 	    {
8948 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8949 	      arg_idx += pack_adjust;
8950 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8951 		{
8952 		  ++fixed_packs;
8953 		  fixed_pack_adjust += pack_adjust;
8954 		}
8955 	    }
8956 
8957           continue;
8958         }
8959       else if (arg)
8960 	{
8961           if (PACK_EXPANSION_P (arg))
8962             {
8963 	      /* "If every valid specialization of a variadic template
8964 		 requires an empty template parameter pack, the template is
8965 		 ill-formed, no diagnostic required."  So check that the
8966 		 pattern works with this parameter.  */
8967 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8968 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8969 						     pattern, new_args,
8970 						     complain, parm_idx,
8971 						     in_decl);
8972 	      if (conv == error_mark_node)
8973 		{
8974 		  if (complain & tf_error)
8975 		    inform (input_location, "so any instantiation with a "
8976 			    "non-empty parameter pack would be ill-formed");
8977 		  ++lost;
8978 		}
8979 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8980 		/* Recover from missing typename.  */
8981 		TREE_VEC_ELT (inner_args, arg_idx)
8982 		  = make_pack_expansion (conv, complain);
8983 
8984               /* We don't know how many args we have yet, just
8985                  use the unconverted ones for now.  */
8986               new_inner_args = inner_args;
8987 	      arg_idx = nargs;
8988               break;
8989             }
8990         }
8991       else if (require_all_args)
8992 	{
8993 	  /* There must be a default arg in this case.  */
8994 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8995 				     complain, in_decl);
8996 	  /* The position of the first default template argument,
8997 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8998 	     Record that.  */
8999 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9000 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9001 						 arg_idx - pack_adjust);
9002 	}
9003       else
9004 	break;
9005 
9006       if (arg == error_mark_node)
9007 	{
9008 	  if (complain & tf_error)
9009 	    error ("template argument %d is invalid", arg_idx + 1);
9010 	}
9011       else if (!arg)
9012 	{
9013 	  /* This can occur if there was an error in the template
9014 	     parameter list itself (which we would already have
9015 	     reported) that we are trying to recover from, e.g., a class
9016 	     template with a parameter list such as
9017 	     template<typename..., typename> (cpp0x/variadic150.C).  */
9018 	  ++lost;
9019 
9020 	  /* This can also happen with a fixed parameter pack (71834).  */
9021 	  if (arg_idx >= nargs)
9022 	    ++missing;
9023 	}
9024       else
9025 	arg = convert_template_argument (TREE_VALUE (parm),
9026 					 arg, new_args, complain,
9027                                          parm_idx, in_decl);
9028 
9029       if (arg == error_mark_node)
9030 	lost++;
9031 
9032       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9033     }
9034 
9035   if (missing || arg_idx < nargs - variadic_args_p)
9036     {
9037       /* If we had fixed parameter packs, we didn't know how many arguments we
9038 	 actually needed earlier; now we do.  */
9039       nparms += fixed_pack_adjust;
9040       variadic_p -= fixed_packs;
9041       goto bad_nargs;
9042     }
9043 
9044   if (arg_idx < nargs)
9045     {
9046       /* We had some pack expansion arguments that will only work if the packs
9047 	 are empty, but wait until instantiation time to complain.
9048 	 See variadic-ttp3.C.  */
9049 
9050       /* Except that we can't provide empty packs to alias templates or
9051          concepts when there are no corresponding parameters. Basically,
9052          we can get here with this:
9053 
9054              template<typename T> concept C = true;
9055 
9056              template<typename... Args>
9057 	       requires C<Args...>
9058              void f();
9059 
9060          When parsing C<Args...>, we try to form a concept check of
9061          C<?, Args...>. Without the extra check for substituting an empty
9062          pack past the last parameter, we can accept the check as valid.
9063 
9064          FIXME: This may be valid for alias templates (but I doubt it).
9065 
9066          FIXME: The error could be better also.   */
9067       if (in_decl && concept_definition_p (in_decl))
9068 	{
9069 	  if (complain & tf_error)
9070 	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9071 		      "too many arguments");
9072 	  return error_mark_node;
9073 	}
9074 
9075       int len = nparms + (nargs - arg_idx);
9076       tree args = make_tree_vec (len);
9077       int i = 0;
9078       for (; i < nparms; ++i)
9079 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9080       for (; i < len; ++i, ++arg_idx)
9081 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9082 					       arg_idx - pack_adjust);
9083       new_inner_args = args;
9084     }
9085 
9086   if (lost)
9087     {
9088       gcc_assert (!(complain & tf_error) || seen_error ());
9089       return error_mark_node;
9090     }
9091 
9092   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9093     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9094 					 TREE_VEC_LENGTH (new_inner_args));
9095 
9096   return new_inner_args;
9097 }
9098 
9099 /* Convert all template arguments to their appropriate types, and
9100    return a vector containing the innermost resulting template
9101    arguments.  If any error occurs, return error_mark_node. Error and
9102    warning messages are not issued.
9103 
9104    Note that no function argument deduction is performed, and default
9105    arguments are used to fill in unspecified arguments. */
9106 tree
coerce_template_parms(tree parms,tree args,tree in_decl)9107 coerce_template_parms (tree parms, tree args, tree in_decl)
9108 {
9109   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9110 }
9111 
9112 /* Convert all template arguments to their appropriate type, and
9113    instantiate default arguments as needed. This returns a vector
9114    containing the innermost resulting template arguments, or
9115    error_mark_node if unsuccessful.  */
9116 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)9117 coerce_template_parms (tree parms, tree args, tree in_decl,
9118                        tsubst_flags_t complain)
9119 {
9120   return coerce_template_parms (parms, args, in_decl, complain, true, true);
9121 }
9122 
9123 /* Like coerce_template_parms.  If PARMS represents all template
9124    parameters levels, this function returns a vector of vectors
9125    representing all the resulting argument levels.  Note that in this
9126    case, only the innermost arguments are coerced because the
9127    outermost ones are supposed to have been coerced already.
9128 
9129    Otherwise, if PARMS represents only (the innermost) vector of
9130    parameters, this function returns a vector containing just the
9131    innermost resulting arguments.  */
9132 
9133 static tree
coerce_innermost_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)9134 coerce_innermost_template_parms (tree parms,
9135 				  tree args,
9136 				  tree in_decl,
9137 				  tsubst_flags_t complain,
9138 				  bool require_all_args,
9139 				  bool use_default_args)
9140 {
9141   int parms_depth = TMPL_PARMS_DEPTH (parms);
9142   int args_depth = TMPL_ARGS_DEPTH (args);
9143   tree coerced_args;
9144 
9145   if (parms_depth > 1)
9146     {
9147       coerced_args = make_tree_vec (parms_depth);
9148       tree level;
9149       int cur_depth;
9150 
9151       for (level = parms, cur_depth = parms_depth;
9152 	   parms_depth > 0 && level != NULL_TREE;
9153 	   level = TREE_CHAIN (level), --cur_depth)
9154 	{
9155 	  tree l;
9156 	  if (cur_depth == args_depth)
9157 	    l = coerce_template_parms (TREE_VALUE (level),
9158 				       args, in_decl, complain,
9159 				       require_all_args,
9160 				       use_default_args);
9161 	  else
9162 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
9163 
9164 	  if (l == error_mark_node)
9165 	    return error_mark_node;
9166 
9167 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9168 	}
9169     }
9170   else
9171     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9172 					  args, in_decl, complain,
9173 					  require_all_args,
9174 					  use_default_args);
9175   return coerced_args;
9176 }
9177 
9178 /* Returns true if T is a wrapper to make a C++20 template parameter
9179    object const.  */
9180 
9181 static bool
class_nttp_const_wrapper_p(tree t)9182 class_nttp_const_wrapper_p (tree t)
9183 {
9184   if (cxx_dialect < cxx20)
9185     return false;
9186   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9187 	  && CP_TYPE_CONST_P (TREE_TYPE (t))
9188 	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9189 }
9190 
9191 /* Returns 1 if template args OT and NT are equivalent.  */
9192 
9193 int
template_args_equal(tree ot,tree nt,bool partial_order)9194 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9195 {
9196   if (nt == ot)
9197     return 1;
9198   if (nt == NULL_TREE || ot == NULL_TREE)
9199     return false;
9200   if (nt == any_targ_node || ot == any_targ_node)
9201     return true;
9202 
9203   if (class_nttp_const_wrapper_p (nt))
9204     nt = TREE_OPERAND (nt, 0);
9205   if (class_nttp_const_wrapper_p (ot))
9206     ot = TREE_OPERAND (ot, 0);
9207 
9208   /* DR 1558: Don't treat an alias template specialization with dependent
9209      arguments as equivalent to its underlying type when used as a template
9210      argument; we need them to be distinct so that we substitute into the
9211      specialization arguments at instantiation time.  And aliases can't be
9212      equivalent without being ==, so we don't need to look any deeper.
9213 
9214      During partial ordering, however, we need to treat them normally so we can
9215      order uses of the same alias with different cv-qualification (79960).  */
9216   auto cso = make_temp_override (comparing_dependent_aliases);
9217   if (!partial_order)
9218     ++comparing_dependent_aliases;
9219 
9220   if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9221     /* For member templates */
9222     return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9223   else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9224     return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9225 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9226 				    PACK_EXPANSION_PATTERN (nt))
9227 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9228 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
9229   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9230     return cp_tree_equal (ot, nt);
9231   else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9232     gcc_unreachable ();
9233   else if (TYPE_P (nt) || TYPE_P (ot))
9234     {
9235       if (!(TYPE_P (nt) && TYPE_P (ot)))
9236 	return false;
9237       return same_type_p (ot, nt);
9238     }
9239   else
9240     {
9241       /* Try to treat a template non-type argument that has been converted
9242 	 to the parameter type as equivalent to one that hasn't yet.  */
9243       for (enum tree_code code1 = TREE_CODE (ot);
9244 	   CONVERT_EXPR_CODE_P (code1)
9245 	     || code1 == NON_LVALUE_EXPR;
9246 	   code1 = TREE_CODE (ot))
9247 	ot = TREE_OPERAND (ot, 0);
9248 
9249       for (enum tree_code code2 = TREE_CODE (nt);
9250 	   CONVERT_EXPR_CODE_P (code2)
9251 	     || code2 == NON_LVALUE_EXPR;
9252 	   code2 = TREE_CODE (nt))
9253 	nt = TREE_OPERAND (nt, 0);
9254 
9255       return cp_tree_equal (ot, nt);
9256     }
9257 }
9258 
9259 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9260    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9261    NEWARG_PTR with the offending arguments if they are non-NULL.  */
9262 
9263 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)9264 comp_template_args (tree oldargs, tree newargs,
9265 		    tree *oldarg_ptr, tree *newarg_ptr,
9266 		    bool partial_order)
9267 {
9268   int i;
9269 
9270   if (oldargs == newargs)
9271     return 1;
9272 
9273   if (!oldargs || !newargs)
9274     return 0;
9275 
9276   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9277     return 0;
9278 
9279   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9280     {
9281       tree nt = TREE_VEC_ELT (newargs, i);
9282       tree ot = TREE_VEC_ELT (oldargs, i);
9283 
9284       if (! template_args_equal (ot, nt, partial_order))
9285 	{
9286 	  if (oldarg_ptr != NULL)
9287 	    *oldarg_ptr = ot;
9288 	  if (newarg_ptr != NULL)
9289 	    *newarg_ptr = nt;
9290 	  return 0;
9291 	}
9292     }
9293   return 1;
9294 }
9295 
9296 inline bool
comp_template_args_porder(tree oargs,tree nargs)9297 comp_template_args_porder (tree oargs, tree nargs)
9298 {
9299   return comp_template_args (oargs, nargs, NULL, NULL, true);
9300 }
9301 
9302 /* Implement a freelist interface for objects of type T.
9303 
9304    Head is a separate object, rather than a regular member, so that we
9305    can define it as a GTY deletable pointer, which is highly
9306    desirable.  A data member could be declared that way, but then the
9307    containing object would implicitly get GTY((user)), which would
9308    prevent us from instantiating freelists as global objects.
9309    Although this way we can create freelist global objects, they're
9310    such thin wrappers that instantiating temporaries at every use
9311    loses nothing and saves permanent storage for the freelist object.
9312 
9313    Member functions next, anew, poison and reinit have default
9314    implementations that work for most of the types we're interested
9315    in, but if they don't work for some type, they should be explicitly
9316    specialized.  See the comments before them for requirements, and
9317    the example specializations for the tree_list_freelist.  */
9318 template <typename T>
9319 class freelist
9320 {
9321   /* Return the next object in a chain.  We could just do type
9322      punning, but if we access the object with its underlying type, we
9323      avoid strict-aliasing trouble.  This needs only work between
9324      poison and reinit.  */
next(T * obj)9325   static T *&next (T *obj) { return obj->next; }
9326 
9327   /* Return a newly allocated, uninitialized or minimally-initialized
9328      object of type T.  Any initialization performed by anew should
9329      either remain across the life of the object and the execution of
9330      poison, or be redone by reinit.  */
anew()9331   static T *anew () { return ggc_alloc<T> (); }
9332 
9333   /* Optionally scribble all over the bits holding the object, so that
9334      they become (mostly?) uninitialized memory.  This is called while
9335      preparing to make the object part of the free list.  */
poison(T * obj)9336   static void poison (T *obj) {
9337     T *p ATTRIBUTE_UNUSED = obj;
9338     T **q ATTRIBUTE_UNUSED = &next (obj);
9339 
9340 #ifdef ENABLE_GC_CHECKING
9341     /* Poison the data, to indicate the data is garbage.  */
9342     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9343     memset (p, 0xa5, sizeof (*p));
9344 #endif
9345     /* Let valgrind know the object is free.  */
9346     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9347 
9348     /* Let valgrind know the next portion of the object is available,
9349        but uninitialized.  */
9350     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9351   }
9352 
9353   /* Bring an object that underwent at least one lifecycle after anew
9354      and before the most recent free and poison, back to a usable
9355      state, reinitializing whatever is needed for it to be
9356      functionally equivalent to an object just allocated and returned
9357      by anew.  This may poison or clear the next field, used by
9358      freelist housekeeping after poison was called.  */
reinit(T * obj)9359   static void reinit (T *obj) {
9360     T **q ATTRIBUTE_UNUSED = &next (obj);
9361 
9362 #ifdef ENABLE_GC_CHECKING
9363     memset (q, 0xa5, sizeof (*q));
9364 #endif
9365     /* Let valgrind know the entire object is available, but
9366        uninitialized.  */
9367     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9368   }
9369 
9370   /* Reference a GTY-deletable pointer that points to the first object
9371      in the free list proper.  */
9372   T *&head;
9373 public:
9374   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)9375   freelist (T *&head) : head(head) {}
9376 
9377   /* Add OBJ to the free object list.  The former head becomes OBJ's
9378      successor.  */
free(T * obj)9379   void free (T *obj)
9380   {
9381     poison (obj);
9382     next (obj) = head;
9383     head = obj;
9384   }
9385 
9386   /* Take an object from the free list, if one is available, or
9387      allocate a new one.  Objects taken from the free list should be
9388      regarded as filled with garbage, except for bits that are
9389      configured to be preserved across free and alloc.  */
alloc()9390   T *alloc ()
9391   {
9392     if (head)
9393       {
9394 	T *obj = head;
9395 	head = next (head);
9396 	reinit (obj);
9397 	return obj;
9398       }
9399     else
9400       return anew ();
9401   }
9402 };
9403 
9404 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9405    want to allocate a TREE_LIST using the usual interface, and ensure
9406    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9407    build_tree_list logic in reinit, so this could go out of sync.  */
9408 template <>
9409 inline tree &
next(tree obj)9410 freelist<tree_node>::next (tree obj)
9411 {
9412   return TREE_CHAIN (obj);
9413 }
9414 template <>
9415 inline tree
anew()9416 freelist<tree_node>::anew ()
9417 {
9418   return build_tree_list (NULL, NULL);
9419 }
9420 template <>
9421 inline void
poison(tree obj ATTRIBUTE_UNUSED)9422 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9423 {
9424   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9425   tree p ATTRIBUTE_UNUSED = obj;
9426   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9427   tree *q ATTRIBUTE_UNUSED = &next (obj);
9428 
9429 #ifdef ENABLE_GC_CHECKING
9430   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9431 
9432   /* Poison the data, to indicate the data is garbage.  */
9433   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9434   memset (p, 0xa5, size);
9435 #endif
9436   /* Let valgrind know the object is free.  */
9437   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9438   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9439   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9440   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9441 
9442 #ifdef ENABLE_GC_CHECKING
9443   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9444   /* Keep TREE_CHAIN functional.  */
9445   TREE_SET_CODE (obj, TREE_LIST);
9446 #else
9447   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9448 #endif
9449 }
9450 template <>
9451 inline void
reinit(tree obj ATTRIBUTE_UNUSED)9452 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9453 {
9454   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9455 
9456 #ifdef ENABLE_GC_CHECKING
9457   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9458   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9459   memset (obj, 0, sizeof (tree_list));
9460 #endif
9461 
9462   /* Let valgrind know the entire object is available, but
9463      uninitialized.  */
9464   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9465 
9466 #ifdef ENABLE_GC_CHECKING
9467   TREE_SET_CODE (obj, TREE_LIST);
9468 #else
9469   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9470 #endif
9471 }
9472 
9473 /* Point to the first object in the TREE_LIST freelist.  */
9474 static GTY((deletable)) tree tree_list_freelist_head;
9475 /* Return the/an actual TREE_LIST freelist.  */
9476 static inline freelist<tree_node>
tree_list_freelist()9477 tree_list_freelist ()
9478 {
9479   return tree_list_freelist_head;
9480 }
9481 
9482 /* Point to the first object in the tinst_level freelist.  */
9483 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9484 /* Return the/an actual tinst_level freelist.  */
9485 static inline freelist<tinst_level>
tinst_level_freelist()9486 tinst_level_freelist ()
9487 {
9488   return tinst_level_freelist_head;
9489 }
9490 
9491 /* Point to the first object in the pending_template freelist.  */
9492 static GTY((deletable)) pending_template *pending_template_freelist_head;
9493 /* Return the/an actual pending_template freelist.  */
9494 static inline freelist<pending_template>
pending_template_freelist()9495 pending_template_freelist ()
9496 {
9497   return pending_template_freelist_head;
9498 }
9499 
9500 /* Build the TREE_LIST object out of a split list, store it
9501    permanently, and return it.  */
9502 tree
to_list()9503 tinst_level::to_list ()
9504 {
9505   gcc_assert (split_list_p ());
9506   tree ret = tree_list_freelist ().alloc ();
9507   TREE_PURPOSE (ret) = tldcl;
9508   TREE_VALUE (ret) = targs;
9509   tldcl = ret;
9510   targs = NULL;
9511   gcc_assert (tree_list_p ());
9512   return ret;
9513 }
9514 
9515 const unsigned short tinst_level::refcount_infinity;
9516 
9517 /* Increment OBJ's refcount unless it is already infinite.  */
9518 static tinst_level *
inc_refcount_use(tinst_level * obj)9519 inc_refcount_use (tinst_level *obj)
9520 {
9521   if (obj && obj->refcount != tinst_level::refcount_infinity)
9522     ++obj->refcount;
9523   return obj;
9524 }
9525 
9526 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9527 void
free(tinst_level * obj)9528 tinst_level::free (tinst_level *obj)
9529 {
9530   if (obj->tree_list_p ())
9531     tree_list_freelist ().free (obj->get_node ());
9532   tinst_level_freelist ().free (obj);
9533 }
9534 
9535 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9536    OBJ's DECL and OBJ, and start over with the tinst_level object that
9537    used to be referenced by OBJ's NEXT.  */
9538 static void
dec_refcount_use(tinst_level * obj)9539 dec_refcount_use (tinst_level *obj)
9540 {
9541   while (obj
9542 	 && obj->refcount != tinst_level::refcount_infinity
9543 	 && !--obj->refcount)
9544     {
9545       tinst_level *next = obj->next;
9546       tinst_level::free (obj);
9547       obj = next;
9548     }
9549 }
9550 
9551 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9552    and of the former PTR.  Omitting the second argument is equivalent
9553    to passing (T*)NULL; this is allowed because passing the
9554    zero-valued integral constant NULL confuses type deduction and/or
9555    overload resolution.  */
9556 template <typename T>
9557 static void
9558 set_refcount_ptr (T *& ptr, T *obj = NULL)
9559 {
9560   T *save = ptr;
9561   ptr = inc_refcount_use (obj);
9562   dec_refcount_use (save);
9563 }
9564 
9565 static void
add_pending_template(tree d)9566 add_pending_template (tree d)
9567 {
9568   tree ti = (TYPE_P (d)
9569 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9570 	     : DECL_TEMPLATE_INFO (d));
9571   struct pending_template *pt;
9572   int level;
9573 
9574   if (TI_PENDING_TEMPLATE_FLAG (ti))
9575     return;
9576 
9577   /* We are called both from instantiate_decl, where we've already had a
9578      tinst_level pushed, and instantiate_template, where we haven't.
9579      Compensate.  */
9580   gcc_assert (TREE_CODE (d) != TREE_LIST);
9581   level = !current_tinst_level
9582     || current_tinst_level->maybe_get_node () != d;
9583 
9584   if (level)
9585     push_tinst_level (d);
9586 
9587   pt = pending_template_freelist ().alloc ();
9588   pt->next = NULL;
9589   pt->tinst = NULL;
9590   set_refcount_ptr (pt->tinst, current_tinst_level);
9591   if (last_pending_template)
9592     last_pending_template->next = pt;
9593   else
9594     pending_templates = pt;
9595 
9596   last_pending_template = pt;
9597 
9598   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9599 
9600   if (level)
9601     pop_tinst_level ();
9602 }
9603 
9604 
9605 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9606    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9607    documentation for TEMPLATE_ID_EXPR.  */
9608 
9609 tree
lookup_template_function(tree fns,tree arglist)9610 lookup_template_function (tree fns, tree arglist)
9611 {
9612   if (fns == error_mark_node || arglist == error_mark_node)
9613     return error_mark_node;
9614 
9615   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9616 
9617   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9618     {
9619       error ("%q#D is not a function template", fns);
9620       return error_mark_node;
9621     }
9622 
9623   if (BASELINK_P (fns))
9624     {
9625       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9626 					 unknown_type_node,
9627 					 BASELINK_FUNCTIONS (fns),
9628 					 arglist);
9629       return fns;
9630     }
9631 
9632   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9633 }
9634 
9635 /* Within the scope of a template class S<T>, the name S gets bound
9636    (in build_self_reference) to a TYPE_DECL for the class, not a
9637    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9638    or one of its enclosing classes, and that type is a template,
9639    return the associated TEMPLATE_DECL.  Otherwise, the original
9640    DECL is returned.
9641 
9642    Also handle the case when DECL is a TREE_LIST of ambiguous
9643    injected-class-names from different bases.  */
9644 
9645 tree
maybe_get_template_decl_from_type_decl(tree decl)9646 maybe_get_template_decl_from_type_decl (tree decl)
9647 {
9648   if (decl == NULL_TREE)
9649     return decl;
9650 
9651   /* DR 176: A lookup that finds an injected-class-name (10.2
9652      [class.member.lookup]) can result in an ambiguity in certain cases
9653      (for example, if it is found in more than one base class). If all of
9654      the injected-class-names that are found refer to specializations of
9655      the same class template, and if the name is followed by a
9656      template-argument-list, the reference refers to the class template
9657      itself and not a specialization thereof, and is not ambiguous.  */
9658   if (TREE_CODE (decl) == TREE_LIST)
9659     {
9660       tree t, tmpl = NULL_TREE;
9661       for (t = decl; t; t = TREE_CHAIN (t))
9662 	{
9663 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9664 	  if (!tmpl)
9665 	    tmpl = elt;
9666 	  else if (tmpl != elt)
9667 	    break;
9668 	}
9669       if (tmpl && t == NULL_TREE)
9670 	return tmpl;
9671       else
9672 	return decl;
9673     }
9674 
9675   return (decl != NULL_TREE
9676 	  && DECL_SELF_REFERENCE_P (decl)
9677 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9678     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9679 }
9680 
9681 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9682    parameters, find the desired type.
9683 
9684    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9685 
9686    IN_DECL, if non-NULL, is the template declaration we are trying to
9687    instantiate.
9688 
9689    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9690    the class we are looking up.
9691 
9692    Issue error and warning messages under control of COMPLAIN.
9693 
9694    If the template class is really a local class in a template
9695    function, then the FUNCTION_CONTEXT is the function in which it is
9696    being instantiated.
9697 
9698    ??? Note that this function is currently called *twice* for each
9699    template-id: the first time from the parser, while creating the
9700    incomplete type (finish_template_type), and the second type during the
9701    real instantiation (instantiate_template_class). This is surely something
9702    that we want to avoid. It also causes some problems with argument
9703    coercion (see convert_nontype_argument for more information on this).  */
9704 
9705 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9706 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9707 			 int entering_scope, tsubst_flags_t complain)
9708 {
9709   tree templ = NULL_TREE, parmlist;
9710   tree t;
9711   spec_entry **slot;
9712   spec_entry *entry;
9713   spec_entry elt;
9714   hashval_t hash;
9715 
9716   if (identifier_p (d1))
9717     {
9718       tree value = innermost_non_namespace_value (d1);
9719       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9720 	templ = value;
9721       else
9722 	{
9723 	  if (context)
9724 	    push_decl_namespace (context);
9725 	  templ = lookup_name (d1);
9726 	  templ = maybe_get_template_decl_from_type_decl (templ);
9727 	  if (context)
9728 	    pop_decl_namespace ();
9729 	}
9730       if (templ)
9731 	context = DECL_CONTEXT (templ);
9732     }
9733   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9734     {
9735       tree type = TREE_TYPE (d1);
9736 
9737       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9738 	 an implicit typename for the second A.  Deal with it.  */
9739       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9740 	type = TREE_TYPE (type);
9741 
9742       if (CLASSTYPE_TEMPLATE_INFO (type))
9743 	{
9744 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9745 	  d1 = DECL_NAME (templ);
9746 	}
9747     }
9748   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9749 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9750     {
9751       templ = TYPE_TI_TEMPLATE (d1);
9752       d1 = DECL_NAME (templ);
9753     }
9754   else if (DECL_TYPE_TEMPLATE_P (d1))
9755     {
9756       templ = d1;
9757       d1 = DECL_NAME (templ);
9758       context = DECL_CONTEXT (templ);
9759     }
9760   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9761     {
9762       templ = d1;
9763       d1 = DECL_NAME (templ);
9764     }
9765 
9766   /* Issue an error message if we didn't find a template.  */
9767   if (! templ)
9768     {
9769       if (complain & tf_error)
9770 	error ("%qT is not a template", d1);
9771       return error_mark_node;
9772     }
9773 
9774   if (TREE_CODE (templ) != TEMPLATE_DECL
9775 	 /* Make sure it's a user visible template, if it was named by
9776 	    the user.  */
9777       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9778 	  && !PRIMARY_TEMPLATE_P (templ)))
9779     {
9780       if (complain & tf_error)
9781 	{
9782 	  error ("non-template type %qT used as a template", d1);
9783 	  if (in_decl)
9784 	    error ("for template declaration %q+D", in_decl);
9785 	}
9786       return error_mark_node;
9787     }
9788 
9789   complain &= ~tf_user;
9790 
9791   /* An alias that just changes the name of a template is equivalent to the
9792      other template, so if any of the arguments are pack expansions, strip
9793      the alias to avoid problems with a pack expansion passed to a non-pack
9794      alias template parameter (DR 1430).  */
9795   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9796     templ = get_underlying_template (templ);
9797 
9798   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9799     {
9800       tree parm;
9801       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9802       if (arglist2 == error_mark_node
9803 	  || (!uses_template_parms (arglist2)
9804 	      && check_instantiated_args (templ, arglist2, complain)))
9805 	return error_mark_node;
9806 
9807       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9808       return parm;
9809     }
9810   else
9811     {
9812       tree template_type = TREE_TYPE (templ);
9813       tree gen_tmpl;
9814       tree type_decl;
9815       tree found = NULL_TREE;
9816       int arg_depth;
9817       int parm_depth;
9818       int is_dependent_type;
9819       int use_partial_inst_tmpl = false;
9820 
9821       if (template_type == error_mark_node)
9822 	/* An error occurred while building the template TEMPL, and a
9823 	   diagnostic has most certainly been emitted for that
9824 	   already.  Let's propagate that error.  */
9825 	return error_mark_node;
9826 
9827       gen_tmpl = most_general_template (templ);
9828       if (modules_p ())
9829 	lazy_load_pendings (gen_tmpl);
9830 
9831       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9832       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9833       arg_depth = TMPL_ARGS_DEPTH (arglist);
9834 
9835       if (arg_depth == 1 && parm_depth > 1)
9836 	{
9837 	  /* We've been given an incomplete set of template arguments.
9838 	     For example, given:
9839 
9840 	       template <class T> struct S1 {
9841 		 template <class U> struct S2 {};
9842 		 template <class U> struct S2<U*> {};
9843 		};
9844 
9845 	     we will be called with an ARGLIST of `U*', but the
9846 	     TEMPLATE will be `template <class T> template
9847 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9848 	     arguments.  */
9849 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9850 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9851 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9852 	}
9853 
9854       /* Now we should have enough arguments.  */
9855       gcc_assert (parm_depth == arg_depth);
9856 
9857       /* From here on, we're only interested in the most general
9858 	 template.  */
9859 
9860       /* Calculate the BOUND_ARGS.  These will be the args that are
9861 	 actually tsubst'd into the definition to create the
9862 	 instantiation.  */
9863       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9864 						 complain,
9865 						 /*require_all_args=*/true,
9866 						 /*use_default_args=*/true);
9867 
9868       if (arglist == error_mark_node)
9869 	/* We were unable to bind the arguments.  */
9870 	return error_mark_node;
9871 
9872       /* In the scope of a template class, explicit references to the
9873 	 template class refer to the type of the template, not any
9874 	 instantiation of it.  For example, in:
9875 
9876 	   template <class T> class C { void f(C<T>); }
9877 
9878 	 the `C<T>' is just the same as `C'.  Outside of the
9879 	 class, however, such a reference is an instantiation.  */
9880       if (entering_scope
9881 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9882 	  || currently_open_class (template_type))
9883 	{
9884 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9885 
9886 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9887 	    return template_type;
9888 	}
9889 
9890       /* If we already have this specialization, return it.  */
9891       elt.tmpl = gen_tmpl;
9892       elt.args = arglist;
9893       elt.spec = NULL_TREE;
9894       hash = spec_hasher::hash (&elt);
9895       entry = type_specializations->find_with_hash (&elt, hash);
9896 
9897       if (entry)
9898 	return entry->spec;
9899 
9900       /* If the template's constraints are not satisfied,
9901          then we cannot form a valid type.
9902 
9903          Note that the check is deferred until after the hash
9904          lookup. This prevents redundant checks on previously
9905          instantiated specializations. */
9906       if (flag_concepts
9907 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9908 	  && !constraints_satisfied_p (gen_tmpl, arglist))
9909         {
9910           if (complain & tf_error)
9911             {
9912 	      auto_diagnostic_group d;
9913               error ("template constraint failure for %qD", gen_tmpl);
9914               diagnose_constraints (input_location, gen_tmpl, arglist);
9915             }
9916           return error_mark_node;
9917         }
9918 
9919       is_dependent_type = uses_template_parms (arglist);
9920 
9921       /* If the deduced arguments are invalid, then the binding
9922 	 failed.  */
9923       if (!is_dependent_type
9924 	  && check_instantiated_args (gen_tmpl,
9925 				      INNERMOST_TEMPLATE_ARGS (arglist),
9926 				      complain))
9927 	return error_mark_node;
9928 
9929       if (!is_dependent_type
9930 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9931 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9932 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9933 	/* This occurs when the user has tried to define a tagged type
9934 	   in a scope that forbids it.  We emitted an error during the
9935 	   parse.  We didn't complete the bail out then, so here we
9936 	   are.  */
9937 	return error_mark_node;
9938 
9939       context = DECL_CONTEXT (gen_tmpl);
9940       if (context && TYPE_P (context))
9941 	{
9942 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9943 	  context = complete_type (context);
9944 	}
9945       else
9946 	context = tsubst (context, arglist, complain, in_decl);
9947 
9948       if (context == error_mark_node)
9949 	return error_mark_node;
9950 
9951       if (!context)
9952 	context = global_namespace;
9953 
9954       /* Create the type.  */
9955       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9956 	{
9957 	  /* The user referred to a specialization of an alias
9958 	    template represented by GEN_TMPL.
9959 
9960 	    [temp.alias]/2 says:
9961 
9962 	        When a template-id refers to the specialization of an
9963 		alias template, it is equivalent to the associated
9964 		type obtained by substitution of its
9965 		template-arguments for the template-parameters in the
9966 		type-id of the alias template.  */
9967 
9968 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9969 	  /* Note that the call above (by indirectly calling
9970 	     register_specialization in tsubst_decl) registers the
9971 	     TYPE_DECL representing the specialization of the alias
9972 	     template.  So next time someone substitutes ARGLIST for
9973 	     the template parms into the alias template (GEN_TMPL),
9974 	     she'll get that TYPE_DECL back.  */
9975 
9976 	  if (t == error_mark_node)
9977 	    return t;
9978 	}
9979       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9980 	{
9981 	  if (!is_dependent_type)
9982 	    {
9983 	      set_current_access_from_decl (TYPE_NAME (template_type));
9984 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9985 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9986 				      arglist, complain, in_decl),
9987 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9988 						 arglist, complain, in_decl),
9989 			      SCOPED_ENUM_P (template_type), NULL);
9990 
9991 	      if (t == error_mark_node)
9992 		return t;
9993 	    }
9994 	  else
9995             {
9996               /* We don't want to call start_enum for this type, since
9997                  the values for the enumeration constants may involve
9998                  template parameters.  And, no one should be interested
9999                  in the enumeration constants for such a type.  */
10000               t = cxx_make_type (ENUMERAL_TYPE);
10001               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10002             }
10003           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10004 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
10005 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10006 	}
10007       else if (CLASS_TYPE_P (template_type))
10008 	{
10009 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
10010 	     instantiated here.  */
10011 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
10012 
10013 	  t = make_class_type (TREE_CODE (template_type));
10014 	  CLASSTYPE_DECLARED_CLASS (t)
10015 	    = CLASSTYPE_DECLARED_CLASS (template_type);
10016 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10017 
10018 	  /* A local class.  Make sure the decl gets registered properly.  */
10019 	  if (context == current_function_decl)
10020 	    if (pushtag (DECL_NAME (gen_tmpl), t)
10021 		== error_mark_node)
10022 	      return error_mark_node;
10023 
10024 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10025 	    /* This instantiation is another name for the primary
10026 	       template type. Set the TYPE_CANONICAL field
10027 	       appropriately. */
10028 	    TYPE_CANONICAL (t) = template_type;
10029 	  else if (any_template_arguments_need_structural_equality_p (arglist))
10030 	    /* Some of the template arguments require structural
10031 	       equality testing, so this template class requires
10032 	       structural equality testing. */
10033 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
10034 	}
10035       else
10036 	gcc_unreachable ();
10037 
10038       /* If we called start_enum or pushtag above, this information
10039 	 will already be set up.  */
10040       type_decl = TYPE_NAME (t);
10041       if (!type_decl)
10042 	{
10043 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10044 
10045 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10046 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10047 	  DECL_SOURCE_LOCATION (type_decl)
10048 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10049 	}
10050 
10051       set_instantiating_module (type_decl);
10052       /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10053 	 of export flag.  We want to propagate this because it might
10054 	 be a friend declaration that pushes a new hidden binding.  */
10055       DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10056 
10057       if (CLASS_TYPE_P (template_type))
10058 	{
10059 	  TREE_PRIVATE (type_decl)
10060 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10061 	  TREE_PROTECTED (type_decl)
10062 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10063 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10064 	    {
10065 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10066 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10067 	    }
10068 	}
10069 
10070       if (OVERLOAD_TYPE_P (t)
10071 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10072 	{
10073 	  static const char *tags[] = {"abi_tag", "may_alias"};
10074 
10075 	  for (unsigned ix = 0; ix != 2; ix++)
10076 	    {
10077 	      tree attributes
10078 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10079 
10080 	      if (attributes)
10081 		TYPE_ATTRIBUTES (t)
10082 		  = tree_cons (TREE_PURPOSE (attributes),
10083 			       TREE_VALUE (attributes),
10084 			       TYPE_ATTRIBUTES (t));
10085 	    }
10086 	}
10087 
10088       /* Let's consider the explicit specialization of a member
10089          of a class template specialization that is implicitly instantiated,
10090 	 e.g.:
10091 	     template<class T>
10092 	     struct S
10093 	     {
10094 	       template<class U> struct M {}; //#0
10095 	     };
10096 
10097 	     template<>
10098 	     template<>
10099 	     struct S<int>::M<char> //#1
10100 	     {
10101 	       int i;
10102 	     };
10103 	[temp.expl.spec]/4 says this is valid.
10104 
10105 	In this case, when we write:
10106 	S<int>::M<char> m;
10107 
10108 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10109 	the one of #0.
10110 
10111 	When we encounter #1, we want to store the partial instantiation
10112 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10113 
10114 	For all cases other than this "explicit specialization of member of a
10115 	class template", we just want to store the most general template into
10116 	the CLASSTYPE_TI_TEMPLATE of M.
10117 
10118 	This case of "explicit specialization of member of a class template"
10119 	only happens when:
10120 	1/ the enclosing class is an instantiation of, and therefore not
10121 	the same as, the context of the most general template, and
10122 	2/ we aren't looking at the partial instantiation itself, i.e.
10123 	the innermost arguments are not the same as the innermost parms of
10124 	the most general template.
10125 
10126 	So it's only when 1/ and 2/ happens that we want to use the partial
10127 	instantiation of the member template in lieu of its most general
10128 	template.  */
10129 
10130       if (PRIMARY_TEMPLATE_P (gen_tmpl)
10131 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10132 	  /* the enclosing class must be an instantiation...  */
10133 	  && CLASS_TYPE_P (context)
10134 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10135 	{
10136 	  TREE_VEC_LENGTH (arglist)--;
10137 	  ++processing_template_decl;
10138 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10139 	  tree partial_inst_args =
10140 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10141 		    arglist, complain, NULL_TREE);
10142 	  --processing_template_decl;
10143 	  TREE_VEC_LENGTH (arglist)++;
10144 	  if (partial_inst_args == error_mark_node)
10145 	    return error_mark_node;
10146 	  use_partial_inst_tmpl =
10147 	    /*...and we must not be looking at the partial instantiation
10148 	     itself. */
10149 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10150 				 partial_inst_args);
10151 	}
10152 
10153       if (!use_partial_inst_tmpl)
10154 	/* This case is easy; there are no member templates involved.  */
10155 	found = gen_tmpl;
10156       else
10157 	{
10158 	  /* This is a full instantiation of a member template.  Find
10159 	     the partial instantiation of which this is an instance.  */
10160 
10161 	  /* Temporarily reduce by one the number of levels in the ARGLIST
10162 	     so as to avoid comparing the last set of arguments.  */
10163 	  TREE_VEC_LENGTH (arglist)--;
10164 	  /* We don't use COMPLAIN in the following call because this isn't
10165 	     the immediate context of deduction.  For instance, tf_partial
10166 	     could be set here as we might be at the beginning of template
10167 	     argument deduction when any explicitly specified template
10168 	     arguments are substituted into the function type.  tf_partial
10169 	     could lead into trouble because we wouldn't find the partial
10170 	     instantiation that might have been created outside tf_partial
10171 	     context, because the levels of template parameters wouldn't
10172 	     match, because in a tf_partial context, tsubst doesn't reduce
10173 	     TEMPLATE_PARM_LEVEL.  */
10174 	  found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10175 	  TREE_VEC_LENGTH (arglist)++;
10176 	  /* FOUND is either a proper class type, or an alias
10177 	     template specialization.  In the later case, it's a
10178 	     TYPE_DECL, resulting from the substituting of arguments
10179 	     for parameters in the TYPE_DECL of the alias template
10180 	     done earlier.  So be careful while getting the template
10181 	     of FOUND.  */
10182 	  found = (TREE_CODE (found) == TEMPLATE_DECL
10183 		   ? found
10184 		   : (TREE_CODE (found) == TYPE_DECL
10185 		      ? DECL_TI_TEMPLATE (found)
10186 		      : CLASSTYPE_TI_TEMPLATE (found)));
10187 
10188 	  if (DECL_CLASS_TEMPLATE_P (found)
10189 	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10190 	    {
10191 	      /* If this partial instantiation is specialized, we want to
10192 		 use it for hash table lookup.  */
10193 	      elt.tmpl = found;
10194 	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10195 	      hash = spec_hasher::hash (&elt);
10196 	    }
10197 	}
10198 
10199       /* Build template info for the new specialization.  */
10200       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10201 
10202       elt.spec = t;
10203       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10204       gcc_checking_assert (*slot == NULL);
10205       entry = ggc_alloc<spec_entry> ();
10206       *entry = elt;
10207       *slot = entry;
10208 
10209       /* Note this use of the partial instantiation so we can check it
10210 	 later in maybe_process_partial_specialization.  */
10211       DECL_TEMPLATE_INSTANTIATIONS (found)
10212 	= tree_cons (arglist, t,
10213 		     DECL_TEMPLATE_INSTANTIATIONS (found));
10214 
10215       if (TREE_CODE (template_type) == ENUMERAL_TYPE
10216 	  && !uses_template_parms (current_nonlambda_scope ())
10217 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10218 	/* Now that the type has been registered on the instantiations
10219 	   list, we set up the enumerators.  Because the enumeration
10220 	   constants may involve the enumeration type itself, we make
10221 	   sure to register the type first, and then create the
10222 	   constants.  That way, doing tsubst_expr for the enumeration
10223 	   constants won't result in recursive calls here; we'll find
10224 	   the instantiation and exit above.  */
10225 	tsubst_enum (template_type, t, arglist);
10226 
10227       if (CLASS_TYPE_P (template_type) && is_dependent_type)
10228 	/* If the type makes use of template parameters, the
10229 	   code that generates debugging information will crash.  */
10230 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10231 
10232       /* Possibly limit visibility based on template args.  */
10233       TREE_PUBLIC (type_decl) = 1;
10234       determine_visibility (type_decl);
10235 
10236       inherit_targ_abi_tags (t);
10237 
10238       return t;
10239     }
10240 }
10241 
10242 /* Wrapper for lookup_template_class_1.  */
10243 
10244 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)10245 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10246                        int entering_scope, tsubst_flags_t complain)
10247 {
10248   tree ret;
10249   timevar_push (TV_TEMPLATE_INST);
10250   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10251                                  entering_scope, complain);
10252   timevar_pop (TV_TEMPLATE_INST);
10253   return ret;
10254 }
10255 
10256 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10257 
10258 tree
lookup_template_variable(tree templ,tree arglist)10259 lookup_template_variable (tree templ, tree arglist)
10260 {
10261   if (flag_concepts && variable_concept_p (templ))
10262     return build_concept_check (templ, arglist, tf_none);
10263 
10264   /* The type of the expression is NULL_TREE since the template-id could refer
10265      to an explicit or partial specialization. */
10266   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10267 }
10268 
10269 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10270 
10271 tree
finish_template_variable(tree var,tsubst_flags_t complain)10272 finish_template_variable (tree var, tsubst_flags_t complain)
10273 {
10274   tree templ = TREE_OPERAND (var, 0);
10275   tree arglist = TREE_OPERAND (var, 1);
10276 
10277   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
10278   arglist = add_outermost_template_args (tmpl_args, arglist);
10279 
10280   templ = most_general_template (templ);
10281   tree parms = DECL_TEMPLATE_PARMS (templ);
10282   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10283 					     /*req_all*/true,
10284 					     /*use_default*/true);
10285   if (arglist == error_mark_node)
10286     return error_mark_node;
10287 
10288   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10289     {
10290       if (complain & tf_error)
10291 	{
10292 	  auto_diagnostic_group d;
10293 	  error ("use of invalid variable template %qE", var);
10294 	  diagnose_constraints (location_of (var), templ, arglist);
10295 	}
10296       return error_mark_node;
10297     }
10298 
10299   return instantiate_template (templ, arglist, complain);
10300 }
10301 
10302 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10303    TARGS template args, and instantiate it if it's not dependent.  */
10304 
10305 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)10306 lookup_and_finish_template_variable (tree templ, tree targs,
10307 				     tsubst_flags_t complain)
10308 {
10309   templ = lookup_template_variable (templ, targs);
10310   if (!any_dependent_template_arguments_p (targs))
10311     {
10312       templ = finish_template_variable (templ, complain);
10313       mark_used (templ);
10314     }
10315 
10316   return convert_from_reference (templ);
10317 }
10318 
10319 /* If the set of template parameters PARMS contains a template parameter
10320    at the given LEVEL and INDEX, then return this parameter.  Otherwise
10321    return NULL_TREE.  */
10322 
10323 static tree
corresponding_template_parameter(tree parms,int level,int index)10324 corresponding_template_parameter (tree parms, int level, int index)
10325 {
10326   while (TMPL_PARMS_DEPTH (parms) > level)
10327     parms = TREE_CHAIN (parms);
10328 
10329   if (TMPL_PARMS_DEPTH (parms) != level
10330       || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10331     return NULL_TREE;
10332 
10333   tree t = TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), index));
10334   /* As in template_parm_to_arg.  */
10335   if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10336     t = TREE_TYPE (t);
10337   else
10338     t = DECL_INITIAL (t);
10339 
10340   gcc_assert (TEMPLATE_PARM_P (t));
10341   return t;
10342 }
10343 
10344 /* Return the template parameter from PARMS that positionally corresponds
10345    to the template parameter PARM, or else return NULL_TREE.  */
10346 
10347 static tree
corresponding_template_parameter(tree parms,tree parm)10348 corresponding_template_parameter (tree parms, tree parm)
10349 {
10350   int level, index;
10351   template_parm_level_and_index (parm, &level, &index);
10352   return corresponding_template_parameter (parms, level, index);
10353 }
10354 
10355 
10356 struct pair_fn_data
10357 {
10358   tree_fn_t fn;
10359   tree_fn_t any_fn;
10360   void *data;
10361   /* True when we should also visit template parameters that occur in
10362      non-deduced contexts.  */
10363   bool include_nondeduced_p;
10364   hash_set<tree> *visited;
10365 };
10366 
10367 /* Called from for_each_template_parm via walk_tree.  */
10368 
10369 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)10370 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10371 {
10372   tree t = *tp;
10373   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10374   tree_fn_t fn = pfd->fn;
10375   void *data = pfd->data;
10376   tree result = NULL_TREE;
10377 
10378 #define WALK_SUBTREE(NODE)						\
10379   do									\
10380     {									\
10381       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
10382 				       pfd->include_nondeduced_p,	\
10383 				       pfd->any_fn);			\
10384       if (result) goto out;						\
10385     }									\
10386   while (0)
10387 
10388   if (pfd->any_fn && (*pfd->any_fn)(t, data))
10389     return t;
10390 
10391   if (TYPE_P (t)
10392       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10393     WALK_SUBTREE (TYPE_CONTEXT (t));
10394 
10395   switch (TREE_CODE (t))
10396     {
10397     case RECORD_TYPE:
10398       if (TYPE_PTRMEMFUNC_P (t))
10399 	break;
10400       /* Fall through.  */
10401 
10402     case UNION_TYPE:
10403     case ENUMERAL_TYPE:
10404       if (!TYPE_TEMPLATE_INFO (t))
10405 	*walk_subtrees = 0;
10406       else
10407 	WALK_SUBTREE (TYPE_TI_ARGS (t));
10408       break;
10409 
10410     case INTEGER_TYPE:
10411       WALK_SUBTREE (TYPE_MIN_VALUE (t));
10412       WALK_SUBTREE (TYPE_MAX_VALUE (t));
10413       break;
10414 
10415     case METHOD_TYPE:
10416       /* Since we're not going to walk subtrees, we have to do this
10417 	 explicitly here.  */
10418       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10419       /* Fall through.  */
10420 
10421     case FUNCTION_TYPE:
10422       /* Check the return type.  */
10423       WALK_SUBTREE (TREE_TYPE (t));
10424 
10425       /* Check the parameter types.  Since default arguments are not
10426 	 instantiated until they are needed, the TYPE_ARG_TYPES may
10427 	 contain expressions that involve template parameters.  But,
10428 	 no-one should be looking at them yet.  And, once they're
10429 	 instantiated, they don't contain template parameters, so
10430 	 there's no point in looking at them then, either.  */
10431       {
10432 	tree parm;
10433 
10434 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10435 	  WALK_SUBTREE (TREE_VALUE (parm));
10436 
10437 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
10438 	   want walk_tree walking into them itself.  */
10439 	*walk_subtrees = 0;
10440       }
10441 
10442       if (flag_noexcept_type)
10443 	{
10444 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
10445 	  if (spec)
10446 	    WALK_SUBTREE (TREE_PURPOSE (spec));
10447 	}
10448       break;
10449 
10450     case TYPEOF_TYPE:
10451     case DECLTYPE_TYPE:
10452     case UNDERLYING_TYPE:
10453       if (pfd->include_nondeduced_p
10454 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10455 				     pfd->visited,
10456 				     pfd->include_nondeduced_p,
10457 				     pfd->any_fn))
10458 	return error_mark_node;
10459       *walk_subtrees = false;
10460       break;
10461 
10462     case FUNCTION_DECL:
10463     case VAR_DECL:
10464       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10465 	WALK_SUBTREE (DECL_TI_ARGS (t));
10466       /* Fall through.  */
10467 
10468     case PARM_DECL:
10469     case CONST_DECL:
10470       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10471 	WALK_SUBTREE (DECL_INITIAL (t));
10472       if (DECL_CONTEXT (t)
10473 	  && pfd->include_nondeduced_p)
10474 	WALK_SUBTREE (DECL_CONTEXT (t));
10475       break;
10476 
10477     case BOUND_TEMPLATE_TEMPLATE_PARM:
10478       /* Record template parameters such as `T' inside `TT<T>'.  */
10479       WALK_SUBTREE (TYPE_TI_ARGS (t));
10480       /* Fall through.  */
10481 
10482     case TEMPLATE_TEMPLATE_PARM:
10483     case TEMPLATE_TYPE_PARM:
10484     case TEMPLATE_PARM_INDEX:
10485       if (fn && (*fn)(t, data))
10486 	return t;
10487       else if (!fn)
10488 	return t;
10489       break;
10490 
10491     case TEMPLATE_DECL:
10492       /* A template template parameter is encountered.  */
10493       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10494 	WALK_SUBTREE (TREE_TYPE (t));
10495 
10496       /* Already substituted template template parameter */
10497       *walk_subtrees = 0;
10498       break;
10499 
10500     case TYPENAME_TYPE:
10501       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10502 	 partial instantiation.  */
10503       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10504       *walk_subtrees = 0;
10505       break;
10506 
10507     case CONSTRUCTOR:
10508       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10509 	  && pfd->include_nondeduced_p)
10510 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10511       break;
10512 
10513     case INDIRECT_REF:
10514     case COMPONENT_REF:
10515       /* If there's no type, then this thing must be some expression
10516 	 involving template parameters.  */
10517       if (!fn && !TREE_TYPE (t))
10518 	return error_mark_node;
10519       break;
10520 
10521     case MODOP_EXPR:
10522     case CAST_EXPR:
10523     case IMPLICIT_CONV_EXPR:
10524     case REINTERPRET_CAST_EXPR:
10525     case CONST_CAST_EXPR:
10526     case STATIC_CAST_EXPR:
10527     case DYNAMIC_CAST_EXPR:
10528     case ARROW_EXPR:
10529     case DOTSTAR_EXPR:
10530     case TYPEID_EXPR:
10531     case PSEUDO_DTOR_EXPR:
10532       if (!fn)
10533 	return error_mark_node;
10534       break;
10535 
10536     case SCOPE_REF:
10537       if (pfd->include_nondeduced_p)
10538 	WALK_SUBTREE (TREE_OPERAND (t, 0));
10539       break;
10540 
10541     case REQUIRES_EXPR:
10542       {
10543 	if (!fn)
10544 	  return error_mark_node;
10545 
10546 	/* Recursively walk the type of each constraint variable.  */
10547 	tree p = TREE_OPERAND (t, 0);
10548 	while (p)
10549 	  {
10550 	    WALK_SUBTREE (TREE_TYPE (p));
10551 	    p = TREE_CHAIN (p);
10552 	  }
10553       }
10554       break;
10555 
10556     default:
10557       break;
10558     }
10559 
10560   #undef WALK_SUBTREE
10561 
10562   /* We didn't find any template parameters we liked.  */
10563  out:
10564   return result;
10565 }
10566 
10567 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10568    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10569    call FN with the parameter and the DATA.
10570    If FN returns nonzero, the iteration is terminated, and
10571    for_each_template_parm returns 1.  Otherwise, the iteration
10572    continues.  If FN never returns a nonzero value, the value
10573    returned by for_each_template_parm is 0.  If FN is NULL, it is
10574    considered to be the function which always returns 1.
10575 
10576    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10577    parameters that occur in non-deduced contexts.  When false, only
10578    visits those template parameters that can be deduced.  */
10579 
10580 static tree
for_each_template_parm(tree t,tree_fn_t fn,void * data,hash_set<tree> * visited,bool include_nondeduced_p,tree_fn_t any_fn)10581 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10582 			hash_set<tree> *visited,
10583 			bool include_nondeduced_p,
10584 			tree_fn_t any_fn)
10585 {
10586   struct pair_fn_data pfd;
10587   tree result;
10588 
10589   /* Set up.  */
10590   pfd.fn = fn;
10591   pfd.any_fn = any_fn;
10592   pfd.data = data;
10593   pfd.include_nondeduced_p = include_nondeduced_p;
10594 
10595   /* Walk the tree.  (Conceptually, we would like to walk without
10596      duplicates, but for_each_template_parm_r recursively calls
10597      for_each_template_parm, so we would need to reorganize a fair
10598      bit to use walk_tree_without_duplicates, so we keep our own
10599      visited list.)  */
10600   if (visited)
10601     pfd.visited = visited;
10602   else
10603     pfd.visited = new hash_set<tree>;
10604   result = cp_walk_tree (&t,
10605 		         for_each_template_parm_r,
10606 		         &pfd,
10607 		         pfd.visited);
10608 
10609   /* Clean up.  */
10610   if (!visited)
10611     {
10612       delete pfd.visited;
10613       pfd.visited = 0;
10614     }
10615 
10616   return result;
10617 }
10618 
10619 struct find_template_parameter_info
10620 {
find_template_parameter_infofind_template_parameter_info10621   explicit find_template_parameter_info (tree ctx_parms)
10622     : parm_list (NULL_TREE),
10623       ctx_parms (ctx_parms),
10624       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10625   {}
10626 
10627   hash_set<tree> visited;
10628   hash_set<tree> parms;
10629   tree parm_list;
10630   tree ctx_parms;
10631   int max_depth;
10632 };
10633 
10634 /* Appends the declaration of T to the list in DATA.  */
10635 
10636 static int
keep_template_parm(tree t,void * data)10637 keep_template_parm (tree t, void* data)
10638 {
10639   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10640 
10641   /* Template parameters declared within the expression are not part of
10642      the parameter mapping. For example, in this concept:
10643 
10644        template<typename T>
10645        concept C = requires { <expr> } -> same_as<int>;
10646 
10647      the return specifier same_as<int> declares a new decltype parameter
10648      that must not be part of the parameter mapping. The same is true
10649      for generic lambda parameters, lambda template parameters, etc.  */
10650   int level;
10651   int index;
10652   template_parm_level_and_index (t, &level, &index);
10653   if (level > ftpi->max_depth)
10654     return 0;
10655 
10656   if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10657     /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10658        BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
10659     t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10660 
10661   /* This template parameter might be an argument to a cached dependent
10662      specalization that was formed earlier inside some other template, in
10663      which case the parameter is not among the ones that are in-scope.
10664      Look in CTX_PARMS to find the corresponding in-scope template
10665      parameter, and use it instead.  */
10666   if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10667     t = in_scope;
10668 
10669   /* Arguments like const T yield parameters like const T. This means that
10670      a template-id like X<T, const T> would yield two distinct parameters:
10671      T and const T. Adjust types to their unqualified versions.  */
10672   if (TYPE_P (t))
10673     t = TYPE_MAIN_VARIANT (t);
10674   if (!ftpi->parms.add (t))
10675     ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10676 
10677   /* Verify the parameter we found has a valid index.  */
10678   if (flag_checking)
10679     {
10680       tree parms = ftpi->ctx_parms;
10681       while (TMPL_PARMS_DEPTH (parms) > level)
10682 	parms = TREE_CHAIN (parms);
10683       if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10684 	gcc_assert (index < len);
10685     }
10686 
10687   return 0;
10688 }
10689 
10690 /* Ensure that we recursively examine certain terms that are not normally
10691    visited in for_each_template_parm_r.  */
10692 
10693 static int
any_template_parm_r(tree t,void * data)10694 any_template_parm_r (tree t, void *data)
10695 {
10696   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10697 
10698 #define WALK_SUBTREE(NODE)						\
10699   do									\
10700     {									\
10701       for_each_template_parm (NODE, keep_template_parm, data,		\
10702 			      &ftpi->visited, true,			\
10703 			      any_template_parm_r);			\
10704     }									\
10705   while (0)
10706 
10707   /* A mention of a member alias/typedef is a use of all of its template
10708      arguments, including those from the enclosing class, so we don't use
10709      alias_template_specialization_p here.  */
10710   if (TYPE_P (t) && typedef_variant_p (t))
10711     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10712       WALK_SUBTREE (TI_ARGS (tinfo));
10713 
10714   switch (TREE_CODE (t))
10715     {
10716     case TEMPLATE_TYPE_PARM:
10717       /* Type constraints of a placeholder type may contain parameters.  */
10718       if (is_auto (t))
10719 	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10720 	  WALK_SUBTREE (constr);
10721       break;
10722 
10723     case TEMPLATE_ID_EXPR:
10724       /* Search through references to variable templates.  */
10725       WALK_SUBTREE (TREE_OPERAND (t, 0));
10726       WALK_SUBTREE (TREE_OPERAND (t, 1));
10727       break;
10728 
10729     case TEMPLATE_PARM_INDEX:
10730     case PARM_DECL:
10731       /* A parameter or constraint variable may also depend on a template
10732 	 parameter without explicitly naming it.  */
10733       WALK_SUBTREE (TREE_TYPE (t));
10734       break;
10735 
10736     case TEMPLATE_DECL:
10737       /* If T is a member template that shares template parameters with
10738 	 ctx_parms, we need to mark all those parameters for mapping.
10739 	 To that end, it should suffice to just walk the DECL_CONTEXT of
10740 	 the template (assuming the template is not overly general).  */
10741       WALK_SUBTREE (DECL_CONTEXT (t));
10742       break;
10743 
10744     case LAMBDA_EXPR:
10745       {
10746 	/* Look in the parms and body.  */
10747 	tree fn = lambda_function (t);
10748 	WALK_SUBTREE (TREE_TYPE (fn));
10749 	WALK_SUBTREE (DECL_SAVED_TREE (fn));
10750       }
10751       break;
10752 
10753     case IDENTIFIER_NODE:
10754       if (IDENTIFIER_CONV_OP_P (t))
10755 	/* The conversion-type-id of a conversion operator may be dependent.  */
10756 	WALK_SUBTREE (TREE_TYPE (t));
10757       break;
10758 
10759     default:
10760       break;
10761     }
10762 
10763   /* Keep walking.  */
10764   return 0;
10765 }
10766 
10767 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10768    are the template parameters in scope.  */
10769 
10770 tree
find_template_parameters(tree t,tree ctx_parms)10771 find_template_parameters (tree t, tree ctx_parms)
10772 {
10773   if (!ctx_parms)
10774     return NULL_TREE;
10775 
10776   find_template_parameter_info ftpi (ctx_parms);
10777   for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10778 			  /*include_nondeduced*/true, any_template_parm_r);
10779   return ftpi.parm_list;
10780 }
10781 
10782 /* Returns true if T depends on any template parameter.  */
10783 
10784 int
uses_template_parms(tree t)10785 uses_template_parms (tree t)
10786 {
10787   if (t == NULL_TREE)
10788     return false;
10789 
10790   bool dependent_p;
10791   int saved_processing_template_decl;
10792 
10793   saved_processing_template_decl = processing_template_decl;
10794   if (!saved_processing_template_decl)
10795     processing_template_decl = 1;
10796   if (TYPE_P (t))
10797     dependent_p = dependent_type_p (t);
10798   else if (TREE_CODE (t) == TREE_VEC)
10799     dependent_p = any_dependent_template_arguments_p (t);
10800   else if (TREE_CODE (t) == TREE_LIST)
10801     dependent_p = (uses_template_parms (TREE_VALUE (t))
10802 		   || uses_template_parms (TREE_CHAIN (t)));
10803   else if (TREE_CODE (t) == TYPE_DECL)
10804     dependent_p = dependent_type_p (TREE_TYPE (t));
10805   else if (t == error_mark_node)
10806     dependent_p = false;
10807   else
10808     dependent_p = instantiation_dependent_expression_p (t);
10809 
10810   processing_template_decl = saved_processing_template_decl;
10811 
10812   return dependent_p;
10813 }
10814 
10815 /* Returns true iff we're processing an incompletely instantiated function
10816    template.  Useful instead of processing_template_decl because the latter
10817    is set to 0 during instantiate_non_dependent_expr.  */
10818 
10819 bool
in_template_function(void)10820 in_template_function (void)
10821 {
10822   /* Inspect the less volatile cfun->decl instead of current_function_decl;
10823      the latter might get set for e.g. access checking during satisfaction.  */
10824   tree fn = cfun ? cfun->decl : NULL_TREE;
10825   bool ret;
10826   ++processing_template_decl;
10827   ret = (fn && DECL_LANG_SPECIFIC (fn)
10828 	 && DECL_TEMPLATE_INFO (fn)
10829 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10830   --processing_template_decl;
10831   return ret;
10832 }
10833 
10834 /* Returns true if T depends on any template parameter with level LEVEL.  */
10835 
10836 bool
uses_template_parms_level(tree t,int level)10837 uses_template_parms_level (tree t, int level)
10838 {
10839   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10840 				 /*include_nondeduced_p=*/true);
10841 }
10842 
10843 /* Returns true if the signature of DECL depends on any template parameter from
10844    its enclosing class.  */
10845 
10846 bool
uses_outer_template_parms(tree decl)10847 uses_outer_template_parms (tree decl)
10848 {
10849   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10850   if (depth == 0)
10851     return false;
10852   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10853 			      &depth, NULL, /*include_nondeduced_p=*/true))
10854     return true;
10855   if (PRIMARY_TEMPLATE_P (decl)
10856       || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10857     {
10858       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10859       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10860 	{
10861 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10862 	  tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10863 	  if (TREE_CODE (parm) == PARM_DECL
10864 	      && for_each_template_parm (TREE_TYPE (parm),
10865 					 template_parm_outer_level,
10866 					 &depth, NULL, /*nondeduced*/true))
10867 	    return true;
10868 	  if (TREE_CODE (parm) == TEMPLATE_DECL
10869 	      && uses_outer_template_parms (parm))
10870 	    return true;
10871 	  if (defarg
10872 	      && for_each_template_parm (defarg, template_parm_outer_level,
10873 					 &depth, NULL, /*nondeduced*/true))
10874 	    return true;
10875 	}
10876     }
10877   tree ci = get_constraints (decl);
10878   if (ci)
10879     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10880   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10881 				    &depth, NULL, /*nondeduced*/true))
10882     return true;
10883   return false;
10884 }
10885 
10886 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10887    ill-formed translation unit, i.e. a variable or function that isn't
10888    usable in a constant expression.  */
10889 
10890 static inline bool
neglectable_inst_p(tree d)10891 neglectable_inst_p (tree d)
10892 {
10893   return (d && DECL_P (d)
10894 	  && !undeduced_auto_decl (d)
10895 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10896 	       : decl_maybe_constant_var_p (d)));
10897 }
10898 
10899 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10900    neglectable and instantiated from within an erroneous instantiation.  */
10901 
10902 static bool
limit_bad_template_recursion(tree decl)10903 limit_bad_template_recursion (tree decl)
10904 {
10905   struct tinst_level *lev = current_tinst_level;
10906   int errs = errorcount + sorrycount;
10907   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10908     return false;
10909 
10910   for (; lev; lev = lev->next)
10911     if (neglectable_inst_p (lev->maybe_get_node ()))
10912       break;
10913 
10914   return (lev && errs > lev->errors);
10915 }
10916 
10917 static int tinst_depth;
10918 extern int max_tinst_depth;
10919 int depth_reached;
10920 
10921 static GTY(()) struct tinst_level *last_error_tinst_level;
10922 
10923 /* We're starting to instantiate D; record the template instantiation context
10924    at LOC for diagnostics and to restore it later.  */
10925 
10926 bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10927 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10928 {
10929   struct tinst_level *new_level;
10930 
10931   if (tinst_depth >= max_tinst_depth)
10932     {
10933       /* Tell error.c not to try to instantiate any templates.  */
10934       at_eof = 2;
10935       fatal_error (input_location,
10936 		   "template instantiation depth exceeds maximum of %d"
10937 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
10938                    max_tinst_depth);
10939       return false;
10940     }
10941 
10942   /* If the current instantiation caused problems, don't let it instantiate
10943      anything else.  Do allow deduction substitution and decls usable in
10944      constant expressions.  */
10945   if (!targs && limit_bad_template_recursion (tldcl))
10946     {
10947       /* Avoid no_linkage_errors and unused function warnings for this
10948 	 decl.  */
10949       TREE_NO_WARNING (tldcl) = 1;
10950       return false;
10951     }
10952 
10953   /* When not -quiet, dump template instantiations other than functions, since
10954      announce_function will take care of those.  */
10955   if (!quiet_flag && !targs
10956       && TREE_CODE (tldcl) != TREE_LIST
10957       && TREE_CODE (tldcl) != FUNCTION_DECL)
10958     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10959 
10960   new_level = tinst_level_freelist ().alloc ();
10961   new_level->tldcl = tldcl;
10962   new_level->targs = targs;
10963   new_level->locus = loc;
10964   new_level->errors = errorcount + sorrycount;
10965   new_level->next = NULL;
10966   new_level->refcount = 0;
10967   new_level->path = new_level->visible = nullptr;
10968   set_refcount_ptr (new_level->next, current_tinst_level);
10969   set_refcount_ptr (current_tinst_level, new_level);
10970 
10971   ++tinst_depth;
10972   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10973     depth_reached = tinst_depth;
10974 
10975   return true;
10976 }
10977 
10978 /* We're starting substitution of TMPL<ARGS>; record the template
10979    substitution context for diagnostics and to restore it later.  */
10980 
10981 bool
push_tinst_level(tree tmpl,tree args)10982 push_tinst_level (tree tmpl, tree args)
10983 {
10984   return push_tinst_level_loc (tmpl, args, input_location);
10985 }
10986 
10987 /* We're starting to instantiate D; record INPUT_LOCATION and the
10988    template instantiation context for diagnostics and to restore it
10989    later.  */
10990 
10991 bool
push_tinst_level(tree d)10992 push_tinst_level (tree d)
10993 {
10994   return push_tinst_level_loc (d, input_location);
10995 }
10996 
10997 /* Likewise, but record LOC as the program location.  */
10998 
10999 bool
push_tinst_level_loc(tree d,location_t loc)11000 push_tinst_level_loc (tree d, location_t loc)
11001 {
11002   gcc_assert (TREE_CODE (d) != TREE_LIST);
11003   return push_tinst_level_loc (d, NULL, loc);
11004 }
11005 
11006 /* We're done instantiating this template; return to the instantiation
11007    context.  */
11008 
11009 void
pop_tinst_level(void)11010 pop_tinst_level (void)
11011 {
11012   /* Restore the filename and line number stashed away when we started
11013      this instantiation.  */
11014   input_location = current_tinst_level->locus;
11015   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11016   --tinst_depth;
11017 }
11018 
11019 /* We're instantiating a deferred template; restore the template
11020    instantiation context in which the instantiation was requested, which
11021    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
11022 
11023 static tree
reopen_tinst_level(struct tinst_level * level)11024 reopen_tinst_level (struct tinst_level *level)
11025 {
11026   struct tinst_level *t;
11027 
11028   tinst_depth = 0;
11029   for (t = level; t; t = t->next)
11030     ++tinst_depth;
11031 
11032   set_refcount_ptr (current_tinst_level, level);
11033   pop_tinst_level ();
11034   if (current_tinst_level)
11035     current_tinst_level->errors = errorcount+sorrycount;
11036   return level->maybe_get_node ();
11037 }
11038 
11039 /* Returns the TINST_LEVEL which gives the original instantiation
11040    context.  */
11041 
11042 struct tinst_level *
outermost_tinst_level(void)11043 outermost_tinst_level (void)
11044 {
11045   struct tinst_level *level = current_tinst_level;
11046   if (level)
11047     while (level->next)
11048       level = level->next;
11049   return level;
11050 }
11051 
11052 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
11053    vector of template arguments, as for tsubst.
11054 
11055    Returns an appropriate tsubst'd friend declaration.  */
11056 
11057 static tree
tsubst_friend_function(tree decl,tree args)11058 tsubst_friend_function (tree decl, tree args)
11059 {
11060   tree new_friend;
11061 
11062   if (TREE_CODE (decl) == FUNCTION_DECL
11063       && DECL_TEMPLATE_INSTANTIATION (decl)
11064       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11065     /* This was a friend declared with an explicit template
11066        argument list, e.g.:
11067 
11068        friend void f<>(T);
11069 
11070        to indicate that f was a template instantiation, not a new
11071        function declaration.  Now, we have to figure out what
11072        instantiation of what template.  */
11073     {
11074       tree template_id, arglist, fns;
11075       tree new_args;
11076       tree tmpl;
11077       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11078 
11079       /* Friend functions are looked up in the containing namespace scope.
11080 	 We must enter that scope, to avoid finding member functions of the
11081 	 current class with same name.  */
11082       push_nested_namespace (ns);
11083       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11084 			 tf_warning_or_error, NULL_TREE,
11085 			 /*integral_constant_expression_p=*/false);
11086       pop_nested_namespace (ns);
11087       arglist = tsubst (DECL_TI_ARGS (decl), args,
11088 			tf_warning_or_error, NULL_TREE);
11089       template_id = lookup_template_function (fns, arglist);
11090 
11091       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11092       tmpl = determine_specialization (template_id, new_friend,
11093 				       &new_args,
11094 				       /*need_member_template=*/0,
11095 				       TREE_VEC_LENGTH (args),
11096 				       tsk_none);
11097       return instantiate_template (tmpl, new_args, tf_error);
11098     }
11099 
11100   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11101   if (new_friend == error_mark_node)
11102     return error_mark_node;
11103 
11104   /* The NEW_FRIEND will look like an instantiation, to the
11105      compiler, but is not an instantiation from the point of view of
11106      the language.  For example, we might have had:
11107 
11108      template <class T> struct S {
11109        template <class U> friend void f(T, U);
11110      };
11111 
11112      Then, in S<int>, template <class U> void f(int, U) is not an
11113      instantiation of anything.  */
11114 
11115   DECL_USE_TEMPLATE (new_friend) = 0;
11116   if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11117     {
11118       DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11119       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11120       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11121 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11122 
11123       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11124 	 match in decls_match.  */
11125       tree parms = DECL_TEMPLATE_PARMS (new_friend);
11126       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11127       treqs = maybe_substitute_reqs_for (treqs, new_friend);
11128       TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11129     }
11130 
11131   /* The mangled name for the NEW_FRIEND is incorrect.  The function
11132      is not a template instantiation and should not be mangled like
11133      one.  Therefore, we forget the mangling here; we'll recompute it
11134      later if we need it.  */
11135   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11136     {
11137       SET_DECL_RTL (new_friend, NULL);
11138       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11139     }
11140 
11141   if (DECL_NAMESPACE_SCOPE_P (new_friend))
11142     {
11143       tree old_decl;
11144       tree ns;
11145 
11146       /* We must save some information from NEW_FRIEND before calling
11147 	 duplicate decls since that function will free NEW_FRIEND if
11148 	 possible.  */
11149       tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11150       tree new_friend_result_template_info = NULL_TREE;
11151       bool new_friend_is_defn =
11152 	(DECL_INITIAL (DECL_TEMPLATE_RESULT
11153 		       (template_for_substitution (new_friend)))
11154 	 != NULL_TREE);
11155       tree not_tmpl = new_friend;
11156 
11157       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11158 	{
11159 	  /* This declaration is a `primary' template.  */
11160 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11161 
11162 	  not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11163 	  new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11164 	}
11165 
11166       /* Inside pushdecl_namespace_level, we will push into the
11167 	 current namespace. However, the friend function should go
11168 	 into the namespace of the template.  */
11169       ns = decl_namespace_context (new_friend);
11170       push_nested_namespace (ns);
11171       old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11172       pop_nested_namespace (ns);
11173 
11174       if (old_decl == error_mark_node)
11175 	return error_mark_node;
11176 
11177       if (old_decl != new_friend)
11178 	{
11179 	  /* This new friend declaration matched an existing
11180 	     declaration.  For example, given:
11181 
11182 	       template <class T> void f(T);
11183 	       template <class U> class C {
11184 		 template <class T> friend void f(T) {}
11185 	       };
11186 
11187 	     the friend declaration actually provides the definition
11188 	     of `f', once C has been instantiated for some type.  So,
11189 	     old_decl will be the out-of-class template declaration,
11190 	     while new_friend is the in-class definition.
11191 
11192 	     But, if `f' was called before this point, the
11193 	     instantiation of `f' will have DECL_TI_ARGS corresponding
11194 	     to `T' but not to `U', references to which might appear
11195 	     in the definition of `f'.  Previously, the most general
11196 	     template for an instantiation of `f' was the out-of-class
11197 	     version; now it is the in-class version.  Therefore, we
11198 	     run through all specialization of `f', adding to their
11199 	     DECL_TI_ARGS appropriately.  In particular, they need a
11200 	     new set of outer arguments, corresponding to the
11201 	     arguments for this class instantiation.
11202 
11203 	     The same situation can arise with something like this:
11204 
11205 	       friend void f(int);
11206 	       template <class T> class C {
11207 		 friend void f(T) {}
11208 	       };
11209 
11210 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
11211 	     in the class.  */
11212 
11213 	  if (!new_friend_is_defn)
11214 	    /* On the other hand, if the in-class declaration does
11215 	       *not* provide a definition, then we don't want to alter
11216 	       existing definitions.  We can just leave everything
11217 	       alone.  */
11218 	    ;
11219 	  else
11220 	    {
11221 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
11222 	      tree new_args = TI_ARGS (new_friend_template_info);
11223 
11224 	      /* Overwrite whatever template info was there before, if
11225 		 any, with the new template information pertaining to
11226 		 the declaration.  */
11227 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11228 
11229 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11230 		{
11231 		  /* We should have called reregister_specialization in
11232 		     duplicate_decls.  */
11233 		  gcc_assert (retrieve_specialization (new_template,
11234 						       new_args, 0)
11235 			      == old_decl);
11236 
11237 		  /* Instantiate it if the global has already been used.  */
11238 		  if (DECL_ODR_USED (old_decl))
11239 		    instantiate_decl (old_decl, /*defer_ok=*/true,
11240 				      /*expl_inst_class_mem_p=*/false);
11241 		}
11242 	      else
11243 		{
11244 		  tree t;
11245 
11246 		  /* Indicate that the old function template is a partial
11247 		     instantiation.  */
11248 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11249 		    = new_friend_result_template_info;
11250 
11251 		  gcc_assert (new_template
11252 			      == most_general_template (new_template));
11253 		  gcc_assert (new_template != old_decl);
11254 
11255 		  /* Reassign any specializations already in the hash table
11256 		     to the new more general template, and add the
11257 		     additional template args.  */
11258 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11259 		       t != NULL_TREE;
11260 		       t = TREE_CHAIN (t))
11261 		    {
11262 		      tree spec = TREE_VALUE (t);
11263 		      spec_entry elt;
11264 
11265 		      elt.tmpl = old_decl;
11266 		      elt.args = DECL_TI_ARGS (spec);
11267 		      elt.spec = NULL_TREE;
11268 
11269 		      decl_specializations->remove_elt (&elt);
11270 
11271 		      DECL_TI_ARGS (spec)
11272 			= add_outermost_template_args (new_args,
11273 						       DECL_TI_ARGS (spec));
11274 
11275 		      register_specialization
11276 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
11277 
11278 		    }
11279 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11280 		}
11281 	    }
11282 
11283 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
11284 	     by duplicate_decls.  */
11285 	  new_friend = old_decl;
11286 	}
11287     }
11288   else
11289     {
11290       tree context = DECL_CONTEXT (new_friend);
11291       bool dependent_p;
11292 
11293       /* In the code
11294 	   template <class T> class C {
11295 	     template <class U> friend void C1<U>::f (); // case 1
11296 	     friend void C2<T>::f ();			 // case 2
11297 	   };
11298 	 we only need to make sure CONTEXT is a complete type for
11299 	 case 2.  To distinguish between the two cases, we note that
11300 	 CONTEXT of case 1 remains dependent type after tsubst while
11301 	 this isn't true for case 2.  */
11302       ++processing_template_decl;
11303       dependent_p = dependent_type_p (context);
11304       --processing_template_decl;
11305 
11306       if (!dependent_p
11307 	  && !complete_type_or_else (context, NULL_TREE))
11308 	return error_mark_node;
11309 
11310       if (COMPLETE_TYPE_P (context))
11311 	{
11312 	  tree fn = new_friend;
11313 	  /* do_friend adds the TEMPLATE_DECL for any member friend
11314 	     template even if it isn't a member template, i.e.
11315 	       template <class T> friend A<T>::f();
11316 	     Look through it in that case.  */
11317 	  if (TREE_CODE (fn) == TEMPLATE_DECL
11318 	      && !PRIMARY_TEMPLATE_P (fn))
11319 	    fn = DECL_TEMPLATE_RESULT (fn);
11320 	  /* Check to see that the declaration is really present, and,
11321 	     possibly obtain an improved declaration.  */
11322 	  fn = check_classfn (context, fn, NULL_TREE);
11323 
11324 	  if (fn)
11325 	    new_friend = fn;
11326 	}
11327     }
11328 
11329   return new_friend;
11330 }
11331 
11332 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11333    template arguments, as for tsubst.
11334 
11335    Returns an appropriate tsubst'd friend type or error_mark_node on
11336    failure.  */
11337 
11338 static tree
tsubst_friend_class(tree friend_tmpl,tree args)11339 tsubst_friend_class (tree friend_tmpl, tree args)
11340 {
11341   tree tmpl;
11342 
11343   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11344     {
11345       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11346       return TREE_TYPE (tmpl);
11347     }
11348 
11349   tree context = CP_DECL_CONTEXT (friend_tmpl);
11350   if (TREE_CODE (context) == NAMESPACE_DECL)
11351     push_nested_namespace (context);
11352   else
11353     {
11354       context = tsubst (context, args, tf_error, NULL_TREE);
11355       push_nested_class (context);
11356     }
11357 
11358   tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11359 		      LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11360 
11361   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11362     {
11363       /* The friend template has already been declared.  Just
11364 	 check to see that the declarations match, and install any new
11365 	 default parameters.  We must tsubst the default parameters,
11366 	 of course.  We only need the innermost template parameters
11367 	 because that is all that redeclare_class_template will look
11368 	 at.  */
11369       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11370 	  > TMPL_ARGS_DEPTH (args))
11371 	{
11372 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11373 					      args, tf_warning_or_error);
11374           location_t saved_input_location = input_location;
11375           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11376           tree cons = get_constraints (tmpl);
11377           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11378           input_location = saved_input_location;
11379 	}
11380     }
11381   else
11382     {
11383       /* The friend template has not already been declared.  In this
11384 	 case, the instantiation of the template class will cause the
11385 	 injection of this template into the namespace scope.  */
11386       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11387 
11388       if (tmpl != error_mark_node)
11389 	{
11390 	  /* The new TMPL is not an instantiation of anything, so we
11391 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11392 	     for the new type because that is supposed to be the
11393 	     corresponding template decl, i.e., TMPL.  */
11394 	  DECL_USE_TEMPLATE (tmpl) = 0;
11395 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11396 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11397 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11398 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11399 
11400 	  /* Substitute into and set the constraints on the new declaration.  */
11401 	  if (tree ci = get_constraints (friend_tmpl))
11402 	    {
11403 	      ++processing_template_decl;
11404 	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11405 					   DECL_FRIEND_CONTEXT (friend_tmpl));
11406 	      --processing_template_decl;
11407 	      set_constraints (tmpl, ci);
11408 	    }
11409 
11410 	  /* Inject this template into the enclosing namspace scope.  */
11411 	  tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11412 	}
11413     }
11414 
11415   if (TREE_CODE (context) == NAMESPACE_DECL)
11416     pop_nested_namespace (context);
11417   else
11418     pop_nested_class ();
11419 
11420   return TREE_TYPE (tmpl);
11421 }
11422 
11423 /* Returns zero if TYPE cannot be completed later due to circularity.
11424    Otherwise returns one.  */
11425 
11426 static int
can_complete_type_without_circularity(tree type)11427 can_complete_type_without_circularity (tree type)
11428 {
11429   if (type == NULL_TREE || type == error_mark_node)
11430     return 0;
11431   else if (COMPLETE_TYPE_P (type))
11432     return 1;
11433   else if (TREE_CODE (type) == ARRAY_TYPE)
11434     return can_complete_type_without_circularity (TREE_TYPE (type));
11435   else if (CLASS_TYPE_P (type)
11436 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11437     return 0;
11438   else
11439     return 1;
11440 }
11441 
11442 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11443 				tsubst_flags_t, tree);
11444 
11445 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11446    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11447 
11448 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)11449 tsubst_attribute (tree t, tree *decl_p, tree args,
11450 		  tsubst_flags_t complain, tree in_decl)
11451 {
11452   gcc_assert (ATTR_IS_DEPENDENT (t));
11453 
11454   tree val = TREE_VALUE (t);
11455   if (val == NULL_TREE)
11456     /* Nothing to do.  */;
11457   else if ((flag_openmp || flag_openmp_simd)
11458 	   && is_attribute_p ("omp declare simd",
11459 			      get_attribute_name (t)))
11460     {
11461       tree clauses = TREE_VALUE (val);
11462       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11463 				    complain, in_decl);
11464       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11465       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11466       tree parms = DECL_ARGUMENTS (*decl_p);
11467       clauses
11468 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11469       if (clauses)
11470 	val = build_tree_list (NULL_TREE, clauses);
11471       else
11472 	val = NULL_TREE;
11473     }
11474   else if (flag_openmp
11475 	   && is_attribute_p ("omp declare variant base",
11476 			      get_attribute_name (t)))
11477     {
11478       ++cp_unevaluated_operand;
11479       tree varid
11480 	= tsubst_expr (TREE_PURPOSE (val), args, complain,
11481 		       in_decl, /*integral_constant_expression_p=*/false);
11482       --cp_unevaluated_operand;
11483       tree chain = TREE_CHAIN (val);
11484       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11485       tree ctx = copy_list (TREE_VALUE (val));
11486       tree simd = get_identifier ("simd");
11487       tree score = get_identifier (" score");
11488       tree condition = get_identifier ("condition");
11489       for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11490 	{
11491 	  const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11492 	  TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11493 	  for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11494 	    {
11495 	      if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11496 		{
11497 		  tree clauses = TREE_VALUE (t2);
11498 		  clauses = tsubst_omp_clauses (clauses,
11499 						C_ORT_OMP_DECLARE_SIMD, args,
11500 						complain, in_decl);
11501 		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11502 		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11503 		  TREE_VALUE (t2) = clauses;
11504 		}
11505 	      else
11506 		{
11507 		  TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11508 		  for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11509 		    if (TREE_VALUE (t3))
11510 		      {
11511 			bool allow_string
11512 			  = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11513 			     && TREE_PURPOSE (t3) != score);
11514 			tree v = TREE_VALUE (t3);
11515 			if (TREE_CODE (v) == STRING_CST && allow_string)
11516 			  continue;
11517 			v = tsubst_expr (v, args, complain, in_decl, true);
11518 			v = fold_non_dependent_expr (v);
11519 			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11520 			    || (TREE_PURPOSE (t3) == score
11521 				? TREE_CODE (v) != INTEGER_CST
11522 				: !tree_fits_shwi_p (v)))
11523 			  {
11524 			    location_t loc
11525 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11526 						    match_loc);
11527 			    if (TREE_PURPOSE (t3) == score)
11528 			      error_at (loc, "score argument must be "
11529 					     "constant integer expression");
11530 			    else if (allow_string)
11531 			      error_at (loc, "property must be constant "
11532 					     "integer expression or string "
11533 					     "literal");
11534 			    else
11535 			      error_at (loc, "property must be constant "
11536 					     "integer expression");
11537 			    return NULL_TREE;
11538 			  }
11539 			else if (TREE_PURPOSE (t3) == score
11540 				 && tree_int_cst_sgn (v) < 0)
11541 			  {
11542 			    location_t loc
11543 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11544 						    match_loc);
11545 			    error_at (loc, "score argument must be "
11546 					   "non-negative");
11547 			    return NULL_TREE;
11548 			  }
11549 			TREE_VALUE (t3) = v;
11550 		      }
11551 		}
11552 	    }
11553 	}
11554       val = tree_cons (varid, ctx, chain);
11555     }
11556   /* If the first attribute argument is an identifier, don't
11557      pass it through tsubst.  Attributes like mode, format,
11558      cleanup and several target specific attributes expect it
11559      unmodified.  */
11560   else if (attribute_takes_identifier_p (get_attribute_name (t)))
11561     {
11562       tree chain
11563 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11564 		       /*integral_constant_expression_p=*/false);
11565       if (chain != TREE_CHAIN (val))
11566 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11567     }
11568   else if (PACK_EXPANSION_P (val))
11569     {
11570       /* An attribute pack expansion.  */
11571       tree purp = TREE_PURPOSE (t);
11572       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11573       if (pack == error_mark_node)
11574 	return error_mark_node;
11575       int len = TREE_VEC_LENGTH (pack);
11576       tree list = NULL_TREE;
11577       tree *q = &list;
11578       for (int i = 0; i < len; ++i)
11579 	{
11580 	  tree elt = TREE_VEC_ELT (pack, i);
11581 	  *q = build_tree_list (purp, elt);
11582 	  q = &TREE_CHAIN (*q);
11583 	}
11584       return list;
11585     }
11586   else
11587     val = tsubst_expr (val, args, complain, in_decl,
11588 		       /*integral_constant_expression_p=*/false);
11589 
11590   if (val == error_mark_node)
11591     return error_mark_node;
11592   if (val != TREE_VALUE (t))
11593     return build_tree_list (TREE_PURPOSE (t), val);
11594   return t;
11595 }
11596 
11597 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11598    unchanged or a new TREE_LIST chain.  */
11599 
11600 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)11601 tsubst_attributes (tree attributes, tree args,
11602 		   tsubst_flags_t complain, tree in_decl)
11603 {
11604   tree last_dep = NULL_TREE;
11605 
11606   for (tree t = attributes; t; t = TREE_CHAIN (t))
11607     if (ATTR_IS_DEPENDENT (t))
11608       {
11609 	last_dep = t;
11610 	attributes = copy_list (attributes);
11611 	break;
11612       }
11613 
11614   if (last_dep)
11615     for (tree *p = &attributes; *p; )
11616       {
11617 	tree t = *p;
11618 	if (ATTR_IS_DEPENDENT (t))
11619 	  {
11620 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11621 	    if (subst != t)
11622 	      {
11623 		*p = subst;
11624 		while (*p)
11625 		  p = &TREE_CHAIN (*p);
11626 		*p = TREE_CHAIN (t);
11627 		continue;
11628 	      }
11629 	  }
11630 	p = &TREE_CHAIN (*p);
11631       }
11632 
11633   return attributes;
11634 }
11635 
11636 /* Apply any attributes which had to be deferred until instantiation
11637    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11638    ARGS, COMPLAIN, IN_DECL are as tsubst.  Returns true normally,
11639    false on error.  */
11640 
11641 static bool
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)11642 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11643 				tree args, tsubst_flags_t complain, tree in_decl)
11644 {
11645   tree last_dep = NULL_TREE;
11646   tree t;
11647   tree *p;
11648 
11649   if (attributes == NULL_TREE)
11650     return true;
11651 
11652   if (DECL_P (*decl_p))
11653     {
11654       if (TREE_TYPE (*decl_p) == error_mark_node)
11655 	return false;
11656       p = &DECL_ATTRIBUTES (*decl_p);
11657       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11658          to our attributes parameter.  */
11659       gcc_assert (*p == attributes);
11660     }
11661   else
11662     {
11663       p = &TYPE_ATTRIBUTES (*decl_p);
11664       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11665 	 lookup_template_class_1, and should be preserved.  */
11666       gcc_assert (*p != attributes);
11667       while (*p)
11668 	p = &TREE_CHAIN (*p);
11669     }
11670 
11671   for (t = attributes; t; t = TREE_CHAIN (t))
11672     if (ATTR_IS_DEPENDENT (t))
11673       {
11674 	last_dep = t;
11675 	attributes = copy_list (attributes);
11676 	break;
11677       }
11678 
11679   *p = attributes;
11680   if (last_dep)
11681     {
11682       tree late_attrs = NULL_TREE;
11683       tree *q = &late_attrs;
11684 
11685       for (; *p; )
11686 	{
11687 	  t = *p;
11688 	  if (ATTR_IS_DEPENDENT (t))
11689 	    {
11690 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11691 	      if (*q == error_mark_node)
11692 		return false;
11693 	      *p = TREE_CHAIN (t);
11694 	      TREE_CHAIN (t) = NULL_TREE;
11695 	      while (*q)
11696 		q = &TREE_CHAIN (*q);
11697 	    }
11698 	  else
11699 	    p = &TREE_CHAIN (t);
11700 	}
11701 
11702       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11703     }
11704   return true;
11705 }
11706 
11707 /* The template TMPL is being instantiated with the template arguments TARGS.
11708    Perform the access checks that we deferred when parsing the template.  */
11709 
11710 static void
perform_instantiation_time_access_checks(tree tmpl,tree targs)11711 perform_instantiation_time_access_checks (tree tmpl, tree targs)
11712 {
11713   unsigned i;
11714   deferred_access_check *chk;
11715 
11716   if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
11717     return;
11718 
11719   if (vec<deferred_access_check, va_gc> *access_checks
11720       = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
11721     FOR_EACH_VEC_ELT (*access_checks, i, chk)
11722       {
11723 	tree decl = chk->decl;
11724 	tree diag_decl = chk->diag_decl;
11725 	tree type_scope = TREE_TYPE (chk->binfo);
11726 
11727 	if (uses_template_parms (type_scope))
11728 	  type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11729 
11730 	/* Make access check error messages point to the location
11731 	   of the use of the typedef.  */
11732 	iloc_sentinel ils (chk->loc);
11733 	perform_or_defer_access_check (TYPE_BINFO (type_scope),
11734 				       decl, diag_decl, tf_warning_or_error);
11735       }
11736 }
11737 
11738 static tree
instantiate_class_template_1(tree type)11739 instantiate_class_template_1 (tree type)
11740 {
11741   tree templ, args, pattern, t, member;
11742   tree typedecl;
11743   tree pbinfo;
11744   tree base_list;
11745   unsigned int saved_maximum_field_alignment;
11746   tree fn_context;
11747 
11748   if (type == error_mark_node)
11749     return error_mark_node;
11750 
11751   if (COMPLETE_OR_OPEN_TYPE_P (type)
11752       || uses_template_parms (type))
11753     return type;
11754 
11755   /* Figure out which template is being instantiated.  */
11756   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11757   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11758 
11759   /* Mark the type as in the process of being defined.  */
11760   TYPE_BEING_DEFINED (type) = 1;
11761 
11762   /* We may be in the middle of deferred access check.  Disable
11763      it now.  */
11764   deferring_access_check_sentinel acs (dk_no_deferred);
11765 
11766   /* Determine what specialization of the original template to
11767      instantiate.  */
11768   t = most_specialized_partial_spec (type, tf_warning_or_error);
11769   if (t == error_mark_node)
11770     return error_mark_node;
11771   else if (t)
11772     {
11773       /* This TYPE is actually an instantiation of a partial
11774 	 specialization.  We replace the innermost set of ARGS with
11775 	 the arguments appropriate for substitution.  For example,
11776 	 given:
11777 
11778 	   template <class T> struct S {};
11779 	   template <class T> struct S<T*> {};
11780 
11781 	 and supposing that we are instantiating S<int*>, ARGS will
11782 	 presently be {int*} -- but we need {int}.  */
11783       pattern = TREE_TYPE (t);
11784       args = TREE_PURPOSE (t);
11785     }
11786   else
11787     {
11788       pattern = TREE_TYPE (templ);
11789       args = CLASSTYPE_TI_ARGS (type);
11790     }
11791 
11792   /* If the template we're instantiating is incomplete, then clearly
11793      there's nothing we can do.  */
11794   if (!COMPLETE_TYPE_P (pattern))
11795     {
11796       /* We can try again later.  */
11797       TYPE_BEING_DEFINED (type) = 0;
11798       return type;
11799     }
11800 
11801   /* If we've recursively instantiated too many templates, stop.  */
11802   if (! push_tinst_level (type))
11803     return type;
11804 
11805   int saved_unevaluated_operand = cp_unevaluated_operand;
11806   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11807 
11808   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11809   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11810   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11811     fn_context = error_mark_node;
11812   if (!fn_context)
11813     push_to_top_level ();
11814   else
11815     {
11816       cp_unevaluated_operand = 0;
11817       c_inhibit_evaluation_warnings = 0;
11818     }
11819   /* Use #pragma pack from the template context.  */
11820   saved_maximum_field_alignment = maximum_field_alignment;
11821   maximum_field_alignment = TYPE_PRECISION (pattern);
11822 
11823   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11824 
11825   /* Set the input location to the most specialized template definition.
11826      This is needed if tsubsting causes an error.  */
11827   typedecl = TYPE_MAIN_DECL (pattern);
11828   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11829     DECL_SOURCE_LOCATION (typedecl);
11830 
11831   set_instantiating_module (TYPE_NAME (type));
11832 
11833   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11834   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11835   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11836   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11837   if (ANON_AGGR_TYPE_P (pattern))
11838     SET_ANON_AGGR_TYPE_P (type);
11839   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11840     {
11841       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11842       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11843       /* Adjust visibility for template arguments.  */
11844       determine_visibility (TYPE_MAIN_DECL (type));
11845     }
11846   if (CLASS_TYPE_P (type))
11847     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11848 
11849   pbinfo = TYPE_BINFO (pattern);
11850 
11851   /* We should never instantiate a nested class before its enclosing
11852      class; we need to look up the nested class by name before we can
11853      instantiate it, and that lookup should instantiate the enclosing
11854      class.  */
11855   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11856 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11857 
11858   base_list = NULL_TREE;
11859   /* Defer access checking while we substitute into the types named in
11860      the base-clause.  */
11861   push_deferring_access_checks (dk_deferred);
11862   if (BINFO_N_BASE_BINFOS (pbinfo))
11863     {
11864       tree pbase_binfo;
11865       int i;
11866 
11867       /* Substitute into each of the bases to determine the actual
11868 	 basetypes.  */
11869       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11870 	{
11871 	  tree base;
11872 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
11873           tree expanded_bases = NULL_TREE;
11874           int idx, len = 1;
11875 
11876           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11877             {
11878               expanded_bases =
11879 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11880 				       args, tf_error, NULL_TREE);
11881               if (expanded_bases == error_mark_node)
11882                 continue;
11883 
11884               len = TREE_VEC_LENGTH (expanded_bases);
11885             }
11886 
11887           for (idx = 0; idx < len; idx++)
11888             {
11889               if (expanded_bases)
11890                 /* Extract the already-expanded base class.  */
11891                 base = TREE_VEC_ELT (expanded_bases, idx);
11892               else
11893                 /* Substitute to figure out the base class.  */
11894                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11895                                NULL_TREE);
11896 
11897               if (base == error_mark_node)
11898                 continue;
11899 
11900               base_list = tree_cons (access, base, base_list);
11901               if (BINFO_VIRTUAL_P (pbase_binfo))
11902                 TREE_TYPE (base_list) = integer_type_node;
11903             }
11904 	}
11905 
11906       /* The list is now in reverse order; correct that.  */
11907       base_list = nreverse (base_list);
11908     }
11909   /* Now call xref_basetypes to set up all the base-class
11910      information.  */
11911   xref_basetypes (type, base_list);
11912 
11913   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11914 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11915 				  args, tf_error, NULL_TREE);
11916   fixup_attribute_variants (type);
11917 
11918   /* Now that our base classes are set up, enter the scope of the
11919      class, so that name lookups into base classes, etc. will work
11920      correctly.  This is precisely analogous to what we do in
11921      begin_class_definition when defining an ordinary non-template
11922      class, except we also need to push the enclosing classes.  */
11923   push_nested_class (type);
11924 
11925   /* Now check accessibility of the types named in its base-clause,
11926      relative to the scope of the class.  */
11927   pop_to_parent_deferring_access_checks ();
11928 
11929   /* A vector to hold members marked with attribute used. */
11930   auto_vec<tree> used;
11931 
11932   /* Now members are processed in the order of declaration.  */
11933   for (member = CLASSTYPE_DECL_LIST (pattern);
11934        member; member = TREE_CHAIN (member))
11935     {
11936       tree t = TREE_VALUE (member);
11937 
11938       if (TREE_PURPOSE (member))
11939 	{
11940 	  if (TYPE_P (t))
11941 	    {
11942 	      if (LAMBDA_TYPE_P (t))
11943 		/* A closure type for a lambda in an NSDMI or default argument.
11944 		   Ignore it; it will be regenerated when needed.  */
11945 		continue;
11946 
11947 	      bool class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11948 				       && TYPE_LANG_SPECIFIC (t)
11949 				       && CLASSTYPE_IS_TEMPLATE (t));
11950 
11951 	      /* If the member is a class template, then -- even after
11952 		 substitution -- there may be dependent types in the
11953 		 template argument list for the class.  We increment
11954 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11955 		 that function will assume that no types are dependent
11956 		 when outside of a template.  */
11957 	      if (class_template_p)
11958 		++processing_template_decl;
11959 	      tree newtag = tsubst (t, args, tf_error, NULL_TREE);
11960 	      if (class_template_p)
11961 		--processing_template_decl;
11962 	      if (newtag == error_mark_node)
11963 		continue;
11964 
11965 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11966 		{
11967 		  tree name = TYPE_IDENTIFIER (t);
11968 
11969 		  if (class_template_p)
11970 		    /* Unfortunately, lookup_template_class sets
11971 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11972 		       instantiation (i.e., for the type of a member
11973 		       template class nested within a template class.)
11974 		       This behavior is required for
11975 		       maybe_process_partial_specialization to work
11976 		       correctly, but is not accurate in this case;
11977 		       the TAG is not an instantiation of anything.
11978 		       (The corresponding TEMPLATE_DECL is an
11979 		       instantiation, but the TYPE is not.) */
11980 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11981 
11982 		  /* Now, install the tag.  We don't use pushtag
11983 		     because that does too much work -- creating an
11984 		     implicit typedef, which we've already done.  */
11985 		  set_identifier_type_value (name, TYPE_NAME (newtag));
11986 		  maybe_add_class_template_decl_list (type, newtag, false);
11987 		  TREE_PUBLIC (TYPE_NAME (newtag)) = true;
11988 		  determine_visibility (TYPE_NAME (newtag));
11989 		}
11990 	    }
11991 	  else if (DECL_DECLARES_FUNCTION_P (t))
11992 	    {
11993 	      tree r;
11994 
11995 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11996 		++processing_template_decl;
11997 	      r = tsubst (t, args, tf_error, NULL_TREE);
11998 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11999 		--processing_template_decl;
12000 	      set_current_access_from_decl (r);
12001 	      finish_member_declaration (r);
12002 	      /* Instantiate members marked with attribute used.  */
12003 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
12004 		used.safe_push (r);
12005 	      if (TREE_CODE (r) == FUNCTION_DECL
12006 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
12007 		cp_check_omp_declare_reduction (r);
12008 	    }
12009 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12010 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
12011 	    /* A closure type for a lambda in an NSDMI or default argument.
12012 	       Ignore it; it will be regenerated when needed.  */;
12013 	  else
12014 	    {
12015 	      /* Build new TYPE_FIELDS.  */
12016               if (TREE_CODE (t) == STATIC_ASSERT)
12017 		tsubst_expr (t, args, tf_warning_or_error, NULL_TREE,
12018 			     /*integral_constant_expression_p=*/true);
12019 	      else if (TREE_CODE (t) != CONST_DECL)
12020 		{
12021 		  tree r;
12022 		  tree vec = NULL_TREE;
12023 		  int len = 1;
12024 
12025 		  gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12026 		  /* The file and line for this declaration, to
12027 		     assist in error message reporting.  Since we
12028 		     called push_tinst_level above, we don't need to
12029 		     restore these.  */
12030 		  input_location = DECL_SOURCE_LOCATION (t);
12031 
12032 		  if (TREE_CODE (t) == TEMPLATE_DECL)
12033 		    ++processing_template_decl;
12034 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12035 		  if (TREE_CODE (t) == TEMPLATE_DECL)
12036 		    --processing_template_decl;
12037 
12038 		  if (TREE_CODE (r) == TREE_VEC)
12039 		    {
12040 		      /* A capture pack became multiple fields.  */
12041 		      vec = r;
12042 		      len = TREE_VEC_LENGTH (vec);
12043 		    }
12044 
12045 		  for (int i = 0; i < len; ++i)
12046 		    {
12047 		      if (vec)
12048 			r = TREE_VEC_ELT (vec, i);
12049 		      if (VAR_P (r))
12050 			{
12051 			  /* In [temp.inst]:
12052 
12053 			     [t]he initialization (and any associated
12054 			     side-effects) of a static data member does
12055 			     not occur unless the static data member is
12056 			     itself used in a way that requires the
12057 			     definition of the static data member to
12058 			     exist.
12059 
12060 			     Therefore, we do not substitute into the
12061 			     initialized for the static data member here.  */
12062 			  finish_static_data_member_decl
12063 			    (r,
12064 			     /*init=*/NULL_TREE,
12065 			     /*init_const_expr_p=*/false,
12066 			     /*asmspec_tree=*/NULL_TREE,
12067 			     /*flags=*/0);
12068 			  /* Instantiate members marked with attribute used. */
12069 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
12070 			    used.safe_push (r);
12071 			}
12072 		      else if (TREE_CODE (r) == FIELD_DECL)
12073 			{
12074 			  /* Determine whether R has a valid type and can be
12075 			     completed later.  If R is invalid, then its type
12076 			     is replaced by error_mark_node.  */
12077 			  tree rtype = TREE_TYPE (r);
12078 			  if (can_complete_type_without_circularity (rtype))
12079 			    complete_type (rtype);
12080 
12081 			  if (!complete_or_array_type_p (rtype))
12082 			    {
12083 			      /* If R's type couldn't be completed and
12084 				 it isn't a flexible array member (whose
12085 				 type is incomplete by definition) give
12086 				 an error.  */
12087 			      cxx_incomplete_type_error (r, rtype);
12088 			      TREE_TYPE (r) = error_mark_node;
12089 			    }
12090 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
12091 				   && TYPE_DOMAIN (rtype) == NULL_TREE
12092 				   && (TREE_CODE (type) == UNION_TYPE
12093 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
12094 			    {
12095 			      error ("flexible array member %qD in union", r);
12096 			      TREE_TYPE (r) = error_mark_node;
12097 			    }
12098 			  else if (!verify_type_context (input_location,
12099 							 TCTX_FIELD, rtype))
12100 			    TREE_TYPE (r) = error_mark_node;
12101 			}
12102 
12103 		      /* If it is a TYPE_DECL for a class-scoped
12104 			 ENUMERAL_TYPE, such a thing will already have
12105 			 been added to the field list by tsubst_enum
12106 			 in finish_member_declaration case above.  */
12107 		      if (!(TREE_CODE (r) == TYPE_DECL
12108 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12109 			    && DECL_ARTIFICIAL (r)))
12110 			{
12111 			  set_current_access_from_decl (r);
12112 			  finish_member_declaration (r);
12113 			}
12114 		    }
12115 		}
12116 	    }
12117 	}
12118       else
12119 	{
12120 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12121 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12122 	    {
12123 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
12124 
12125 	      tree friend_type = t;
12126 	      bool adjust_processing_template_decl = false;
12127 
12128 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12129 		{
12130 		  /* template <class T> friend class C;  */
12131 		  friend_type = tsubst_friend_class (friend_type, args);
12132 		  adjust_processing_template_decl = true;
12133 		}
12134 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12135 		{
12136 		  /* template <class T> friend class C::D;  */
12137 		  friend_type = tsubst (friend_type, args,
12138 					tf_warning_or_error, NULL_TREE);
12139 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12140 		    friend_type = TREE_TYPE (friend_type);
12141 		  adjust_processing_template_decl = true;
12142 		}
12143 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12144 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12145 		{
12146 		  /* This could be either
12147 
12148 		       friend class T::C;
12149 
12150 		     when dependent_type_p is false or
12151 
12152 		       template <class U> friend class T::C;
12153 
12154 		     otherwise.  */
12155 		  /* Bump processing_template_decl in case this is something like
12156 		     template <class T> friend struct A<T>::B.  */
12157 		  ++processing_template_decl;
12158 		  friend_type = tsubst (friend_type, args,
12159 					tf_warning_or_error, NULL_TREE);
12160 		  if (dependent_type_p (friend_type))
12161 		    adjust_processing_template_decl = true;
12162 		  --processing_template_decl;
12163 		}
12164 	      else if (uses_template_parms (friend_type))
12165 		/* friend class C<T>;  */
12166 		friend_type = tsubst (friend_type, args,
12167 				      tf_warning_or_error, NULL_TREE);
12168 
12169 	      /* Otherwise it's
12170 
12171 		   friend class C;
12172 
12173 		 where C is already declared or
12174 
12175 		   friend class C<int>;
12176 
12177 		 We don't have to do anything in these cases.  */
12178 
12179 	      if (adjust_processing_template_decl)
12180 		/* Trick make_friend_class into realizing that the friend
12181 		   we're adding is a template, not an ordinary class.  It's
12182 		   important that we use make_friend_class since it will
12183 		   perform some error-checking and output cross-reference
12184 		   information.  */
12185 		++processing_template_decl;
12186 
12187 	      if (friend_type != error_mark_node)
12188 		make_friend_class (type, friend_type, /*complain=*/false);
12189 
12190 	      if (adjust_processing_template_decl)
12191 		--processing_template_decl;
12192 	    }
12193 	  else
12194 	    {
12195 	      /* Build new DECL_FRIENDLIST.  */
12196 	      tree r;
12197 
12198 	      /* The file and line for this declaration, to
12199 		 assist in error message reporting.  Since we
12200 		 called push_tinst_level above, we don't need to
12201 		 restore these.  */
12202 	      input_location = DECL_SOURCE_LOCATION (t);
12203 
12204 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12205 		{
12206 		  ++processing_template_decl;
12207 		  push_deferring_access_checks (dk_no_check);
12208 		}
12209 
12210 	      r = tsubst_friend_function (t, args);
12211 	      add_friend (type, r, /*complain=*/false);
12212 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12213 		{
12214 		  pop_deferring_access_checks ();
12215 		  --processing_template_decl;
12216 		}
12217 	    }
12218 	}
12219     }
12220 
12221   if (fn_context)
12222     {
12223       /* Restore these before substituting into the lambda capture
12224 	 initializers.  */
12225       cp_unevaluated_operand = saved_unevaluated_operand;
12226       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12227     }
12228 
12229   /* Set the file and line number information to whatever is given for
12230      the class itself.  This puts error messages involving generated
12231      implicit functions at a predictable point, and the same point
12232      that would be used for non-template classes.  */
12233   input_location = DECL_SOURCE_LOCATION (typedecl);
12234 
12235   unreverse_member_declarations (type);
12236   finish_struct_1 (type);
12237   TYPE_BEING_DEFINED (type) = 0;
12238 
12239   /* We don't instantiate default arguments for member functions.  14.7.1:
12240 
12241      The implicit instantiation of a class template specialization causes
12242      the implicit instantiation of the declarations, but not of the
12243      definitions or default arguments, of the class member functions,
12244      member classes, static data members and member templates....  */
12245 
12246   perform_instantiation_time_access_checks (pattern, args);
12247   perform_deferred_access_checks (tf_warning_or_error);
12248   pop_nested_class ();
12249   maximum_field_alignment = saved_maximum_field_alignment;
12250   if (!fn_context)
12251     pop_from_top_level ();
12252   pop_tinst_level ();
12253 
12254   /* The vtable for a template class can be emitted in any translation
12255      unit in which the class is instantiated.  When there is no key
12256      method, however, finish_struct_1 will already have added TYPE to
12257      the keyed_classes.  */
12258   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12259     vec_safe_push (keyed_classes, type);
12260 
12261   /* Now that we've gone through all the members, instantiate those
12262      marked with attribute used.  */
12263   for (tree x : used)
12264     mark_used (x);
12265 
12266   return type;
12267 }
12268 
12269 /* Wrapper for instantiate_class_template_1.  */
12270 
12271 tree
instantiate_class_template(tree type)12272 instantiate_class_template (tree type)
12273 {
12274   tree ret;
12275   timevar_push (TV_TEMPLATE_INST);
12276   ret = instantiate_class_template_1 (type);
12277   timevar_pop (TV_TEMPLATE_INST);
12278   return ret;
12279 }
12280 
12281 tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)12282 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12283 {
12284   tree r;
12285 
12286   if (!t)
12287     r = t;
12288   else if (TYPE_P (t))
12289     r = tsubst (t, args, complain, in_decl);
12290   else
12291     {
12292       if (!(complain & tf_warning))
12293 	++c_inhibit_evaluation_warnings;
12294       r = tsubst_expr (t, args, complain, in_decl,
12295 		       /*integral_constant_expression_p=*/true);
12296       if (!(complain & tf_warning))
12297 	--c_inhibit_evaluation_warnings;
12298     }
12299 
12300   return r;
12301 }
12302 
12303 /* Given a function parameter pack TMPL_PARM and some function parameters
12304    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12305    and set *SPEC_P to point at the next point in the list.  */
12306 
12307 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)12308 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12309 {
12310   /* Collect all of the extra "packed" parameters into an
12311      argument pack.  */
12312   tree argpack;
12313   tree spec_parm = *spec_p;
12314   int len;
12315 
12316   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12317     if (tmpl_parm
12318 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12319       break;
12320 
12321   spec_parm = *spec_p;
12322   if (len == 1 && DECL_PACK_P (spec_parm))
12323     {
12324       /* The instantiation is still a parameter pack; don't wrap it in a
12325 	 NONTYPE_ARGUMENT_PACK.  */
12326       argpack = spec_parm;
12327       spec_parm = DECL_CHAIN (spec_parm);
12328     }
12329   else
12330     {
12331       /* Fill in PARMVEC with all of the parameters.  */
12332       tree parmvec = make_tree_vec (len);
12333       argpack = make_node (NONTYPE_ARGUMENT_PACK);
12334       for (int i = 0; i < len; i++)
12335 	{
12336 	  tree elt = spec_parm;
12337 	  if (DECL_PACK_P (elt))
12338 	    elt = make_pack_expansion (elt);
12339 	  TREE_VEC_ELT (parmvec, i) = elt;
12340 	  spec_parm = DECL_CHAIN (spec_parm);
12341 	}
12342 
12343       /* Build the argument packs.  */
12344       SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12345     }
12346   *spec_p = spec_parm;
12347 
12348   return argpack;
12349 }
12350 
12351 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12352    NONTYPE_ARGUMENT_PACK.  */
12353 
12354 static tree
make_fnparm_pack(tree spec_parm)12355 make_fnparm_pack (tree spec_parm)
12356 {
12357   return extract_fnparm_pack (NULL_TREE, &spec_parm);
12358 }
12359 
12360 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12361    pack expansion with no extra args, 2 if it has extra args, or 0
12362    if it is not a pack expansion.  */
12363 
12364 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)12365 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12366 {
12367   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12368     /* We're being called before this happens in tsubst_pack_expansion.  */
12369     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12370   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12371   if (i >= TREE_VEC_LENGTH (vec))
12372     return 0;
12373   tree elt = TREE_VEC_ELT (vec, i);
12374   if (DECL_P (elt))
12375     /* A decl pack is itself an expansion.  */
12376     elt = TREE_TYPE (elt);
12377   if (!PACK_EXPANSION_P (elt))
12378     return 0;
12379   if (PACK_EXPANSION_EXTRA_ARGS (elt))
12380     return 2;
12381   return 1;
12382 }
12383 
12384 
12385 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12386 
12387 static tree
make_argument_pack_select(tree arg_pack,unsigned index)12388 make_argument_pack_select (tree arg_pack, unsigned index)
12389 {
12390   tree aps = make_node (ARGUMENT_PACK_SELECT);
12391 
12392   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12393   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12394 
12395   return aps;
12396 }
12397 
12398 /*  This is a subroutine of tsubst_pack_expansion.
12399 
12400     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12401     mechanism to store the (non complete list of) arguments of the
12402     substitution and return a non substituted pack expansion, in order
12403     to wait for when we have enough arguments to really perform the
12404     substitution.  */
12405 
12406 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)12407 use_pack_expansion_extra_args_p (tree parm_packs,
12408 				 int arg_pack_len,
12409 				 bool has_empty_arg)
12410 {
12411   /* If one pack has an expansion and another pack has a normal
12412      argument or if one pack has an empty argument and an another
12413      one hasn't then tsubst_pack_expansion cannot perform the
12414      substitution and need to fall back on the
12415      PACK_EXPANSION_EXTRA mechanism.  */
12416   if (parm_packs == NULL_TREE)
12417     return false;
12418   else if (has_empty_arg)
12419     {
12420       /* If all the actual packs are pack expansions, we can still
12421 	 subsitute directly.  */
12422       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12423 	{
12424 	  tree a = TREE_VALUE (p);
12425 	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12426 	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12427 	  a = ARGUMENT_PACK_ARGS (a);
12428 	  if (TREE_VEC_LENGTH (a) == 1)
12429 	    a = TREE_VEC_ELT (a, 0);
12430 	  if (PACK_EXPANSION_P (a))
12431 	    continue;
12432 	  return true;
12433 	}
12434       return false;
12435     }
12436 
12437   for (int i = 0 ; i < arg_pack_len; ++i)
12438     {
12439       bool has_expansion_arg = false;
12440       bool has_non_expansion_arg = false;
12441       for (tree parm_pack = parm_packs;
12442 	   parm_pack;
12443 	   parm_pack = TREE_CHAIN (parm_pack))
12444 	{
12445 	  tree arg = TREE_VALUE (parm_pack);
12446 
12447 	  int exp = argument_pack_element_is_expansion_p (arg, i);
12448 	  if (exp == 2)
12449 	    /* We can't substitute a pack expansion with extra args into
12450 	       our pattern.  */
12451 	    return true;
12452 	  else if (exp)
12453 	    has_expansion_arg = true;
12454 	  else
12455 	    has_non_expansion_arg = true;
12456 	}
12457 
12458       if (has_expansion_arg && has_non_expansion_arg)
12459 	{
12460 	  gcc_checking_assert (false);
12461 	  return true;
12462 	}
12463     }
12464   return false;
12465 }
12466 
12467 /* [temp.variadic]/6 says that:
12468 
12469        The instantiation of a pack expansion [...]
12470        produces a list E1,E2, ..., En, where N is the number of elements
12471        in the pack expansion parameters.
12472 
12473    This subroutine of tsubst_pack_expansion produces one of these Ei.
12474 
12475    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12476    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12477    PATTERN, and each TREE_VALUE is its corresponding argument pack.
12478    INDEX is the index 'i' of the element Ei to produce.  ARGS,
12479    COMPLAIN, and IN_DECL are the same parameters as for the
12480    tsubst_pack_expansion function.
12481 
12482    The function returns the resulting Ei upon successful completion,
12483    or error_mark_node.
12484 
12485    Note that this function possibly modifies the ARGS parameter, so
12486    it's the responsibility of the caller to restore it.  */
12487 
12488 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)12489 gen_elem_of_pack_expansion_instantiation (tree pattern,
12490 					  tree parm_packs,
12491 					  unsigned index,
12492 					  tree args /* This parm gets
12493 						       modified.  */,
12494 					  tsubst_flags_t complain,
12495 					  tree in_decl)
12496 {
12497   tree t;
12498   bool ith_elem_is_expansion = false;
12499 
12500   /* For each parameter pack, change the substitution of the parameter
12501      pack to the ith argument in its argument pack, then expand the
12502      pattern.  */
12503   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12504     {
12505       tree parm = TREE_PURPOSE (pack);
12506       tree arg_pack = TREE_VALUE (pack);
12507       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
12508 
12509       ith_elem_is_expansion |=
12510 	argument_pack_element_is_expansion_p (arg_pack, index);
12511 
12512       /* Select the Ith argument from the pack.  */
12513       if (TREE_CODE (parm) == PARM_DECL
12514 	  || VAR_P (parm)
12515 	  || TREE_CODE (parm) == FIELD_DECL)
12516 	{
12517 	  if (index == 0)
12518 	    {
12519 	      aps = make_argument_pack_select (arg_pack, index);
12520 	      if (!mark_used (parm, complain) && !(complain & tf_error))
12521 		return error_mark_node;
12522 	      register_local_specialization (aps, parm);
12523 	    }
12524 	  else
12525 	    aps = retrieve_local_specialization (parm);
12526 	}
12527       else
12528 	{
12529 	  int idx, level;
12530 	  template_parm_level_and_index (parm, &level, &idx);
12531 
12532 	  if (index == 0)
12533 	    {
12534 	      aps = make_argument_pack_select (arg_pack, index);
12535 	      /* Update the corresponding argument.  */
12536 	      TMPL_ARG (args, level, idx) = aps;
12537 	    }
12538 	  else
12539 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
12540 	    aps = TMPL_ARG (args, level, idx);
12541 	}
12542       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12543     }
12544 
12545   /* Substitute into the PATTERN with the (possibly altered)
12546      arguments.  */
12547   if (pattern == in_decl)
12548     /* Expanding a fixed parameter pack from
12549        coerce_template_parameter_pack.  */
12550     t = tsubst_decl (pattern, args, complain);
12551   else if (pattern == error_mark_node)
12552     t = error_mark_node;
12553   else if (!TYPE_P (pattern))
12554     t = tsubst_expr (pattern, args, complain, in_decl,
12555 		     /*integral_constant_expression_p=*/false);
12556   else
12557     t = tsubst (pattern, args, complain, in_decl);
12558 
12559   /*  If the Ith argument pack element is a pack expansion, then
12560       the Ith element resulting from the substituting is going to
12561       be a pack expansion as well.  */
12562   if (ith_elem_is_expansion)
12563     t = make_pack_expansion (t, complain);
12564 
12565   return t;
12566 }
12567 
12568 /* When the unexpanded parameter pack in a fold expression expands to an empty
12569    sequence, the value of the expression is as follows; the program is
12570    ill-formed if the operator is not listed in this table.
12571 
12572    &&	true
12573    ||	false
12574    ,	void()  */
12575 
12576 tree
expand_empty_fold(tree t,tsubst_flags_t complain)12577 expand_empty_fold (tree t, tsubst_flags_t complain)
12578 {
12579   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12580   if (!FOLD_EXPR_MODIFY_P (t))
12581     switch (code)
12582       {
12583       case TRUTH_ANDIF_EXPR:
12584 	return boolean_true_node;
12585       case TRUTH_ORIF_EXPR:
12586 	return boolean_false_node;
12587       case COMPOUND_EXPR:
12588 	return void_node;
12589       default:
12590 	break;
12591       }
12592 
12593   if (complain & tf_error)
12594     error_at (location_of (t),
12595 	      "fold of empty expansion over %O", code);
12596   return error_mark_node;
12597 }
12598 
12599 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12600    form an expression that combines the two terms using the
12601    operator of T. */
12602 
12603 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)12604 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12605 {
12606   tree op = FOLD_EXPR_OP (t);
12607   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
12608 
12609   // Handle compound assignment operators.
12610   if (FOLD_EXPR_MODIFY_P (t))
12611     return build_x_modify_expr (input_location, left, code, right, complain);
12612 
12613   warning_sentinel s(warn_parentheses);
12614   switch (code)
12615     {
12616     case COMPOUND_EXPR:
12617       return build_x_compound_expr (input_location, left, right, complain);
12618     default:
12619       return build_x_binary_op (input_location, code,
12620                                 left, TREE_CODE (left),
12621                                 right, TREE_CODE (right),
12622                                 /*overload=*/NULL,
12623                                 complain);
12624     }
12625 }
12626 
12627 /* Substitute ARGS into the pack of a fold expression T. */
12628 
12629 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)12630 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12631 {
12632   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12633 }
12634 
12635 /* Substitute ARGS into the pack of a fold expression T. */
12636 
12637 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)12638 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12639 {
12640   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12641 }
12642 
12643 /* Expand a PACK of arguments into a grouped as left fold.
12644    Given a pack containing elements A0, A1, ..., An and an
12645    operator @, this builds the expression:
12646 
12647       ((A0 @ A1) @ A2) ... @ An
12648 
12649    Note that PACK must not be empty.
12650 
12651    The operator is defined by the original fold expression T. */
12652 
12653 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)12654 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12655 {
12656   tree left = TREE_VEC_ELT (pack, 0);
12657   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12658     {
12659       tree right = TREE_VEC_ELT (pack, i);
12660       left = fold_expression (t, left, right, complain);
12661     }
12662   return left;
12663 }
12664 
12665 /* Substitute into a unary left fold expression. */
12666 
12667 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12668 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12669                         tree in_decl)
12670 {
12671   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12672   if (pack == error_mark_node)
12673     return error_mark_node;
12674   if (PACK_EXPANSION_P (pack))
12675     {
12676       tree r = copy_node (t);
12677       FOLD_EXPR_PACK (r) = pack;
12678       return r;
12679     }
12680   if (TREE_VEC_LENGTH (pack) == 0)
12681     return expand_empty_fold (t, complain);
12682   else
12683     return expand_left_fold (t, pack, complain);
12684 }
12685 
12686 /* Substitute into a binary left fold expression.
12687 
12688    Do ths by building a single (non-empty) vector of argumnts and
12689    building the expression from those elements. */
12690 
12691 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12692 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12693                          tree in_decl)
12694 {
12695   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12696   if (pack == error_mark_node)
12697     return error_mark_node;
12698   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12699   if (init == error_mark_node)
12700     return error_mark_node;
12701 
12702   if (PACK_EXPANSION_P (pack))
12703     {
12704       tree r = copy_node (t);
12705       FOLD_EXPR_PACK (r) = pack;
12706       FOLD_EXPR_INIT (r) = init;
12707       return r;
12708     }
12709 
12710   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12711   TREE_VEC_ELT (vec, 0) = init;
12712   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12713     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12714 
12715   return expand_left_fold (t, vec, complain);
12716 }
12717 
12718 /* Expand a PACK of arguments into a grouped as right fold.
12719    Given a pack containing elementns A0, A1, ..., and an
12720    operator @, this builds the expression:
12721 
12722       A0@ ... (An-2 @ (An-1 @ An))
12723 
12724    Note that PACK must not be empty.
12725 
12726    The operator is defined by the original fold expression T. */
12727 
12728 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)12729 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12730 {
12731   // Build the expression.
12732   int n = TREE_VEC_LENGTH (pack);
12733   tree right = TREE_VEC_ELT (pack, n - 1);
12734   for (--n; n != 0; --n)
12735     {
12736       tree left = TREE_VEC_ELT (pack, n - 1);
12737       right = fold_expression (t, left, right, complain);
12738     }
12739   return right;
12740 }
12741 
12742 /* Substitute into a unary right fold expression. */
12743 
12744 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12745 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12746                          tree in_decl)
12747 {
12748   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12749   if (pack == error_mark_node)
12750     return error_mark_node;
12751   if (PACK_EXPANSION_P (pack))
12752     {
12753       tree r = copy_node (t);
12754       FOLD_EXPR_PACK (r) = pack;
12755       return r;
12756     }
12757   if (TREE_VEC_LENGTH (pack) == 0)
12758     return expand_empty_fold (t, complain);
12759   else
12760     return expand_right_fold (t, pack, complain);
12761 }
12762 
12763 /* Substitute into a binary right fold expression.
12764 
12765    Do ths by building a single (non-empty) vector of arguments and
12766    building the expression from those elements. */
12767 
12768 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12769 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12770                          tree in_decl)
12771 {
12772   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12773   if (pack == error_mark_node)
12774     return error_mark_node;
12775   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12776   if (init == error_mark_node)
12777     return error_mark_node;
12778 
12779   if (PACK_EXPANSION_P (pack))
12780     {
12781       tree r = copy_node (t);
12782       FOLD_EXPR_PACK (r) = pack;
12783       FOLD_EXPR_INIT (r) = init;
12784       return r;
12785     }
12786 
12787   int n = TREE_VEC_LENGTH (pack);
12788   tree vec = make_tree_vec (n + 1);
12789   for (int i = 0; i < n; ++i)
12790     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12791   TREE_VEC_ELT (vec, n) = init;
12792 
12793   return expand_right_fold (t, vec, complain);
12794 }
12795 
12796 /* Walk through the pattern of a pack expansion, adding everything in
12797    local_specializations to a list.  */
12798 
12799 class el_data
12800 {
12801 public:
12802   /* Set of variables declared within the pattern.  */
12803   hash_set<tree> internal;
12804   /* Set of AST nodes that have been visited by the traversal.  */
12805   hash_set<tree> visited;
12806   /* List of local_specializations used within the pattern.  */
12807   tree extra;
12808   tsubst_flags_t complain;
12809 
el_data(tsubst_flags_t c)12810   el_data (tsubst_flags_t c)
12811     : extra (NULL_TREE), complain (c) {}
12812 };
12813 static tree
extract_locals_r(tree * tp,int *,void * data_)12814 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12815 {
12816   el_data &data = *reinterpret_cast<el_data*>(data_);
12817   tree *extra = &data.extra;
12818   tsubst_flags_t complain = data.complain;
12819 
12820   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12821     /* Remember local typedefs (85214).  */
12822     tp = &TYPE_NAME (*tp);
12823 
12824   if (TREE_CODE (*tp) == DECL_EXPR)
12825     {
12826       tree decl = DECL_EXPR_DECL (*tp);
12827       data.internal.add (decl);
12828       if (VAR_P (decl)
12829 	  && DECL_DECOMPOSITION_P (decl)
12830 	  && TREE_TYPE (decl) != error_mark_node)
12831 	{
12832 	  gcc_assert (DECL_NAME (decl) == NULL_TREE);
12833 	  for (tree decl2 = DECL_CHAIN (decl);
12834 	       decl2
12835 	       && VAR_P (decl2)
12836 	       && DECL_DECOMPOSITION_P (decl2)
12837 	       && DECL_NAME (decl2)
12838 	       && TREE_TYPE (decl2) != error_mark_node;
12839 	       decl2 = DECL_CHAIN (decl2))
12840 	    {
12841 	      gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
12842 	      data.internal.add (decl2);
12843 	    }
12844 	}
12845     }
12846   else if (TREE_CODE (*tp) == LAMBDA_EXPR)
12847     {
12848       /* Since we defer implicit capture, look in the parms and body.  */
12849       tree fn = lambda_function (*tp);
12850       cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
12851 		    &data.visited);
12852       cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
12853 		    &data.visited);
12854     }
12855   else if (tree spec = retrieve_local_specialization (*tp))
12856     {
12857       if (data.internal.contains (*tp))
12858 	/* Don't mess with variables declared within the pattern.  */
12859 	return NULL_TREE;
12860       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12861 	{
12862 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12863 	  tree args = ARGUMENT_PACK_ARGS (spec);
12864 	  if (TREE_VEC_LENGTH (args) == 1)
12865 	    {
12866 	      tree elt = TREE_VEC_ELT (args, 0);
12867 	      if (PACK_EXPANSION_P (elt))
12868 		elt = PACK_EXPANSION_PATTERN (elt);
12869 	      if (DECL_PACK_P (elt))
12870 		spec = elt;
12871 	    }
12872 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12873 	    {
12874 	      /* Handle lambda capture here, since we aren't doing any
12875 		 substitution now, and so tsubst_copy won't call
12876 		 process_outer_var_ref.  */
12877 	      tree args = ARGUMENT_PACK_ARGS (spec);
12878 	      int len = TREE_VEC_LENGTH (args);
12879 	      for (int i = 0; i < len; ++i)
12880 		{
12881 		  tree arg = TREE_VEC_ELT (args, i);
12882 		  tree carg = arg;
12883 		  if (outer_automatic_var_p (arg))
12884 		    carg = process_outer_var_ref (arg, complain);
12885 		  if (carg != arg)
12886 		    {
12887 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12888 			 proxies.  */
12889 		      if (i == 0)
12890 			{
12891 			  spec = copy_node (spec);
12892 			  args = copy_node (args);
12893 			  SET_ARGUMENT_PACK_ARGS (spec, args);
12894 			  register_local_specialization (spec, *tp);
12895 			}
12896 		      TREE_VEC_ELT (args, i) = carg;
12897 		    }
12898 		}
12899 	    }
12900 	}
12901       if (outer_automatic_var_p (spec))
12902 	spec = process_outer_var_ref (spec, complain);
12903       *extra = tree_cons (*tp, spec, *extra);
12904     }
12905   return NULL_TREE;
12906 }
12907 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)12908 extract_local_specs (tree pattern, tsubst_flags_t complain)
12909 {
12910   el_data data (complain);
12911   cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
12912   return data.extra;
12913 }
12914 
12915 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12916    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12917 
12918 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12919 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12920 {
12921   /* Make a copy of the extra arguments so that they won't get changed
12922      out from under us.  */
12923   tree extra = copy_template_args (args);
12924   if (local_specializations)
12925     if (tree locals = extract_local_specs (pattern, complain))
12926       extra = tree_cons (NULL_TREE, extra, locals);
12927   return extra;
12928 }
12929 
12930 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12931    normal template args to ARGS.  */
12932 
12933 tree
add_extra_args(tree extra,tree args,tsubst_flags_t complain,tree in_decl)12934 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
12935 {
12936   if (extra && TREE_CODE (extra) == TREE_LIST)
12937     {
12938       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12939 	{
12940 	  /* The partial instantiation involved local declarations collected in
12941 	     extract_local_specs; map from the general template to our local
12942 	     context.  */
12943 	  tree gen = TREE_PURPOSE (elt);
12944 	  tree inst = TREE_VALUE (elt);
12945 	  if (DECL_P (inst))
12946 	    if (tree local = retrieve_local_specialization (inst))
12947 	      inst = local;
12948 	  /* else inst is already a full instantiation of the pack.  */
12949 	  register_local_specialization (inst, gen);
12950 	}
12951       gcc_assert (!TREE_PURPOSE (extra));
12952       extra = TREE_VALUE (extra);
12953     }
12954   if (uses_template_parms (extra))
12955     {
12956       /* This can happen after dependent substitution into a
12957 	 requires-expr or a lambda that uses constexpr if.  */
12958       extra = tsubst_template_args (extra, args, complain, in_decl);
12959       args = add_outermost_template_args (args, extra);
12960     }
12961   else
12962     args = add_to_template_args (extra, args);
12963   return args;
12964 }
12965 
12966 /* Substitute ARGS into T, which is an pack expansion
12967    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12968    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12969    (if only a partial substitution could be performed) or
12970    ERROR_MARK_NODE if there was an error.  */
12971 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12972 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12973 		       tree in_decl)
12974 {
12975   tree pattern;
12976   tree pack, packs = NULL_TREE;
12977   bool unsubstituted_packs = false;
12978   int i, len = -1;
12979   tree result;
12980   bool need_local_specializations = false;
12981   int levels;
12982 
12983   gcc_assert (PACK_EXPANSION_P (t));
12984   pattern = PACK_EXPANSION_PATTERN (t);
12985 
12986   /* Add in any args remembered from an earlier partial instantiation.  */
12987   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
12988 
12989   levels = TMPL_ARGS_DEPTH (args);
12990 
12991   /* Determine the argument packs that will instantiate the parameter
12992      packs used in the expansion expression. While we're at it,
12993      compute the number of arguments to be expanded and make sure it
12994      is consistent.  */
12995   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12996        pack = TREE_CHAIN (pack))
12997     {
12998       tree parm_pack = TREE_VALUE (pack);
12999       tree arg_pack = NULL_TREE;
13000       tree orig_arg = NULL_TREE;
13001       int level = 0;
13002 
13003       if (TREE_CODE (parm_pack) == BASES)
13004 	{
13005 	  gcc_assert (parm_pack == pattern);
13006 	  if (BASES_DIRECT (parm_pack))
13007 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13008 							args, complain,
13009 							in_decl, false),
13010 					   complain);
13011 	  else
13012 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13013 						 args, complain, in_decl,
13014 						 false), complain);
13015 	}
13016       else if (builtin_pack_call_p (parm_pack))
13017 	{
13018 	  if (parm_pack != pattern)
13019 	    {
13020 	      if (complain & tf_error)
13021 		sorry ("%qE is not the entire pattern of the pack expansion",
13022 		       parm_pack);
13023 	      return error_mark_node;
13024 	    }
13025 	  return expand_builtin_pack_call (parm_pack, args,
13026 					   complain, in_decl);
13027 	}
13028       else if (TREE_CODE (parm_pack) == PARM_DECL)
13029 	{
13030 	  /* We know we have correct local_specializations if this
13031 	     expansion is at function scope, or if we're dealing with a
13032 	     local parameter in a requires expression; for the latter,
13033 	     tsubst_requires_expr set it up appropriately.  */
13034 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13035 	    arg_pack = retrieve_local_specialization (parm_pack);
13036 	  else
13037 	    /* We can't rely on local_specializations for a parameter
13038 	       name used later in a function declaration (such as in a
13039 	       late-specified return type).  Even if it exists, it might
13040 	       have the wrong value for a recursive call.  */
13041 	    need_local_specializations = true;
13042 
13043 	  if (!arg_pack)
13044 	    {
13045 	      /* This parameter pack was used in an unevaluated context.  Just
13046 		 make a dummy decl, since it's only used for its type.  */
13047 	      ++cp_unevaluated_operand;
13048 	      arg_pack = tsubst_decl (parm_pack, args, complain);
13049 	      --cp_unevaluated_operand;
13050 	      if (arg_pack && DECL_PACK_P (arg_pack))
13051 		/* Partial instantiation of the parm_pack, we can't build
13052 		   up an argument pack yet.  */
13053 		arg_pack = NULL_TREE;
13054 	      else
13055 		arg_pack = make_fnparm_pack (arg_pack);
13056 	    }
13057 	  else if (DECL_PACK_P (arg_pack))
13058 	    /* This argument pack isn't fully instantiated yet.  */
13059 	    arg_pack = NULL_TREE;
13060 	}
13061       else if (is_capture_proxy (parm_pack))
13062 	{
13063 	  arg_pack = retrieve_local_specialization (parm_pack);
13064 	  if (DECL_PACK_P (arg_pack))
13065 	    arg_pack = NULL_TREE;
13066 	}
13067       else
13068         {
13069 	  int idx;
13070           template_parm_level_and_index (parm_pack, &level, &idx);
13071           if (level <= levels)
13072             arg_pack = TMPL_ARG (args, level, idx);
13073 
13074 	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13075 	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13076 	    arg_pack = NULL_TREE;
13077         }
13078 
13079       orig_arg = arg_pack;
13080       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13081 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13082 
13083       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13084 	/* This can only happen if we forget to expand an argument
13085 	   pack somewhere else. Just return an error, silently.  */
13086 	{
13087 	  result = make_tree_vec (1);
13088 	  TREE_VEC_ELT (result, 0) = error_mark_node;
13089 	  return result;
13090 	}
13091 
13092       if (arg_pack)
13093         {
13094           int my_len =
13095             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13096 
13097 	  /* Don't bother trying to do a partial substitution with
13098 	     incomplete packs; we'll try again after deduction.  */
13099           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13100             return t;
13101 
13102           if (len < 0)
13103 	    len = my_len;
13104 	  else if (len != my_len)
13105             {
13106 	      if (!(complain & tf_error))
13107 		/* Fail quietly.  */;
13108               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13109                 error ("mismatched argument pack lengths while expanding %qT",
13110                        pattern);
13111               else
13112                 error ("mismatched argument pack lengths while expanding %qE",
13113                        pattern);
13114               return error_mark_node;
13115             }
13116 
13117           /* Keep track of the parameter packs and their corresponding
13118              argument packs.  */
13119           packs = tree_cons (parm_pack, arg_pack, packs);
13120           TREE_TYPE (packs) = orig_arg;
13121         }
13122       else
13123 	{
13124 	  /* We can't substitute for this parameter pack.  We use a flag as
13125 	     well as the missing_level counter because function parameter
13126 	     packs don't have a level.  */
13127 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
13128 	  unsubstituted_packs = true;
13129 	}
13130     }
13131 
13132   /* If the expansion is just T..., return the matching argument pack, unless
13133      we need to call convert_from_reference on all the elements.  This is an
13134      important optimization; see c++/68422.  */
13135   if (!unsubstituted_packs
13136       && TREE_PURPOSE (packs) == pattern)
13137     {
13138       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13139 
13140       /* If the argument pack is a single pack expansion, pull it out.  */
13141       if (TREE_VEC_LENGTH (args) == 1
13142 	  && pack_expansion_args_count (args))
13143 	return TREE_VEC_ELT (args, 0);
13144 
13145       /* Types need no adjustment, nor does sizeof..., and if we still have
13146 	 some pack expansion args we won't do anything yet.  */
13147       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13148 	  || PACK_EXPANSION_SIZEOF_P (t)
13149 	  || pack_expansion_args_count (args))
13150 	return args;
13151       /* Also optimize expression pack expansions if we can tell that the
13152 	 elements won't have reference type.  */
13153       tree type = TREE_TYPE (pattern);
13154       if (type && !TYPE_REF_P (type)
13155 	  && !PACK_EXPANSION_P (type)
13156 	  && !WILDCARD_TYPE_P (type))
13157 	return args;
13158       /* Otherwise use the normal path so we get convert_from_reference.  */
13159     }
13160 
13161   /* We cannot expand this expansion expression, because we don't have
13162      all of the argument packs we need.  */
13163   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
13164     {
13165       /* We got some full packs, but we can't substitute them in until we
13166 	 have values for all the packs.  So remember these until then.  */
13167 
13168       t = make_pack_expansion (pattern, complain);
13169       PACK_EXPANSION_EXTRA_ARGS (t)
13170 	= build_extra_args (pattern, args, complain);
13171       return t;
13172     }
13173 
13174   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13175      type, so create our own local specializations map; the current map is
13176      either NULL or (in the case of recursive unification) might have
13177      bindings that we don't want to use or alter.  */
13178   local_specialization_stack lss (need_local_specializations
13179 				  ? lss_blank : lss_nop);
13180 
13181   if (unsubstituted_packs)
13182     {
13183       /* There were no real arguments, we're just replacing a parameter
13184 	 pack with another version of itself. Substitute into the
13185 	 pattern and return a PACK_EXPANSION_*. The caller will need to
13186 	 deal with that.  */
13187       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13188 	result = tsubst_expr (pattern, args, complain, in_decl,
13189 			 /*integral_constant_expression_p=*/false);
13190       else
13191 	result = tsubst (pattern, args, complain, in_decl);
13192       result = make_pack_expansion (result, complain);
13193       PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13194       PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13195       if (PACK_EXPANSION_AUTO_P (t))
13196 	{
13197 	  /* This is a fake auto... pack expansion created in add_capture with
13198 	     _PACKS that don't appear in the pattern.  Copy one over.  */
13199 	  packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13200 	  pack = retrieve_local_specialization (TREE_VALUE (packs));
13201 	  gcc_checking_assert (DECL_PACK_P (pack));
13202 	  PACK_EXPANSION_PARAMETER_PACKS (result)
13203 	    = build_tree_list (NULL_TREE, pack);
13204 	  PACK_EXPANSION_AUTO_P (result) = true;
13205 	}
13206       return result;
13207     }
13208 
13209   gcc_assert (len >= 0);
13210 
13211   /* For each argument in each argument pack, substitute into the
13212      pattern.  */
13213   result = make_tree_vec (len);
13214   tree elem_args = copy_template_args (args);
13215   for (i = 0; i < len; ++i)
13216     {
13217       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13218 						    i,
13219 						    elem_args, complain,
13220 						    in_decl);
13221       TREE_VEC_ELT (result, i) = t;
13222       if (t == error_mark_node)
13223 	{
13224 	  result = error_mark_node;
13225 	  break;
13226 	}
13227     }
13228 
13229   /* Update ARGS to restore the substitution from parameter packs to
13230      their argument packs.  */
13231   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13232     {
13233       tree parm = TREE_PURPOSE (pack);
13234 
13235       if (TREE_CODE (parm) == PARM_DECL
13236 	  || VAR_P (parm)
13237 	  || TREE_CODE (parm) == FIELD_DECL)
13238         register_local_specialization (TREE_TYPE (pack), parm);
13239       else
13240         {
13241           int idx, level;
13242 
13243 	  if (TREE_VALUE (pack) == NULL_TREE)
13244 	    continue;
13245 
13246           template_parm_level_and_index (parm, &level, &idx);
13247 
13248           /* Update the corresponding argument.  */
13249           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13250             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13251               TREE_TYPE (pack);
13252           else
13253             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13254         }
13255     }
13256 
13257   /* If the dependent pack arguments were such that we end up with only a
13258      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13259   if (len == 1 && TREE_CODE (result) == TREE_VEC
13260       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13261     return TREE_VEC_ELT (result, 0);
13262 
13263   return result;
13264 }
13265 
13266 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
13267    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
13268    parameter packs; all parms generated from a function parameter pack will
13269    have the same DECL_PARM_INDEX.  */
13270 
13271 tree
get_pattern_parm(tree parm,tree tmpl)13272 get_pattern_parm (tree parm, tree tmpl)
13273 {
13274   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
13275   tree patparm;
13276 
13277   if (DECL_ARTIFICIAL (parm))
13278     {
13279       for (patparm = DECL_ARGUMENTS (pattern);
13280 	   patparm; patparm = DECL_CHAIN (patparm))
13281 	if (DECL_ARTIFICIAL (patparm)
13282 	    && DECL_NAME (parm) == DECL_NAME (patparm))
13283 	  break;
13284     }
13285   else
13286     {
13287       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
13288       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
13289       gcc_assert (DECL_PARM_INDEX (patparm)
13290 		  == DECL_PARM_INDEX (parm));
13291     }
13292 
13293   return patparm;
13294 }
13295 
13296 /* Make an argument pack out of the TREE_VEC VEC.  */
13297 
13298 static tree
make_argument_pack(tree vec)13299 make_argument_pack (tree vec)
13300 {
13301   tree pack;
13302 
13303   if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13304     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13305   else
13306     {
13307       pack = make_node (NONTYPE_ARGUMENT_PACK);
13308       TREE_CONSTANT (pack) = 1;
13309     }
13310   SET_ARGUMENT_PACK_ARGS (pack, vec);
13311   return pack;
13312 }
13313 
13314 /* Return an exact copy of template args T that can be modified
13315    independently.  */
13316 
13317 static tree
copy_template_args(tree t)13318 copy_template_args (tree t)
13319 {
13320   if (t == error_mark_node)
13321     return t;
13322 
13323   int len = TREE_VEC_LENGTH (t);
13324   tree new_vec = make_tree_vec (len);
13325 
13326   for (int i = 0; i < len; ++i)
13327     {
13328       tree elt = TREE_VEC_ELT (t, i);
13329       if (elt && TREE_CODE (elt) == TREE_VEC)
13330 	elt = copy_template_args (elt);
13331       TREE_VEC_ELT (new_vec, i) = elt;
13332     }
13333 
13334   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13335     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13336 
13337   return new_vec;
13338 }
13339 
13340 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13341 
13342 tree
tsubst_argument_pack(tree orig_arg,tree args,tsubst_flags_t complain,tree in_decl)13343 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13344 		      tree in_decl)
13345 {
13346   /* Substitute into each of the arguments.  */
13347   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13348 					 args, complain, in_decl);
13349   tree new_arg = error_mark_node;
13350   if (pack_args != error_mark_node)
13351     {
13352       if (TYPE_P (orig_arg))
13353 	{
13354 	  new_arg = cxx_make_type (TREE_CODE (orig_arg));
13355 	  SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13356 	}
13357       else
13358 	{
13359 	  new_arg = make_node (TREE_CODE (orig_arg));
13360 	  TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13361 	}
13362 
13363       SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13364     }
13365 
13366   return new_arg;
13367 }
13368 
13369 /* Substitute ARGS into the vector or list of template arguments T.  */
13370 
13371 tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)13372 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13373 {
13374   tree orig_t = t;
13375   int len, need_new = 0, i, expanded_len_adjust = 0, out;
13376   tree *elts;
13377 
13378   if (t == error_mark_node)
13379     return error_mark_node;
13380 
13381   len = TREE_VEC_LENGTH (t);
13382   elts = XALLOCAVEC (tree, len);
13383 
13384   for (i = 0; i < len; i++)
13385     {
13386       tree orig_arg = TREE_VEC_ELT (t, i);
13387       tree new_arg;
13388 
13389       if (!orig_arg)
13390 	new_arg = NULL_TREE;
13391       else if (TREE_CODE (orig_arg) == TREE_VEC)
13392 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13393       else if (PACK_EXPANSION_P (orig_arg))
13394         {
13395           /* Substitute into an expansion expression.  */
13396           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13397 
13398           if (TREE_CODE (new_arg) == TREE_VEC)
13399             /* Add to the expanded length adjustment the number of
13400                expanded arguments. We subtract one from this
13401                measurement, because the argument pack expression
13402                itself is already counted as 1 in
13403                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13404                the argument pack is empty.  */
13405             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13406         }
13407       else if (ARGUMENT_PACK_P (orig_arg))
13408 	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13409       else
13410 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13411 
13412       if (new_arg == error_mark_node)
13413 	return error_mark_node;
13414 
13415       elts[i] = new_arg;
13416       if (new_arg != orig_arg)
13417 	need_new = 1;
13418     }
13419 
13420   if (!need_new)
13421     return t;
13422 
13423   /* Make space for the expanded arguments coming from template
13424      argument packs.  */
13425   t = make_tree_vec (len + expanded_len_adjust);
13426   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13427      arguments for a member template.
13428      In that case each TREE_VEC in ORIG_T represents a level of template
13429      arguments, and ORIG_T won't carry any non defaulted argument count.
13430      It will rather be the nested TREE_VECs that will carry one.
13431      In other words, ORIG_T carries a non defaulted argument count only
13432      if it doesn't contain any nested TREE_VEC.  */
13433   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13434     {
13435       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13436       count += expanded_len_adjust;
13437       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13438     }
13439   for (i = 0, out = 0; i < len; i++)
13440     {
13441       tree orig_arg = TREE_VEC_ELT (orig_t, i);
13442       if (orig_arg
13443 	  && (PACK_EXPANSION_P (orig_arg) || ARGUMENT_PACK_P (orig_arg))
13444           && TREE_CODE (elts[i]) == TREE_VEC)
13445         {
13446           int idx;
13447 
13448           /* Now expand the template argument pack "in place".  */
13449           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13450             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13451         }
13452       else
13453         {
13454           TREE_VEC_ELT (t, out) = elts[i];
13455           out++;
13456         }
13457     }
13458 
13459   return t;
13460 }
13461 
13462 /* Substitute ARGS into one level PARMS of template parameters.  */
13463 
13464 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)13465 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13466 {
13467   if (parms == error_mark_node)
13468     return error_mark_node;
13469 
13470   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13471 
13472   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13473     {
13474       tree tuple = TREE_VEC_ELT (parms, i);
13475 
13476       if (tuple == error_mark_node)
13477 	continue;
13478 
13479       TREE_VEC_ELT (new_vec, i) =
13480 	tsubst_template_parm (tuple, args, complain);
13481     }
13482 
13483   return new_vec;
13484 }
13485 
13486 /* Return the result of substituting ARGS into the template parameters
13487    given by PARMS.  If there are m levels of ARGS and m + n levels of
13488    PARMS, then the result will contain n levels of PARMS.  For
13489    example, if PARMS is `template <class T> template <class U>
13490    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13491    result will be `template <int*, double, class V>'.  */
13492 
13493 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)13494 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13495 {
13496   tree r = NULL_TREE;
13497   tree* new_parms;
13498 
13499   /* When substituting into a template, we must set
13500      PROCESSING_TEMPLATE_DECL as the template parameters may be
13501      dependent if they are based on one-another, and the dependency
13502      predicates are short-circuit outside of templates.  */
13503   ++processing_template_decl;
13504 
13505   for (new_parms = &r;
13506        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13507        new_parms = &(TREE_CHAIN (*new_parms)),
13508 	 parms = TREE_CHAIN (parms))
13509     {
13510       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13511 						  args, complain);
13512       *new_parms =
13513 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13514 			     - TMPL_ARGS_DEPTH (args)),
13515 		   new_vec, NULL_TREE);
13516       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13517 	= TEMPLATE_PARMS_CONSTRAINTS (parms);
13518     }
13519 
13520   --processing_template_decl;
13521 
13522   return r;
13523 }
13524 
13525 /* Return the result of substituting ARGS into one template parameter
13526    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13527    parameter and which TREE_PURPOSE is the default argument of the
13528    template parameter.  */
13529 
13530 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)13531 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13532 {
13533   tree default_value, parm_decl;
13534 
13535   if (args == NULL_TREE
13536       || t == NULL_TREE
13537       || t == error_mark_node)
13538     return t;
13539 
13540   gcc_assert (TREE_CODE (t) == TREE_LIST);
13541 
13542   default_value = TREE_PURPOSE (t);
13543   parm_decl = TREE_VALUE (t);
13544   tree constraint = TEMPLATE_PARM_CONSTRAINTS (t);
13545 
13546   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13547   if (TREE_CODE (parm_decl) == PARM_DECL
13548       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13549     parm_decl = error_mark_node;
13550   default_value = tsubst_template_arg (default_value, args,
13551 				       complain, NULL_TREE);
13552   constraint = tsubst_constraint (constraint, args, complain, NULL_TREE);
13553 
13554   tree r = build_tree_list (default_value, parm_decl);
13555   TEMPLATE_PARM_CONSTRAINTS (r) = constraint;
13556   return r;
13557 }
13558 
13559 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13560    type T.  If T is not an aggregate or enumeration type, it is
13561    handled as if by tsubst.  IN_DECL is as for tsubst.  If
13562    ENTERING_SCOPE is nonzero, T is the context for a template which
13563    we are presently tsubst'ing.  Return the substituted value.  */
13564 
13565 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)13566 tsubst_aggr_type (tree t,
13567 		  tree args,
13568 		  tsubst_flags_t complain,
13569 		  tree in_decl,
13570 		  int entering_scope)
13571 {
13572   if (t == NULL_TREE)
13573     return NULL_TREE;
13574 
13575   switch (TREE_CODE (t))
13576     {
13577     case RECORD_TYPE:
13578       if (TYPE_PTRMEMFUNC_P (t))
13579 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13580 
13581       /* Fall through.  */
13582     case ENUMERAL_TYPE:
13583     case UNION_TYPE:
13584       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13585 	{
13586 	  tree argvec;
13587 	  tree context;
13588 	  tree r;
13589 
13590 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
13591 	  cp_evaluated ev;
13592 
13593 	  /* First, determine the context for the type we are looking
13594 	     up.  */
13595 	  context = TYPE_CONTEXT (t);
13596 	  if (context && TYPE_P (context))
13597 	    {
13598 	      context = tsubst_aggr_type (context, args, complain,
13599 					  in_decl, /*entering_scope=*/1);
13600 	      /* If context is a nested class inside a class template,
13601 	         it may still need to be instantiated (c++/33959).  */
13602 	      context = complete_type (context);
13603 	    }
13604 
13605 	  /* Then, figure out what arguments are appropriate for the
13606 	     type we are trying to find.  For example, given:
13607 
13608 	       template <class T> struct S;
13609 	       template <class T, class U> void f(T, U) { S<U> su; }
13610 
13611 	     and supposing that we are instantiating f<int, double>,
13612 	     then our ARGS will be {int, double}, but, when looking up
13613 	     S we only want {double}.  */
13614 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13615 					 complain, in_decl);
13616 	  if (argvec == error_mark_node)
13617 	    r = error_mark_node;
13618 	  else if (!entering_scope
13619 		   && cxx_dialect >= cxx17 && dependent_scope_p (context))
13620 	    {
13621 	      /* See maybe_dependent_member_ref.  */
13622 	      tree name = TYPE_IDENTIFIER (t);
13623 	      tree fullname = name;
13624 	      if (instantiates_primary_template_p (t))
13625 		fullname = build_nt (TEMPLATE_ID_EXPR, name,
13626 				     INNERMOST_TEMPLATE_ARGS (argvec));
13627 	      return build_typename_type (context, name, fullname,
13628 					  typename_type);
13629 	    }
13630 	  else
13631 	    {
13632 	      r = lookup_template_class (t, argvec, in_decl, context,
13633 					 entering_scope, complain);
13634 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13635 	    }
13636 
13637 	  return r;
13638 	}
13639       else
13640 	/* This is not a template type, so there's nothing to do.  */
13641 	return t;
13642 
13643     default:
13644       return tsubst (t, args, complain, in_decl);
13645     }
13646 }
13647 
13648 static GTY((cache)) decl_tree_cache_map *defarg_inst;
13649 
13650 /* Substitute into the default argument ARG (a default argument for
13651    FN), which has the indicated TYPE.  */
13652 
13653 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)13654 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13655 			 tsubst_flags_t complain)
13656 {
13657   int errs = errorcount + sorrycount;
13658 
13659   /* This can happen in invalid code.  */
13660   if (TREE_CODE (arg) == DEFERRED_PARSE)
13661     return arg;
13662 
13663   /* Shortcut {}.  */
13664   if (BRACE_ENCLOSED_INITIALIZER_P (arg)
13665       && CONSTRUCTOR_NELTS (arg) == 0)
13666     return arg;
13667 
13668   tree parm = FUNCTION_FIRST_USER_PARM (fn);
13669   parm = chain_index (parmnum, parm);
13670   tree parmtype = TREE_TYPE (parm);
13671   if (DECL_BY_REFERENCE (parm))
13672     parmtype = TREE_TYPE (parmtype);
13673   if (parmtype == error_mark_node)
13674     return error_mark_node;
13675 
13676   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13677 
13678   tree *slot;
13679   if (defarg_inst && (slot = defarg_inst->get (parm)))
13680     return *slot;
13681 
13682   /* This default argument came from a template.  Instantiate the
13683      default argument here, not in tsubst.  In the case of
13684      something like:
13685 
13686        template <class T>
13687        struct S {
13688 	 static T t();
13689 	 void f(T = t());
13690        };
13691 
13692      we must be careful to do name lookup in the scope of S<T>,
13693      rather than in the current class.  */
13694   push_to_top_level ();
13695   push_access_scope (fn);
13696   push_deferring_access_checks (dk_no_deferred);
13697   start_lambda_scope (parm);
13698 
13699   /* The default argument expression may cause implicitly defined
13700      member functions to be synthesized, which will result in garbage
13701      collection.  We must treat this situation as if we were within
13702      the body of function so as to avoid collecting live data on the
13703      stack.  */
13704   ++function_depth;
13705   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13706 		     complain, NULL_TREE,
13707 		     /*integral_constant_expression_p=*/false);
13708   --function_depth;
13709 
13710   finish_lambda_scope ();
13711 
13712   /* Make sure the default argument is reasonable.  */
13713   arg = check_default_argument (type, arg, complain);
13714 
13715   if (errorcount+sorrycount > errs
13716       && (complain & tf_warning_or_error))
13717     inform (input_location,
13718 	    "  when instantiating default argument for call to %qD", fn);
13719 
13720   pop_deferring_access_checks ();
13721   pop_access_scope (fn);
13722   pop_from_top_level ();
13723 
13724   if (arg != error_mark_node && !cp_unevaluated_operand)
13725     {
13726       if (!defarg_inst)
13727 	defarg_inst = decl_tree_cache_map::create_ggc (37);
13728       defarg_inst->put (parm, arg);
13729     }
13730 
13731   return arg;
13732 }
13733 
13734 /* Substitute into all the default arguments for FN.  */
13735 
13736 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)13737 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13738 {
13739   tree arg;
13740   tree tmpl_args;
13741 
13742   tmpl_args = DECL_TI_ARGS (fn);
13743 
13744   /* If this function is not yet instantiated, we certainly don't need
13745      its default arguments.  */
13746   if (uses_template_parms (tmpl_args))
13747     return;
13748   /* Don't do this again for clones.  */
13749   if (DECL_CLONED_FUNCTION_P (fn))
13750     return;
13751 
13752   int i = 0;
13753   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
13754        arg;
13755        arg = TREE_CHAIN (arg), ++i)
13756     if (TREE_PURPOSE (arg))
13757       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
13758 						    TREE_VALUE (arg),
13759 						    TREE_PURPOSE (arg),
13760 						    complain);
13761 }
13762 
13763 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
13764 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
13765 
13766 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
13767 
13768 void
store_explicit_specifier(tree v,tree t)13769 store_explicit_specifier (tree v, tree t)
13770 {
13771   if (!explicit_specifier_map)
13772     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
13773   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
13774   explicit_specifier_map->put (v, t);
13775 }
13776 
13777 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
13778 
13779 static tree
lookup_explicit_specifier(tree v)13780 lookup_explicit_specifier (tree v)
13781 {
13782   return *explicit_specifier_map->get (v);
13783 }
13784 
13785 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
13786    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
13787    are ARG_TYPES, and exception specification is RAISES, and otherwise is
13788    identical to T.  */
13789 
13790 static tree
rebuild_function_or_method_type(tree t,tree return_type,tree arg_types,tree raises,tsubst_flags_t complain)13791 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
13792 				 tree raises, tsubst_flags_t complain)
13793 {
13794   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
13795 
13796   tree new_type;
13797   if (TREE_CODE (t) == FUNCTION_TYPE)
13798     {
13799       new_type = build_function_type (return_type, arg_types);
13800       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
13801     }
13802   else
13803     {
13804       tree r = TREE_TYPE (TREE_VALUE (arg_types));
13805       /* Don't pick up extra function qualifiers from the basetype.  */
13806       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
13807       if (! MAYBE_CLASS_TYPE_P (r))
13808 	{
13809 	  /* [temp.deduct]
13810 
13811 	     Type deduction may fail for any of the following
13812 	     reasons:
13813 
13814 	     -- Attempting to create "pointer to member of T" when T
13815 	     is not a class type.  */
13816 	  if (complain & tf_error)
13817 	    error ("creating pointer to member function of non-class type %qT",
13818 		   r);
13819 	  return error_mark_node;
13820 	}
13821 
13822       new_type = build_method_type_directly (r, return_type,
13823 					     TREE_CHAIN (arg_types));
13824     }
13825   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
13826 
13827   cp_ref_qualifier rqual = type_memfn_rqual (t);
13828   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13829   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
13830 }
13831 
13832 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
13833    each of its formal parameters.  If there is a disagreement then rebuild
13834    DECL's function type according to its formal parameter types, as part of a
13835    resolution for Core issues 1001/1322.  */
13836 
13837 static void
maybe_rebuild_function_decl_type(tree decl)13838 maybe_rebuild_function_decl_type (tree decl)
13839 {
13840   bool function_type_needs_rebuilding = false;
13841   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
13842     {
13843       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
13844       while (parm_type_list && parm_type_list != void_list_node)
13845 	{
13846 	  tree parm_type = TREE_VALUE (parm_type_list);
13847 	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13848 	  if (!same_type_p (parm_type, formal_parm_type_unqual))
13849 	    {
13850 	      function_type_needs_rebuilding = true;
13851 	      break;
13852 	    }
13853 
13854 	  parm_list = DECL_CHAIN (parm_list);
13855 	  parm_type_list = TREE_CHAIN (parm_type_list);
13856 	}
13857     }
13858 
13859   if (!function_type_needs_rebuilding)
13860     return;
13861 
13862   const tree fntype = TREE_TYPE (decl);
13863   tree parm_list = DECL_ARGUMENTS (decl);
13864   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
13865   tree new_parm_type_list = NULL_TREE;
13866   tree *q = &new_parm_type_list;
13867   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
13868     {
13869       *q = copy_node (old_parm_type_list);
13870       parm_list = DECL_CHAIN (parm_list);
13871       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13872       q = &TREE_CHAIN (*q);
13873     }
13874   while (old_parm_type_list && old_parm_type_list != void_list_node)
13875     {
13876       *q = copy_node (old_parm_type_list);
13877       tree *new_parm_type = &TREE_VALUE (*q);
13878       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13879       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
13880 	*new_parm_type = formal_parm_type_unqual;
13881 
13882       parm_list = DECL_CHAIN (parm_list);
13883       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13884       q = &TREE_CHAIN (*q);
13885     }
13886   if (old_parm_type_list == void_list_node)
13887     *q = void_list_node;
13888 
13889   TREE_TYPE (decl)
13890     = rebuild_function_or_method_type (fntype,
13891 				       TREE_TYPE (fntype), new_parm_type_list,
13892 				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
13893 }
13894 
13895 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
13896 
13897 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13898 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
13899 		      tree lambda_fntype)
13900 {
13901   tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
13902   hashval_t hash = 0;
13903   tree in_decl = t;
13904 
13905   /* Nobody should be tsubst'ing into non-template functions.  */
13906   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
13907 	      || DECL_LOCAL_DECL_P (t));
13908 
13909   if (DECL_LOCAL_DECL_P (t))
13910     {
13911       if (tree spec = retrieve_local_specialization (t))
13912 	return spec;
13913     }
13914   else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
13915     {
13916       /* If T is not dependent, just return it.  */
13917       if (!uses_template_parms (DECL_TI_ARGS (t))
13918 	  && !LAMBDA_FUNCTION_P (t))
13919 	return t;
13920 
13921       /* Calculate the most general template of which R is a
13922 	 specialization.  */
13923       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
13924 
13925       /* We're substituting a lambda function under tsubst_lambda_expr but not
13926 	 directly from it; find the matching function we're already inside.
13927 	 But don't do this if T is a generic lambda with a single level of
13928 	 template parms, as in that case we're doing a normal instantiation. */
13929       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
13930 	  && (!generic_lambda_fn_p (t)
13931 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
13932 	return enclosing_instantiation_of (t);
13933 
13934       /* Calculate the complete set of arguments used to
13935 	 specialize R.  */
13936       argvec = tsubst_template_args (DECL_TI_ARGS
13937 				     (DECL_TEMPLATE_RESULT
13938 				      (DECL_TI_TEMPLATE (t))),
13939 				     args, complain, in_decl);
13940       if (argvec == error_mark_node)
13941 	return error_mark_node;
13942 
13943       /* Check to see if we already have this specialization.  */
13944       if (!lambda_fntype)
13945 	{
13946 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
13947 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
13948 	    return spec;
13949 	}
13950     }
13951   else
13952     {
13953       /* This special case arises when we have something like this:
13954 
13955 	 template <class T> struct S {
13956 	 friend void f<int>(int, double);
13957 	 };
13958 
13959 	 Here, the DECL_TI_TEMPLATE for the friend declaration
13960 	 will be an IDENTIFIER_NODE.  We are being called from
13961 	 tsubst_friend_function, and we want only to create a
13962 	 new decl (R) with appropriate types so that we can call
13963 	 determine_specialization.  */
13964       gen_tmpl = NULL_TREE;
13965       argvec = NULL_TREE;
13966     }
13967 
13968   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13969 		  : NULL_TREE);
13970   tree ctx = closure ? closure : DECL_CONTEXT (t);
13971   bool member = ctx && TYPE_P (ctx);
13972 
13973   if (member && !closure)
13974     ctx = tsubst_aggr_type (ctx, args,
13975 			    complain, t, /*entering_scope=*/1);
13976 
13977   tree type = (lambda_fntype ? lambda_fntype
13978 	       : tsubst (TREE_TYPE (t), args,
13979 			 complain | tf_fndecl_type, in_decl));
13980   if (type == error_mark_node)
13981     return error_mark_node;
13982 
13983   /* If we hit excessive deduction depth, the type is bogus even if
13984      it isn't error_mark_node, so don't build a decl.  */
13985   if (excessive_deduction_depth)
13986     return error_mark_node;
13987 
13988   /* We do NOT check for matching decls pushed separately at this
13989      point, as they may not represent instantiations of this
13990      template, and in any case are considered separate under the
13991      discrete model.  */
13992   tree r = copy_decl (t);
13993   DECL_USE_TEMPLATE (r) = 0;
13994   TREE_TYPE (r) = type;
13995   /* Clear out the mangled name and RTL for the instantiation.  */
13996   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13997   SET_DECL_RTL (r, NULL);
13998   /* Leave DECL_INITIAL set on deleted instantiations.  */
13999   if (!DECL_DELETED_FN (r))
14000     DECL_INITIAL (r) = NULL_TREE;
14001   DECL_CONTEXT (r) = ctx;
14002   set_instantiating_module (r);
14003 
14004   /* Handle explicit(dependent-expr).  */
14005   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14006     {
14007       tree spec = lookup_explicit_specifier (t);
14008       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
14009 				    /*function_p=*/false,
14010 				    /*i_c_e_p=*/true);
14011       spec = build_explicit_specifier (spec, complain);
14012       DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14013     }
14014 
14015   /* OpenMP UDRs have the only argument a reference to the declared
14016      type.  We want to diagnose if the declared type is a reference,
14017      which is invalid, but as references to references are usually
14018      quietly merged, diagnose it here.  */
14019   if (DECL_OMP_DECLARE_REDUCTION_P (t))
14020     {
14021       tree argtype
14022 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14023       argtype = tsubst (argtype, args, complain, in_decl);
14024       if (TYPE_REF_P (argtype))
14025 	error_at (DECL_SOURCE_LOCATION (t),
14026 		  "reference type %qT in "
14027 		  "%<#pragma omp declare reduction%>", argtype);
14028       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14029 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14030 					  argtype);
14031     }
14032 
14033   if (member && DECL_CONV_FN_P (r))
14034     /* Type-conversion operator.  Reconstruct the name, in
14035        case it's the name of one of the template's parameters.  */
14036     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14037 
14038   tree parms = DECL_ARGUMENTS (t);
14039   if (closure)
14040     parms = DECL_CHAIN (parms);
14041   parms = tsubst (parms, args, complain, t);
14042   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14043     DECL_CONTEXT (parm) = r;
14044   if (closure)
14045     {
14046       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14047       DECL_NAME (tparm) = closure_identifier;
14048       DECL_CHAIN (tparm) = parms;
14049       parms = tparm;
14050     }
14051   DECL_ARGUMENTS (r) = parms;
14052   DECL_RESULT (r) = NULL_TREE;
14053 
14054   maybe_rebuild_function_decl_type (r);
14055 
14056   TREE_STATIC (r) = 0;
14057   TREE_PUBLIC (r) = TREE_PUBLIC (t);
14058   DECL_EXTERNAL (r) = 1;
14059   /* If this is an instantiation of a function with internal
14060      linkage, we already know what object file linkage will be
14061      assigned to the instantiation.  */
14062   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14063   DECL_DEFER_OUTPUT (r) = 0;
14064   DECL_CHAIN (r) = NULL_TREE;
14065   DECL_PENDING_INLINE_INFO (r) = 0;
14066   DECL_PENDING_INLINE_P (r) = 0;
14067   DECL_SAVED_TREE (r) = NULL_TREE;
14068   DECL_STRUCT_FUNCTION (r) = NULL;
14069   TREE_USED (r) = 0;
14070   /* We'll re-clone as appropriate in instantiate_template.  */
14071   DECL_CLONED_FUNCTION (r) = NULL_TREE;
14072 
14073   /* If we aren't complaining now, return on error before we register
14074      the specialization so that we'll complain eventually.  */
14075   if ((complain & tf_error) == 0
14076       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14077       && !grok_op_properties (r, /*complain=*/false))
14078     return error_mark_node;
14079 
14080   /* Associate the constraints directly with the instantiation. We
14081      don't substitute through the constraints; that's only done when
14082      they are checked.  */
14083   if (tree ci = get_constraints (t))
14084     set_constraints (r, ci);
14085 
14086   if (DECL_FRIEND_CONTEXT (t))
14087     SET_DECL_FRIEND_CONTEXT (r,
14088 			     tsubst (DECL_FRIEND_CONTEXT (t),
14089 				     args, complain, in_decl));
14090 
14091   if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14092 				       args, complain, in_decl))
14093     return error_mark_node;
14094 
14095   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
14096      this in the special friend case mentioned above where
14097      GEN_TMPL is NULL.  */
14098   if (gen_tmpl && !closure)
14099     {
14100       DECL_TEMPLATE_INFO (r)
14101 	= build_template_info (gen_tmpl, argvec);
14102       SET_DECL_IMPLICIT_INSTANTIATION (r);
14103 
14104       tree new_r
14105 	= register_specialization (r, gen_tmpl, argvec, false, hash);
14106       if (new_r != r)
14107 	/* We instantiated this while substituting into
14108 	   the type earlier (template/friend54.C).  */
14109 	return new_r;
14110 
14111       /* We're not supposed to instantiate default arguments
14112 	 until they are called, for a template.  But, for a
14113 	 declaration like:
14114 
14115 	 template <class T> void f ()
14116 	 { extern void g(int i = T()); }
14117 
14118 	 we should do the substitution when the template is
14119 	 instantiated.  We handle the member function case in
14120 	 instantiate_class_template since the default arguments
14121 	 might refer to other members of the class.  */
14122       if (!member
14123 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
14124 	  && !uses_template_parms (argvec))
14125 	tsubst_default_arguments (r, complain);
14126     }
14127   else if (DECL_LOCAL_DECL_P (r))
14128     {
14129       if (!cp_unevaluated_operand)
14130 	register_local_specialization (r, t);
14131     }
14132   else
14133     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14134 
14135   /* Copy the list of befriending classes.  */
14136   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14137        *friends;
14138        friends = &TREE_CHAIN (*friends))
14139     {
14140       *friends = copy_node (*friends);
14141       TREE_VALUE (*friends)
14142 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14143     }
14144 
14145   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14146     {
14147       maybe_retrofit_in_chrg (r);
14148       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14149 	return error_mark_node;
14150       /* If this is an instantiation of a member template, clone it.
14151 	 If it isn't, that'll be handled by
14152 	 clone_constructors_and_destructors.  */
14153       if (PRIMARY_TEMPLATE_P (gen_tmpl))
14154 	clone_cdtor (r, /*update_methods=*/false);
14155     }
14156   else if ((complain & tf_error) != 0
14157 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14158 	   && !grok_op_properties (r, /*complain=*/true))
14159     return error_mark_node;
14160 
14161   /* Possibly limit visibility based on template args.  */
14162   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14163   if (DECL_VISIBILITY_SPECIFIED (t))
14164     {
14165       DECL_VISIBILITY_SPECIFIED (r) = 0;
14166       DECL_ATTRIBUTES (r)
14167 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14168     }
14169   determine_visibility (r);
14170   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14171       && !processing_template_decl)
14172     defaulted_late_check (r);
14173 
14174   if (flag_openmp)
14175     if (tree attr = lookup_attribute ("omp declare variant base",
14176 				      DECL_ATTRIBUTES (r)))
14177       omp_declare_variant_finalize (r, attr);
14178 
14179   return r;
14180 }
14181 
14182 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
14183 
14184 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)14185 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14186 		      tree lambda_fntype)
14187 {
14188   /* We can get here when processing a member function template,
14189      member class template, or template template parameter.  */
14190   tree decl = DECL_TEMPLATE_RESULT (t);
14191   tree in_decl = t;
14192   tree spec;
14193   tree tmpl_args;
14194   tree full_args;
14195   tree r;
14196   hashval_t hash = 0;
14197 
14198   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14199     {
14200       /* Template template parameter is treated here.  */
14201       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14202       if (new_type == error_mark_node)
14203 	r = error_mark_node;
14204       /* If we get a real template back, return it.  This can happen in
14205 	 the context of most_specialized_partial_spec.  */
14206       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14207 	r = new_type;
14208       else
14209 	/* The new TEMPLATE_DECL was built in
14210 	   reduce_template_parm_level.  */
14211 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14212       return r;
14213     }
14214 
14215   if (!lambda_fntype)
14216     {
14217       /* We might already have an instance of this template.
14218 	 The ARGS are for the surrounding class type, so the
14219 	 full args contain the tsubst'd args for the context,
14220 	 plus the innermost args from the template decl.  */
14221       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14222 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14223 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14224       /* Because this is a template, the arguments will still be
14225 	 dependent, even after substitution.  If
14226 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
14227 	 predicates will short-circuit.  */
14228       ++processing_template_decl;
14229       full_args = tsubst_template_args (tmpl_args, args,
14230 					complain, in_decl);
14231       --processing_template_decl;
14232       if (full_args == error_mark_node)
14233 	return error_mark_node;
14234 
14235       /* If this is a default template template argument,
14236 	 tsubst might not have changed anything.  */
14237       if (full_args == tmpl_args)
14238 	return t;
14239 
14240       hash = hash_tmpl_and_args (t, full_args);
14241       spec = retrieve_specialization (t, full_args, hash);
14242       if (spec != NULL_TREE)
14243 	{
14244 	  if (TYPE_P (spec))
14245 	    /* Type partial instantiations are stored as the type by
14246 	       lookup_template_class_1, not here as the template.  */
14247 	    spec = CLASSTYPE_TI_TEMPLATE (spec);
14248 	  return spec;
14249 	}
14250     }
14251 
14252   /* Make a new template decl.  It will be similar to the
14253      original, but will record the current template arguments.
14254      We also create a new function declaration, which is just
14255      like the old one, but points to this new template, rather
14256      than the old one.  */
14257   r = copy_decl (t);
14258   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14259   DECL_CHAIN (r) = NULL_TREE;
14260 
14261   // Build new template info linking to the original template decl.
14262   if (!lambda_fntype)
14263     {
14264       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14265       SET_DECL_IMPLICIT_INSTANTIATION (r);
14266     }
14267   else
14268     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14269 
14270   /* The template parameters for this new template are all the
14271      template parameters for the old template, except the
14272      outermost level of parameters.  */
14273   auto tparm_guard = make_temp_override (current_template_parms);
14274   DECL_TEMPLATE_PARMS (r)
14275     = current_template_parms
14276     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14277 			     complain);
14278 
14279   bool class_p = false;
14280   tree inner = decl;
14281   ++processing_template_decl;
14282   if (TREE_CODE (inner) == FUNCTION_DECL)
14283     inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14284   else
14285     {
14286       if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14287 	{
14288 	  class_p = true;
14289 	  inner = TREE_TYPE (inner);
14290 	}
14291       if (class_p)
14292 	inner = tsubst_aggr_type (inner, args, complain,
14293 				  in_decl, /*entering*/1);
14294       else
14295 	inner = tsubst (inner, args, complain, in_decl);
14296     }
14297   --processing_template_decl;
14298   if (inner == error_mark_node)
14299     return error_mark_node;
14300 
14301   if (class_p)
14302     {
14303       /* For a partial specialization, we need to keep pointing to
14304 	 the primary template.  */
14305       if (!DECL_TEMPLATE_SPECIALIZATION (t))
14306 	CLASSTYPE_TI_TEMPLATE (inner) = r;
14307 
14308       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14309       inner = TYPE_MAIN_DECL (inner);
14310     }
14311   else if (lambda_fntype)
14312     {
14313       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14314       DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14315     }
14316   else
14317     {
14318       DECL_TI_TEMPLATE (inner) = r;
14319       DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14320     }
14321 
14322   DECL_TEMPLATE_RESULT (r) = inner;
14323   TREE_TYPE (r) = TREE_TYPE (inner);
14324   DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14325 
14326   if (modules_p ())
14327     {
14328       /* Propagate module information from the decl.  */
14329       DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14330       if (DECL_LANG_SPECIFIC (inner))
14331 	/* If this is a constrained template, the above tsubst of
14332 	   inner can find the unconstrained template, which may have
14333 	   come from an import.  This is ok, because we don't
14334 	   register this instantiation (see below).  */
14335 	gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14336 			     || (TEMPLATE_PARMS_CONSTRAINTS
14337 				 (DECL_TEMPLATE_PARMS (t))));
14338     }
14339 
14340   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14341   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14342 
14343   if (PRIMARY_TEMPLATE_P (t))
14344     DECL_PRIMARY_TEMPLATE (r) = r;
14345 
14346   if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14347     /* Record this non-type partial instantiation.  */
14348     register_specialization (r, t,
14349 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14350 			     false, hash);
14351 
14352   return r;
14353 }
14354 
14355 /* True if FN is the op() for a lambda in an uninstantiated template.  */
14356 
14357 bool
lambda_fn_in_template_p(tree fn)14358 lambda_fn_in_template_p (tree fn)
14359 {
14360   if (!fn || !LAMBDA_FUNCTION_P (fn))
14361     return false;
14362   tree closure = DECL_CONTEXT (fn);
14363   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14364 }
14365 
14366 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14367    which the above is true.  */
14368 
14369 bool
regenerated_lambda_fn_p(tree fn)14370 regenerated_lambda_fn_p (tree fn)
14371 {
14372   if (!fn || !LAMBDA_FUNCTION_P (fn))
14373     return false;
14374   tree closure = DECL_CONTEXT (fn);
14375   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14376   return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14377 }
14378 
14379 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14380    If T is not a regenerated LAMBDA_EXPR, return T.  */
14381 
14382 tree
most_general_lambda(tree t)14383 most_general_lambda (tree t)
14384 {
14385   while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14386     t = TI_TEMPLATE (ti);
14387   return t;
14388 }
14389 
14390 /* We're instantiating a variable from template function TCTX.  Return the
14391    corresponding current enclosing scope.  This gets complicated because lambda
14392    functions in templates are regenerated rather than instantiated, but generic
14393    lambda functions are subsequently instantiated.  */
14394 
14395 static tree
enclosing_instantiation_of(tree otctx)14396 enclosing_instantiation_of (tree otctx)
14397 {
14398   tree tctx = otctx;
14399   tree fn = current_function_decl;
14400   int lambda_count = 0;
14401 
14402   for (; tctx && (lambda_fn_in_template_p (tctx)
14403 		  || regenerated_lambda_fn_p (tctx));
14404        tctx = decl_function_context (tctx))
14405     ++lambda_count;
14406 
14407   if (!tctx)
14408     {
14409       /* Match using DECL_SOURCE_LOCATION, which is unique for all lambdas.
14410 
14411 	 For GCC 11 the above condition limits this to the previously failing
14412 	 case where all enclosing functions are lambdas (95870).  FIXME.  */
14413       for (tree ofn = fn; ofn; ofn = decl_function_context (ofn))
14414 	if (DECL_SOURCE_LOCATION (ofn) == DECL_SOURCE_LOCATION (otctx))
14415 	  return ofn;
14416       gcc_unreachable ();
14417     }
14418 
14419   for (; fn; fn = decl_function_context (fn))
14420     {
14421       tree ofn = fn;
14422       int flambda_count = 0;
14423       for (; fn && regenerated_lambda_fn_p (fn);
14424 	   fn = decl_function_context (fn))
14425 	++flambda_count;
14426       if ((fn && DECL_TEMPLATE_INFO (fn))
14427 	  ? most_general_template (fn) != most_general_template (tctx)
14428 	  : fn != tctx)
14429 	continue;
14430       if (flambda_count != lambda_count)
14431 	{
14432 	  gcc_assert (flambda_count > lambda_count);
14433 	  for (; flambda_count > lambda_count; --flambda_count)
14434 	    ofn = decl_function_context (ofn);
14435 	}
14436       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
14437 		  || DECL_CONV_FN_P (ofn));
14438       return ofn;
14439     }
14440   gcc_unreachable ();
14441 }
14442 
14443 /* Substitute the ARGS into the T, which is a _DECL.  Return the
14444    result of the substitution.  Issue error and warning messages under
14445    control of COMPLAIN.  */
14446 
14447 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)14448 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14449 {
14450 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14451   location_t saved_loc;
14452   tree r = NULL_TREE;
14453   tree in_decl = t;
14454   hashval_t hash = 0;
14455 
14456   /* Set the filename and linenumber to improve error-reporting.  */
14457   saved_loc = input_location;
14458   input_location = DECL_SOURCE_LOCATION (t);
14459 
14460   switch (TREE_CODE (t))
14461     {
14462     case TEMPLATE_DECL:
14463       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14464       break;
14465 
14466     case FUNCTION_DECL:
14467       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14468       break;
14469 
14470     case PARM_DECL:
14471       {
14472 	tree type = NULL_TREE;
14473         int i, len = 1;
14474         tree expanded_types = NULL_TREE;
14475         tree prev_r = NULL_TREE;
14476         tree first_r = NULL_TREE;
14477 
14478         if (DECL_PACK_P (t))
14479           {
14480             /* If there is a local specialization that isn't a
14481                parameter pack, it means that we're doing a "simple"
14482                substitution from inside tsubst_pack_expansion. Just
14483                return the local specialization (which will be a single
14484                parm).  */
14485             tree spec = retrieve_local_specialization (t);
14486             if (spec
14487                 && TREE_CODE (spec) == PARM_DECL
14488                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14489               RETURN (spec);
14490 
14491             /* Expand the TYPE_PACK_EXPANSION that provides the types for
14492                the parameters in this function parameter pack.  */
14493             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14494 						    complain, in_decl);
14495             if (TREE_CODE (expanded_types) == TREE_VEC)
14496               {
14497                 len = TREE_VEC_LENGTH (expanded_types);
14498 
14499                 /* Zero-length parameter packs are boring. Just substitute
14500                    into the chain.  */
14501 		if (len == 0 && !cp_unevaluated_operand)
14502                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
14503 				  TREE_CHAIN (t)));
14504               }
14505             else
14506               {
14507                 /* All we did was update the type. Make a note of that.  */
14508                 type = expanded_types;
14509                 expanded_types = NULL_TREE;
14510               }
14511           }
14512 
14513         /* Loop through all of the parameters we'll build. When T is
14514            a function parameter pack, LEN is the number of expanded
14515            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14516         r = NULL_TREE;
14517         for (i = 0; i < len; ++i)
14518           {
14519             prev_r = r;
14520             r = copy_node (t);
14521             if (DECL_TEMPLATE_PARM_P (t))
14522               SET_DECL_TEMPLATE_PARM_P (r);
14523 
14524             if (expanded_types)
14525               /* We're on the Ith parameter of the function parameter
14526                  pack.  */
14527               {
14528                 /* Get the Ith type.  */
14529                 type = TREE_VEC_ELT (expanded_types, i);
14530 
14531 		/* Rename the parameter to include the index.  */
14532 		DECL_NAME (r)
14533 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14534               }
14535             else if (!type)
14536               /* We're dealing with a normal parameter.  */
14537               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14538 
14539             type = type_decays_to (type);
14540             TREE_TYPE (r) = type;
14541             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14542 
14543             if (DECL_INITIAL (r))
14544               {
14545                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14546                   DECL_INITIAL (r) = TREE_TYPE (r);
14547                 else
14548                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14549                                              complain, in_decl);
14550               }
14551 
14552             DECL_CONTEXT (r) = NULL_TREE;
14553 
14554             if (!DECL_TEMPLATE_PARM_P (r))
14555               DECL_ARG_TYPE (r) = type_passed_as (type);
14556 
14557 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14558 						 args, complain, in_decl))
14559 	      return error_mark_node;
14560 
14561             /* Keep track of the first new parameter we
14562                generate. That's what will be returned to the
14563                caller.  */
14564             if (!first_r)
14565               first_r = r;
14566 
14567             /* Build a proper chain of parameters when substituting
14568                into a function parameter pack.  */
14569             if (prev_r)
14570               DECL_CHAIN (prev_r) = r;
14571           }
14572 
14573 	/* If cp_unevaluated_operand is set, we're just looking for a
14574 	   single dummy parameter, so don't keep going.  */
14575 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14576 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14577 				   complain, DECL_CHAIN (t));
14578 
14579         /* FIRST_R contains the start of the chain we've built.  */
14580         r = first_r;
14581       }
14582       break;
14583 
14584     case FIELD_DECL:
14585       {
14586 	tree type = NULL_TREE;
14587 	tree vec = NULL_TREE;
14588 	tree expanded_types = NULL_TREE;
14589 	int len = 1;
14590 
14591 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
14592 	  {
14593 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
14594 	       the expanded fields to instantiate_class_template_1.  */
14595             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14596 						    complain, in_decl);
14597             if (TREE_CODE (expanded_types) == TREE_VEC)
14598               {
14599                 len = TREE_VEC_LENGTH (expanded_types);
14600 		vec = make_tree_vec (len);
14601               }
14602             else
14603               {
14604                 /* All we did was update the type. Make a note of that.  */
14605                 type = expanded_types;
14606                 expanded_types = NULL_TREE;
14607               }
14608 	  }
14609 
14610 	for (int i = 0; i < len; ++i)
14611 	  {
14612 	    r = copy_decl (t);
14613 	    if (expanded_types)
14614 	      {
14615 		type = TREE_VEC_ELT (expanded_types, i);
14616 		DECL_NAME (r)
14617 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14618 	      }
14619             else if (!type)
14620               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14621 
14622 	    if (type == error_mark_node)
14623 	      RETURN (error_mark_node);
14624 	    TREE_TYPE (r) = type;
14625 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14626 
14627 	    if (DECL_C_BIT_FIELD (r))
14628 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14629 		 number of bits.  */
14630 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
14631 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14632 			       complain, in_decl,
14633 			       /*integral_constant_expression_p=*/true);
14634 	    if (DECL_INITIAL (t))
14635 	      {
14636 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
14637 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
14638 		   so that we know there is one.  */
14639 		DECL_INITIAL (r) = void_node;
14640 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14641 		retrofit_lang_decl (r);
14642 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14643 	      }
14644 	    /* We don't have to set DECL_CONTEXT here; it is set by
14645 	       finish_member_declaration.  */
14646 	    DECL_CHAIN (r) = NULL_TREE;
14647 
14648 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14649 						 args, complain, in_decl))
14650 	      return error_mark_node;
14651 
14652 	    if (vec)
14653 	      TREE_VEC_ELT (vec, i) = r;
14654 	  }
14655 
14656 	if (vec)
14657 	  r = vec;
14658       }
14659       break;
14660 
14661     case USING_DECL:
14662       /* We reach here only for member using decls.  We also need to check
14663 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
14664 	 using-declaration that designates a member of the current
14665 	 instantiation (c++/53549).  */
14666       if (DECL_DEPENDENT_P (t)
14667 	  || uses_template_parms (USING_DECL_SCOPE (t)))
14668 	{
14669 	  tree scope = USING_DECL_SCOPE (t);
14670 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14671 	  if (PACK_EXPANSION_P (scope))
14672 	    {
14673 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14674 	      int len = TREE_VEC_LENGTH (vec);
14675 	      r = make_tree_vec (len);
14676 	      for (int i = 0; i < len; ++i)
14677 		{
14678 		  tree escope = TREE_VEC_ELT (vec, i);
14679 		  tree elt = do_class_using_decl (escope, name);
14680 		  if (!elt)
14681 		    {
14682 		      r = error_mark_node;
14683 		      break;
14684 		    }
14685 		  else
14686 		    {
14687 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14688 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14689 		    }
14690 		  TREE_VEC_ELT (r, i) = elt;
14691 		}
14692 	    }
14693 	  else
14694 	    {
14695 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14696 					     complain, in_decl);
14697 	      r = do_class_using_decl (inst_scope, name);
14698 	      if (!r)
14699 		r = error_mark_node;
14700 	      else
14701 		{
14702 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
14703 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
14704 		}
14705 	    }
14706 	}
14707       else
14708 	{
14709 	  r = copy_node (t);
14710 	  DECL_CHAIN (r) = NULL_TREE;
14711 	}
14712       break;
14713 
14714     case TYPE_DECL:
14715     case VAR_DECL:
14716       {
14717 	tree argvec = NULL_TREE;
14718 	tree gen_tmpl = NULL_TREE;
14719 	tree tmpl = NULL_TREE;
14720 	tree type = NULL_TREE;
14721 
14722 	if (TREE_TYPE (t) == error_mark_node)
14723 	  RETURN (error_mark_node);
14724 
14725 	if (TREE_CODE (t) == TYPE_DECL
14726 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14727 	  {
14728 	    /* If this is the canonical decl, we don't have to
14729 	       mess with instantiations, and often we can't (for
14730 	       typename, template type parms and such).  Note that
14731 	       TYPE_NAME is not correct for the above test if
14732 	       we've copied the type for a typedef.  */
14733 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14734 	    if (type == error_mark_node)
14735 	      RETURN (error_mark_node);
14736 	    r = TYPE_NAME (type);
14737 	    break;
14738 	  }
14739 
14740 	/* Check to see if we already have the specialization we
14741 	   need.  */
14742 	tree spec = NULL_TREE;
14743 	bool local_p = false;
14744 	tree ctx = DECL_CONTEXT (t);
14745 	if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
14746 	    && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
14747 	  {
14748 	    local_p = false;
14749 	    if (DECL_CLASS_SCOPE_P (t))
14750 	      {
14751 		ctx = tsubst_aggr_type (ctx, args,
14752 					complain,
14753 					in_decl, /*entering_scope=*/1);
14754 		/* If CTX is unchanged, then T is in fact the
14755 		   specialization we want.  That situation occurs when
14756 		   referencing a static data member within in its own
14757 		   class.  We can use pointer equality, rather than
14758 		   same_type_p, because DECL_CONTEXT is always
14759 		   canonical...  */
14760 		if (ctx == DECL_CONTEXT (t)
14761 		    /* ... unless T is a member template; in which
14762 		       case our caller can be willing to create a
14763 		       specialization of that template represented
14764 		       by T.  */
14765 		    && !(DECL_TI_TEMPLATE (t)
14766 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
14767 		  spec = t;
14768 	      }
14769 
14770 	    if (!spec)
14771 	      {
14772 		tmpl = DECL_TI_TEMPLATE (t);
14773 		gen_tmpl = most_general_template (tmpl);
14774 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
14775 		if (argvec != error_mark_node)
14776 		  argvec = (coerce_innermost_template_parms
14777 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
14778 			     argvec, t, complain,
14779 			     /*all*/true, /*defarg*/true));
14780 		if (argvec == error_mark_node)
14781 		  RETURN (error_mark_node);
14782 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
14783 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
14784 	      }
14785 	  }
14786 	else
14787 	  {
14788 	    if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
14789 	      /* Subsequent calls to pushdecl will fill this in.  */
14790 	      ctx = NULL_TREE;
14791 	    /* A local variable.  */
14792 	    local_p = true;
14793 	    /* Unless this is a reference to a static variable from an
14794 	       enclosing function, in which case we need to fill it in now.  */
14795 	    if (TREE_STATIC (t))
14796 	      {
14797 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
14798 		if (fn != current_function_decl)
14799 		  ctx = fn;
14800 	      }
14801 	    spec = retrieve_local_specialization (t);
14802 	  }
14803 	/* If we already have the specialization we need, there is
14804 	   nothing more to do.  */
14805 	if (spec)
14806 	  {
14807 	    r = spec;
14808 	    break;
14809 	  }
14810 
14811 	/* Create a new node for the specialization we need.  */
14812 	if (type == NULL_TREE)
14813 	  {
14814 	    if (is_typedef_decl (t))
14815 	      type = DECL_ORIGINAL_TYPE (t);
14816 	    else
14817 	      type = TREE_TYPE (t);
14818 	    if (VAR_P (t)
14819 		&& VAR_HAD_UNKNOWN_BOUND (t)
14820 		&& type != error_mark_node)
14821 	      type = strip_array_domain (type);
14822 	    tree sub_args = args;
14823 	    if (tree auto_node = type_uses_auto (type))
14824 	      {
14825 		/* Mask off any template args past the variable's context so we
14826 		   don't replace the auto with an unrelated argument.  */
14827 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
14828 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
14829 		if (extra > 0)
14830 		  /* This should never happen with the new lambda instantiation
14831 		     model, but keep the handling just in case.  */
14832 		  gcc_assert (!CHECKING_P),
14833 		  sub_args = strip_innermost_template_args (args, extra);
14834 	      }
14835 	    type = tsubst (type, sub_args, complain, in_decl);
14836 	    /* Substituting the type might have recursively instantiated this
14837 	       same alias (c++/86171).  */
14838 	    if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
14839 		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
14840 	      {
14841 		r = spec;
14842 		break;
14843 	      }
14844 	  }
14845 	r = copy_decl (t);
14846 	if (VAR_P (r))
14847 	  {
14848 	    DECL_INITIALIZED_P (r) = 0;
14849 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
14850 	    if (type == error_mark_node)
14851 	      RETURN (error_mark_node);
14852 	    if (TREE_CODE (type) == FUNCTION_TYPE)
14853 	      {
14854 		/* It may seem that this case cannot occur, since:
14855 
14856 		   typedef void f();
14857 		   void g() { f x; }
14858 
14859 		   declares a function, not a variable.  However:
14860 
14861 		   typedef void f();
14862 		   template <typename T> void g() { T t; }
14863 		   template void g<f>();
14864 
14865 		   is an attempt to declare a variable with function
14866 		   type.  */
14867 		error ("variable %qD has function type",
14868 		       /* R is not yet sufficiently initialized, so we
14869 			  just use its name.  */
14870 		       DECL_NAME (r));
14871 		RETURN (error_mark_node);
14872 	      }
14873 	    type = complete_type (type);
14874 	    /* Wait until cp_finish_decl to set this again, to handle
14875 	       circular dependency (template/instantiate6.C). */
14876 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
14877 	    type = check_var_type (DECL_NAME (r), type,
14878 				   DECL_SOURCE_LOCATION (r));
14879 	    if (DECL_HAS_VALUE_EXPR_P (t))
14880 	      {
14881 		tree ve = DECL_VALUE_EXPR (t);
14882 		/* If the DECL_VALUE_EXPR is converted to the declared type,
14883 		   preserve the identity so that gimplify_type_sizes works.  */
14884 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
14885 		if (nop)
14886 		  ve = TREE_OPERAND (ve, 0);
14887 		ve = tsubst_expr (ve, args, complain, in_decl,
14888 				  /*constant_expression_p=*/false);
14889 		if (REFERENCE_REF_P (ve))
14890 		  {
14891 		    gcc_assert (TYPE_REF_P (type));
14892 		    ve = TREE_OPERAND (ve, 0);
14893 		  }
14894 		if (nop)
14895 		  ve = build_nop (type, ve);
14896 		else if (DECL_LANG_SPECIFIC (t)
14897 			 && DECL_OMP_PRIVATIZED_MEMBER (t)
14898 			 && TREE_CODE (ve) == COMPONENT_REF
14899 			 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
14900 			 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
14901 		  type = TREE_TYPE (ve);
14902 		else
14903 		  gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
14904 				       == TYPE_MAIN_VARIANT (type));
14905 		SET_DECL_VALUE_EXPR (r, ve);
14906 	      }
14907 	    if (CP_DECL_THREAD_LOCAL_P (r)
14908 		&& !processing_template_decl)
14909 	      set_decl_tls_model (r, decl_default_tls_model (r));
14910 	  }
14911 	else if (DECL_SELF_REFERENCE_P (t))
14912 	  SET_DECL_SELF_REFERENCE_P (r);
14913 	TREE_TYPE (r) = type;
14914 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14915 	DECL_CONTEXT (r) = ctx;
14916 	/* Clear out the mangled name and RTL for the instantiation.  */
14917 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14918 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
14919 	  SET_DECL_RTL (r, NULL);
14920 	set_instantiating_module (r);
14921 
14922 	/* The initializer must not be expanded until it is required;
14923 	   see [temp.inst].  */
14924 	DECL_INITIAL (r) = NULL_TREE;
14925 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
14926 	if (VAR_P (r))
14927 	  {
14928 	    if (DECL_LANG_SPECIFIC (r))
14929 	      SET_DECL_DEPENDENT_INIT_P (r, false);
14930 
14931 	    SET_DECL_MODE (r, VOIDmode);
14932 
14933 	    /* Possibly limit visibility based on template args.  */
14934 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14935 	    if (DECL_VISIBILITY_SPECIFIED (t))
14936 	      {
14937 		DECL_VISIBILITY_SPECIFIED (r) = 0;
14938 		DECL_ATTRIBUTES (r)
14939 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14940 	      }
14941 	    determine_visibility (r);
14942 	  }
14943 
14944 	if (!local_p)
14945 	  {
14946 	    /* A static data member declaration is always marked
14947 	       external when it is declared in-class, even if an
14948 	       initializer is present.  We mimic the non-template
14949 	       processing here.  */
14950 	    DECL_EXTERNAL (r) = 1;
14951 	    if (DECL_NAMESPACE_SCOPE_P (t))
14952 	      DECL_NOT_REALLY_EXTERN (r) = 1;
14953 
14954 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
14955 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
14956 	    if (!error_operand_p (r) || (complain & tf_error))
14957 	      register_specialization (r, gen_tmpl, argvec, false, hash);
14958 	  }
14959 	else
14960 	  {
14961 	    if (DECL_LANG_SPECIFIC (r))
14962 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
14963 	    if (!cp_unevaluated_operand)
14964 	      register_local_specialization (r, t);
14965 	  }
14966 
14967 	DECL_CHAIN (r) = NULL_TREE;
14968 
14969 	if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
14970 					     /*flags=*/0,
14971 					     args, complain, in_decl))
14972 	  return error_mark_node;
14973 
14974 	/* Preserve a typedef that names a type.  */
14975 	if (is_typedef_decl (r) && type != error_mark_node)
14976 	  {
14977 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
14978 	    set_underlying_type (r);
14979 	  }
14980 
14981 	layout_decl (r, 0);
14982       }
14983       break;
14984 
14985     default:
14986       gcc_unreachable ();
14987     }
14988 #undef RETURN
14989 
14990  out:
14991   /* Restore the file and line information.  */
14992   input_location = saved_loc;
14993 
14994   return r;
14995 }
14996 
14997 /* Substitute into the complete parameter type list PARMS.  */
14998 
14999 tree
tsubst_function_parms(tree parms,tree args,tsubst_flags_t complain,tree in_decl)15000 tsubst_function_parms (tree parms,
15001 		       tree args,
15002 		       tsubst_flags_t complain,
15003 		       tree in_decl)
15004 {
15005   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15006 }
15007 
15008 /* Substitute into the ARG_TYPES of a function type.
15009    If END is a TREE_CHAIN, leave it and any following types
15010    un-substituted.  */
15011 
15012 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)15013 tsubst_arg_types (tree arg_types,
15014 		  tree args,
15015 		  tree end,
15016 		  tsubst_flags_t complain,
15017 		  tree in_decl)
15018 {
15019   tree remaining_arg_types;
15020   tree type = NULL_TREE;
15021   int i = 1;
15022   tree expanded_args = NULL_TREE;
15023   tree default_arg;
15024 
15025   if (!arg_types || arg_types == void_list_node || arg_types == end)
15026     return arg_types;
15027 
15028   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15029 					  args, end, complain, in_decl);
15030   if (remaining_arg_types == error_mark_node)
15031     return error_mark_node;
15032 
15033   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15034     {
15035       /* For a pack expansion, perform substitution on the
15036          entire expression. Later on, we'll handle the arguments
15037          one-by-one.  */
15038       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15039                                             args, complain, in_decl);
15040 
15041       if (TREE_CODE (expanded_args) == TREE_VEC)
15042         /* So that we'll spin through the parameters, one by one.  */
15043         i = TREE_VEC_LENGTH (expanded_args);
15044       else
15045         {
15046           /* We only partially substituted into the parameter
15047              pack. Our type is TYPE_PACK_EXPANSION.  */
15048           type = expanded_args;
15049           expanded_args = NULL_TREE;
15050         }
15051     }
15052 
15053   while (i > 0) {
15054     --i;
15055 
15056     if (expanded_args)
15057       type = TREE_VEC_ELT (expanded_args, i);
15058     else if (!type)
15059       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15060 
15061     if (type == error_mark_node)
15062       return error_mark_node;
15063     if (VOID_TYPE_P (type))
15064       {
15065         if (complain & tf_error)
15066           {
15067             error ("invalid parameter type %qT", type);
15068             if (in_decl)
15069               error ("in declaration %q+D", in_decl);
15070           }
15071         return error_mark_node;
15072     }
15073 
15074     /* Do array-to-pointer, function-to-pointer conversion, and ignore
15075        top-level qualifiers as required.  */
15076     type = cv_unqualified (type_decays_to (type));
15077 
15078     /* We do not substitute into default arguments here.  The standard
15079        mandates that they be instantiated only when needed, which is
15080        done in build_over_call.  */
15081     default_arg = TREE_PURPOSE (arg_types);
15082 
15083     /* Except that we do substitute default arguments under tsubst_lambda_expr,
15084        since the new op() won't have any associated template arguments for us
15085        to refer to later.  */
15086     if (lambda_fn_in_template_p (in_decl))
15087       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
15088 					   false/*fn*/, false/*constexpr*/);
15089 
15090     if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15091       {
15092         /* We've instantiated a template before its default arguments
15093            have been parsed.  This can happen for a nested template
15094            class, and is not an error unless we require the default
15095            argument in a call of this function.  */
15096         remaining_arg_types =
15097           tree_cons (default_arg, type, remaining_arg_types);
15098 	vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15099 		       remaining_arg_types);
15100       }
15101     else
15102       remaining_arg_types =
15103         hash_tree_cons (default_arg, type, remaining_arg_types);
15104   }
15105 
15106   return remaining_arg_types;
15107 }
15108 
15109 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
15110    *not* handle the exception-specification for FNTYPE, because the
15111    initial substitution of explicitly provided template parameters
15112    during argument deduction forbids substitution into the
15113    exception-specification:
15114 
15115      [temp.deduct]
15116 
15117      All references in the function type of the function template to  the
15118      corresponding template parameters are replaced by the specified tem-
15119      plate argument values.  If a substitution in a template parameter or
15120      in  the function type of the function template results in an invalid
15121      type, type deduction fails.  [Note: The equivalent  substitution  in
15122      exception specifications is done only when the function is instanti-
15123      ated, at which point a program is  ill-formed  if  the  substitution
15124      results in an invalid type.]  */
15125 
15126 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)15127 tsubst_function_type (tree t,
15128 		      tree args,
15129 		      tsubst_flags_t complain,
15130 		      tree in_decl)
15131 {
15132   tree return_type;
15133   tree arg_types = NULL_TREE;
15134 
15135   /* The TYPE_CONTEXT is not used for function/method types.  */
15136   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15137 
15138   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15139      failure.  */
15140   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15141 
15142   if (late_return_type_p)
15143     {
15144       /* Substitute the argument types.  */
15145       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15146 				    complain, in_decl);
15147       if (arg_types == error_mark_node)
15148 	return error_mark_node;
15149 
15150       tree save_ccp = current_class_ptr;
15151       tree save_ccr = current_class_ref;
15152       tree this_type = (TREE_CODE (t) == METHOD_TYPE
15153 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15154       bool do_inject = this_type && CLASS_TYPE_P (this_type);
15155       if (do_inject)
15156 	{
15157 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
15158 	  inject_this_parameter (this_type, cp_type_quals (this_type));
15159 	}
15160 
15161       /* Substitute the return type.  */
15162       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15163 
15164       if (do_inject)
15165 	{
15166 	  current_class_ptr = save_ccp;
15167 	  current_class_ref = save_ccr;
15168 	}
15169     }
15170   else
15171     /* Substitute the return type.  */
15172     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15173 
15174   if (return_type == error_mark_node)
15175     return error_mark_node;
15176   /* DR 486 clarifies that creation of a function type with an
15177      invalid return type is a deduction failure.  */
15178   if (TREE_CODE (return_type) == ARRAY_TYPE
15179       || TREE_CODE (return_type) == FUNCTION_TYPE)
15180     {
15181       if (complain & tf_error)
15182 	{
15183 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
15184 	    error ("function returning an array");
15185 	  else
15186 	    error ("function returning a function");
15187 	}
15188       return error_mark_node;
15189     }
15190 
15191   if (!late_return_type_p)
15192     {
15193       /* Substitute the argument types.  */
15194       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15195 				    complain, in_decl);
15196       if (arg_types == error_mark_node)
15197 	return error_mark_node;
15198     }
15199 
15200   /* Construct a new type node and return it.  */
15201   return rebuild_function_or_method_type (t, return_type, arg_types,
15202 					  /*raises=*/NULL_TREE, complain);
15203 }
15204 
15205 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
15206    ARGS into that specification, and return the substituted
15207    specification.  If there is no specification, return NULL_TREE.  */
15208 
15209 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)15210 tsubst_exception_specification (tree fntype,
15211 				tree args,
15212 				tsubst_flags_t complain,
15213 				tree in_decl,
15214 				bool defer_ok)
15215 {
15216   tree specs;
15217   tree new_specs;
15218 
15219   specs = TYPE_RAISES_EXCEPTIONS (fntype);
15220   new_specs = NULL_TREE;
15221   if (specs && TREE_PURPOSE (specs))
15222     {
15223       /* A noexcept-specifier.  */
15224       tree expr = TREE_PURPOSE (specs);
15225       if (TREE_CODE (expr) == INTEGER_CST)
15226 	new_specs = expr;
15227       else if (defer_ok)
15228 	{
15229 	  /* Defer instantiation of noexcept-specifiers to avoid
15230 	     excessive instantiations (c++/49107).  */
15231 	  new_specs = make_node (DEFERRED_NOEXCEPT);
15232 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15233 	    {
15234 	      /* We already partially instantiated this member template,
15235 		 so combine the new args with the old.  */
15236 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
15237 		= DEFERRED_NOEXCEPT_PATTERN (expr);
15238 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
15239 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15240 	    }
15241 	  else
15242 	    {
15243 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15244 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15245 	    }
15246 	}
15247       else
15248 	{
15249 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15250 	    {
15251 	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15252 					   args);
15253 	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15254 	    }
15255 	  new_specs = tsubst_copy_and_build
15256 	    (expr, args, complain, in_decl, /*function_p=*/false,
15257 	     /*integral_constant_expression_p=*/true);
15258 	}
15259       new_specs = build_noexcept_spec (new_specs, complain);
15260       /* We've instantiated a template before a noexcept-specifier
15261 	 contained therein has been parsed.  This can happen for
15262 	 a nested template class:
15263 
15264 	  struct S {
15265 	    template<typename> struct B { B() noexcept(...); };
15266 	    struct A : B<int> { ... use B() ... };
15267 	  };
15268 
15269 	 where completing B<int> will trigger instantiating the
15270 	 noexcept, even though we only parse it at the end of S.  */
15271       if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15272 	{
15273 	  gcc_checking_assert (defer_ok);
15274 	  vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15275 	}
15276     }
15277   else if (specs)
15278     {
15279       if (! TREE_VALUE (specs))
15280 	new_specs = specs;
15281       else
15282 	while (specs)
15283 	  {
15284 	    tree spec;
15285             int i, len = 1;
15286             tree expanded_specs = NULL_TREE;
15287 
15288             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15289               {
15290                 /* Expand the pack expansion type.  */
15291                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15292                                                        args, complain,
15293                                                        in_decl);
15294 
15295 		if (expanded_specs == error_mark_node)
15296 		  return error_mark_node;
15297 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
15298 		  len = TREE_VEC_LENGTH (expanded_specs);
15299 		else
15300 		  {
15301 		    /* We're substituting into a member template, so
15302 		       we got a TYPE_PACK_EXPANSION back.  Add that
15303 		       expansion and move on.  */
15304 		    gcc_assert (TREE_CODE (expanded_specs)
15305 				== TYPE_PACK_EXPANSION);
15306 		    new_specs = add_exception_specifier (new_specs,
15307 							 expanded_specs,
15308 							 complain);
15309 		    specs = TREE_CHAIN (specs);
15310 		    continue;
15311 		  }
15312               }
15313 
15314             for (i = 0; i < len; ++i)
15315               {
15316                 if (expanded_specs)
15317                   spec = TREE_VEC_ELT (expanded_specs, i);
15318                 else
15319                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15320                 if (spec == error_mark_node)
15321                   return spec;
15322                 new_specs = add_exception_specifier (new_specs, spec,
15323                                                      complain);
15324               }
15325 
15326             specs = TREE_CHAIN (specs);
15327 	  }
15328     }
15329   return new_specs;
15330 }
15331 
15332 /* Substitute through a TREE_LIST of types or expressions, handling pack
15333    expansions.  */
15334 
15335 tree
tsubst_tree_list(tree t,tree args,tsubst_flags_t complain,tree in_decl)15336 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15337 {
15338   if (t == void_list_node)
15339     return t;
15340 
15341   tree purpose = TREE_PURPOSE (t);
15342   tree purposevec = NULL_TREE;
15343   if (!purpose)
15344     ;
15345   else if (PACK_EXPANSION_P (purpose))
15346     {
15347       purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15348       if (TREE_CODE (purpose) == TREE_VEC)
15349 	purposevec = purpose;
15350     }
15351   else if (TYPE_P (purpose))
15352     purpose = tsubst (purpose, args, complain, in_decl);
15353   else
15354     purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15355   if (purpose == error_mark_node || purposevec == error_mark_node)
15356     return error_mark_node;
15357 
15358   tree value = TREE_VALUE (t);
15359   tree valuevec = NULL_TREE;
15360   if (!value)
15361     ;
15362   else if (PACK_EXPANSION_P (value))
15363     {
15364       value = tsubst_pack_expansion (value, args, complain, in_decl);
15365       if (TREE_CODE (value) == TREE_VEC)
15366 	valuevec = value;
15367     }
15368   else if (TYPE_P (value))
15369     value = tsubst (value, args, complain, in_decl);
15370   else
15371     value = tsubst_copy_and_build (value, args, complain, in_decl);
15372   if (value == error_mark_node || valuevec == error_mark_node)
15373     return error_mark_node;
15374 
15375   tree chain = TREE_CHAIN (t);
15376   if (!chain)
15377     ;
15378   else if (TREE_CODE (chain) == TREE_LIST)
15379     chain = tsubst_tree_list (chain, args, complain, in_decl);
15380   else if (TYPE_P (chain))
15381     chain = tsubst (chain, args, complain, in_decl);
15382   else
15383     chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15384   if (chain == error_mark_node)
15385     return error_mark_node;
15386 
15387   if (purpose == TREE_PURPOSE (t)
15388       && value == TREE_VALUE (t)
15389       && chain == TREE_CHAIN (t))
15390     return t;
15391 
15392   int len;
15393   /* Determine the number of arguments.  */
15394   if (purposevec)
15395     {
15396       len = TREE_VEC_LENGTH (purposevec);
15397       gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15398     }
15399   else if (valuevec)
15400     len = TREE_VEC_LENGTH (valuevec);
15401   else
15402     len = 1;
15403 
15404   for (int i = len; i-- > 0; )
15405     {
15406       if (purposevec)
15407 	purpose = TREE_VEC_ELT (purposevec, i);
15408       if (valuevec)
15409 	value = TREE_VEC_ELT (valuevec, i);
15410 
15411       if (value && TYPE_P (value))
15412 	chain = hash_tree_cons (purpose, value, chain);
15413       else
15414 	chain = tree_cons (purpose, value, chain);
15415     }
15416 
15417   return chain;
15418 }
15419 
15420 /* Take the tree structure T and replace template parameters used
15421    therein with the argument vector ARGS.  IN_DECL is an associated
15422    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15423    Issue error and warning messages under control of COMPLAIN.  Note
15424    that we must be relatively non-tolerant of extensions here, in
15425    order to preserve conformance; if we allow substitutions that
15426    should not be allowed, we may allow argument deductions that should
15427    not succeed, and therefore report ambiguous overload situations
15428    where there are none.  In theory, we could allow the substitution,
15429    but indicate that it should have failed, and allow our caller to
15430    make sure that the right thing happens, but we don't try to do this
15431    yet.
15432 
15433    This function is used for dealing with types, decls and the like;
15434    for expressions, use tsubst_expr or tsubst_copy.  */
15435 
15436 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)15437 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15438 {
15439   enum tree_code code;
15440   tree type, r = NULL_TREE;
15441 
15442   if (t == NULL_TREE || t == error_mark_node
15443       || t == integer_type_node
15444       || t == void_type_node
15445       || t == char_type_node
15446       || t == unknown_type_node
15447       || TREE_CODE (t) == NAMESPACE_DECL
15448       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15449     return t;
15450 
15451   if (DECL_P (t))
15452     return tsubst_decl (t, args, complain);
15453 
15454   if (args == NULL_TREE)
15455     return t;
15456 
15457   code = TREE_CODE (t);
15458 
15459   gcc_assert (code != IDENTIFIER_NODE);
15460   type = TREE_TYPE (t);
15461 
15462   gcc_assert (type != unknown_type_node);
15463 
15464   /* Reuse typedefs.  We need to do this to handle dependent attributes,
15465      such as attribute aligned.  */
15466   if (TYPE_P (t)
15467       && typedef_variant_p (t))
15468     {
15469       tree decl = TYPE_NAME (t);
15470 
15471       if (alias_template_specialization_p (t, nt_opaque))
15472 	{
15473 	  /* DECL represents an alias template and we want to
15474 	     instantiate it.  */
15475 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15476 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15477 	  r = instantiate_alias_template (tmpl, gen_args, complain);
15478 	}
15479       else if (DECL_CLASS_SCOPE_P (decl)
15480 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15481 	       && uses_template_parms (DECL_CONTEXT (decl)))
15482 	{
15483 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15484 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15485 	  r = retrieve_specialization (tmpl, gen_args, 0);
15486 	}
15487       else if (DECL_FUNCTION_SCOPE_P (decl)
15488 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15489 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15490 	r = retrieve_local_specialization (decl);
15491       else
15492 	/* The typedef is from a non-template context.  */
15493 	return t;
15494 
15495       if (r)
15496 	{
15497 	  r = TREE_TYPE (r);
15498 	  r = cp_build_qualified_type_real
15499 	    (r, cp_type_quals (t) | cp_type_quals (r),
15500 	     complain | tf_ignore_bad_quals);
15501 	  return r;
15502 	}
15503       else
15504 	{
15505 	  /* We don't have an instantiation yet, so drop the typedef.  */
15506 	  int quals = cp_type_quals (t);
15507 	  t = DECL_ORIGINAL_TYPE (decl);
15508 	  t = cp_build_qualified_type_real (t, quals,
15509 					    complain | tf_ignore_bad_quals);
15510 	}
15511     }
15512 
15513   bool fndecl_type = (complain & tf_fndecl_type);
15514   complain &= ~tf_fndecl_type;
15515 
15516   if (type
15517       && code != TYPENAME_TYPE
15518       && code != TEMPLATE_TYPE_PARM
15519       && code != TEMPLATE_PARM_INDEX
15520       && code != IDENTIFIER_NODE
15521       && code != FUNCTION_TYPE
15522       && code != METHOD_TYPE)
15523     type = tsubst (type, args, complain, in_decl);
15524   if (type == error_mark_node)
15525     return error_mark_node;
15526 
15527   switch (code)
15528     {
15529     case RECORD_TYPE:
15530     case UNION_TYPE:
15531     case ENUMERAL_TYPE:
15532       return tsubst_aggr_type (t, args, complain, in_decl,
15533 			       /*entering_scope=*/0);
15534 
15535     case ERROR_MARK:
15536     case IDENTIFIER_NODE:
15537     case VOID_TYPE:
15538     case OPAQUE_TYPE:
15539     case REAL_TYPE:
15540     case COMPLEX_TYPE:
15541     case VECTOR_TYPE:
15542     case BOOLEAN_TYPE:
15543     case NULLPTR_TYPE:
15544     case LANG_TYPE:
15545       return t;
15546 
15547     case INTEGER_TYPE:
15548       if (t == integer_type_node)
15549 	return t;
15550 
15551       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15552           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15553         return t;
15554 
15555       {
15556 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15557 
15558 	max = tsubst_expr (omax, args, complain, in_decl,
15559 			   /*integral_constant_expression_p=*/false);
15560 
15561 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15562 	   needed.  */
15563 	if (TREE_CODE (max) == NOP_EXPR
15564 	    && TREE_SIDE_EFFECTS (omax)
15565 	    && !TREE_TYPE (max))
15566 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15567 
15568 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
15569 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
15570 	   constant expression.  */
15571 	if (processing_template_decl
15572 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15573 	  {
15574 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
15575 	    TREE_SIDE_EFFECTS (max) = 1;
15576 	  }
15577 
15578 	return compute_array_index_type (NULL_TREE, max, complain);
15579       }
15580 
15581     case TEMPLATE_TYPE_PARM:
15582     case TEMPLATE_TEMPLATE_PARM:
15583     case BOUND_TEMPLATE_TEMPLATE_PARM:
15584     case TEMPLATE_PARM_INDEX:
15585       {
15586 	int idx;
15587 	int level;
15588 	int levels;
15589 	tree arg = NULL_TREE;
15590 
15591 	r = NULL_TREE;
15592 
15593 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
15594 	template_parm_level_and_index (t, &level, &idx);
15595 
15596 	levels = TMPL_ARGS_DEPTH (args);
15597 	if (level <= levels
15598 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15599 	  {
15600 	    arg = TMPL_ARG (args, level, idx);
15601 
15602 	    /* See through ARGUMENT_PACK_SELECT arguments. */
15603 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15604 	      arg = argument_pack_select_arg (arg);
15605 	  }
15606 
15607 	if (arg == error_mark_node)
15608 	  return error_mark_node;
15609 	else if (arg != NULL_TREE)
15610 	  {
15611 	    if (ARGUMENT_PACK_P (arg))
15612 	      /* If ARG is an argument pack, we don't actually want to
15613 		 perform a substitution here, because substitutions
15614 		 for argument packs are only done
15615 		 element-by-element. We can get to this point when
15616 		 substituting the type of a non-type template
15617 		 parameter pack, when that type actually contains
15618 		 template parameter packs from an outer template, e.g.,
15619 
15620 	         template<typename... Types> struct A {
15621 		   template<Types... Values> struct B { };
15622                  };  */
15623 	      return t;
15624 
15625 	    if (code == TEMPLATE_TYPE_PARM)
15626 	      {
15627 		int quals;
15628 
15629 		/* When building concept checks for the purpose of
15630 		   deducing placeholders, we can end up with wildcards
15631 		   where types are expected. Adjust this to the deduced
15632 		   value.  */
15633 		if (TREE_CODE (arg) == WILDCARD_DECL)
15634 		  arg = TREE_TYPE (TREE_TYPE (arg));
15635 
15636 		gcc_assert (TYPE_P (arg));
15637 
15638 		quals = cp_type_quals (arg) | cp_type_quals (t);
15639 
15640 		return cp_build_qualified_type_real
15641 		  (arg, quals, complain | tf_ignore_bad_quals);
15642 	      }
15643 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15644 	      {
15645 		/* We are processing a type constructed from a
15646 		   template template parameter.  */
15647 		tree argvec = tsubst (TYPE_TI_ARGS (t),
15648 				      args, complain, in_decl);
15649 		if (argvec == error_mark_node)
15650 		  return error_mark_node;
15651 
15652 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15653 			    || TREE_CODE (arg) == TEMPLATE_DECL
15654 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15655 
15656 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15657 		  /* Consider this code:
15658 
15659 			template <template <class> class Template>
15660 			struct Internal {
15661 			template <class Arg> using Bind = Template<Arg>;
15662 			};
15663 
15664 			template <template <class> class Template, class Arg>
15665 			using Instantiate = Template<Arg>; //#0
15666 
15667 			template <template <class> class Template,
15668                                   class Argument>
15669 			using Bind =
15670 			  Instantiate<Internal<Template>::template Bind,
15671 				      Argument>; //#1
15672 
15673 		     When #1 is parsed, the
15674 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
15675 		     parameter `Template' in #0 matches the
15676 		     UNBOUND_CLASS_TEMPLATE representing the argument
15677 		     `Internal<Template>::template Bind'; We then want
15678 		     to assemble the type `Bind<Argument>' that can't
15679 		     be fully created right now, because
15680 		     `Internal<Template>' not being complete, the Bind
15681 		     template cannot be looked up in that context.  So
15682 		     we need to "store" `Bind<Argument>' for later
15683 		     when the context of Bind becomes complete.  Let's
15684 		     store that in a TYPENAME_TYPE.  */
15685 		  return make_typename_type (TYPE_CONTEXT (arg),
15686 					     build_nt (TEMPLATE_ID_EXPR,
15687 						       TYPE_IDENTIFIER (arg),
15688 						       argvec),
15689 					     typename_type,
15690 					     complain);
15691 
15692 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
15693 		   are resolving nested-types in the signature of a
15694 		   member function templates.  Otherwise ARG is a
15695 		   TEMPLATE_DECL and is the real template to be
15696 		   instantiated.  */
15697 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15698 		  arg = TYPE_NAME (arg);
15699 
15700 		r = lookup_template_class (arg,
15701 					   argvec, in_decl,
15702 					   DECL_CONTEXT (arg),
15703 					    /*entering_scope=*/0,
15704 					   complain);
15705 		return cp_build_qualified_type_real
15706 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
15707 	      }
15708 	    else if (code == TEMPLATE_TEMPLATE_PARM)
15709 	      return arg;
15710 	    else
15711 	      /* TEMPLATE_PARM_INDEX.  */
15712 	      return convert_from_reference (unshare_expr (arg));
15713 	  }
15714 
15715 	if (level == 1)
15716 	  /* This can happen during the attempted tsubst'ing in
15717 	     unify.  This means that we don't yet have any information
15718 	     about the template parameter in question.  */
15719 	  return t;
15720 
15721 	/* Early in template argument deduction substitution, we don't
15722 	   want to reduce the level of 'auto', or it will be confused
15723 	   with a normal template parm in subsequent deduction.
15724 	   Similarly, don't reduce the level of template parameters to
15725 	   avoid mismatches when deducing their types.  */
15726 	if (complain & tf_partial)
15727 	  return t;
15728 
15729 	/* If we get here, we must have been looking at a parm for a
15730 	   more deeply nested template.  Make a new version of this
15731 	   template parameter, but with a lower level.  */
15732 	switch (code)
15733 	  {
15734 	  case TEMPLATE_TYPE_PARM:
15735 	  case TEMPLATE_TEMPLATE_PARM:
15736 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
15737 	    if (cp_type_quals (t))
15738 	      {
15739 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
15740 		r = cp_build_qualified_type_real
15741 		  (r, cp_type_quals (t),
15742 		   complain | (code == TEMPLATE_TYPE_PARM
15743 			       ? tf_ignore_bad_quals : 0));
15744 	      }
15745 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15746 		     && PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
15747 		     && (r = (TEMPLATE_PARM_DESCENDANTS
15748 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
15749 		     && (r = TREE_TYPE (r))
15750 		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r))
15751 	      /* Break infinite recursion when substituting the constraints
15752 		 of a constrained placeholder.  */;
15753 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15754 		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
15755 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
15756 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
15757 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
15758 		     && (TEMPLATE_PARM_LEVEL (r)
15759 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
15760 		/* Cache the simple case of lowering a type parameter.  */
15761 	      r = TREE_TYPE (r);
15762 	    else
15763 	      {
15764 		r = copy_type (t);
15765 		TEMPLATE_TYPE_PARM_INDEX (r)
15766 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
15767 						r, levels, args, complain);
15768 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
15769 		TYPE_MAIN_VARIANT (r) = r;
15770 		TYPE_POINTER_TO (r) = NULL_TREE;
15771 		TYPE_REFERENCE_TO (r) = NULL_TREE;
15772 
15773                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
15774 		  {
15775 		    /* Propagate constraints on placeholders since they are
15776 		       only instantiated during satisfaction.  */
15777 		    if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
15778 		      PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
15779 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
15780 		      {
15781 			pl = tsubst_copy (pl, args, complain, in_decl);
15782 			if (TREE_CODE (pl) == TEMPLATE_TEMPLATE_PARM)
15783 			  pl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (pl);
15784 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
15785 		      }
15786 		  }
15787 
15788 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
15789 		  /* We have reduced the level of the template
15790 		     template parameter, but not the levels of its
15791 		     template parameters, so canonical_type_parameter
15792 		     will not be able to find the canonical template
15793 		     template parameter for this level. Thus, we
15794 		     require structural equality checking to compare
15795 		     TEMPLATE_TEMPLATE_PARMs. */
15796 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15797 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
15798 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15799 		else
15800 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
15801 
15802 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15803 		  {
15804 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
15805 		    /* We might need to substitute into the types of non-type
15806 		       template parameters.  */
15807 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
15808 					complain, in_decl);
15809 		    if (tmpl == error_mark_node)
15810 		      return error_mark_node;
15811 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
15812 					  complain, in_decl);
15813 		    if (argvec == error_mark_node)
15814 		      return error_mark_node;
15815 
15816 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
15817 		      = build_template_info (tmpl, argvec);
15818 		  }
15819 	      }
15820 	    break;
15821 
15822 	  case TEMPLATE_PARM_INDEX:
15823 	    /* OK, now substitute the type of the non-type parameter.  We
15824 	       couldn't do it earlier because it might be an auto parameter,
15825 	       and we wouldn't need to if we had an argument.  */
15826 	    type = tsubst (type, args, complain, in_decl);
15827 	    if (type == error_mark_node)
15828 	      return error_mark_node;
15829 	    r = reduce_template_parm_level (t, type, levels, args, complain);
15830 	    break;
15831 
15832 	  default:
15833 	    gcc_unreachable ();
15834 	  }
15835 
15836 	return r;
15837       }
15838 
15839     case TREE_LIST:
15840       return tsubst_tree_list (t, args, complain, in_decl);
15841 
15842     case TREE_BINFO:
15843       /* We should never be tsubsting a binfo.  */
15844       gcc_unreachable ();
15845 
15846     case TREE_VEC:
15847       /* A vector of template arguments.  */
15848       gcc_assert (!type);
15849       return tsubst_template_args (t, args, complain, in_decl);
15850 
15851     case POINTER_TYPE:
15852     case REFERENCE_TYPE:
15853       {
15854 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
15855 	  return t;
15856 
15857 	/* [temp.deduct]
15858 
15859 	   Type deduction may fail for any of the following
15860 	   reasons:
15861 
15862 	   -- Attempting to create a pointer to reference type.
15863 	   -- Attempting to create a reference to a reference type or
15864 	      a reference to void.
15865 
15866 	  Core issue 106 says that creating a reference to a reference
15867 	  during instantiation is no longer a cause for failure. We
15868 	  only enforce this check in strict C++98 mode.  */
15869 	if ((TYPE_REF_P (type)
15870 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
15871 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
15872 	  {
15873 	    static location_t last_loc;
15874 
15875 	    /* We keep track of the last time we issued this error
15876 	       message to avoid spewing a ton of messages during a
15877 	       single bad template instantiation.  */
15878 	    if (complain & tf_error
15879 		&& last_loc != input_location)
15880 	      {
15881 		if (VOID_TYPE_P (type))
15882 		  error ("forming reference to void");
15883                else if (code == POINTER_TYPE)
15884                  error ("forming pointer to reference type %qT", type);
15885                else
15886 		  error ("forming reference to reference type %qT", type);
15887 		last_loc = input_location;
15888 	      }
15889 
15890 	    return error_mark_node;
15891 	  }
15892 	else if (TREE_CODE (type) == FUNCTION_TYPE
15893 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
15894 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
15895 	  {
15896 	    if (complain & tf_error)
15897 	      {
15898 		if (code == POINTER_TYPE)
15899 		  error ("forming pointer to qualified function type %qT",
15900 			 type);
15901 		else
15902 		  error ("forming reference to qualified function type %qT",
15903 			 type);
15904 	      }
15905 	    return error_mark_node;
15906 	  }
15907 	else if (code == POINTER_TYPE)
15908 	  {
15909 	    r = build_pointer_type (type);
15910 	    if (TREE_CODE (type) == METHOD_TYPE)
15911 	      r = build_ptrmemfunc_type (r);
15912 	  }
15913 	else if (TYPE_REF_P (type))
15914 	  /* In C++0x, during template argument substitution, when there is an
15915 	     attempt to create a reference to a reference type, reference
15916 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
15917 
15918 	     "If a template-argument for a template-parameter T names a type
15919 	     that is a reference to a type A, an attempt to create the type
15920 	     'lvalue reference to cv T' creates the type 'lvalue reference to
15921 	     A,' while an attempt to create the type type rvalue reference to
15922 	     cv T' creates the type T"
15923 	  */
15924 	  r = cp_build_reference_type
15925 	      (TREE_TYPE (type),
15926 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
15927 	else
15928 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
15929 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
15930 
15931 	if (r != error_mark_node)
15932 	  /* Will this ever be needed for TYPE_..._TO values?  */
15933 	  layout_type (r);
15934 
15935 	return r;
15936       }
15937     case OFFSET_TYPE:
15938       {
15939 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
15940 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
15941 	  {
15942 	    /* [temp.deduct]
15943 
15944 	       Type deduction may fail for any of the following
15945 	       reasons:
15946 
15947 	       -- Attempting to create "pointer to member of T" when T
15948 		  is not a class type.  */
15949 	    if (complain & tf_error)
15950 	      error ("creating pointer to member of non-class type %qT", r);
15951 	    return error_mark_node;
15952 	  }
15953 	if (TYPE_REF_P (type))
15954 	  {
15955 	    if (complain & tf_error)
15956 	      error ("creating pointer to member reference type %qT", type);
15957 	    return error_mark_node;
15958 	  }
15959 	if (VOID_TYPE_P (type))
15960 	  {
15961 	    if (complain & tf_error)
15962 	      error ("creating pointer to member of type void");
15963 	    return error_mark_node;
15964 	  }
15965 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
15966 	if (TREE_CODE (type) == FUNCTION_TYPE)
15967 	  {
15968 	    /* The type of the implicit object parameter gets its
15969 	       cv-qualifiers from the FUNCTION_TYPE. */
15970 	    tree memptr;
15971 	    tree method_type
15972 	      = build_memfn_type (type, r, type_memfn_quals (type),
15973 				  type_memfn_rqual (type));
15974 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
15975 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
15976 						 complain);
15977 	  }
15978 	else
15979 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
15980 					       cp_type_quals (t),
15981 					       complain);
15982       }
15983     case FUNCTION_TYPE:
15984     case METHOD_TYPE:
15985       {
15986 	tree fntype;
15987 	tree specs;
15988 	fntype = tsubst_function_type (t, args, complain, in_decl);
15989 	if (fntype == error_mark_node)
15990 	  return error_mark_node;
15991 
15992 	/* Substitute the exception specification.  */
15993 	specs = tsubst_exception_specification (t, args, complain, in_decl,
15994 						/*defer_ok*/fndecl_type);
15995 	if (specs == error_mark_node)
15996 	  return error_mark_node;
15997 	if (specs)
15998 	  fntype = build_exception_variant (fntype, specs);
15999 	return fntype;
16000       }
16001     case ARRAY_TYPE:
16002       {
16003 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16004 	if (domain == error_mark_node)
16005 	  return error_mark_node;
16006 
16007 	/* As an optimization, we avoid regenerating the array type if
16008 	   it will obviously be the same as T.  */
16009 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16010 	  return t;
16011 
16012 	/* These checks should match the ones in create_array_type_for_decl.
16013 
16014 	   [temp.deduct]
16015 
16016 	   The deduction may fail for any of the following reasons:
16017 
16018 	   -- Attempting to create an array with an element type that
16019 	      is void, a function type, or a reference type, or [DR337]
16020 	      an abstract class type.  */
16021 	if (VOID_TYPE_P (type)
16022 	    || TREE_CODE (type) == FUNCTION_TYPE
16023 	    || (TREE_CODE (type) == ARRAY_TYPE
16024 		&& TYPE_DOMAIN (type) == NULL_TREE)
16025 	    || TYPE_REF_P (type))
16026 	  {
16027 	    if (complain & tf_error)
16028 	      error ("creating array of %qT", type);
16029 	    return error_mark_node;
16030 	  }
16031 
16032 	if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16033 				  !(complain & tf_error)))
16034 	  return error_mark_node;
16035 
16036 	r = build_cplus_array_type (type, domain);
16037 
16038 	if (!valid_array_size_p (input_location, r, in_decl,
16039 				 (complain & tf_error)))
16040 	  return error_mark_node;
16041 
16042 	if (TYPE_USER_ALIGN (t))
16043 	  {
16044 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16045 	    TYPE_USER_ALIGN (r) = 1;
16046 	  }
16047 
16048 	return r;
16049       }
16050 
16051     case TYPENAME_TYPE:
16052       {
16053 	tree ctx = TYPE_CONTEXT (t);
16054 	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16055 	  {
16056 	    ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
16057 	    if (ctx == error_mark_node
16058 		|| TREE_VEC_LENGTH (ctx) > 1)
16059 	      return error_mark_node;
16060 	    if (TREE_VEC_LENGTH (ctx) == 0)
16061 	      {
16062 		if (complain & tf_error)
16063 		  error ("%qD is instantiated for an empty pack",
16064 			 TYPENAME_TYPE_FULLNAME (t));
16065 		return error_mark_node;
16066 	      }
16067 	    ctx = TREE_VEC_ELT (ctx, 0);
16068 	  }
16069 	else
16070 	  ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
16071 				  /*entering_scope=*/1);
16072 	if (ctx == error_mark_node)
16073 	  return error_mark_node;
16074 
16075 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16076 			      complain, in_decl);
16077 	if (f == error_mark_node)
16078 	  return error_mark_node;
16079 
16080 	if (!MAYBE_CLASS_TYPE_P (ctx))
16081 	  {
16082 	    if (complain & tf_error)
16083 	      error ("%qT is not a class, struct, or union type", ctx);
16084 	    return error_mark_node;
16085 	  }
16086 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16087 	  {
16088 	    /* Normally, make_typename_type does not require that the CTX
16089 	       have complete type in order to allow things like:
16090 
16091 		 template <class T> struct S { typename S<T>::X Y; };
16092 
16093 	       But, such constructs have already been resolved by this
16094 	       point, so here CTX really should have complete type, unless
16095 	       it's a partial instantiation.  */
16096 	    if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16097 	      return error_mark_node;
16098 	  }
16099 
16100 	f = make_typename_type (ctx, f, typename_type,
16101 				complain | tf_keep_type_decl);
16102 	if (f == error_mark_node)
16103 	  return f;
16104 	if (TREE_CODE (f) == TYPE_DECL)
16105 	  {
16106 	    complain |= tf_ignore_bad_quals;
16107 	    f = TREE_TYPE (f);
16108 	  }
16109 
16110 	if (TREE_CODE (f) != TYPENAME_TYPE)
16111 	  {
16112 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16113 	      {
16114 		if (complain & tf_error)
16115 		  error ("%qT resolves to %qT, which is not an enumeration type",
16116 			 t, f);
16117 		else
16118 		  return error_mark_node;
16119 	      }
16120 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16121 	      {
16122 		if (complain & tf_error)
16123 		  error ("%qT resolves to %qT, which is not a class type",
16124 			 t, f);
16125 		else
16126 		  return error_mark_node;
16127 	      }
16128 	  }
16129 
16130 	return cp_build_qualified_type_real
16131 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
16132       }
16133 
16134     case UNBOUND_CLASS_TEMPLATE:
16135       {
16136 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16137 				     in_decl, /*entering_scope=*/1);
16138 	tree name = TYPE_IDENTIFIER (t);
16139 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16140 
16141 	if (ctx == error_mark_node || name == error_mark_node)
16142 	  return error_mark_node;
16143 
16144 	if (parm_list)
16145 	  parm_list = tsubst_template_parms (parm_list, args, complain);
16146 	return make_unbound_class_template (ctx, name, parm_list, complain);
16147       }
16148 
16149     case TYPEOF_TYPE:
16150       {
16151 	tree type;
16152 
16153 	++cp_unevaluated_operand;
16154 	++c_inhibit_evaluation_warnings;
16155 
16156 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
16157 			    complain, in_decl,
16158 			    /*integral_constant_expression_p=*/false);
16159 
16160 	--cp_unevaluated_operand;
16161 	--c_inhibit_evaluation_warnings;
16162 
16163 	type = finish_typeof (type);
16164 	return cp_build_qualified_type_real (type,
16165 					     cp_type_quals (t)
16166 					     | cp_type_quals (type),
16167 					     complain);
16168       }
16169 
16170     case DECLTYPE_TYPE:
16171       {
16172 	tree type;
16173 
16174 	++cp_unevaluated_operand;
16175 	++c_inhibit_evaluation_warnings;
16176 
16177 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16178 				      complain|tf_decltype, in_decl,
16179 				      /*function_p*/false,
16180 				      /*integral_constant_expression*/false);
16181 
16182 	--cp_unevaluated_operand;
16183 	--c_inhibit_evaluation_warnings;
16184 
16185 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16186 	  type = lambda_capture_field_type (type,
16187 					    false /*explicit_init*/,
16188 					    DECLTYPE_FOR_REF_CAPTURE (t));
16189 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16190 	  type = lambda_proxy_type (type);
16191 	else
16192 	  {
16193 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16194 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16195 		&& EXPR_P (type))
16196 	      /* In a template ~id could be either a complement expression
16197 		 or an unqualified-id naming a destructor; if instantiating
16198 		 it produces an expression, it's not an id-expression or
16199 		 member access.  */
16200 	      id = false;
16201 	    type = finish_decltype_type (type, id, complain);
16202 	  }
16203 	return cp_build_qualified_type_real (type,
16204 					     cp_type_quals (t)
16205 					     | cp_type_quals (type),
16206 					     complain | tf_ignore_bad_quals);
16207       }
16208 
16209     case UNDERLYING_TYPE:
16210       {
16211 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16212 			    complain, in_decl);
16213 	return finish_underlying_type (type);
16214       }
16215 
16216     case TYPE_ARGUMENT_PACK:
16217     case NONTYPE_ARGUMENT_PACK:
16218       return tsubst_argument_pack (t, args, complain, in_decl);
16219 
16220     case VOID_CST:
16221     case INTEGER_CST:
16222     case REAL_CST:
16223     case STRING_CST:
16224     case PLUS_EXPR:
16225     case MINUS_EXPR:
16226     case NEGATE_EXPR:
16227     case NOP_EXPR:
16228     case INDIRECT_REF:
16229     case ADDR_EXPR:
16230     case CALL_EXPR:
16231     case ARRAY_REF:
16232     case SCOPE_REF:
16233       /* We should use one of the expression tsubsts for these codes.  */
16234       gcc_unreachable ();
16235 
16236     default:
16237       sorry ("use of %qs in template", get_tree_code_name (code));
16238       return error_mark_node;
16239     }
16240 }
16241 
16242 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16243    expression on the left-hand side of the "." or "->" operator.  We
16244    only do the lookup if we had a dependent BASELINK.  Otherwise we
16245    adjust it onto the instantiated heirarchy.  */
16246 
16247 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)16248 tsubst_baselink (tree baselink, tree object_type,
16249 		 tree args, tsubst_flags_t complain, tree in_decl)
16250 {
16251   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16252   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16253   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16254 
16255   tree optype = BASELINK_OPTYPE (baselink);
16256   optype = tsubst (optype, args, complain, in_decl);
16257 
16258   tree template_args = NULL_TREE;
16259   bool template_id_p = false;
16260   tree fns = BASELINK_FUNCTIONS (baselink);
16261   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16262     {
16263       template_id_p = true;
16264       template_args = TREE_OPERAND (fns, 1);
16265       fns = TREE_OPERAND (fns, 0);
16266       if (template_args)
16267 	template_args = tsubst_template_args (template_args, args,
16268 					      complain, in_decl);
16269     }
16270 
16271   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16272   binfo_type = tsubst (binfo_type, args, complain, in_decl);
16273   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
16274 
16275   if (dependent_p)
16276     {
16277       tree name = OVL_NAME (fns);
16278       if (IDENTIFIER_CONV_OP_P (name))
16279 	name = make_conv_op_name (optype);
16280 
16281       /* See maybe_dependent_member_ref.  */
16282       if (dependent_scope_p (qualifying_scope))
16283 	{
16284 	  if (template_id_p)
16285 	    name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16286 			   template_args);
16287 	  return build_qualified_name (NULL_TREE, qualifying_scope, name,
16288 				       /* ::template */false);
16289 	}
16290 
16291       if (name == complete_dtor_identifier)
16292 	/* Treat as-if non-dependent below.  */
16293 	dependent_p = false;
16294 
16295       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16296 				  complain);
16297       if (!baselink)
16298 	{
16299 	  if ((complain & tf_error)
16300 	      && constructor_name_p (name, qualifying_scope))
16301 	    error ("cannot call constructor %<%T::%D%> directly",
16302 		   qualifying_scope, name);
16303 	  return error_mark_node;
16304 	}
16305 
16306       if (BASELINK_P (baselink))
16307 	fns = BASELINK_FUNCTIONS (baselink);
16308     }
16309   else
16310     {
16311       /* We're going to overwrite pieces below, make a duplicate.  */
16312       baselink = copy_node (baselink);
16313 
16314       if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16315 	{
16316 	  /* The decl we found was from non-dependent scope, but we still need
16317 	     to update the binfos for the instantiated qualifying_scope.  */
16318 	  BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16319 	  BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16320 						   ba_unique, nullptr, complain);
16321 	}
16322     }
16323 
16324   /* If lookup found a single function, mark it as used at this point.
16325      (If lookup found multiple functions the one selected later by
16326      overload resolution will be marked as used at that point.)  */
16327   if (!template_id_p && !really_overloaded_fn (fns))
16328     {
16329       tree fn = OVL_FIRST (fns);
16330       bool ok = mark_used (fn, complain);
16331       if (!ok && !(complain & tf_error))
16332 	return error_mark_node;
16333       if (ok && BASELINK_P (baselink))
16334 	/* We might have instantiated an auto function.  */
16335 	TREE_TYPE (baselink) = TREE_TYPE (fn);
16336     }
16337 
16338   if (BASELINK_P (baselink))
16339     {
16340       /* Add back the template arguments, if present.  */
16341       if (template_id_p)
16342 	BASELINK_FUNCTIONS (baselink)
16343 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16344 
16345       /* Update the conversion operator type.  */
16346       BASELINK_OPTYPE (baselink) = optype;
16347     }
16348 
16349   if (!object_type)
16350     object_type = current_class_type;
16351 
16352   if (qualified_p || !dependent_p)
16353     {
16354       baselink = adjust_result_of_qualified_name_lookup (baselink,
16355 							 qualifying_scope,
16356 							 object_type);
16357       if (!qualified_p)
16358 	/* We need to call adjust_result_of_qualified_name_lookup in case the
16359 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
16360 	   so that we still get virtual function binding.  */
16361 	BASELINK_QUALIFIED_P (baselink) = false;
16362     }
16363 
16364   return baselink;
16365 }
16366 
16367 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16368    true if the qualified-id will be a postfix-expression in-and-of
16369    itself; false if more of the postfix-expression follows the
16370    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16371    of "&".  */
16372 
16373 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)16374 tsubst_qualified_id (tree qualified_id, tree args,
16375 		     tsubst_flags_t complain, tree in_decl,
16376 		     bool done, bool address_p)
16377 {
16378   tree expr;
16379   tree scope;
16380   tree name;
16381   bool is_template;
16382   tree template_args;
16383   location_t loc = EXPR_LOCATION (qualified_id);
16384 
16385   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16386 
16387   /* Figure out what name to look up.  */
16388   name = TREE_OPERAND (qualified_id, 1);
16389   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16390     {
16391       is_template = true;
16392       template_args = TREE_OPERAND (name, 1);
16393       if (template_args)
16394 	template_args = tsubst_template_args (template_args, args,
16395 					      complain, in_decl);
16396       if (template_args == error_mark_node)
16397 	return error_mark_node;
16398       name = TREE_OPERAND (name, 0);
16399     }
16400   else
16401     {
16402       is_template = false;
16403       template_args = NULL_TREE;
16404     }
16405 
16406   /* Substitute into the qualifying scope.  When there are no ARGS, we
16407      are just trying to simplify a non-dependent expression.  In that
16408      case the qualifying scope may be dependent, and, in any case,
16409      substituting will not help.  */
16410   scope = TREE_OPERAND (qualified_id, 0);
16411   if (args)
16412     {
16413       scope = tsubst (scope, args, complain, in_decl);
16414       expr = tsubst_copy (name, args, complain, in_decl);
16415     }
16416   else
16417     expr = name;
16418 
16419   if (dependent_scope_p (scope))
16420     {
16421       if (is_template)
16422 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
16423       tree r = build_qualified_name (NULL_TREE, scope, expr,
16424 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
16425       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
16426       return r;
16427     }
16428 
16429   if (!BASELINK_P (name) && !DECL_P (expr))
16430     {
16431       if (TREE_CODE (expr) == BIT_NOT_EXPR)
16432 	{
16433 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
16434 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16435 	    {
16436 	      error ("qualifying type %qT does not match destructor name ~%qT",
16437 		     scope, TREE_OPERAND (expr, 0));
16438 	      expr = error_mark_node;
16439 	    }
16440 	  else
16441 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
16442 					  LOOK_want::NORMAL, false);
16443 	}
16444       else
16445 	expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
16446       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16447 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16448 	{
16449 	  if (complain & tf_error)
16450 	    {
16451 	      error ("dependent-name %qE is parsed as a non-type, but "
16452 		     "instantiation yields a type", qualified_id);
16453 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16454 	    }
16455 	  return error_mark_node;
16456 	}
16457     }
16458 
16459   if (DECL_P (expr))
16460     {
16461       if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16462 						scope, complain))
16463 	return error_mark_node;
16464       /* Remember that there was a reference to this entity.  */
16465       if (!mark_used (expr, complain) && !(complain & tf_error))
16466 	return error_mark_node;
16467     }
16468 
16469   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16470     {
16471       if (complain & tf_error)
16472 	qualified_name_lookup_error (scope,
16473 				     TREE_OPERAND (qualified_id, 1),
16474 				     expr, input_location);
16475       return error_mark_node;
16476     }
16477 
16478   if (is_template)
16479     {
16480       /* We may be repeating a check already done during parsing, but
16481 	 if it was well-formed and passed then, it will pass again
16482 	 now, and if it didn't, we wouldn't have got here.  The case
16483 	 we want to catch is when we couldn't tell then, and can now,
16484 	 namely when templ prior to substitution was an
16485 	 identifier.  */
16486       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16487 	return error_mark_node;
16488 
16489       if (variable_template_p (expr))
16490 	expr = lookup_and_finish_template_variable (expr, template_args,
16491 						    complain);
16492       else
16493 	expr = lookup_template_function (expr, template_args);
16494     }
16495 
16496   if (expr == error_mark_node && complain & tf_error)
16497     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16498 				 expr, input_location);
16499   else if (TYPE_P (scope))
16500     {
16501       expr = (adjust_result_of_qualified_name_lookup
16502 	      (expr, scope, current_nonlambda_class_type ()));
16503       expr = (finish_qualified_id_expr
16504 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16505 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16506 	       /*template_arg_p=*/false, complain));
16507     }
16508 
16509   /* Expressions do not generally have reference type.  */
16510   if (TREE_CODE (expr) != SCOPE_REF
16511       /* However, if we're about to form a pointer-to-member, we just
16512 	 want the referenced member referenced.  */
16513       && TREE_CODE (expr) != OFFSET_REF)
16514     expr = convert_from_reference (expr);
16515 
16516   if (REF_PARENTHESIZED_P (qualified_id))
16517     expr = force_paren_expr (expr);
16518 
16519   expr = maybe_wrap_with_location (expr, loc);
16520 
16521   return expr;
16522 }
16523 
16524 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16525    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16526    for tsubst.  */
16527 
16528 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)16529 tsubst_init (tree init, tree decl, tree args,
16530 	     tsubst_flags_t complain, tree in_decl)
16531 {
16532   if (!init)
16533     return NULL_TREE;
16534 
16535   init = tsubst_expr (init, args, complain, in_decl, false);
16536 
16537   tree type = TREE_TYPE (decl);
16538 
16539   if (!init && type != error_mark_node)
16540     {
16541       if (tree auto_node = type_uses_auto (type))
16542 	{
16543 	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16544 	    {
16545 	      if (complain & tf_error)
16546 		error ("initializer for %q#D expands to an empty list "
16547 		       "of expressions", decl);
16548 	      return error_mark_node;
16549 	    }
16550 	}
16551       else if (!dependent_type_p (type))
16552 	{
16553 	  /* If we had an initializer but it
16554 	     instantiated to nothing,
16555 	     value-initialize the object.  This will
16556 	     only occur when the initializer was a
16557 	     pack expansion where the parameter packs
16558 	     used in that expansion were of length
16559 	     zero.  */
16560 	  init = build_value_init (type, complain);
16561 	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
16562 	    init = get_target_expr_sfinae (init, complain);
16563 	  if (TREE_CODE (init) == TARGET_EXPR)
16564 	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
16565 	}
16566     }
16567 
16568   return init;
16569 }
16570 
16571 /* If T is a reference to a dependent member of the current instantiation C and
16572    we are trying to refer to that member in a partial instantiation of C,
16573    return a SCOPE_REF; otherwise, return NULL_TREE.
16574 
16575    This can happen when forming a C++17 deduction guide, as in PR96199.  */
16576 
16577 static tree
maybe_dependent_member_ref(tree t,tree args,tsubst_flags_t complain,tree in_decl)16578 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16579 			    tree in_decl)
16580 {
16581   if (cxx_dialect < cxx17)
16582     return NULL_TREE;
16583 
16584   tree ctx = context_for_name_lookup (t);
16585   if (!CLASS_TYPE_P (ctx))
16586     return NULL_TREE;
16587 
16588   ctx = tsubst (ctx, args, complain, in_decl);
16589   if (dependent_scope_p (ctx))
16590     return build_qualified_name (NULL_TREE, ctx, DECL_NAME (t),
16591 				 /*template_p=*/false);
16592 
16593   return NULL_TREE;
16594 }
16595 
16596 /* Like tsubst, but deals with expressions.  This function just replaces
16597    template parms; to finish processing the resultant expression, use
16598    tsubst_copy_and_build or tsubst_expr.  */
16599 
16600 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)16601 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16602 {
16603   enum tree_code code;
16604   tree r;
16605 
16606   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16607     return t;
16608 
16609   code = TREE_CODE (t);
16610 
16611   switch (code)
16612     {
16613     case PARM_DECL:
16614       r = retrieve_local_specialization (t);
16615 
16616       if (r == NULL_TREE)
16617 	{
16618 	  /* We get here for a use of 'this' in an NSDMI.  */
16619 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
16620 	    return current_class_ptr;
16621 
16622 	  /* This can happen for a parameter name used later in a function
16623 	     declaration (such as in a late-specified return type).  Just
16624 	     make a dummy decl, since it's only used for its type.  */
16625 	  gcc_assert (cp_unevaluated_operand != 0);
16626 	  r = tsubst_decl (t, args, complain);
16627 	  /* Give it the template pattern as its context; its true context
16628 	     hasn't been instantiated yet and this is good enough for
16629 	     mangling.  */
16630 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
16631 	}
16632 
16633       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16634 	r = argument_pack_select_arg (r);
16635       if (!mark_used (r, complain) && !(complain & tf_error))
16636 	return error_mark_node;
16637       return r;
16638 
16639     case CONST_DECL:
16640       {
16641 	tree enum_type;
16642 	tree v;
16643 
16644 	if (DECL_TEMPLATE_PARM_P (t))
16645 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
16646 	/* There is no need to substitute into namespace-scope
16647 	   enumerators.  */
16648 	if (DECL_NAMESPACE_SCOPE_P (t))
16649 	  return t;
16650 	/* If ARGS is NULL, then T is known to be non-dependent.  */
16651 	if (args == NULL_TREE)
16652 	  return scalar_constant_value (t);
16653 
16654 	if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16655 	  return ref;
16656 
16657 	/* Unfortunately, we cannot just call lookup_name here.
16658 	   Consider:
16659 
16660 	     template <int I> int f() {
16661 	     enum E { a = I };
16662 	     struct S { void g() { E e = a; } };
16663 	     };
16664 
16665 	   When we instantiate f<7>::S::g(), say, lookup_name is not
16666 	   clever enough to find f<7>::a.  */
16667 	enum_type
16668 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16669 			      /*entering_scope=*/0);
16670 
16671 	for (v = TYPE_VALUES (enum_type);
16672 	     v != NULL_TREE;
16673 	     v = TREE_CHAIN (v))
16674 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
16675 	    return TREE_VALUE (v);
16676 
16677 	  /* We didn't find the name.  That should never happen; if
16678 	     name-lookup found it during preliminary parsing, we
16679 	     should find it again here during instantiation.  */
16680 	gcc_unreachable ();
16681       }
16682       return t;
16683 
16684     case FIELD_DECL:
16685       if (DECL_CONTEXT (t))
16686 	{
16687 	  tree ctx;
16688 
16689 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16690 				  /*entering_scope=*/1);
16691 	  if (ctx != DECL_CONTEXT (t))
16692 	    {
16693 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
16694 	      if (!r)
16695 		{
16696 		  if (complain & tf_error)
16697 		    error ("using invalid field %qD", t);
16698 		  return error_mark_node;
16699 		}
16700 	      return r;
16701 	    }
16702 	}
16703 
16704       return t;
16705 
16706     case VAR_DECL:
16707       if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16708 	return ref;
16709       gcc_fallthrough();
16710     case FUNCTION_DECL:
16711       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
16712 	r = tsubst (t, args, complain, in_decl);
16713       else if (DECL_LOCAL_DECL_P (t))
16714 	{
16715 	  /* Local specialization will usually have been created when
16716 	     we instantiated the DECL_EXPR_DECL. */
16717 	  r = retrieve_local_specialization (t);
16718 	  if (!r)
16719 	    {
16720 	      /* We're in a generic lambda referencing a local extern
16721 		 from an outer block-scope of a non-template.  */
16722 	      gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
16723 	      r = t;
16724 	    }
16725 	}
16726       else if (local_variable_p (t)
16727 	       && uses_template_parms (DECL_CONTEXT (t)))
16728 	{
16729 	  r = retrieve_local_specialization (t);
16730 	  if (r == NULL_TREE)
16731 	    {
16732 	      /* First try name lookup to find the instantiation.  */
16733 	      r = lookup_name (DECL_NAME (t));
16734 	      if (r)
16735 		{
16736 		  if (!VAR_P (r))
16737 		    {
16738 		      /* During error-recovery we may find a non-variable,
16739 			 even an OVERLOAD: just bail out and avoid ICEs and
16740 			 duplicate diagnostics (c++/62207).  */
16741 		      gcc_assert (seen_error ());
16742 		      return error_mark_node;
16743 		    }
16744 		  if (!is_capture_proxy (r))
16745 		    {
16746 		      /* Make sure the one we found is the one we want.  */
16747 		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
16748 		      if (ctx != DECL_CONTEXT (r))
16749 			r = NULL_TREE;
16750 		    }
16751 		}
16752 
16753 	      if (r)
16754 		/* OK */;
16755 	      else
16756 		{
16757 		  /* This can happen for a variable used in a
16758 		     late-specified return type of a local lambda, or for a
16759 		     local static or constant.  Building a new VAR_DECL
16760 		     should be OK in all those cases.  */
16761 		  r = tsubst_decl (t, args, complain);
16762 		  if (local_specializations)
16763 		    /* Avoid infinite recursion (79640).  */
16764 		    register_local_specialization (r, t);
16765 		  if (decl_maybe_constant_var_p (r))
16766 		    {
16767 		      /* We can't call cp_finish_decl, so handle the
16768 			 initializer by hand.  */
16769 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
16770 					       complain, in_decl);
16771 		      if (!processing_template_decl)
16772 			init = maybe_constant_init (init);
16773 		      if (processing_template_decl
16774 			  ? potential_constant_expression (init)
16775 			  : reduced_constant_expression_p (init))
16776 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
16777 			  = TREE_CONSTANT (r) = true;
16778 		      DECL_INITIAL (r) = init;
16779 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
16780 			TREE_TYPE (r)
16781 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
16782 					       complain, adc_variable_type);
16783 		    }
16784 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
16785 			      || decl_constant_var_p (r)
16786 			      || seen_error ());
16787 		  if (!processing_template_decl
16788 		      && !TREE_STATIC (r))
16789 		    r = process_outer_var_ref (r, complain);
16790 		}
16791 	      /* Remember this for subsequent uses.  */
16792 	      if (local_specializations)
16793 		register_local_specialization (r, t);
16794 	    }
16795 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16796 	    r = argument_pack_select_arg (r);
16797 	}
16798       else
16799 	r = t;
16800       if (!mark_used (r, complain))
16801 	return error_mark_node;
16802       return r;
16803 
16804     case NAMESPACE_DECL:
16805       return t;
16806 
16807     case OVERLOAD:
16808       return t;
16809 
16810     case BASELINK:
16811       return tsubst_baselink (t, current_nonlambda_class_type (),
16812 			      args, complain, in_decl);
16813 
16814     case TEMPLATE_DECL:
16815       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
16816 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
16817 		       args, complain, in_decl);
16818       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
16819 	return tsubst (t, args, complain, in_decl);
16820       else if (DECL_CLASS_SCOPE_P (t)
16821 	       && uses_template_parms (DECL_CONTEXT (t)))
16822 	{
16823 	  /* Template template argument like the following example need
16824 	     special treatment:
16825 
16826 	       template <template <class> class TT> struct C {};
16827 	       template <class T> struct D {
16828 		 template <class U> struct E {};
16829 		 C<E> c;				// #1
16830 	       };
16831 	       D<int> d;				// #2
16832 
16833 	     We are processing the template argument `E' in #1 for
16834 	     the template instantiation #2.  Originally, `E' is a
16835 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
16836 	     have to substitute this with one having context `D<int>'.  */
16837 
16838 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
16839 	  if (dependent_scope_p (context))
16840 	    {
16841 	      /* When rewriting a constructor into a deduction guide, a
16842 		 non-dependent name can become dependent, so memtmpl<args>
16843 		 becomes context::template memtmpl<args>.  */
16844 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16845 	      return build_qualified_name (type, context, DECL_NAME (t),
16846 					   /*template*/true);
16847 	    }
16848 	  return lookup_field (context, DECL_NAME(t), 0, false);
16849 	}
16850       else
16851 	/* Ordinary template template argument.  */
16852 	return t;
16853 
16854     case NON_LVALUE_EXPR:
16855     case VIEW_CONVERT_EXPR:
16856 	{
16857 	  /* Handle location wrappers by substituting the wrapped node
16858 	     first, *then* reusing the resulting type.  Doing the type
16859 	     first ensures that we handle template parameters and
16860 	     parameter pack expansions.  */
16861 	  if (location_wrapper_p (t))
16862 	    {
16863 	      tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
16864 				      complain, in_decl);
16865 	      return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
16866 	    }
16867 	  tree op = TREE_OPERAND (t, 0);
16868 	  if (code == VIEW_CONVERT_EXPR
16869 	      && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16870 	    {
16871 	      /* Wrapper to make a C++20 template parameter object const.  */
16872 	      op = tsubst_copy (op, args, complain, in_decl);
16873 	      if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
16874 		{
16875 		  /* The template argument is not const, presumably because
16876 		     it is still dependent, and so not the const template parm
16877 		     object.  */
16878 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16879 		  gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
16880 				       (type, TREE_TYPE (op)));
16881 		  if (TREE_CODE (op) == CONSTRUCTOR
16882 		      || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
16883 		    {
16884 		      /* Don't add a wrapper to these.  */
16885 		      op = copy_node (op);
16886 		      TREE_TYPE (op) = type;
16887 		    }
16888 		  else
16889 		    /* Do add a wrapper otherwise (in particular, if op is
16890 		       another TEMPLATE_PARM_INDEX).  */
16891 		    op = build1 (code, type, op);
16892 		}
16893 	      return op;
16894 	    }
16895 	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
16896 	  else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
16897 	    {
16898 	      op = tsubst_copy (op, args, complain, in_decl);
16899 	      op = build1 (code, TREE_TYPE (op), op);
16900 	      REF_PARENTHESIZED_P (op) = true;
16901 	      return op;
16902 	    }
16903 	  /* We shouldn't see any other uses of these in templates.  */
16904 	  gcc_unreachable ();
16905 	}
16906 
16907     case CAST_EXPR:
16908     case REINTERPRET_CAST_EXPR:
16909     case CONST_CAST_EXPR:
16910     case STATIC_CAST_EXPR:
16911     case DYNAMIC_CAST_EXPR:
16912     case IMPLICIT_CONV_EXPR:
16913     case CONVERT_EXPR:
16914     case NOP_EXPR:
16915       {
16916 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16917 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16918 	return build1 (code, type, op0);
16919       }
16920 
16921     case BIT_CAST_EXPR:
16922       {
16923 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16924 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16925 	r = build_min (BIT_CAST_EXPR, type, op0);
16926 	SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
16927 	return r;
16928       }
16929 
16930     case SIZEOF_EXPR:
16931       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16932 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16933         {
16934           tree expanded, op = TREE_OPERAND (t, 0);
16935 	  int len = 0;
16936 
16937 	  if (SIZEOF_EXPR_TYPE_P (t))
16938 	    op = TREE_TYPE (op);
16939 
16940 	  ++cp_unevaluated_operand;
16941 	  ++c_inhibit_evaluation_warnings;
16942 	  /* We only want to compute the number of arguments.  */
16943 	  if (PACK_EXPANSION_P (op))
16944 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
16945 	  else
16946 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
16947 					     args, complain, in_decl);
16948 	  --cp_unevaluated_operand;
16949 	  --c_inhibit_evaluation_warnings;
16950 
16951 	  if (TREE_CODE (expanded) == TREE_VEC)
16952 	    {
16953 	      len = TREE_VEC_LENGTH (expanded);
16954 	      /* Set TREE_USED for the benefit of -Wunused.  */
16955 	      for (int i = 0; i < len; i++)
16956 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
16957 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
16958 	    }
16959 
16960 	  if (expanded == error_mark_node)
16961 	    return error_mark_node;
16962 	  else if (PACK_EXPANSION_P (expanded)
16963 		   || (TREE_CODE (expanded) == TREE_VEC
16964 		       && pack_expansion_args_count (expanded)))
16965 
16966 	    {
16967 	      if (PACK_EXPANSION_P (expanded))
16968 		/* OK.  */;
16969 	      else if (TREE_VEC_LENGTH (expanded) == 1)
16970 		expanded = TREE_VEC_ELT (expanded, 0);
16971 	      else
16972 		expanded = make_argument_pack (expanded);
16973 
16974 	      if (TYPE_P (expanded))
16975 		return cxx_sizeof_or_alignof_type (input_location,
16976 						   expanded, SIZEOF_EXPR,
16977 						   false,
16978 						   complain & tf_error);
16979 	      else
16980 		return cxx_sizeof_or_alignof_expr (input_location,
16981 						   expanded, SIZEOF_EXPR,
16982 						   false,
16983                                                    complain & tf_error);
16984 	    }
16985 	  else
16986 	    return build_int_cst (size_type_node, len);
16987         }
16988       if (SIZEOF_EXPR_TYPE_P (t))
16989 	{
16990 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
16991 		      args, complain, in_decl);
16992 	  r = build1 (NOP_EXPR, r, error_mark_node);
16993 	  r = build1 (SIZEOF_EXPR,
16994 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
16995 	  SIZEOF_EXPR_TYPE_P (r) = 1;
16996 	  return r;
16997 	}
16998       /* Fall through */
16999 
17000     case INDIRECT_REF:
17001     case NEGATE_EXPR:
17002     case TRUTH_NOT_EXPR:
17003     case BIT_NOT_EXPR:
17004     case ADDR_EXPR:
17005     case UNARY_PLUS_EXPR:      /* Unary + */
17006     case ALIGNOF_EXPR:
17007     case AT_ENCODE_EXPR:
17008     case ARROW_EXPR:
17009     case THROW_EXPR:
17010     case TYPEID_EXPR:
17011     case REALPART_EXPR:
17012     case IMAGPART_EXPR:
17013     case PAREN_EXPR:
17014       {
17015 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17016 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17017 	r = build1 (code, type, op0);
17018 	if (code == ALIGNOF_EXPR)
17019 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17020 	return r;
17021       }
17022 
17023     case COMPONENT_REF:
17024       {
17025 	tree object;
17026 	tree name;
17027 
17028 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17029 	name = TREE_OPERAND (t, 1);
17030 	if (TREE_CODE (name) == BIT_NOT_EXPR)
17031 	  {
17032 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17033 				complain, in_decl);
17034 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17035 	  }
17036 	else if (TREE_CODE (name) == SCOPE_REF
17037 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17038 	  {
17039 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17040 				     complain, in_decl);
17041 	    name = TREE_OPERAND (name, 1);
17042 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17043 				complain, in_decl);
17044 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17045 	    name = build_qualified_name (/*type=*/NULL_TREE,
17046 					 base, name,
17047 					 /*template_p=*/false);
17048 	  }
17049 	else if (BASELINK_P (name))
17050 	  name = tsubst_baselink (name,
17051 				  non_reference (TREE_TYPE (object)),
17052 				  args, complain,
17053 				  in_decl);
17054 	else
17055 	  name = tsubst_copy (name, args, complain, in_decl);
17056 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17057       }
17058 
17059     case PLUS_EXPR:
17060     case MINUS_EXPR:
17061     case MULT_EXPR:
17062     case TRUNC_DIV_EXPR:
17063     case CEIL_DIV_EXPR:
17064     case FLOOR_DIV_EXPR:
17065     case ROUND_DIV_EXPR:
17066     case EXACT_DIV_EXPR:
17067     case BIT_AND_EXPR:
17068     case BIT_IOR_EXPR:
17069     case BIT_XOR_EXPR:
17070     case TRUNC_MOD_EXPR:
17071     case FLOOR_MOD_EXPR:
17072     case TRUTH_ANDIF_EXPR:
17073     case TRUTH_ORIF_EXPR:
17074     case TRUTH_AND_EXPR:
17075     case TRUTH_OR_EXPR:
17076     case RSHIFT_EXPR:
17077     case LSHIFT_EXPR:
17078     case EQ_EXPR:
17079     case NE_EXPR:
17080     case MAX_EXPR:
17081     case MIN_EXPR:
17082     case LE_EXPR:
17083     case GE_EXPR:
17084     case LT_EXPR:
17085     case GT_EXPR:
17086     case COMPOUND_EXPR:
17087     case DOTSTAR_EXPR:
17088     case MEMBER_REF:
17089     case PREDECREMENT_EXPR:
17090     case PREINCREMENT_EXPR:
17091     case POSTDECREMENT_EXPR:
17092     case POSTINCREMENT_EXPR:
17093       {
17094 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17095 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17096 	return build_nt (code, op0, op1);
17097       }
17098 
17099     case SCOPE_REF:
17100       {
17101 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17102 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17103 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17104 				     QUALIFIED_NAME_IS_TEMPLATE (t));
17105       }
17106 
17107     case ARRAY_REF:
17108       {
17109 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17110 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17111 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17112       }
17113 
17114     case CALL_EXPR:
17115       {
17116 	int n = VL_EXP_OPERAND_LENGTH (t);
17117 	tree result = build_vl_exp (CALL_EXPR, n);
17118 	int i;
17119 	for (i = 0; i < n; i++)
17120 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17121 					     complain, in_decl);
17122 	return result;
17123       }
17124 
17125     case COND_EXPR:
17126     case MODOP_EXPR:
17127     case PSEUDO_DTOR_EXPR:
17128     case VEC_PERM_EXPR:
17129       {
17130 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17131 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17132 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17133 	r = build_nt (code, op0, op1, op2);
17134 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
17135 	return r;
17136       }
17137 
17138     case NEW_EXPR:
17139       {
17140 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17141 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17142 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17143 	r = build_nt (code, op0, op1, op2);
17144 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17145 	return r;
17146       }
17147 
17148     case DELETE_EXPR:
17149       {
17150 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17151 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17152 	r = build_nt (code, op0, op1);
17153 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17154 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17155 	return r;
17156       }
17157 
17158     case TEMPLATE_ID_EXPR:
17159       {
17160 	/* Substituted template arguments */
17161 	tree tmpl = TREE_OPERAND (t, 0);
17162 	tree targs = TREE_OPERAND (t, 1);
17163 
17164 	tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17165 	if (targs)
17166 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17167 
17168 	if (variable_template_p (tmpl))
17169 	  return lookup_template_variable (tmpl, targs);
17170 	else
17171 	  return lookup_template_function (tmpl, targs);
17172       }
17173 
17174     case TREE_LIST:
17175       {
17176 	tree purpose, value, chain;
17177 
17178 	if (t == void_list_node)
17179 	  return t;
17180 
17181 	purpose = TREE_PURPOSE (t);
17182 	if (purpose)
17183 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
17184 	value = TREE_VALUE (t);
17185 	if (value)
17186 	  value = tsubst_copy (value, args, complain, in_decl);
17187 	chain = TREE_CHAIN (t);
17188 	if (chain && chain != void_type_node)
17189 	  chain = tsubst_copy (chain, args, complain, in_decl);
17190 	if (purpose == TREE_PURPOSE (t)
17191 	    && value == TREE_VALUE (t)
17192 	    && chain == TREE_CHAIN (t))
17193 	  return t;
17194 	return tree_cons (purpose, value, chain);
17195       }
17196 
17197     case RECORD_TYPE:
17198     case UNION_TYPE:
17199     case ENUMERAL_TYPE:
17200     case INTEGER_TYPE:
17201     case TEMPLATE_TYPE_PARM:
17202     case TEMPLATE_TEMPLATE_PARM:
17203     case BOUND_TEMPLATE_TEMPLATE_PARM:
17204     case TEMPLATE_PARM_INDEX:
17205     case POINTER_TYPE:
17206     case REFERENCE_TYPE:
17207     case OFFSET_TYPE:
17208     case FUNCTION_TYPE:
17209     case METHOD_TYPE:
17210     case ARRAY_TYPE:
17211     case TYPENAME_TYPE:
17212     case UNBOUND_CLASS_TEMPLATE:
17213     case TYPEOF_TYPE:
17214     case DECLTYPE_TYPE:
17215     case TYPE_DECL:
17216       return tsubst (t, args, complain, in_decl);
17217 
17218     case USING_DECL:
17219       t = DECL_NAME (t);
17220       /* Fall through.  */
17221     case IDENTIFIER_NODE:
17222       if (IDENTIFIER_CONV_OP_P (t))
17223 	{
17224 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17225 	  return make_conv_op_name (new_type);
17226 	}
17227       else
17228 	return t;
17229 
17230     case CONSTRUCTOR:
17231       /* This is handled by tsubst_copy_and_build.  */
17232       gcc_unreachable ();
17233 
17234     case VA_ARG_EXPR:
17235       {
17236 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17237 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17238 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17239       }
17240 
17241     case CLEANUP_POINT_EXPR:
17242       /* We shouldn't have built any of these during initial template
17243 	 generation.  Instead, they should be built during instantiation
17244 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
17245       gcc_unreachable ();
17246 
17247     case OFFSET_REF:
17248       {
17249 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17250 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17251 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17252 	r = build2 (code, type, op0, op1);
17253 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17254 	if (!mark_used (TREE_OPERAND (r, 1), complain)
17255 	    && !(complain & tf_error))
17256 	  return error_mark_node;
17257 	return r;
17258       }
17259 
17260     case EXPR_PACK_EXPANSION:
17261       error ("invalid use of pack expansion expression");
17262       return error_mark_node;
17263 
17264     case NONTYPE_ARGUMENT_PACK:
17265       error ("use %<...%> to expand argument pack");
17266       return error_mark_node;
17267 
17268     case VOID_CST:
17269       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17270       return t;
17271 
17272     case INTEGER_CST:
17273     case REAL_CST:
17274     case COMPLEX_CST:
17275       {
17276 	/* Instantiate any typedefs in the type.  */
17277 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17278 	r = fold_convert (type, t);
17279 	gcc_assert (TREE_CODE (r) == code);
17280 	return r;
17281       }
17282 
17283     case STRING_CST:
17284       {
17285 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17286 	r = t;
17287 	if (type != TREE_TYPE (t))
17288 	  {
17289 	    r = copy_node (t);
17290 	    TREE_TYPE (r) = type;
17291 	  }
17292 	return r;
17293       }
17294 
17295     case PTRMEM_CST:
17296       /* These can sometimes show up in a partial instantiation, but never
17297 	 involve template parms.  */
17298       gcc_assert (!uses_template_parms (t));
17299       return t;
17300 
17301     case UNARY_LEFT_FOLD_EXPR:
17302       return tsubst_unary_left_fold (t, args, complain, in_decl);
17303     case UNARY_RIGHT_FOLD_EXPR:
17304       return tsubst_unary_right_fold (t, args, complain, in_decl);
17305     case BINARY_LEFT_FOLD_EXPR:
17306       return tsubst_binary_left_fold (t, args, complain, in_decl);
17307     case BINARY_RIGHT_FOLD_EXPR:
17308       return tsubst_binary_right_fold (t, args, complain, in_decl);
17309     case PREDICT_EXPR:
17310       return t;
17311 
17312     case DEBUG_BEGIN_STMT:
17313       /* ??? There's no point in copying it for now, but maybe some
17314 	 day it will contain more information, such as a pointer back
17315 	 to the containing function, inlined copy or so.  */
17316       return t;
17317 
17318     case CO_AWAIT_EXPR:
17319       return tsubst_expr (t, args, complain, in_decl,
17320 			  /*integral_constant_expression_p=*/false);
17321       break;
17322 
17323     default:
17324       /* We shouldn't get here, but keep going if !flag_checking.  */
17325       if (flag_checking)
17326 	gcc_unreachable ();
17327       return t;
17328     }
17329 }
17330 
17331 /* Helper function for tsubst_omp_clauses, used for instantiation of
17332    OMP_CLAUSE_DECL of clauses.  */
17333 
17334 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl,tree * iterator_cache)17335 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17336 			tree in_decl, tree *iterator_cache)
17337 {
17338   if (decl == NULL_TREE)
17339     return NULL_TREE;
17340 
17341   /* Handle OpenMP iterators.  */
17342   if (TREE_CODE (decl) == TREE_LIST
17343       && TREE_PURPOSE (decl)
17344       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17345     {
17346       tree ret;
17347       if (iterator_cache[0] == TREE_PURPOSE (decl))
17348 	ret = iterator_cache[1];
17349       else
17350 	{
17351 	  tree *tp = &ret;
17352 	  begin_scope (sk_omp, NULL);
17353 	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17354 	    {
17355 	      *tp = copy_node (it);
17356 	      TREE_VEC_ELT (*tp, 0)
17357 		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17358 	      TREE_VEC_ELT (*tp, 1)
17359 		= tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17360 			       /*integral_constant_expression_p=*/false);
17361 	      TREE_VEC_ELT (*tp, 2)
17362 		= tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17363 			       /*integral_constant_expression_p=*/false);
17364 	      TREE_VEC_ELT (*tp, 3)
17365 		= tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17366 			       /*integral_constant_expression_p=*/false);
17367 	      TREE_CHAIN (*tp) = NULL_TREE;
17368 	      tp = &TREE_CHAIN (*tp);
17369 	    }
17370 	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17371 	  iterator_cache[0] = TREE_PURPOSE (decl);
17372 	  iterator_cache[1] = ret;
17373 	}
17374       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17375 							   args, complain,
17376 							   in_decl, NULL));
17377     }
17378 
17379   /* Handle an OpenMP array section represented as a TREE_LIST (or
17380      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17381      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17382      TREE_LIST.  We can handle it exactly the same as an array section
17383      (purpose, value, and a chain), even though the nomenclature
17384      (low_bound, length, etc) is different.  */
17385   if (TREE_CODE (decl) == TREE_LIST)
17386     {
17387       tree low_bound
17388 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17389 		       /*integral_constant_expression_p=*/false);
17390       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17391 				 /*integral_constant_expression_p=*/false);
17392       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17393 					   in_decl, NULL);
17394       if (TREE_PURPOSE (decl) == low_bound
17395 	  && TREE_VALUE (decl) == length
17396 	  && TREE_CHAIN (decl) == chain)
17397 	return decl;
17398       tree ret = tree_cons (low_bound, length, chain);
17399       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17400 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17401       return ret;
17402     }
17403   tree ret = tsubst_expr (decl, args, complain, in_decl,
17404 			  /*integral_constant_expression_p=*/false);
17405   /* Undo convert_from_reference tsubst_expr could have called.  */
17406   if (decl
17407       && REFERENCE_REF_P (ret)
17408       && !REFERENCE_REF_P (decl))
17409     ret = TREE_OPERAND (ret, 0);
17410   return ret;
17411 }
17412 
17413 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
17414 
17415 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)17416 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17417 		    tree args, tsubst_flags_t complain, tree in_decl)
17418 {
17419   tree new_clauses = NULL_TREE, nc, oc;
17420   tree linear_no_step = NULL_TREE;
17421   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17422 
17423   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17424     {
17425       nc = copy_node (oc);
17426       OMP_CLAUSE_CHAIN (nc) = new_clauses;
17427       new_clauses = nc;
17428 
17429       switch (OMP_CLAUSE_CODE (nc))
17430 	{
17431 	case OMP_CLAUSE_LASTPRIVATE:
17432 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17433 	    {
17434 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17435 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17436 			   in_decl, /*integral_constant_expression_p=*/false);
17437 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17438 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17439 	    }
17440 	  /* FALLTHRU */
17441 	case OMP_CLAUSE_PRIVATE:
17442 	case OMP_CLAUSE_SHARED:
17443 	case OMP_CLAUSE_FIRSTPRIVATE:
17444 	case OMP_CLAUSE_COPYIN:
17445 	case OMP_CLAUSE_COPYPRIVATE:
17446 	case OMP_CLAUSE_UNIFORM:
17447 	case OMP_CLAUSE_DEPEND:
17448 	case OMP_CLAUSE_FROM:
17449 	case OMP_CLAUSE_TO:
17450 	case OMP_CLAUSE_MAP:
17451 	case OMP_CLAUSE__CACHE_:
17452 	case OMP_CLAUSE_NONTEMPORAL:
17453 	case OMP_CLAUSE_USE_DEVICE_PTR:
17454 	case OMP_CLAUSE_USE_DEVICE_ADDR:
17455 	case OMP_CLAUSE_IS_DEVICE_PTR:
17456 	case OMP_CLAUSE_INCLUSIVE:
17457 	case OMP_CLAUSE_EXCLUSIVE:
17458 	  OMP_CLAUSE_DECL (nc)
17459 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17460 				      in_decl, iterator_cache);
17461 	  break;
17462 	case OMP_CLAUSE_TILE:
17463 	case OMP_CLAUSE_IF:
17464 	case OMP_CLAUSE_NUM_THREADS:
17465 	case OMP_CLAUSE_SCHEDULE:
17466 	case OMP_CLAUSE_COLLAPSE:
17467 	case OMP_CLAUSE_FINAL:
17468 	case OMP_CLAUSE_DEVICE:
17469 	case OMP_CLAUSE_DIST_SCHEDULE:
17470 	case OMP_CLAUSE_NUM_TEAMS:
17471 	case OMP_CLAUSE_THREAD_LIMIT:
17472 	case OMP_CLAUSE_SAFELEN:
17473 	case OMP_CLAUSE_SIMDLEN:
17474 	case OMP_CLAUSE_NUM_TASKS:
17475 	case OMP_CLAUSE_GRAINSIZE:
17476 	case OMP_CLAUSE_PRIORITY:
17477 	case OMP_CLAUSE_ORDERED:
17478 	case OMP_CLAUSE_HINT:
17479 	case OMP_CLAUSE_NUM_GANGS:
17480 	case OMP_CLAUSE_NUM_WORKERS:
17481 	case OMP_CLAUSE_VECTOR_LENGTH:
17482 	case OMP_CLAUSE_WORKER:
17483 	case OMP_CLAUSE_VECTOR:
17484 	case OMP_CLAUSE_ASYNC:
17485 	case OMP_CLAUSE_WAIT:
17486 	case OMP_CLAUSE_DETACH:
17487 	  OMP_CLAUSE_OPERAND (nc, 0)
17488 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17489 			   in_decl, /*integral_constant_expression_p=*/false);
17490 	  break;
17491 	case OMP_CLAUSE_REDUCTION:
17492 	case OMP_CLAUSE_IN_REDUCTION:
17493 	case OMP_CLAUSE_TASK_REDUCTION:
17494 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17495 	    {
17496 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17497 	      if (TREE_CODE (placeholder) == SCOPE_REF)
17498 		{
17499 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17500 				       complain, in_decl);
17501 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17502 		    = build_qualified_name (NULL_TREE, scope,
17503 					    TREE_OPERAND (placeholder, 1),
17504 					    false);
17505 		}
17506 	      else
17507 		gcc_assert (identifier_p (placeholder));
17508 	    }
17509 	  OMP_CLAUSE_DECL (nc)
17510 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17511 				      in_decl, NULL);
17512 	  break;
17513 	case OMP_CLAUSE_GANG:
17514 	case OMP_CLAUSE_ALIGNED:
17515 	case OMP_CLAUSE_ALLOCATE:
17516 	  OMP_CLAUSE_DECL (nc)
17517 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17518 				      in_decl, NULL);
17519 	  OMP_CLAUSE_OPERAND (nc, 1)
17520 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17521 			   in_decl, /*integral_constant_expression_p=*/false);
17522 	  break;
17523 	case OMP_CLAUSE_LINEAR:
17524 	  OMP_CLAUSE_DECL (nc)
17525 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17526 				      in_decl, NULL);
17527 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17528 	    {
17529 	      gcc_assert (!linear_no_step);
17530 	      linear_no_step = nc;
17531 	    }
17532 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17533 	    OMP_CLAUSE_LINEAR_STEP (nc)
17534 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17535 					complain, in_decl, NULL);
17536 	  else
17537 	    OMP_CLAUSE_LINEAR_STEP (nc)
17538 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17539 			     in_decl,
17540 			     /*integral_constant_expression_p=*/false);
17541 	  break;
17542 	case OMP_CLAUSE_NOWAIT:
17543 	case OMP_CLAUSE_DEFAULT:
17544 	case OMP_CLAUSE_UNTIED:
17545 	case OMP_CLAUSE_MERGEABLE:
17546 	case OMP_CLAUSE_INBRANCH:
17547 	case OMP_CLAUSE_NOTINBRANCH:
17548 	case OMP_CLAUSE_PROC_BIND:
17549 	case OMP_CLAUSE_FOR:
17550 	case OMP_CLAUSE_PARALLEL:
17551 	case OMP_CLAUSE_SECTIONS:
17552 	case OMP_CLAUSE_TASKGROUP:
17553 	case OMP_CLAUSE_NOGROUP:
17554 	case OMP_CLAUSE_THREADS:
17555 	case OMP_CLAUSE_SIMD:
17556 	case OMP_CLAUSE_DEFAULTMAP:
17557 	case OMP_CLAUSE_ORDER:
17558 	case OMP_CLAUSE_BIND:
17559 	case OMP_CLAUSE_INDEPENDENT:
17560 	case OMP_CLAUSE_AUTO:
17561 	case OMP_CLAUSE_SEQ:
17562 	case OMP_CLAUSE_IF_PRESENT:
17563 	case OMP_CLAUSE_FINALIZE:
17564 	  break;
17565 	default:
17566 	  gcc_unreachable ();
17567 	}
17568       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17569 	switch (OMP_CLAUSE_CODE (nc))
17570 	  {
17571 	  case OMP_CLAUSE_SHARED:
17572 	  case OMP_CLAUSE_PRIVATE:
17573 	  case OMP_CLAUSE_FIRSTPRIVATE:
17574 	  case OMP_CLAUSE_LASTPRIVATE:
17575 	  case OMP_CLAUSE_COPYPRIVATE:
17576 	  case OMP_CLAUSE_LINEAR:
17577 	  case OMP_CLAUSE_REDUCTION:
17578 	  case OMP_CLAUSE_IN_REDUCTION:
17579 	  case OMP_CLAUSE_TASK_REDUCTION:
17580 	  case OMP_CLAUSE_USE_DEVICE_PTR:
17581 	  case OMP_CLAUSE_USE_DEVICE_ADDR:
17582 	  case OMP_CLAUSE_IS_DEVICE_PTR:
17583 	  case OMP_CLAUSE_INCLUSIVE:
17584 	  case OMP_CLAUSE_EXCLUSIVE:
17585 	  case OMP_CLAUSE_ALLOCATE:
17586 	    /* tsubst_expr on SCOPE_REF results in returning
17587 	       finish_non_static_data_member result.  Undo that here.  */
17588 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17589 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17590 		    == IDENTIFIER_NODE))
17591 	      {
17592 		tree t = OMP_CLAUSE_DECL (nc);
17593 		tree v = t;
17594 		while (v)
17595 		  switch (TREE_CODE (v))
17596 		    {
17597 		    case COMPONENT_REF:
17598 		    case MEM_REF:
17599 		    case INDIRECT_REF:
17600 		    CASE_CONVERT:
17601 		    case POINTER_PLUS_EXPR:
17602 		      v = TREE_OPERAND (v, 0);
17603 		      continue;
17604 		    case PARM_DECL:
17605 		      if (DECL_CONTEXT (v) == current_function_decl
17606 			  && DECL_ARTIFICIAL (v)
17607 			  && DECL_NAME (v) == this_identifier)
17608 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17609 		      /* FALLTHRU */
17610 		    default:
17611 		      v = NULL_TREE;
17612 		      break;
17613 		    }
17614 	      }
17615 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
17616 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17617 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17618 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17619 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17620 	      {
17621 		tree decl = OMP_CLAUSE_DECL (nc);
17622 		if (VAR_P (decl))
17623 		  {
17624 		    retrofit_lang_decl (decl);
17625 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17626 		  }
17627 	      }
17628 	    break;
17629 	  default:
17630 	    break;
17631 	  }
17632     }
17633 
17634   new_clauses = nreverse (new_clauses);
17635   if (ort != C_ORT_OMP_DECLARE_SIMD)
17636     {
17637       new_clauses = finish_omp_clauses (new_clauses, ort);
17638       if (linear_no_step)
17639 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17640 	  if (nc == linear_no_step)
17641 	    {
17642 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17643 	      break;
17644 	    }
17645     }
17646   return new_clauses;
17647 }
17648 
17649 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
17650 
17651 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)17652 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17653 			  tree in_decl)
17654 {
17655 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17656 
17657   tree purpose, value, chain;
17658 
17659   if (t == NULL)
17660     return t;
17661 
17662   if (TREE_CODE (t) != TREE_LIST)
17663     return tsubst_copy_and_build (t, args, complain, in_decl,
17664 				  /*function_p=*/false,
17665 				  /*integral_constant_expression_p=*/false);
17666 
17667   if (t == void_list_node)
17668     return t;
17669 
17670   purpose = TREE_PURPOSE (t);
17671   if (purpose)
17672     purpose = RECUR (purpose);
17673   value = TREE_VALUE (t);
17674   if (value)
17675     {
17676       if (TREE_CODE (value) != LABEL_DECL)
17677 	value = RECUR (value);
17678       else
17679 	{
17680 	  value = lookup_label (DECL_NAME (value));
17681 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
17682 	  TREE_USED (value) = 1;
17683 	}
17684     }
17685   chain = TREE_CHAIN (t);
17686   if (chain && chain != void_type_node)
17687     chain = RECUR (chain);
17688   return tree_cons (purpose, value, chain);
17689 #undef RECUR
17690 }
17691 
17692 /* Used to temporarily communicate the list of #pragma omp parallel
17693    clauses to #pragma omp for instantiation if they are combined
17694    together.  */
17695 
17696 static tree *omp_parallel_combined_clauses;
17697 
17698 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17699 				 tree *, unsigned int *);
17700 
17701 /* Substitute one OMP_FOR iterator.  */
17702 
17703 static bool
tsubst_omp_for_iterator(tree t,int i,tree declv,tree & orig_declv,tree initv,tree condv,tree incrv,tree * clauses,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)17704 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17705 			 tree initv, tree condv, tree incrv, tree *clauses,
17706 			 tree args, tsubst_flags_t complain, tree in_decl,
17707 			 bool integral_constant_expression_p)
17708 {
17709 #define RECUR(NODE)				\
17710   tsubst_expr ((NODE), args, complain, in_decl,	\
17711 	       integral_constant_expression_p)
17712   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17713   bool ret = false;
17714 
17715   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17716   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17717 
17718   decl = TREE_OPERAND (init, 0);
17719   init = TREE_OPERAND (init, 1);
17720   tree decl_expr = NULL_TREE;
17721   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17722   if (range_for)
17723     {
17724       bool decomp = false;
17725       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17726 	{
17727 	  tree v = DECL_VALUE_EXPR (decl);
17728 	  if (TREE_CODE (v) == ARRAY_REF
17729 	      && VAR_P (TREE_OPERAND (v, 0))
17730 	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17731 	    {
17732 	      tree decomp_first = NULL_TREE;
17733 	      unsigned decomp_cnt = 0;
17734 	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17735 	      maybe_push_decl (d);
17736 	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17737 				       in_decl, &decomp_first, &decomp_cnt);
17738 	      decomp = true;
17739 	      if (d == error_mark_node)
17740 		decl = error_mark_node;
17741 	      else
17742 		for (unsigned int i = 0; i < decomp_cnt; i++)
17743 		  {
17744 		    if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
17745 		      {
17746 			tree v = build_nt (ARRAY_REF, d,
17747 					   size_int (decomp_cnt - i - 1),
17748 					   NULL_TREE, NULL_TREE);
17749 			SET_DECL_VALUE_EXPR (decomp_first, v);
17750 			DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
17751 		      }
17752 		    fit_decomposition_lang_decl (decomp_first, d);
17753 		    decomp_first = DECL_CHAIN (decomp_first);
17754 		  }
17755 	    }
17756 	}
17757       decl = tsubst_decl (decl, args, complain);
17758       if (!decomp)
17759 	maybe_push_decl (decl);
17760     }
17761   else if (init && TREE_CODE (init) == DECL_EXPR)
17762     {
17763       /* We need to jump through some hoops to handle declarations in the
17764 	 init-statement, since we might need to handle auto deduction,
17765 	 but we need to keep control of initialization.  */
17766       decl_expr = init;
17767       init = DECL_INITIAL (DECL_EXPR_DECL (init));
17768       decl = tsubst_decl (decl, args, complain);
17769     }
17770   else
17771     {
17772       if (TREE_CODE (decl) == SCOPE_REF)
17773 	{
17774 	  decl = RECUR (decl);
17775 	  if (TREE_CODE (decl) == COMPONENT_REF)
17776 	    {
17777 	      tree v = decl;
17778 	      while (v)
17779 		switch (TREE_CODE (v))
17780 		  {
17781 		  case COMPONENT_REF:
17782 		  case MEM_REF:
17783 		  case INDIRECT_REF:
17784 		  CASE_CONVERT:
17785 		  case POINTER_PLUS_EXPR:
17786 		    v = TREE_OPERAND (v, 0);
17787 		    continue;
17788 		  case PARM_DECL:
17789 		    if (DECL_CONTEXT (v) == current_function_decl
17790 			&& DECL_ARTIFICIAL (v)
17791 			&& DECL_NAME (v) == this_identifier)
17792 		      {
17793 			decl = TREE_OPERAND (decl, 1);
17794 			decl = omp_privatize_field (decl, false);
17795 		      }
17796 		    /* FALLTHRU */
17797 		  default:
17798 		    v = NULL_TREE;
17799 		    break;
17800 		  }
17801 	    }
17802 	}
17803       else
17804 	decl = RECUR (decl);
17805     }
17806   if (init && TREE_CODE (init) == TREE_VEC)
17807     {
17808       init = copy_node (init);
17809       TREE_VEC_ELT (init, 0)
17810 	= tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
17811       TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
17812       TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
17813     }
17814   else
17815     init = RECUR (init);
17816 
17817   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17818     {
17819       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17820       if (TREE_CODE (o) == TREE_LIST)
17821 	TREE_VEC_ELT (orig_declv, i)
17822 	  = tree_cons (RECUR (TREE_PURPOSE (o)),
17823 		       RECUR (TREE_VALUE (o)),
17824 		       NULL_TREE);
17825       else
17826 	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17827     }
17828 
17829   if (range_for)
17830     {
17831       tree this_pre_body = NULL_TREE;
17832       tree orig_init = NULL_TREE;
17833       tree orig_decl = NULL_TREE;
17834       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
17835 				orig_init, cond, incr);
17836       if (orig_decl)
17837 	{
17838 	  if (orig_declv == NULL_TREE)
17839 	    orig_declv = copy_node (declv);
17840 	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
17841 	  ret = true;
17842 	}
17843       else if (orig_declv)
17844 	TREE_VEC_ELT (orig_declv, i) = decl;
17845     }
17846 
17847   tree auto_node = type_uses_auto (TREE_TYPE (decl));
17848   if (!range_for && auto_node && init)
17849     TREE_TYPE (decl)
17850       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17851 
17852   gcc_assert (!type_dependent_expression_p (decl));
17853 
17854   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17855     {
17856       if (decl_expr)
17857 	{
17858 	  /* Declare the variable, but don't let that initialize it.  */
17859 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17860 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17861 	  RECUR (decl_expr);
17862 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17863 	}
17864 
17865       if (!range_for)
17866 	{
17867 	  cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17868 	  if (COMPARISON_CLASS_P (cond)
17869 	      && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
17870 	    {
17871 	      tree lhs = RECUR (TREE_OPERAND (cond, 0));
17872 	      tree rhs = copy_node (TREE_OPERAND (cond, 1));
17873 	      TREE_VEC_ELT (rhs, 0)
17874 		= tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
17875 	      TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
17876 	      TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
17877 	      cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
17878 			     lhs, rhs);
17879 	    }
17880 	  else
17881 	    cond = RECUR (cond);
17882 	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17883 	  if (TREE_CODE (incr) == MODIFY_EXPR)
17884 	    {
17885 	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
17886 	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
17887 	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17888 					  NOP_EXPR, rhs, complain);
17889 	    }
17890 	  else
17891 	    incr = RECUR (incr);
17892 	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17893 	    TREE_VEC_ELT (orig_declv, i) = decl;
17894 	}
17895       TREE_VEC_ELT (declv, i) = decl;
17896       TREE_VEC_ELT (initv, i) = init;
17897       TREE_VEC_ELT (condv, i) = cond;
17898       TREE_VEC_ELT (incrv, i) = incr;
17899       return ret;
17900     }
17901 
17902   if (decl_expr)
17903     {
17904       /* Declare and initialize the variable.  */
17905       RECUR (decl_expr);
17906       init = NULL_TREE;
17907     }
17908   else if (init)
17909     {
17910       tree *pc;
17911       int j;
17912       for (j = ((omp_parallel_combined_clauses == NULL
17913 		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17914 	{
17915 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17916 	    {
17917 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17918 		  && OMP_CLAUSE_DECL (*pc) == decl)
17919 		break;
17920 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17921 		       && OMP_CLAUSE_DECL (*pc) == decl)
17922 		{
17923 		  if (j)
17924 		    break;
17925 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
17926 		  tree c = *pc;
17927 		  *pc = OMP_CLAUSE_CHAIN (c);
17928 		  OMP_CLAUSE_CHAIN (c) = *clauses;
17929 		  *clauses = c;
17930 		}
17931 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17932 		       && OMP_CLAUSE_DECL (*pc) == decl)
17933 		{
17934 		  error ("iteration variable %qD should not be firstprivate",
17935 			 decl);
17936 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17937 		}
17938 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17939 		       && OMP_CLAUSE_DECL (*pc) == decl)
17940 		{
17941 		  error ("iteration variable %qD should not be reduction",
17942 			 decl);
17943 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17944 		}
17945 	      else
17946 		pc = &OMP_CLAUSE_CHAIN (*pc);
17947 	    }
17948 	  if (*pc)
17949 	    break;
17950 	}
17951       if (*pc == NULL_TREE)
17952 	{
17953 	  tree c = build_omp_clause (input_location,
17954 				     TREE_CODE (t) == OMP_LOOP
17955 				     ? OMP_CLAUSE_LASTPRIVATE
17956 				     : OMP_CLAUSE_PRIVATE);
17957 	  OMP_CLAUSE_DECL (c) = decl;
17958 	  c = finish_omp_clauses (c, C_ORT_OMP);
17959 	  if (c)
17960 	    {
17961 	      OMP_CLAUSE_CHAIN (c) = *clauses;
17962 	      *clauses = c;
17963 	    }
17964 	}
17965     }
17966   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17967   if (COMPARISON_CLASS_P (cond))
17968     {
17969       tree op0 = RECUR (TREE_OPERAND (cond, 0));
17970       tree op1 = RECUR (TREE_OPERAND (cond, 1));
17971       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
17972     }
17973   else
17974     cond = RECUR (cond);
17975   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17976   switch (TREE_CODE (incr))
17977     {
17978     case PREINCREMENT_EXPR:
17979     case PREDECREMENT_EXPR:
17980     case POSTINCREMENT_EXPR:
17981     case POSTDECREMENT_EXPR:
17982       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
17983 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
17984       break;
17985     case MODIFY_EXPR:
17986       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17987 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17988 	{
17989 	  tree rhs = TREE_OPERAND (incr, 1);
17990 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17991 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17992 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17993 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17994 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17995 				 rhs0, rhs1));
17996 	}
17997       else
17998 	incr = RECUR (incr);
17999       break;
18000     case MODOP_EXPR:
18001       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18002 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18003 	{
18004 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18005 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18006 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18007 				 TREE_TYPE (decl), lhs,
18008 				 RECUR (TREE_OPERAND (incr, 2))));
18009 	}
18010       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18011 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18012 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18013 	{
18014 	  tree rhs = TREE_OPERAND (incr, 2);
18015 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18016 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18017 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18018 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18019 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18020 				 rhs0, rhs1));
18021 	}
18022       else
18023 	incr = RECUR (incr);
18024       break;
18025     default:
18026       incr = RECUR (incr);
18027       break;
18028     }
18029 
18030   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18031     TREE_VEC_ELT (orig_declv, i) = decl;
18032   TREE_VEC_ELT (declv, i) = decl;
18033   TREE_VEC_ELT (initv, i) = init;
18034   TREE_VEC_ELT (condv, i) = cond;
18035   TREE_VEC_ELT (incrv, i) = incr;
18036   return false;
18037 #undef RECUR
18038 }
18039 
18040 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18041    of OMP_TARGET's body.  */
18042 
18043 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)18044 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18045 {
18046   *walk_subtrees = 0;
18047   switch (TREE_CODE (*tp))
18048     {
18049     case OMP_TEAMS:
18050       return *tp;
18051     case BIND_EXPR:
18052     case STATEMENT_LIST:
18053       *walk_subtrees = 1;
18054       break;
18055     default:
18056       break;
18057     }
18058   return NULL_TREE;
18059 }
18060 
18061 /* Helper function for tsubst_expr.  For decomposition declaration
18062    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18063    also the corresponding decls representing the identifiers
18064    of the decomposition declaration.  Return DECL if successful
18065    or error_mark_node otherwise, set *FIRST to the first decl
18066    in the list chained through DECL_CHAIN and *CNT to the number
18067    of such decls.  */
18068 
18069 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)18070 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18071 		     tsubst_flags_t complain, tree in_decl, tree *first,
18072 		     unsigned int *cnt)
18073 {
18074   tree decl2, decl3, prev = decl;
18075   *cnt = 0;
18076   gcc_assert (DECL_NAME (decl) == NULL_TREE);
18077   for (decl2 = DECL_CHAIN (pattern_decl);
18078        decl2
18079        && VAR_P (decl2)
18080        && DECL_DECOMPOSITION_P (decl2)
18081        && DECL_NAME (decl2);
18082        decl2 = DECL_CHAIN (decl2))
18083     {
18084       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18085 	{
18086 	  gcc_assert (errorcount);
18087 	  return error_mark_node;
18088 	}
18089       (*cnt)++;
18090       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18091       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18092       tree v = DECL_VALUE_EXPR (decl2);
18093       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18094       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18095       decl3 = tsubst (decl2, args, complain, in_decl);
18096       SET_DECL_VALUE_EXPR (decl2, v);
18097       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18098       if (VAR_P (decl3))
18099 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18100       else
18101 	{
18102 	  gcc_assert (errorcount);
18103 	  decl = error_mark_node;
18104 	  continue;
18105 	}
18106       maybe_push_decl (decl3);
18107       if (error_operand_p (decl3))
18108 	decl = error_mark_node;
18109       else if (decl != error_mark_node
18110 	       && DECL_CHAIN (decl3) != prev
18111 	       && decl != prev)
18112 	{
18113 	  gcc_assert (errorcount);
18114 	  decl = error_mark_node;
18115 	}
18116       else
18117 	prev = decl3;
18118     }
18119   *first = prev;
18120   return decl;
18121 }
18122 
18123 /* Return the proper local_specialization for init-capture pack DECL.  */
18124 
18125 static tree
lookup_init_capture_pack(tree decl)18126 lookup_init_capture_pack (tree decl)
18127 {
18128   /* We handle normal pack captures by forwarding to the specialization of the
18129      captured parameter.  We can't do that for pack init-captures; we need them
18130      to have their own local_specialization.  We created the individual
18131      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18132      when we process the DECL_EXPR for the pack init-capture in the template.
18133      So, how do we find them?  We don't know the capture proxy pack when
18134      building the individual resulting proxies, and we don't know the
18135      individual proxies when instantiating the pack.  What we have in common is
18136      the FIELD_DECL.
18137 
18138      So...when we instantiate the FIELD_DECL, we stick the result in
18139      local_specializations.  Then at the DECL_EXPR we look up that result, see
18140      how many elements it has, synthesize the names, and look them up.  */
18141 
18142   tree cname = DECL_NAME (decl);
18143   tree val = DECL_VALUE_EXPR (decl);
18144   tree field = TREE_OPERAND (val, 1);
18145   gcc_assert (TREE_CODE (field) == FIELD_DECL);
18146   tree fpack = retrieve_local_specialization (field);
18147   if (fpack == error_mark_node)
18148     return error_mark_node;
18149 
18150   int len = 1;
18151   tree vec = NULL_TREE;
18152   tree r = NULL_TREE;
18153   if (TREE_CODE (fpack) == TREE_VEC)
18154     {
18155       len = TREE_VEC_LENGTH (fpack);
18156       vec = make_tree_vec (len);
18157       r = make_node (NONTYPE_ARGUMENT_PACK);
18158       SET_ARGUMENT_PACK_ARGS (r, vec);
18159     }
18160   for (int i = 0; i < len; ++i)
18161     {
18162       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18163       tree elt = lookup_name (ename);
18164       if (vec)
18165 	TREE_VEC_ELT (vec, i) = elt;
18166       else
18167 	r = elt;
18168     }
18169   return r;
18170 }
18171 
18172 /* Like tsubst_copy for expressions, etc. but also does semantic
18173    processing.  */
18174 
18175 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)18176 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
18177 	     bool integral_constant_expression_p)
18178 {
18179 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18180 #define RECUR(NODE)				\
18181   tsubst_expr ((NODE), args, complain, in_decl,	\
18182 	       integral_constant_expression_p)
18183 
18184   tree stmt, tmp;
18185   tree r;
18186   location_t loc;
18187 
18188   if (t == NULL_TREE || t == error_mark_node)
18189     return t;
18190 
18191   loc = input_location;
18192   if (location_t eloc = cp_expr_location (t))
18193     input_location = eloc;
18194   if (STATEMENT_CODE_P (TREE_CODE (t)))
18195     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18196 
18197   switch (TREE_CODE (t))
18198     {
18199     case STATEMENT_LIST:
18200       {
18201 	tree_stmt_iterator i;
18202 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
18203 	  RECUR (tsi_stmt (i));
18204 	break;
18205       }
18206 
18207     case CTOR_INITIALIZER:
18208       finish_mem_initializers (tsubst_initializer_list
18209 			       (TREE_OPERAND (t, 0), args));
18210       break;
18211 
18212     case RETURN_EXPR:
18213       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18214       break;
18215 
18216     case CO_RETURN_EXPR:
18217       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18218       break;
18219 
18220     case CO_YIELD_EXPR:
18221       stmt = finish_co_yield_expr (input_location,
18222 				   RECUR (TREE_OPERAND (t, 0)));
18223       RETURN (stmt);
18224       break;
18225 
18226     case CO_AWAIT_EXPR:
18227       stmt = finish_co_await_expr (input_location,
18228 				   RECUR (TREE_OPERAND (t, 0)));
18229       RETURN (stmt);
18230       break;
18231 
18232     case EXPR_STMT:
18233       tmp = RECUR (EXPR_STMT_EXPR (t));
18234       if (EXPR_STMT_STMT_EXPR_RESULT (t))
18235 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
18236       else
18237 	finish_expr_stmt (tmp);
18238       break;
18239 
18240     case USING_STMT:
18241       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18242       break;
18243 
18244     case DECL_EXPR:
18245       {
18246 	tree decl, pattern_decl;
18247 	tree init;
18248 
18249 	pattern_decl = decl = DECL_EXPR_DECL (t);
18250 	if (TREE_CODE (decl) == LABEL_DECL)
18251 	  finish_label_decl (DECL_NAME (decl));
18252 	else if (TREE_CODE (decl) == USING_DECL)
18253 	  {
18254 	    tree scope = USING_DECL_SCOPE (decl);
18255 	    if (DECL_DEPENDENT_P (decl))
18256 	      {
18257 		scope = tsubst (scope, args, complain, in_decl);
18258 		if (!MAYBE_CLASS_TYPE_P (scope)
18259 		    && TREE_CODE (scope) != ENUMERAL_TYPE)
18260 		  {
18261 		    if (complain & tf_error)
18262 		      error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18263 				"class, namespace, or enumeration", scope);
18264 		    return error_mark_node;
18265 		  }
18266 		finish_nonmember_using_decl (scope, DECL_NAME (decl));
18267 	      }
18268 	    else
18269 	      {
18270 		/* This is a non-dependent using-decl, and we'll have
18271 		   used the names it found during template parsing.  We do
18272 		   not want to do the lookup again, because we might not
18273 		   find the things we found then.  */
18274 		gcc_checking_assert (scope == tsubst (scope, args,
18275 						      complain, in_decl));
18276 		/* We still need to push the bindings so that we can look up
18277 		   this name later.  */
18278 		push_using_decl_bindings (DECL_NAME (decl),
18279 					  USING_DECL_DECLS (decl));
18280 	      }
18281 	  }
18282 	else if (is_capture_proxy (decl)
18283 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18284 	  {
18285 	    /* We're in tsubst_lambda_expr, we've already inserted a new
18286 	       capture proxy, so look it up and register it.  */
18287 	    tree inst;
18288 	    if (!DECL_PACK_P (decl))
18289 	      {
18290 		inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18291 				    LOOK_want::HIDDEN_LAMBDA);
18292 		gcc_assert (inst != decl && is_capture_proxy (inst));
18293 	      }
18294 	    else if (is_normal_capture_proxy (decl))
18295 	      {
18296 		inst = (retrieve_local_specialization
18297 			(DECL_CAPTURED_VARIABLE (decl)));
18298 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18299 			    || DECL_PACK_P (inst));
18300 	      }
18301 	    else
18302 	      inst = lookup_init_capture_pack (decl);
18303 
18304 	    register_local_specialization (inst, decl);
18305 	    break;
18306 	  }
18307 	else if (DECL_PRETTY_FUNCTION_P (decl))
18308 	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18309 				  DECL_NAME (decl),
18310 				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18311 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18312 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18313 	  /* Don't copy the old closure; we'll create a new one in
18314 	     tsubst_lambda_expr.  */
18315 	  break;
18316 	else
18317 	  {
18318 	    init = DECL_INITIAL (decl);
18319 	    decl = tsubst (decl, args, complain, in_decl);
18320 	    if (decl != error_mark_node)
18321 	      {
18322 		/* By marking the declaration as instantiated, we avoid
18323 		   trying to instantiate it.  Since instantiate_decl can't
18324 		   handle local variables, and since we've already done
18325 		   all that needs to be done, that's the right thing to
18326 		   do.  */
18327 		if (VAR_P (decl))
18328 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18329 		if (VAR_P (decl) && !DECL_NAME (decl)
18330 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18331 		  /* Anonymous aggregates are a special case.  */
18332 		  finish_anon_union (decl);
18333 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18334 		  {
18335 		    DECL_CONTEXT (decl) = current_function_decl;
18336 		    if (DECL_NAME (decl) == this_identifier)
18337 		      {
18338 			tree lam = DECL_CONTEXT (current_function_decl);
18339 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
18340 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18341 		      }
18342 		    insert_capture_proxy (decl);
18343 		  }
18344 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
18345 		  /* We already did a pushtag.  */;
18346 		else if (VAR_OR_FUNCTION_DECL_P (decl)
18347 			 && DECL_LOCAL_DECL_P (decl))
18348 		  {
18349 		    if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18350 		      DECL_CONTEXT (decl) = NULL_TREE;
18351 		    decl = pushdecl (decl);
18352 		    if (TREE_CODE (decl) == FUNCTION_DECL
18353 			&& DECL_OMP_DECLARE_REDUCTION_P (decl)
18354 			&& cp_check_omp_declare_reduction (decl))
18355 		      instantiate_body (pattern_decl, args, decl, true);
18356 		  }
18357 		else
18358 		  {
18359 		    bool const_init = false;
18360 		    unsigned int cnt = 0;
18361 		    tree first = NULL_TREE, ndecl = error_mark_node;
18362 		    tree asmspec_tree = NULL_TREE;
18363 		    maybe_push_decl (decl);
18364 
18365 		    if (VAR_P (decl)
18366 			&& DECL_DECOMPOSITION_P (decl)
18367 			&& TREE_TYPE (pattern_decl) != error_mark_node)
18368 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18369 						   complain, in_decl, &first,
18370 						   &cnt);
18371 
18372 		    init = tsubst_init (init, decl, args, complain, in_decl);
18373 
18374 		    if (VAR_P (decl))
18375 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18376 				    (pattern_decl));
18377 
18378 		    if (ndecl != error_mark_node)
18379 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
18380 
18381 		    /* In a non-template function, VLA type declarations are
18382 		       handled in grokdeclarator; for templates, handle them
18383 		       now.  */
18384 		    predeclare_vla (decl);
18385 
18386 		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18387 		      {
18388 			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18389 			const char *asmspec = IDENTIFIER_POINTER (id);
18390 			gcc_assert (asmspec[0] == '*');
18391 			asmspec_tree
18392 			  = build_string (IDENTIFIER_LENGTH (id) - 1,
18393 					  asmspec + 1);
18394 			TREE_TYPE (asmspec_tree) = char_array_type_node;
18395 		      }
18396 
18397 		    cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
18398 
18399 		    if (ndecl != error_mark_node)
18400 		      cp_finish_decomp (ndecl, first, cnt);
18401 		  }
18402 	      }
18403 	  }
18404 
18405 	break;
18406       }
18407 
18408     case FOR_STMT:
18409       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18410       RECUR (FOR_INIT_STMT (t));
18411       finish_init_stmt (stmt);
18412       tmp = RECUR (FOR_COND (t));
18413       finish_for_cond (tmp, stmt, false, 0);
18414       tmp = RECUR (FOR_EXPR (t));
18415       finish_for_expr (tmp, stmt);
18416       {
18417 	bool prev = note_iteration_stmt_body_start ();
18418 	RECUR (FOR_BODY (t));
18419 	note_iteration_stmt_body_end (prev);
18420       }
18421       finish_for_stmt (stmt);
18422       break;
18423 
18424     case RANGE_FOR_STMT:
18425       {
18426 	/* Construct another range_for, if this is not a final
18427 	   substitution (for inside a generic lambda of a
18428 	   template).  Otherwise convert to a regular for.  */
18429         tree decl, expr;
18430         stmt = (processing_template_decl
18431 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18432 		: begin_for_stmt (NULL_TREE, NULL_TREE));
18433 	RECUR (RANGE_FOR_INIT_STMT (t));
18434         decl = RANGE_FOR_DECL (t);
18435         decl = tsubst (decl, args, complain, in_decl);
18436         maybe_push_decl (decl);
18437         expr = RECUR (RANGE_FOR_EXPR (t));
18438 
18439 	tree decomp_first = NULL_TREE;
18440 	unsigned decomp_cnt = 0;
18441 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18442 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18443 				      complain, in_decl,
18444 				      &decomp_first, &decomp_cnt);
18445 
18446 	if (processing_template_decl)
18447 	  {
18448 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18449 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18450 	    finish_range_for_decl (stmt, decl, expr);
18451 	    if (decomp_first && decl != error_mark_node)
18452 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
18453 	  }
18454 	else
18455 	  {
18456 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
18457 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18458 	    stmt = cp_convert_range_for (stmt, decl, expr,
18459 					 decomp_first, decomp_cnt,
18460 					 RANGE_FOR_IVDEP (t), unroll);
18461 	  }
18462 
18463 	bool prev = note_iteration_stmt_body_start ();
18464         RECUR (RANGE_FOR_BODY (t));
18465 	note_iteration_stmt_body_end (prev);
18466         finish_for_stmt (stmt);
18467       }
18468       break;
18469 
18470     case WHILE_STMT:
18471       stmt = begin_while_stmt ();
18472       tmp = RECUR (WHILE_COND (t));
18473       finish_while_stmt_cond (tmp, stmt, false, 0);
18474       {
18475 	bool prev = note_iteration_stmt_body_start ();
18476 	RECUR (WHILE_BODY (t));
18477 	note_iteration_stmt_body_end (prev);
18478       }
18479       finish_while_stmt (stmt);
18480       break;
18481 
18482     case DO_STMT:
18483       stmt = begin_do_stmt ();
18484       {
18485 	bool prev = note_iteration_stmt_body_start ();
18486 	RECUR (DO_BODY (t));
18487 	note_iteration_stmt_body_end (prev);
18488       }
18489       finish_do_body (stmt);
18490       tmp = RECUR (DO_COND (t));
18491       finish_do_stmt (tmp, stmt, false, 0);
18492       break;
18493 
18494     case IF_STMT:
18495       stmt = begin_if_stmt ();
18496       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18497       if (IF_STMT_CONSTEXPR_P (t))
18498 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18499       tmp = RECUR (IF_COND (t));
18500       tmp = finish_if_stmt_cond (tmp, stmt);
18501       if (IF_STMT_CONSTEXPR_P (t)
18502 	  && instantiation_dependent_expression_p (tmp))
18503 	{
18504 	  /* We're partially instantiating a generic lambda, but the condition
18505 	     of the constexpr if is still dependent.  Don't substitute into the
18506 	     branches now, just remember the template arguments.  */
18507 	  do_poplevel (IF_SCOPE (stmt));
18508 	  IF_COND (stmt) = IF_COND (t);
18509 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18510 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18511 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18512 	  add_stmt (stmt);
18513 	  break;
18514 	}
18515       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18516 	/* Don't instantiate the THEN_CLAUSE. */;
18517       else
18518 	{
18519 	  tree folded = fold_non_dependent_expr (tmp, complain);
18520 	  bool inhibit = integer_zerop (folded);
18521 	  if (inhibit)
18522 	    ++c_inhibit_evaluation_warnings;
18523 	  RECUR (THEN_CLAUSE (t));
18524 	  if (inhibit)
18525 	    --c_inhibit_evaluation_warnings;
18526 	}
18527       finish_then_clause (stmt);
18528 
18529       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18530 	/* Don't instantiate the ELSE_CLAUSE. */;
18531       else if (ELSE_CLAUSE (t))
18532 	{
18533 	  tree folded = fold_non_dependent_expr (tmp, complain);
18534 	  bool inhibit = integer_nonzerop (folded);
18535 	  begin_else_clause (stmt);
18536 	  if (inhibit)
18537 	    ++c_inhibit_evaluation_warnings;
18538 	  RECUR (ELSE_CLAUSE (t));
18539 	  if (inhibit)
18540 	    --c_inhibit_evaluation_warnings;
18541 	  finish_else_clause (stmt);
18542 	}
18543 
18544       finish_if_stmt (stmt);
18545       break;
18546 
18547     case BIND_EXPR:
18548       if (BIND_EXPR_BODY_BLOCK (t))
18549 	stmt = begin_function_body ();
18550       else
18551 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18552 				    ? BCS_TRY_BLOCK : 0);
18553 
18554       RECUR (BIND_EXPR_BODY (t));
18555 
18556       if (BIND_EXPR_BODY_BLOCK (t))
18557 	finish_function_body (stmt);
18558       else
18559 	finish_compound_stmt (stmt);
18560       break;
18561 
18562     case BREAK_STMT:
18563       finish_break_stmt ();
18564       break;
18565 
18566     case CONTINUE_STMT:
18567       finish_continue_stmt ();
18568       break;
18569 
18570     case SWITCH_STMT:
18571       stmt = begin_switch_stmt ();
18572       tmp = RECUR (SWITCH_STMT_COND (t));
18573       finish_switch_cond (tmp, stmt);
18574       RECUR (SWITCH_STMT_BODY (t));
18575       finish_switch_stmt (stmt);
18576       break;
18577 
18578     case CASE_LABEL_EXPR:
18579       {
18580 	tree decl = CASE_LABEL (t);
18581 	tree low = RECUR (CASE_LOW (t));
18582 	tree high = RECUR (CASE_HIGH (t));
18583 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18584 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18585 	  {
18586 	    tree label = CASE_LABEL (l);
18587 	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18588 	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18589 	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18590 	  }
18591       }
18592       break;
18593 
18594     case LABEL_EXPR:
18595       {
18596 	tree decl = LABEL_EXPR_LABEL (t);
18597 	tree label;
18598 
18599 	label = finish_label_stmt (DECL_NAME (decl));
18600 	if (TREE_CODE (label) == LABEL_DECL)
18601 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18602 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18603 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18604       }
18605       break;
18606 
18607     case GOTO_EXPR:
18608       tmp = GOTO_DESTINATION (t);
18609       if (TREE_CODE (tmp) != LABEL_DECL)
18610 	/* Computed goto's must be tsubst'd into.  On the other hand,
18611 	   non-computed gotos must not be; the identifier in question
18612 	   will have no binding.  */
18613 	tmp = RECUR (tmp);
18614       else
18615 	tmp = DECL_NAME (tmp);
18616       finish_goto_stmt (tmp);
18617       break;
18618 
18619     case ASM_EXPR:
18620       {
18621 	tree string = RECUR (ASM_STRING (t));
18622 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18623 						 complain, in_decl);
18624 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18625 						complain, in_decl);
18626 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18627 	 					  complain, in_decl);
18628 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18629 						complain, in_decl);
18630 	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18631 			       outputs, inputs, clobbers, labels,
18632 			       ASM_INLINE_P (t));
18633 	tree asm_expr = tmp;
18634 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18635 	  asm_expr = TREE_OPERAND (asm_expr, 0);
18636 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18637       }
18638       break;
18639 
18640     case TRY_BLOCK:
18641       if (CLEANUP_P (t))
18642 	{
18643 	  stmt = begin_try_block ();
18644 	  RECUR (TRY_STMTS (t));
18645 	  finish_cleanup_try_block (stmt);
18646 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18647 	}
18648       else
18649 	{
18650 	  tree compound_stmt = NULL_TREE;
18651 
18652 	  if (FN_TRY_BLOCK_P (t))
18653 	    stmt = begin_function_try_block (&compound_stmt);
18654 	  else
18655 	    stmt = begin_try_block ();
18656 
18657 	  RECUR (TRY_STMTS (t));
18658 
18659 	  if (FN_TRY_BLOCK_P (t))
18660 	    finish_function_try_block (stmt);
18661 	  else
18662 	    finish_try_block (stmt);
18663 
18664 	  RECUR (TRY_HANDLERS (t));
18665 	  if (FN_TRY_BLOCK_P (t))
18666 	    finish_function_handler_sequence (stmt, compound_stmt);
18667 	  else
18668 	    finish_handler_sequence (stmt);
18669 	}
18670       break;
18671 
18672     case HANDLER:
18673       {
18674 	tree decl = HANDLER_PARMS (t);
18675 
18676 	if (decl)
18677 	  {
18678 	    decl = tsubst (decl, args, complain, in_decl);
18679 	    /* Prevent instantiate_decl from trying to instantiate
18680 	       this variable.  We've already done all that needs to be
18681 	       done.  */
18682 	    if (decl != error_mark_node)
18683 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18684 	  }
18685 	stmt = begin_handler ();
18686 	finish_handler_parms (decl, stmt);
18687 	RECUR (HANDLER_BODY (t));
18688 	finish_handler (stmt);
18689       }
18690       break;
18691 
18692     case TAG_DEFN:
18693       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18694       if (CLASS_TYPE_P (tmp))
18695 	{
18696 	  /* Local classes are not independent templates; they are
18697 	     instantiated along with their containing function.  And this
18698 	     way we don't have to deal with pushing out of one local class
18699 	     to instantiate a member of another local class.  */
18700 	  /* Closures are handled by the LAMBDA_EXPR.  */
18701 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18702 	  complete_type (tmp);
18703 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18704 	    if ((VAR_P (fld)
18705 		 || (TREE_CODE (fld) == FUNCTION_DECL
18706 		     && !DECL_ARTIFICIAL (fld)))
18707 		&& DECL_TEMPLATE_INSTANTIATION (fld))
18708 	      instantiate_decl (fld, /*defer_ok=*/false,
18709 				/*expl_inst_class=*/false);
18710 	}
18711       break;
18712 
18713     case STATIC_ASSERT:
18714       {
18715 	tree condition;
18716 
18717 	++c_inhibit_evaluation_warnings;
18718 	condition =
18719 	  tsubst_expr (STATIC_ASSERT_CONDITION (t),
18720                        args,
18721                        complain, in_decl,
18722                        /*integral_constant_expression_p=*/true);
18723 	--c_inhibit_evaluation_warnings;
18724 
18725         finish_static_assert (condition,
18726                               STATIC_ASSERT_MESSAGE (t),
18727                               STATIC_ASSERT_SOURCE_LOCATION (t),
18728 			      /*member_p=*/false, /*show_expr_p=*/true);
18729       }
18730       break;
18731 
18732     case OACC_KERNELS:
18733     case OACC_PARALLEL:
18734     case OACC_SERIAL:
18735       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
18736 				in_decl);
18737       stmt = begin_omp_parallel ();
18738       RECUR (OMP_BODY (t));
18739       finish_omp_construct (TREE_CODE (t), stmt, tmp);
18740       break;
18741 
18742     case OMP_PARALLEL:
18743       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18744       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18745 				complain, in_decl);
18746       if (OMP_PARALLEL_COMBINED (t))
18747 	omp_parallel_combined_clauses = &tmp;
18748       stmt = begin_omp_parallel ();
18749       RECUR (OMP_PARALLEL_BODY (t));
18750       gcc_assert (omp_parallel_combined_clauses == NULL);
18751       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18752 	= OMP_PARALLEL_COMBINED (t);
18753       pop_omp_privatization_clauses (r);
18754       break;
18755 
18756     case OMP_TASK:
18757       if (OMP_TASK_BODY (t) == NULL_TREE)
18758 	{
18759 	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18760 				    complain, in_decl);
18761 	  t = copy_node (t);
18762 	  OMP_TASK_CLAUSES (t) = tmp;
18763 	  add_stmt (t);
18764 	  break;
18765 	}
18766       r = push_omp_privatization_clauses (false);
18767       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18768 				complain, in_decl);
18769       stmt = begin_omp_task ();
18770       RECUR (OMP_TASK_BODY (t));
18771       finish_omp_task (tmp, stmt);
18772       pop_omp_privatization_clauses (r);
18773       break;
18774 
18775     case OMP_FOR:
18776     case OMP_LOOP:
18777     case OMP_SIMD:
18778     case OMP_DISTRIBUTE:
18779     case OMP_TASKLOOP:
18780     case OACC_LOOP:
18781       {
18782 	tree clauses, body, pre_body;
18783 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18784 	tree orig_declv = NULL_TREE;
18785 	tree incrv = NULL_TREE;
18786 	enum c_omp_region_type ort = C_ORT_OMP;
18787 	bool any_range_for = false;
18788 	int i;
18789 
18790 	if (TREE_CODE (t) == OACC_LOOP)
18791 	  ort = C_ORT_ACC;
18792 
18793 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
18794 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
18795 				      in_decl);
18796 	if (OMP_FOR_INIT (t) != NULL_TREE)
18797 	  {
18798 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18799 	    if (OMP_FOR_ORIG_DECLS (t))
18800 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18801 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18802 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18803 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18804 	  }
18805 
18806 	keep_next_level (true);
18807 	stmt = begin_omp_structured_block ();
18808 
18809 	pre_body = push_stmt_list ();
18810 	RECUR (OMP_FOR_PRE_BODY (t));
18811 	pre_body = pop_stmt_list (pre_body);
18812 
18813 	if (OMP_FOR_INIT (t) != NULL_TREE)
18814 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18815 	    any_range_for
18816 	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
18817 					  condv, incrv, &clauses, args,
18818 					  complain, in_decl,
18819 					  integral_constant_expression_p);
18820 	omp_parallel_combined_clauses = NULL;
18821 
18822 	if (any_range_for)
18823 	  {
18824 	    gcc_assert (orig_declv);
18825 	    body = begin_omp_structured_block ();
18826 	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18827 	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
18828 		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
18829 		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
18830 		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
18831 					 TREE_VEC_ELT (declv, i));
18832 	  }
18833 	else
18834 	  body = push_stmt_list ();
18835 	RECUR (OMP_FOR_BODY (t));
18836 	if (any_range_for)
18837 	  body = finish_omp_structured_block (body);
18838 	else
18839 	  body = pop_stmt_list (body);
18840 
18841 	if (OMP_FOR_INIT (t) != NULL_TREE)
18842 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
18843 			      orig_declv, initv, condv, incrv, body, pre_body,
18844 			      NULL, clauses);
18845 	else
18846 	  {
18847 	    t = make_node (TREE_CODE (t));
18848 	    TREE_TYPE (t) = void_type_node;
18849 	    OMP_FOR_BODY (t) = body;
18850 	    OMP_FOR_PRE_BODY (t) = pre_body;
18851 	    OMP_FOR_CLAUSES (t) = clauses;
18852 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
18853 	    add_stmt (t);
18854 	  }
18855 
18856 	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
18857 					t));
18858 	pop_omp_privatization_clauses (r);
18859       }
18860       break;
18861 
18862     case OMP_SECTIONS:
18863       omp_parallel_combined_clauses = NULL;
18864       /* FALLTHRU */
18865     case OMP_SINGLE:
18866     case OMP_TEAMS:
18867     case OMP_CRITICAL:
18868     case OMP_TASKGROUP:
18869     case OMP_SCAN:
18870       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18871 					  && OMP_TEAMS_COMBINED (t));
18872       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18873 				in_decl);
18874       if (TREE_CODE (t) == OMP_TEAMS)
18875 	{
18876 	  keep_next_level (true);
18877 	  stmt = begin_omp_structured_block ();
18878 	  RECUR (OMP_BODY (t));
18879 	  stmt = finish_omp_structured_block (stmt);
18880 	}
18881       else
18882 	{
18883 	  stmt = push_stmt_list ();
18884 	  RECUR (OMP_BODY (t));
18885 	  stmt = pop_stmt_list (stmt);
18886 	}
18887 
18888       if (TREE_CODE (t) == OMP_CRITICAL
18889 	  && tmp != NULL_TREE
18890 	  && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
18891 	{
18892 	  error_at (OMP_CLAUSE_LOCATION (tmp),
18893 		    "%<#pragma omp critical%> with %<hint%> clause requires "
18894 		    "a name, except when %<omp_sync_hint_none%> is used");
18895 	  RETURN (error_mark_node);
18896 	}
18897       t = copy_node (t);
18898       OMP_BODY (t) = stmt;
18899       OMP_CLAUSES (t) = tmp;
18900       add_stmt (t);
18901       pop_omp_privatization_clauses (r);
18902       break;
18903 
18904     case OMP_DEPOBJ:
18905       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18906       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18907 	{
18908 	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
18909 	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18910 	    {
18911 	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18912 					args, complain, in_decl);
18913 	      if (tmp == NULL_TREE)
18914 		tmp = error_mark_node;
18915 	    }
18916 	  else
18917 	    {
18918 	      kind = (enum omp_clause_depend_kind)
18919 		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18920 	      tmp = NULL_TREE;
18921 	    }
18922 	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18923 	}
18924       else
18925 	finish_omp_depobj (EXPR_LOCATION (t), r,
18926 			   OMP_CLAUSE_DEPEND_SOURCE,
18927 			   OMP_DEPOBJ_CLAUSES (t));
18928       break;
18929 
18930     case OACC_DATA:
18931     case OMP_TARGET_DATA:
18932     case OMP_TARGET:
18933       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
18934 				? C_ORT_ACC : C_ORT_OMP, args, complain,
18935 				in_decl);
18936       keep_next_level (true);
18937       stmt = begin_omp_structured_block ();
18938 
18939       RECUR (OMP_BODY (t));
18940       stmt = finish_omp_structured_block (stmt);
18941 
18942       t = copy_node (t);
18943       OMP_BODY (t) = stmt;
18944       OMP_CLAUSES (t) = tmp;
18945       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18946 	{
18947 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18948 	  if (teams)
18949 	    {
18950 	      /* For combined target teams, ensure the num_teams and
18951 		 thread_limit clause expressions are evaluated on the host,
18952 		 before entering the target construct.  */
18953 	      tree c;
18954 	      for (c = OMP_TEAMS_CLAUSES (teams);
18955 		   c; c = OMP_CLAUSE_CHAIN (c))
18956 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18957 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18958 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
18959 		  {
18960 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
18961 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
18962 		    if (expr == error_mark_node)
18963 		      continue;
18964 		    tmp = TARGET_EXPR_SLOT (expr);
18965 		    add_stmt (expr);
18966 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
18967 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
18968 						OMP_CLAUSE_FIRSTPRIVATE);
18969 		    OMP_CLAUSE_DECL (tc) = tmp;
18970 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
18971 		    OMP_TARGET_CLAUSES (t) = tc;
18972 		  }
18973 	    }
18974 	}
18975       add_stmt (t);
18976       break;
18977 
18978     case OACC_DECLARE:
18979       t = copy_node (t);
18980       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
18981 				complain, in_decl);
18982       OACC_DECLARE_CLAUSES (t) = tmp;
18983       add_stmt (t);
18984       break;
18985 
18986     case OMP_TARGET_UPDATE:
18987     case OMP_TARGET_ENTER_DATA:
18988     case OMP_TARGET_EXIT_DATA:
18989       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
18990 				complain, in_decl);
18991       t = copy_node (t);
18992       OMP_STANDALONE_CLAUSES (t) = tmp;
18993       add_stmt (t);
18994       break;
18995 
18996     case OACC_CACHE:
18997     case OACC_ENTER_DATA:
18998     case OACC_EXIT_DATA:
18999     case OACC_UPDATE:
19000       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19001 				complain, in_decl);
19002       t = copy_node (t);
19003       OMP_STANDALONE_CLAUSES (t) = tmp;
19004       add_stmt (t);
19005       break;
19006 
19007     case OMP_ORDERED:
19008       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19009 				complain, in_decl);
19010       stmt = push_stmt_list ();
19011       RECUR (OMP_BODY (t));
19012       stmt = pop_stmt_list (stmt);
19013 
19014       t = copy_node (t);
19015       OMP_BODY (t) = stmt;
19016       OMP_ORDERED_CLAUSES (t) = tmp;
19017       add_stmt (t);
19018       break;
19019 
19020     case OMP_MASTER:
19021       omp_parallel_combined_clauses = NULL;
19022       /* FALLTHRU */
19023     case OMP_SECTION:
19024       stmt = push_stmt_list ();
19025       RECUR (OMP_BODY (t));
19026       stmt = pop_stmt_list (stmt);
19027 
19028       t = copy_node (t);
19029       OMP_BODY (t) = stmt;
19030       add_stmt (t);
19031       break;
19032 
19033     case OMP_ATOMIC:
19034       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19035       tmp = NULL_TREE;
19036       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19037 	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19038 				  complain, in_decl);
19039       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19040 	{
19041 	  tree op1 = TREE_OPERAND (t, 1);
19042 	  tree rhs1 = NULL_TREE;
19043 	  tree lhs, rhs;
19044 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
19045 	    {
19046 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
19047 	      op1 = TREE_OPERAND (op1, 1);
19048 	    }
19049 	  lhs = RECUR (TREE_OPERAND (op1, 0));
19050 	  rhs = RECUR (TREE_OPERAND (op1, 1));
19051 	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19052 			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
19053 			     OMP_ATOMIC_MEMORY_ORDER (t));
19054 	}
19055       else
19056 	{
19057 	  tree op1 = TREE_OPERAND (t, 1);
19058 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19059 	  tree rhs1 = NULL_TREE;
19060 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19061 	  enum tree_code opcode = NOP_EXPR;
19062 	  if (code == OMP_ATOMIC_READ)
19063 	    {
19064 	      v = RECUR (TREE_OPERAND (op1, 0));
19065 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19066 	    }
19067 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
19068 		   || code == OMP_ATOMIC_CAPTURE_NEW)
19069 	    {
19070 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19071 	      v = RECUR (TREE_OPERAND (op1, 0));
19072 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19073 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
19074 		{
19075 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
19076 		  op11 = TREE_OPERAND (op11, 1);
19077 		}
19078 	      lhs = RECUR (TREE_OPERAND (op11, 0));
19079 	      rhs = RECUR (TREE_OPERAND (op11, 1));
19080 	      opcode = TREE_CODE (op11);
19081 	      if (opcode == MODIFY_EXPR)
19082 		opcode = NOP_EXPR;
19083 	    }
19084 	  else
19085 	    {
19086 	      code = OMP_ATOMIC;
19087 	      lhs = RECUR (TREE_OPERAND (op1, 0));
19088 	      rhs = RECUR (TREE_OPERAND (op1, 1));
19089 	    }
19090 	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19091 			     lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
19092 	}
19093       break;
19094 
19095     case TRANSACTION_EXPR:
19096       {
19097 	int flags = 0;
19098 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19099 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19100 
19101         if (TRANSACTION_EXPR_IS_STMT (t))
19102           {
19103 	    tree body = TRANSACTION_EXPR_BODY (t);
19104 	    tree noex = NULL_TREE;
19105 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19106 	      {
19107 		noex = MUST_NOT_THROW_COND (body);
19108 		if (noex == NULL_TREE)
19109 		  noex = boolean_true_node;
19110 		body = TREE_OPERAND (body, 0);
19111 	      }
19112             stmt = begin_transaction_stmt (input_location, NULL, flags);
19113             RECUR (body);
19114             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19115           }
19116         else
19117           {
19118             stmt = build_transaction_expr (EXPR_LOCATION (t),
19119 					   RECUR (TRANSACTION_EXPR_BODY (t)),
19120 					   flags, NULL_TREE);
19121             RETURN (stmt);
19122           }
19123       }
19124       break;
19125 
19126     case MUST_NOT_THROW_EXPR:
19127       {
19128 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19129 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
19130 	RETURN (build_must_not_throw_expr (op0, cond));
19131       }
19132 
19133     case EXPR_PACK_EXPANSION:
19134       error ("invalid use of pack expansion expression");
19135       RETURN (error_mark_node);
19136 
19137     case NONTYPE_ARGUMENT_PACK:
19138       error ("use %<...%> to expand argument pack");
19139       RETURN (error_mark_node);
19140 
19141     case COMPOUND_EXPR:
19142       tmp = RECUR (TREE_OPERAND (t, 0));
19143       if (tmp == NULL_TREE)
19144 	/* If the first operand was a statement, we're done with it.  */
19145 	RETURN (RECUR (TREE_OPERAND (t, 1)));
19146       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19147 				    RECUR (TREE_OPERAND (t, 1)),
19148 				    complain));
19149 
19150     case ANNOTATE_EXPR:
19151       tmp = RECUR (TREE_OPERAND (t, 0));
19152       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19153 			  TREE_TYPE (tmp), tmp,
19154 			  RECUR (TREE_OPERAND (t, 1)),
19155 			  RECUR (TREE_OPERAND (t, 2))));
19156 
19157     case PREDICT_EXPR:
19158       RETURN (add_stmt (copy_node (t)));
19159 
19160     default:
19161       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19162 
19163       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
19164 				    /*function_p=*/false,
19165 				    integral_constant_expression_p));
19166     }
19167 
19168   RETURN (NULL_TREE);
19169  out:
19170   input_location = loc;
19171   return r;
19172 #undef RECUR
19173 #undef RETURN
19174 }
19175 
19176 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19177    function.  For description of the body see comment above
19178    cp_parser_omp_declare_reduction_exprs.  */
19179 
19180 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19181 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19182 {
19183   if (t == NULL_TREE || t == error_mark_node)
19184     return;
19185 
19186   gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19187 
19188   tree_stmt_iterator tsi;
19189   int i;
19190   tree stmts[7];
19191   memset (stmts, 0, sizeof stmts);
19192   for (i = 0, tsi = tsi_start (t);
19193        i < 7 && !tsi_end_p (tsi);
19194        i++, tsi_next (&tsi))
19195     stmts[i] = tsi_stmt (tsi);
19196   gcc_assert (tsi_end_p (tsi));
19197 
19198   if (i >= 3)
19199     {
19200       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19201 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
19202       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19203 			     args, complain, in_decl);
19204       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19205 			    args, complain, in_decl);
19206       /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19207 	 expect to be pushing it.  */
19208       DECL_CONTEXT (omp_out) = current_function_decl;
19209       DECL_CONTEXT (omp_in) = current_function_decl;
19210       keep_next_level (true);
19211       tree block = begin_omp_structured_block ();
19212       tsubst_expr (stmts[2], args, complain, in_decl, false);
19213       block = finish_omp_structured_block (block);
19214       block = maybe_cleanup_point_expr_void (block);
19215       add_decl_expr (omp_out);
19216       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
19217 	TREE_NO_WARNING (omp_out) = 1;
19218       add_decl_expr (omp_in);
19219       finish_expr_stmt (block);
19220     }
19221   if (i >= 6)
19222     {
19223       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19224 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
19225       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19226 			      args, complain, in_decl);
19227       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19228 			      args, complain, in_decl);
19229       DECL_CONTEXT (omp_priv) = current_function_decl;
19230       DECL_CONTEXT (omp_orig) = current_function_decl;
19231       keep_next_level (true);
19232       tree block = begin_omp_structured_block ();
19233       tsubst_expr (stmts[5], args, complain, in_decl, false);
19234       block = finish_omp_structured_block (block);
19235       block = maybe_cleanup_point_expr_void (block);
19236       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19237       add_decl_expr (omp_priv);
19238       add_decl_expr (omp_orig);
19239       finish_expr_stmt (block);
19240       if (i == 7)
19241 	add_decl_expr (omp_orig);
19242     }
19243 }
19244 
19245 /* T is a postfix-expression that is not being used in a function
19246    call.  Return the substituted version of T.  */
19247 
19248 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)19249 tsubst_non_call_postfix_expression (tree t, tree args,
19250 				    tsubst_flags_t complain,
19251 				    tree in_decl)
19252 {
19253   if (TREE_CODE (t) == SCOPE_REF)
19254     t = tsubst_qualified_id (t, args, complain, in_decl,
19255 			     /*done=*/false, /*address_p=*/false);
19256   else
19257     t = tsubst_copy_and_build (t, args, complain, in_decl,
19258 			       /*function_p=*/false,
19259 			       /*integral_constant_expression_p=*/false);
19260 
19261   return t;
19262 }
19263 
19264 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19265    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
19266    dependent init-capture.  */
19267 
19268 static void
prepend_one_capture(tree field,tree init,tree & list,tsubst_flags_t complain)19269 prepend_one_capture (tree field, tree init, tree &list,
19270 		     tsubst_flags_t complain)
19271 {
19272   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19273     {
19274       tree type = NULL_TREE;
19275       if (!init)
19276 	{
19277 	  if (complain & tf_error)
19278 	    error ("empty initializer in lambda init-capture");
19279 	  init = error_mark_node;
19280 	}
19281       else if (TREE_CODE (init) == TREE_LIST)
19282 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19283       if (!type)
19284 	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19285       TREE_TYPE (field) = type;
19286       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19287     }
19288   list = tree_cons (field, init, list);
19289 }
19290 
19291 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
19292    instantiation context.  Instantiating a pack expansion containing a lambda
19293    might result in multiple lambdas all based on the same lambda in the
19294    template.  */
19295 
19296 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19297 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19298 {
19299   tree oldfn = lambda_function (t);
19300   in_decl = oldfn;
19301 
19302   tree r = build_lambda_expr ();
19303 
19304   LAMBDA_EXPR_LOCATION (r)
19305     = LAMBDA_EXPR_LOCATION (t);
19306   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19307     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19308   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19309   if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19310     LAMBDA_EXPR_REGEN_INFO (r)
19311       = build_template_info (t, add_to_template_args (TI_ARGS (ti), args));
19312   else
19313     LAMBDA_EXPR_REGEN_INFO (r)
19314       = build_template_info (t, args);
19315 
19316   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19317 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19318 
19319   vec<tree,va_gc>* field_packs = NULL;
19320 
19321   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19322        cap = TREE_CHAIN (cap))
19323     {
19324       tree ofield = TREE_PURPOSE (cap);
19325       tree init = TREE_VALUE (cap);
19326       if (PACK_EXPANSION_P (init))
19327 	init = tsubst_pack_expansion (init, args, complain, in_decl);
19328       else
19329 	init = tsubst_copy_and_build (init, args, complain, in_decl,
19330 				      /*fn*/false, /*constexpr*/false);
19331 
19332       if (init == error_mark_node)
19333 	return error_mark_node;
19334 
19335       if (init && TREE_CODE (init) == TREE_LIST)
19336 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19337 
19338       if (!processing_template_decl
19339 	  && init && TREE_CODE (init) != TREE_VEC
19340 	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19341 	{
19342 	  /* For a VLA, simply tsubsting the field type won't work, we need to
19343 	     go through add_capture again.  XXX do we want to do this for all
19344 	     captures?  */
19345 	  tree name = (get_identifier
19346 		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19347 	  tree ftype = TREE_TYPE (ofield);
19348 	  bool by_ref = (TYPE_REF_P (ftype)
19349 			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19350 			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19351 	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19352 	  continue;
19353 	}
19354 
19355       if (PACK_EXPANSION_P (ofield))
19356 	ofield = PACK_EXPANSION_PATTERN (ofield);
19357       tree field = tsubst_decl (ofield, args, complain);
19358 
19359       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19360 	{
19361 	  /* Remember these for when we've pushed local_specializations.  */
19362 	  vec_safe_push (field_packs, ofield);
19363 	  vec_safe_push (field_packs, field);
19364 	}
19365 
19366       if (field == error_mark_node)
19367 	return error_mark_node;
19368 
19369       if (TREE_CODE (field) == TREE_VEC)
19370 	{
19371 	  int len = TREE_VEC_LENGTH (field);
19372 	  gcc_assert (TREE_CODE (init) == TREE_VEC
19373 		      && TREE_VEC_LENGTH (init) == len);
19374 	  for (int i = 0; i < len; ++i)
19375 	    prepend_one_capture (TREE_VEC_ELT (field, i),
19376 				 TREE_VEC_ELT (init, i),
19377 				 LAMBDA_EXPR_CAPTURE_LIST (r),
19378 				 complain);
19379 	}
19380       else
19381 	{
19382 	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19383 			       complain);
19384 
19385 	  if (id_equal (DECL_NAME (field), "__this"))
19386 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19387 	}
19388     }
19389 
19390   tree type = begin_lambda_type (r);
19391   if (type == error_mark_node)
19392     return error_mark_node;
19393 
19394   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19395     /* A lambda in a default argument outside a class gets no
19396        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
19397        tsubst_default_argument calls start_lambda_scope, so we need to
19398        specifically ignore it here, and use the global scope.  */
19399     record_null_lambda_scope (r);
19400   else
19401     record_lambda_scope (r);
19402 
19403   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19404   determine_visibility (TYPE_NAME (type));
19405 
19406   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19407 
19408   tree oldtmpl = (generic_lambda_fn_p (oldfn)
19409 		  ? DECL_TI_TEMPLATE (oldfn)
19410 		  : NULL_TREE);
19411 
19412   tree fntype = static_fn_type (oldfn);
19413   if (oldtmpl)
19414     ++processing_template_decl;
19415   fntype = tsubst (fntype, args, complain, in_decl);
19416   if (oldtmpl)
19417     --processing_template_decl;
19418 
19419   if (fntype == error_mark_node)
19420     r = error_mark_node;
19421   else
19422     {
19423       /* The body of a lambda-expression is not a subexpression of the
19424 	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19425 	 which would be skipped if cp_unevaluated_operand.  */
19426       cp_evaluated ev;
19427 
19428       /* Fix the type of 'this'.  */
19429       fntype = build_memfn_type (fntype, type,
19430 				 type_memfn_quals (fntype),
19431 				 type_memfn_rqual (fntype));
19432       tree fn, tmpl;
19433       if (oldtmpl)
19434 	{
19435 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19436 	  if (tmpl == error_mark_node)
19437 	    {
19438 	      r = error_mark_node;
19439 	      goto out;
19440 	    }
19441 	  fn = DECL_TEMPLATE_RESULT (tmpl);
19442 	  finish_member_declaration (tmpl);
19443 	}
19444       else
19445 	{
19446 	  tmpl = NULL_TREE;
19447 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
19448 	  if (fn == error_mark_node)
19449 	    {
19450 	      r = error_mark_node;
19451 	      goto out;
19452 	    }
19453 	  finish_member_declaration (fn);
19454 	}
19455 
19456       /* Let finish_function set this.  */
19457       DECL_DECLARED_CONSTEXPR_P (fn) = false;
19458 
19459       bool nested = cfun;
19460       if (nested)
19461 	push_function_context ();
19462       else
19463 	/* Still increment function_depth so that we don't GC in the
19464 	   middle of an expression.  */
19465 	++function_depth;
19466 
19467       local_specialization_stack s (lss_copy);
19468 
19469       tree body = start_lambda_function (fn, r);
19470 
19471       /* Now record them for lookup_init_capture_pack.  */
19472       int fplen = vec_safe_length (field_packs);
19473       for (int i = 0; i < fplen; )
19474 	{
19475 	  tree pack = (*field_packs)[i++];
19476 	  tree inst = (*field_packs)[i++];
19477 	  register_local_specialization (inst, pack);
19478 	}
19479       release_tree_vector (field_packs);
19480 
19481       register_parameter_specializations (oldfn, fn);
19482 
19483       if (oldtmpl)
19484 	{
19485 	  /* We might not partially instantiate some parts of the function, so
19486 	     copy these flags from the original template.  */
19487 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19488 	  current_function_returns_value = ol->returns_value;
19489 	  current_function_returns_null = ol->returns_null;
19490 	  current_function_returns_abnormally = ol->returns_abnormally;
19491 	  current_function_infinite_loop = ol->infinite_loop;
19492 	}
19493 
19494       /* [temp.deduct] A lambda-expression appearing in a function type or a
19495 	 template parameter is not considered part of the immediate context for
19496 	 the purposes of template argument deduction. */
19497       complain = tf_warning_or_error;
19498 
19499       tree saved = DECL_SAVED_TREE (oldfn);
19500       if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19501 	/* We already have a body block from start_lambda_function, we don't
19502 	   need another to confuse NRV (91217).  */
19503 	saved = BIND_EXPR_BODY (saved);
19504 
19505       tsubst_expr (saved, args, complain, r, /*constexpr*/false);
19506 
19507       finish_lambda_function (body);
19508 
19509       if (nested)
19510 	pop_function_context ();
19511       else
19512 	--function_depth;
19513 
19514       /* The capture list was built up in reverse order; fix that now.  */
19515       LAMBDA_EXPR_CAPTURE_LIST (r)
19516 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19517 
19518       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19519 
19520       maybe_add_lambda_conv_op (type);
19521     }
19522 
19523 out:
19524   finish_struct (type, /*attr*/NULL_TREE);
19525 
19526   insert_pending_capture_proxies ();
19527 
19528   return r;
19529 }
19530 
19531 /* Like tsubst but deals with expressions and performs semantic
19532    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)" or
19533    "F<TARGS> (ARGS)".  */
19534 
19535 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)19536 tsubst_copy_and_build (tree t,
19537 		       tree args,
19538 		       tsubst_flags_t complain,
19539 		       tree in_decl,
19540 		       bool function_p,
19541 		       bool integral_constant_expression_p)
19542 {
19543 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19544 #define RECUR(NODE)						\
19545   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
19546 			 /*function_p=*/false,			\
19547 			 integral_constant_expression_p)
19548 
19549   tree retval, op1;
19550   location_t save_loc;
19551 
19552   if (t == NULL_TREE || t == error_mark_node)
19553     return t;
19554 
19555   save_loc = input_location;
19556   if (location_t eloc = cp_expr_location (t))
19557     input_location = eloc;
19558 
19559   /* N3276 decltype magic only applies to calls at the top level or on the
19560      right side of a comma.  */
19561   tsubst_flags_t decltype_flag = (complain & tf_decltype);
19562   complain &= ~tf_decltype;
19563 
19564   switch (TREE_CODE (t))
19565     {
19566     case USING_DECL:
19567       t = DECL_NAME (t);
19568       /* Fall through.  */
19569     case IDENTIFIER_NODE:
19570       {
19571 	tree decl;
19572 	cp_id_kind idk;
19573 	bool non_integral_constant_expression_p;
19574 	const char *error_msg;
19575 
19576 	if (IDENTIFIER_CONV_OP_P (t))
19577 	  {
19578 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19579 	    t = make_conv_op_name (new_type);
19580 	  }
19581 
19582 	/* Look up the name.  */
19583 	decl = lookup_name (t);
19584 
19585 	/* By convention, expressions use ERROR_MARK_NODE to indicate
19586 	   failure, not NULL_TREE.  */
19587 	if (decl == NULL_TREE)
19588 	  decl = error_mark_node;
19589 
19590 	decl = finish_id_expression (t, decl, NULL_TREE,
19591 				     &idk,
19592 				     integral_constant_expression_p,
19593           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
19594 				     &non_integral_constant_expression_p,
19595 				     /*template_p=*/false,
19596 				     /*done=*/true,
19597 				     /*address_p=*/false,
19598 				     /*template_arg_p=*/false,
19599 				     &error_msg,
19600 				     input_location);
19601 	if (error_msg)
19602 	  error (error_msg);
19603 	if (!function_p && identifier_p (decl))
19604 	  {
19605 	    if (complain & tf_error)
19606 	      unqualified_name_lookup_error (decl);
19607 	    decl = error_mark_node;
19608 	  }
19609 	RETURN (decl);
19610       }
19611 
19612     case TEMPLATE_ID_EXPR:
19613       {
19614 	tree object;
19615 	tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19616 					    complain, in_decl,
19617 					    function_p,
19618 					    integral_constant_expression_p);
19619 	tree targs = TREE_OPERAND (t, 1);
19620 
19621 	if (targs)
19622 	  targs = tsubst_template_args (targs, args, complain, in_decl);
19623 	if (targs == error_mark_node)
19624 	  RETURN (error_mark_node);
19625 
19626 	if (TREE_CODE (templ) == SCOPE_REF)
19627 	  {
19628 	    tree name = TREE_OPERAND (templ, 1);
19629 	    tree tid = lookup_template_function (name, targs);
19630 	    TREE_OPERAND (templ, 1) = tid;
19631 	    RETURN (templ);
19632 	  }
19633 
19634 	if (concept_definition_p (templ))
19635 	  {
19636 	    tree check = build_concept_check (templ, targs, complain);
19637 	    if (check == error_mark_node)
19638 	      RETURN (error_mark_node);
19639 
19640 	    tree id = unpack_concept_check (check);
19641 
19642 	    /* If we built a function concept check, return the underlying
19643 	       template-id. So we can evaluate it as a function call.  */
19644 	    if (function_concept_p (TREE_OPERAND (id, 0)))
19645 	      RETURN (id);
19646 
19647 	    RETURN (check);
19648 	  }
19649 
19650 	if (variable_template_p (templ))
19651 	  {
19652 	    tree r = lookup_and_finish_template_variable (templ, targs,
19653 							  complain);
19654 	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
19655 	    RETURN (r);
19656 	  }
19657 
19658 	if (TREE_CODE (templ) == COMPONENT_REF)
19659 	  {
19660 	    object = TREE_OPERAND (templ, 0);
19661 	    templ = TREE_OPERAND (templ, 1);
19662 	  }
19663 	else
19664 	  object = NULL_TREE;
19665 
19666 	tree tid = lookup_template_function (templ, targs);
19667 
19668 	if (object)
19669 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
19670 			 object, tid, NULL_TREE));
19671 	else if (identifier_p (templ))
19672 	  {
19673 	    /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
19674 	       name lookup found nothing when parsing the template name.  */
19675 	    gcc_assert (cxx_dialect >= cxx20 || seen_error ());
19676 	    RETURN (tid);
19677 	  }
19678 	else
19679 	  RETURN (baselink_for_fns (tid));
19680       }
19681 
19682     case INDIRECT_REF:
19683       {
19684 	tree r = RECUR (TREE_OPERAND (t, 0));
19685 
19686 	if (REFERENCE_REF_P (t))
19687 	  {
19688 	    /* A type conversion to reference type will be enclosed in
19689 	       such an indirect ref, but the substitution of the cast
19690 	       will have also added such an indirect ref.  */
19691 	    r = convert_from_reference (r);
19692 	  }
19693 	else
19694 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
19695 				    complain|decltype_flag);
19696 
19697 	if (REF_PARENTHESIZED_P (t))
19698 	  r = force_paren_expr (r);
19699 
19700 	RETURN (r);
19701       }
19702 
19703     case NOP_EXPR:
19704       {
19705 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19706 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19707 	RETURN (build_nop (type, op0));
19708       }
19709 
19710     case IMPLICIT_CONV_EXPR:
19711       {
19712 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19713 	tree expr = RECUR (TREE_OPERAND (t, 0));
19714 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
19715 	  {
19716 	    retval = copy_node (t);
19717 	    TREE_TYPE (retval) = type;
19718 	    TREE_OPERAND (retval, 0) = expr;
19719 	    RETURN (retval);
19720 	  }
19721 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
19722 	  /* We'll pass this to convert_nontype_argument again, we don't need
19723 	     to actually perform any conversion here.  */
19724 	  RETURN (expr);
19725 	int flags = LOOKUP_IMPLICIT;
19726 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
19727 	  flags = LOOKUP_NORMAL;
19728 	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
19729 	  flags |= LOOKUP_NO_NARROWING;
19730 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
19731 						  flags));
19732       }
19733 
19734     case CONVERT_EXPR:
19735       {
19736 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19737 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19738 	if (op0 == error_mark_node)
19739 	  RETURN (error_mark_node);
19740 	RETURN (build1 (CONVERT_EXPR, type, op0));
19741       }
19742 
19743     case CAST_EXPR:
19744     case REINTERPRET_CAST_EXPR:
19745     case CONST_CAST_EXPR:
19746     case DYNAMIC_CAST_EXPR:
19747     case STATIC_CAST_EXPR:
19748       {
19749 	tree type;
19750 	tree op, r = NULL_TREE;
19751 
19752 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19753 	if (integral_constant_expression_p
19754 	    && !cast_valid_in_integral_constant_expression_p (type))
19755 	  {
19756             if (complain & tf_error)
19757               error ("a cast to a type other than an integral or "
19758                      "enumeration type cannot appear in a constant-expression");
19759 	    RETURN (error_mark_node);
19760 	  }
19761 
19762 	op = RECUR (TREE_OPERAND (t, 0));
19763 
19764 	warning_sentinel s(warn_useless_cast);
19765 	warning_sentinel s2(warn_ignored_qualifiers);
19766 	switch (TREE_CODE (t))
19767 	  {
19768 	  case CAST_EXPR:
19769 	    r = build_functional_cast (input_location, type, op, complain);
19770 	    break;
19771 	  case REINTERPRET_CAST_EXPR:
19772 	    r = build_reinterpret_cast (input_location, type, op, complain);
19773 	    break;
19774 	  case CONST_CAST_EXPR:
19775 	    r = build_const_cast (input_location, type, op, complain);
19776 	    break;
19777 	  case DYNAMIC_CAST_EXPR:
19778 	    r = build_dynamic_cast (input_location, type, op, complain);
19779 	    break;
19780 	  case STATIC_CAST_EXPR:
19781 	    r = build_static_cast (input_location, type, op, complain);
19782 	    if (IMPLICIT_RVALUE_P (t))
19783 	      set_implicit_rvalue_p (r);
19784 	    break;
19785 	  default:
19786 	    gcc_unreachable ();
19787 	  }
19788 
19789 	RETURN (r);
19790       }
19791 
19792     case BIT_CAST_EXPR:
19793       {
19794 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19795 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19796 	RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
19797       }
19798 
19799     case POSTDECREMENT_EXPR:
19800     case POSTINCREMENT_EXPR:
19801       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19802 						args, complain, in_decl);
19803       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
19804 				complain|decltype_flag));
19805 
19806     case PREDECREMENT_EXPR:
19807     case PREINCREMENT_EXPR:
19808     case NEGATE_EXPR:
19809     case BIT_NOT_EXPR:
19810     case ABS_EXPR:
19811     case TRUTH_NOT_EXPR:
19812     case UNARY_PLUS_EXPR:  /* Unary + */
19813     case REALPART_EXPR:
19814     case IMAGPART_EXPR:
19815       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
19816 				RECUR (TREE_OPERAND (t, 0)),
19817 				complain|decltype_flag));
19818 
19819     case FIX_TRUNC_EXPR:
19820       /* convert_like should have created an IMPLICIT_CONV_EXPR.  */
19821       gcc_unreachable ();
19822 
19823     case ADDR_EXPR:
19824       op1 = TREE_OPERAND (t, 0);
19825       if (TREE_CODE (op1) == LABEL_DECL)
19826 	RETURN (finish_label_address_expr (DECL_NAME (op1),
19827 					  EXPR_LOCATION (op1)));
19828       if (TREE_CODE (op1) == SCOPE_REF)
19829 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
19830 				   /*done=*/true, /*address_p=*/true);
19831       else
19832 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
19833 						  in_decl);
19834       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
19835 				complain|decltype_flag));
19836 
19837     case PLUS_EXPR:
19838     case MINUS_EXPR:
19839     case MULT_EXPR:
19840     case TRUNC_DIV_EXPR:
19841     case CEIL_DIV_EXPR:
19842     case FLOOR_DIV_EXPR:
19843     case ROUND_DIV_EXPR:
19844     case EXACT_DIV_EXPR:
19845     case BIT_AND_EXPR:
19846     case BIT_IOR_EXPR:
19847     case BIT_XOR_EXPR:
19848     case TRUNC_MOD_EXPR:
19849     case FLOOR_MOD_EXPR:
19850     case TRUTH_ANDIF_EXPR:
19851     case TRUTH_ORIF_EXPR:
19852     case TRUTH_AND_EXPR:
19853     case TRUTH_OR_EXPR:
19854     case RSHIFT_EXPR:
19855     case LSHIFT_EXPR:
19856     case EQ_EXPR:
19857     case NE_EXPR:
19858     case MAX_EXPR:
19859     case MIN_EXPR:
19860     case LE_EXPR:
19861     case GE_EXPR:
19862     case LT_EXPR:
19863     case GT_EXPR:
19864     case SPACESHIP_EXPR:
19865     case MEMBER_REF:
19866     case DOTSTAR_EXPR:
19867       {
19868 	/* If either OP0 or OP1 was value- or type-dependent, suppress
19869 	   warnings that depend on the range of the types involved.  */
19870 	tree op0 = TREE_OPERAND (t, 0);
19871 	tree op1 = TREE_OPERAND (t, 1);
19872 	auto dep_p = [](tree t) {
19873 	  ++processing_template_decl;
19874 	  bool r = (potential_constant_expression (t)
19875 		    ? value_dependent_expression_p (t)
19876 		    : type_dependent_expression_p (t));
19877 	  --processing_template_decl;
19878 	  return r;
19879 	};
19880 	const bool was_dep = dep_p (op0) || dep_p (op1);
19881 	op0 = RECUR (op0);
19882 	op1 = RECUR (op1);
19883 
19884 	warning_sentinel s1(warn_type_limits, was_dep);
19885 	warning_sentinel s2(warn_div_by_zero, was_dep);
19886 	warning_sentinel s3(warn_logical_op, was_dep);
19887 	warning_sentinel s4(warn_tautological_compare, was_dep);
19888 
19889 	tree r = build_x_binary_op
19890 	  (input_location, TREE_CODE (t),
19891 	   op0,
19892 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
19893 	    ? ERROR_MARK
19894 	    : TREE_CODE (TREE_OPERAND (t, 0))),
19895 	   op1,
19896 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
19897 	    ? ERROR_MARK
19898 	    : TREE_CODE (TREE_OPERAND (t, 1))),
19899 	   /*overload=*/NULL,
19900 	   complain|decltype_flag);
19901 	if (EXPR_P (r) && TREE_NO_WARNING (t))
19902 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19903 
19904 	RETURN (r);
19905       }
19906 
19907     case POINTER_PLUS_EXPR:
19908       {
19909 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19910 	if (op0 == error_mark_node)
19911 	  RETURN (error_mark_node);
19912 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19913 	if (op1 == error_mark_node)
19914 	  RETURN (error_mark_node);
19915 	RETURN (fold_build_pointer_plus (op0, op1));
19916       }
19917 
19918     case SCOPE_REF:
19919       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
19920 				  /*address_p=*/false));
19921 
19922     case BASELINK:
19923       RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
19924 			       args, complain, in_decl));
19925 
19926     case ARRAY_REF:
19927       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19928 						args, complain, in_decl);
19929       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
19930 				 RECUR (TREE_OPERAND (t, 1)),
19931 				 complain|decltype_flag));
19932 
19933     case SIZEOF_EXPR:
19934       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
19935 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
19936 	RETURN (tsubst_copy (t, args, complain, in_decl));
19937       /* Fall through */
19938 
19939     case ALIGNOF_EXPR:
19940       {
19941 	tree r;
19942 
19943 	op1 = TREE_OPERAND (t, 0);
19944 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
19945 	  op1 = TREE_TYPE (op1);
19946 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
19947 			    && ALIGNOF_EXPR_STD_P (t));
19948         if (!args)
19949 	  {
19950 	    /* When there are no ARGS, we are trying to evaluate a
19951 	       non-dependent expression from the parser.  Trying to do
19952 	       the substitutions may not work.  */
19953 	    if (!TYPE_P (op1))
19954 	      op1 = TREE_TYPE (op1);
19955 	  }
19956 	else
19957 	  {
19958 	    ++cp_unevaluated_operand;
19959 	    ++c_inhibit_evaluation_warnings;
19960 	    if (TYPE_P (op1))
19961 	      op1 = tsubst (op1, args, complain, in_decl);
19962 	    else
19963 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19964 					   /*function_p=*/false,
19965 					   /*integral_constant_expression_p=*/
19966 					   false);
19967 	    --cp_unevaluated_operand;
19968 	    --c_inhibit_evaluation_warnings;
19969 	  }
19970         if (TYPE_P (op1))
19971 	  r = cxx_sizeof_or_alignof_type (input_location,
19972 					  op1, TREE_CODE (t), std_alignof,
19973 					  complain & tf_error);
19974 	else
19975 	  r = cxx_sizeof_or_alignof_expr (input_location,
19976 					  op1, TREE_CODE (t), std_alignof,
19977 					  complain & tf_error);
19978 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
19979 	  {
19980 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
19981 	      {
19982 		if (!processing_template_decl && TYPE_P (op1))
19983 		  {
19984 		    r = build_min (SIZEOF_EXPR, size_type_node,
19985 				   build1 (NOP_EXPR, op1, error_mark_node));
19986 		    SIZEOF_EXPR_TYPE_P (r) = 1;
19987 		  }
19988 		else
19989 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
19990 		TREE_SIDE_EFFECTS (r) = 0;
19991 		TREE_READONLY (r) = 1;
19992 	      }
19993 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
19994 	  }
19995 	RETURN (r);
19996       }
19997 
19998     case AT_ENCODE_EXPR:
19999       {
20000 	op1 = TREE_OPERAND (t, 0);
20001 	++cp_unevaluated_operand;
20002 	++c_inhibit_evaluation_warnings;
20003 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20004 				     /*function_p=*/false,
20005 				     /*integral_constant_expression_p=*/false);
20006 	--cp_unevaluated_operand;
20007 	--c_inhibit_evaluation_warnings;
20008 	RETURN (objc_build_encode_expr (op1));
20009       }
20010 
20011     case NOEXCEPT_EXPR:
20012       op1 = TREE_OPERAND (t, 0);
20013       ++cp_unevaluated_operand;
20014       ++c_inhibit_evaluation_warnings;
20015       ++cp_noexcept_operand;
20016       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20017 				   /*function_p=*/false,
20018 				   /*integral_constant_expression_p=*/false);
20019       --cp_unevaluated_operand;
20020       --c_inhibit_evaluation_warnings;
20021       --cp_noexcept_operand;
20022       RETURN (finish_noexcept_expr (op1, complain));
20023 
20024     case MODOP_EXPR:
20025       {
20026 	warning_sentinel s(warn_div_by_zero);
20027 	tree lhs = RECUR (TREE_OPERAND (t, 0));
20028 	tree rhs = RECUR (TREE_OPERAND (t, 2));
20029 	tree r = build_x_modify_expr
20030 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20031 	   complain|decltype_flag);
20032 	/* TREE_NO_WARNING must be set if either the expression was
20033 	   parenthesized or it uses an operator such as >>= rather
20034 	   than plain assignment.  In the former case, it was already
20035 	   set and must be copied.  In the latter case,
20036 	   build_x_modify_expr sets it and it must not be reset
20037 	   here.  */
20038 	if (TREE_NO_WARNING (t))
20039 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
20040 
20041 	RETURN (r);
20042       }
20043 
20044     case ARROW_EXPR:
20045       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20046 						args, complain, in_decl);
20047       /* Remember that there was a reference to this entity.  */
20048       if (DECL_P (op1)
20049 	  && !mark_used (op1, complain) && !(complain & tf_error))
20050 	RETURN (error_mark_node);
20051       RETURN (build_x_arrow (input_location, op1, complain));
20052 
20053     case NEW_EXPR:
20054       {
20055 	tree placement = RECUR (TREE_OPERAND (t, 0));
20056 	tree init = RECUR (TREE_OPERAND (t, 3));
20057 	vec<tree, va_gc> *placement_vec;
20058 	vec<tree, va_gc> *init_vec;
20059 	tree ret;
20060 	location_t loc = EXPR_LOCATION (t);
20061 
20062 	if (placement == NULL_TREE)
20063 	  placement_vec = NULL;
20064 	else if (placement == error_mark_node)
20065 	  RETURN (error_mark_node);
20066 	else
20067 	  {
20068 	    placement_vec = make_tree_vector ();
20069 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20070 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
20071 	  }
20072 
20073 	/* If there was an initializer in the original tree, but it
20074 	   instantiated to an empty list, then we should pass a
20075 	   non-NULL empty vector to tell build_new that it was an
20076 	   empty initializer() rather than no initializer.  This can
20077 	   only happen when the initializer is a pack expansion whose
20078 	   parameter packs are of length zero.  */
20079 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20080 	  init_vec = NULL;
20081 	else if (init == error_mark_node)
20082 	  RETURN (error_mark_node);
20083 	else
20084 	  {
20085 	    init_vec = make_tree_vector ();
20086 	    if (init == void_node)
20087 	      gcc_assert (init_vec != NULL);
20088 	    else
20089 	      {
20090 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
20091 		  vec_safe_push (init_vec, TREE_VALUE (init));
20092 	      }
20093 	  }
20094 
20095 	/* Avoid passing an enclosing decl to valid_array_size_p.  */
20096 	in_decl = NULL_TREE;
20097 
20098 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20099 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20100 	ret = build_new (loc, &placement_vec, op1, op2,
20101 			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20102 			 complain);
20103 
20104 	if (placement_vec != NULL)
20105 	  release_tree_vector (placement_vec);
20106 	if (init_vec != NULL)
20107 	  release_tree_vector (init_vec);
20108 
20109 	RETURN (ret);
20110       }
20111 
20112     case DELETE_EXPR:
20113       {
20114 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20115 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20116 	RETURN (delete_sanity (input_location, op0, op1,
20117 			       DELETE_EXPR_USE_VEC (t),
20118 			       DELETE_EXPR_USE_GLOBAL (t),
20119 			       complain));
20120       }
20121 
20122     case COMPOUND_EXPR:
20123       {
20124 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20125 					  complain & ~tf_decltype, in_decl,
20126 					  /*function_p=*/false,
20127 					  integral_constant_expression_p);
20128 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20129 				       op0,
20130 				       RECUR (TREE_OPERAND (t, 1)),
20131 				       complain|decltype_flag));
20132       }
20133 
20134     case CALL_EXPR:
20135       {
20136 	tree function;
20137 	unsigned int nargs, i;
20138 	bool qualified_p;
20139 	bool koenig_p;
20140 	tree ret;
20141 
20142 	function = CALL_EXPR_FN (t);
20143 	/* Internal function with no arguments.  */
20144 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
20145 	  RETURN (t);
20146 
20147 	/* When we parsed the expression, we determined whether or
20148 	   not Koenig lookup should be performed.  */
20149 	koenig_p = KOENIG_LOOKUP_P (t);
20150 	if (function == NULL_TREE)
20151 	  {
20152 	    koenig_p = false;
20153 	    qualified_p = false;
20154 	  }
20155 	else if (TREE_CODE (function) == SCOPE_REF)
20156 	  {
20157 	    qualified_p = true;
20158 	    function = tsubst_qualified_id (function, args, complain, in_decl,
20159 					    /*done=*/false,
20160 					    /*address_p=*/false);
20161 	  }
20162 	else if (koenig_p && identifier_p (function))
20163 	  {
20164 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
20165 	       would incorrectly perform unqualified lookup again.
20166 
20167 	       Note that we can also have an IDENTIFIER_NODE if the earlier
20168 	       unqualified lookup found a member function; in that case
20169 	       koenig_p will be false and we do want to do the lookup
20170 	       again to find the instantiated member function.
20171 
20172 	       FIXME but doing that causes c++/15272, so we need to stop
20173 	       using IDENTIFIER_NODE in that situation.  */
20174 	    qualified_p = false;
20175 	  }
20176 	else
20177 	  {
20178 	    if (TREE_CODE (function) == COMPONENT_REF)
20179 	      {
20180 		tree op = TREE_OPERAND (function, 1);
20181 
20182 		qualified_p = (TREE_CODE (op) == SCOPE_REF
20183 			       || (BASELINK_P (op)
20184 				   && BASELINK_QUALIFIED_P (op)));
20185 	      }
20186 	    else
20187 	      qualified_p = false;
20188 
20189 	    if (TREE_CODE (function) == ADDR_EXPR
20190 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20191 	      /* Avoid error about taking the address of a constructor.  */
20192 	      function = TREE_OPERAND (function, 0);
20193 
20194 	    function = tsubst_copy_and_build (function, args, complain,
20195 					      in_decl,
20196 					      !qualified_p,
20197 					      integral_constant_expression_p);
20198 
20199 	    if (BASELINK_P (function))
20200 	      qualified_p = true;
20201 	  }
20202 
20203 	nargs = call_expr_nargs (t);
20204 	releasing_vec call_args;
20205 	for (i = 0; i < nargs; ++i)
20206 	  {
20207 	    tree arg = CALL_EXPR_ARG (t, i);
20208 
20209 	    if (!PACK_EXPANSION_P (arg))
20210 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
20211 	    else
20212 	      {
20213 		/* Expand the pack expansion and push each entry onto
20214 		   CALL_ARGS.  */
20215 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20216 		if (TREE_CODE (arg) == TREE_VEC)
20217 		  {
20218 		    unsigned int len, j;
20219 
20220 		    len = TREE_VEC_LENGTH (arg);
20221 		    for (j = 0; j < len; ++j)
20222 		      {
20223 			tree value = TREE_VEC_ELT (arg, j);
20224 			if (value != NULL_TREE)
20225 			  value = convert_from_reference (value);
20226 			vec_safe_push (call_args, value);
20227 		      }
20228 		  }
20229 		else
20230 		  {
20231 		    /* A partial substitution.  Add one entry.  */
20232 		    vec_safe_push (call_args, arg);
20233 		  }
20234 	      }
20235 	  }
20236 
20237 	/* Stripped-down processing for a call in a thunk.  Specifically, in
20238 	   the thunk template for a generic lambda.  */
20239 	if (call_from_lambda_thunk_p (t))
20240 	  {
20241 	    /* Now that we've expanded any packs, the number of call args
20242 	       might be different.  */
20243 	    unsigned int cargs = call_args->length ();
20244 	    tree thisarg = NULL_TREE;
20245 	    if (TREE_CODE (function) == COMPONENT_REF)
20246 	      {
20247 		thisarg = TREE_OPERAND (function, 0);
20248 		if (TREE_CODE (thisarg) == INDIRECT_REF)
20249 		  thisarg = TREE_OPERAND (thisarg, 0);
20250 		function = TREE_OPERAND (function, 1);
20251 		if (TREE_CODE (function) == BASELINK)
20252 		  function = BASELINK_FUNCTIONS (function);
20253 	      }
20254 	    /* We aren't going to do normal overload resolution, so force the
20255 	       template-id to resolve.  */
20256 	    function = resolve_nondeduced_context (function, complain);
20257 	    for (unsigned i = 0; i < cargs; ++i)
20258 	      {
20259 		/* In a thunk, pass through args directly, without any
20260 		   conversions.  */
20261 		tree arg = (*call_args)[i];
20262 		while (TREE_CODE (arg) != PARM_DECL)
20263 		  arg = TREE_OPERAND (arg, 0);
20264 		(*call_args)[i] = arg;
20265 	      }
20266 	    if (thisarg)
20267 	      {
20268 		/* If there are no other args, just push 'this'.  */
20269 		if (cargs == 0)
20270 		  vec_safe_push (call_args, thisarg);
20271 		else
20272 		  {
20273 		    /* Otherwise, shift the other args over to make room.  */
20274 		    tree last = (*call_args)[cargs - 1];
20275 		    vec_safe_push (call_args, last);
20276 		    for (int i = cargs - 1; i > 0; --i)
20277 		      (*call_args)[i] = (*call_args)[i - 1];
20278 		    (*call_args)[0] = thisarg;
20279 		  }
20280 	      }
20281 	    ret = build_call_a (function, call_args->length (),
20282 				call_args->address ());
20283 	    /* The thunk location is not interesting.  */
20284 	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20285 	    CALL_FROM_THUNK_P (ret) = true;
20286 	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
20287 	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20288 
20289 	    RETURN (ret);
20290 	  }
20291 
20292 	/* We do not perform argument-dependent lookup if normal
20293 	   lookup finds a non-function, in accordance with the
20294 	   resolution of DR 218.  */
20295 	if (koenig_p
20296 	    && ((is_overloaded_fn (function)
20297 		 /* If lookup found a member function, the Koenig lookup is
20298 		    not appropriate, even if an unqualified-name was used
20299 		    to denote the function.  */
20300 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20301 		|| identifier_p (function)
20302 		/* C++20 P0846: Lookup found nothing.  */
20303 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20304 		    && identifier_p (TREE_OPERAND (function, 0))))
20305 	    /* Only do this when substitution turns a dependent call
20306 	       into a non-dependent call.  */
20307 	    && type_dependent_expression_p_push (t)
20308 	    && !any_type_dependent_arguments_p (call_args))
20309 	  function = perform_koenig_lookup (function, call_args, tf_none);
20310 
20311 	if (function != NULL_TREE
20312 	    && (identifier_p (function)
20313 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20314 		    && identifier_p (TREE_OPERAND (function, 0))))
20315 	    && !any_type_dependent_arguments_p (call_args))
20316 	  {
20317 	    if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20318 	      function = TREE_OPERAND (function, 0);
20319 	    if (koenig_p && (complain & tf_warning_or_error))
20320 	      {
20321 		/* For backwards compatibility and good diagnostics, try
20322 		   the unqualified lookup again if we aren't in SFINAE
20323 		   context.  */
20324 		tree unq = (tsubst_copy_and_build
20325 			    (function, args, complain, in_decl, true,
20326 			     integral_constant_expression_p));
20327 		if (unq == error_mark_node)
20328 		  RETURN (error_mark_node);
20329 
20330 		if (unq != function)
20331 		  {
20332 		    /* In a lambda fn, we have to be careful to not
20333 		       introduce new this captures.  Legacy code can't
20334 		       be using lambdas anyway, so it's ok to be
20335 		       stricter.  */
20336 		    bool in_lambda = (current_class_type
20337 				      && LAMBDA_TYPE_P (current_class_type));
20338 		    char const *const msg
20339 		      = G_("%qD was not declared in this scope, "
20340 			   "and no declarations were found by "
20341 			   "argument-dependent lookup at the point "
20342 			   "of instantiation");
20343 
20344 		    bool diag = true;
20345 		    if (in_lambda)
20346 		      error_at (cp_expr_loc_or_input_loc (t),
20347 				msg, function);
20348 		    else
20349 		      diag = permerror (cp_expr_loc_or_input_loc (t),
20350 					msg, function);
20351 		    if (diag)
20352 		      {
20353 			tree fn = unq;
20354 
20355 			if (INDIRECT_REF_P (fn))
20356 			  fn = TREE_OPERAND (fn, 0);
20357 			if (is_overloaded_fn (fn))
20358 			  fn = get_first_fn (fn);
20359 
20360 			if (!DECL_P (fn))
20361 			  /* Can't say anything more.  */;
20362 			else if (DECL_CLASS_SCOPE_P (fn))
20363 			  {
20364 			    location_t loc = cp_expr_loc_or_input_loc (t);
20365 			    inform (loc,
20366 				    "declarations in dependent base %qT are "
20367 				    "not found by unqualified lookup",
20368 				    DECL_CLASS_CONTEXT (fn));
20369 			    if (current_class_ptr)
20370 			      inform (loc,
20371 				      "use %<this->%D%> instead", function);
20372 			    else
20373 			      inform (loc,
20374 				      "use %<%T::%D%> instead",
20375 				      current_class_name, function);
20376 			  }
20377 			else
20378 			  inform (DECL_SOURCE_LOCATION (fn),
20379 				  "%qD declared here, later in the "
20380 				  "translation unit", fn);
20381 			if (in_lambda)
20382 			  RETURN (error_mark_node);
20383 		      }
20384 
20385 		    function = unq;
20386 		  }
20387 	      }
20388 	    if (identifier_p (function))
20389 	      {
20390 		if (complain & tf_error)
20391 		  unqualified_name_lookup_error (function);
20392 		RETURN (error_mark_node);
20393 	      }
20394 	  }
20395 
20396 	/* Remember that there was a reference to this entity.  */
20397 	if (function != NULL_TREE
20398 	    && DECL_P (function)
20399 	    && !mark_used (function, complain) && !(complain & tf_error))
20400 	  RETURN (error_mark_node);
20401 
20402 	/* Put back tf_decltype for the actual call.  */
20403 	complain |= decltype_flag;
20404 
20405 	if (function == NULL_TREE)
20406 	  switch (CALL_EXPR_IFN (t))
20407 	    {
20408 	    case IFN_LAUNDER:
20409 	      gcc_assert (nargs == 1);
20410 	      if (vec_safe_length (call_args) != 1)
20411 		{
20412 		  error_at (cp_expr_loc_or_input_loc (t),
20413 			    "wrong number of arguments to "
20414 			    "%<__builtin_launder%>");
20415 		  ret = error_mark_node;
20416 		}
20417 	      else
20418 		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20419 					      (*call_args)[0], complain);
20420 	      break;
20421 
20422 	    case IFN_VEC_CONVERT:
20423 	      gcc_assert (nargs == 1);
20424 	      if (vec_safe_length (call_args) != 1)
20425 		{
20426 		  error_at (cp_expr_loc_or_input_loc (t),
20427 			    "wrong number of arguments to "
20428 			    "%<__builtin_convertvector%>");
20429 		  ret = error_mark_node;
20430 		  break;
20431 		}
20432 	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
20433 					  tsubst (TREE_TYPE (t), args,
20434 						  complain, in_decl),
20435 					  complain);
20436 	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20437 		RETURN (ret);
20438 	      break;
20439 
20440 	    default:
20441 	      /* Unsupported internal function with arguments.  */
20442 	      gcc_unreachable ();
20443 	    }
20444 	else if (TREE_CODE (function) == OFFSET_REF
20445 		 || TREE_CODE (function) == DOTSTAR_EXPR
20446 		 || TREE_CODE (function) == MEMBER_REF)
20447 	  ret = build_offset_ref_call_from_tree (function, &call_args,
20448 						 complain);
20449 	else if (TREE_CODE (function) == COMPONENT_REF)
20450 	  {
20451 	    tree instance = TREE_OPERAND (function, 0);
20452 	    tree fn = TREE_OPERAND (function, 1);
20453 
20454 	    if (processing_template_decl
20455 		&& (type_dependent_expression_p (instance)
20456 		    || (!BASELINK_P (fn)
20457 			&& TREE_CODE (fn) != FIELD_DECL)
20458 		    || type_dependent_expression_p (fn)
20459 		    || any_type_dependent_arguments_p (call_args)))
20460 	      ret = build_min_nt_call_vec (function, call_args);
20461 	    else if (!BASELINK_P (fn))
20462 	      ret = finish_call_expr (function, &call_args,
20463 				       /*disallow_virtual=*/false,
20464 				       /*koenig_p=*/false,
20465 				       complain);
20466 	    else
20467 	      ret = (build_new_method_call
20468 		      (instance, fn,
20469 		       &call_args, NULL_TREE,
20470 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
20471 		       /*fn_p=*/NULL,
20472 		       complain));
20473 	  }
20474 	else if (concept_check_p (function))
20475 	  {
20476 	    /* FUNCTION is a template-id referring to a concept definition.  */
20477 	    tree id = unpack_concept_check (function);
20478 	    tree tmpl = TREE_OPERAND (id, 0);
20479 	    tree args = TREE_OPERAND (id, 1);
20480 
20481 	    /* Calls to standard and variable concepts should have been
20482 	       previously diagnosed.  */
20483 	    gcc_assert (function_concept_p (tmpl));
20484 
20485 	    /* Ensure the result is wrapped as a call expression.  */
20486 	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
20487 	  }
20488 	else
20489 	  ret = finish_call_expr (function, &call_args,
20490 				  /*disallow_virtual=*/qualified_p,
20491 				  koenig_p,
20492 				  complain);
20493 
20494 	if (ret != error_mark_node)
20495 	  {
20496 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20497 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
20498 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
20499 	    if (op || ord || rev)
20500 	      {
20501 		function = extract_call_expr (ret);
20502 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
20503 		CALL_EXPR_ORDERED_ARGS (function) = ord;
20504 		CALL_EXPR_REVERSE_ARGS (function) = rev;
20505 	      }
20506 	  }
20507 
20508 	RETURN (ret);
20509       }
20510 
20511     case COND_EXPR:
20512       {
20513 	tree cond = RECUR (TREE_OPERAND (t, 0));
20514 	cond = mark_rvalue_use (cond);
20515 	tree folded_cond = fold_non_dependent_expr (cond, complain);
20516 	tree exp1, exp2;
20517 
20518 	if (TREE_CODE (folded_cond) == INTEGER_CST)
20519 	  {
20520 	    if (integer_zerop (folded_cond))
20521 	      {
20522 		++c_inhibit_evaluation_warnings;
20523 		exp1 = RECUR (TREE_OPERAND (t, 1));
20524 		--c_inhibit_evaluation_warnings;
20525 		exp2 = RECUR (TREE_OPERAND (t, 2));
20526 	      }
20527 	    else
20528 	      {
20529 		exp1 = RECUR (TREE_OPERAND (t, 1));
20530 		++c_inhibit_evaluation_warnings;
20531 		exp2 = RECUR (TREE_OPERAND (t, 2));
20532 		--c_inhibit_evaluation_warnings;
20533 	      }
20534 	    cond = folded_cond;
20535 	  }
20536 	else
20537 	  {
20538 	    exp1 = RECUR (TREE_OPERAND (t, 1));
20539 	    exp2 = RECUR (TREE_OPERAND (t, 2));
20540 	  }
20541 
20542 	warning_sentinel s(warn_duplicated_branches);
20543 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
20544 					 cond, exp1, exp2, complain));
20545       }
20546 
20547     case PSEUDO_DTOR_EXPR:
20548       {
20549 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20550 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20551 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
20552 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
20553 					       input_location));
20554       }
20555 
20556     case TREE_LIST:
20557       RETURN (tsubst_tree_list (t, args, complain, in_decl));
20558 
20559     case COMPONENT_REF:
20560       {
20561 	tree object;
20562 	tree object_type;
20563 	tree member;
20564 	tree r;
20565 
20566 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20567 						     args, complain, in_decl);
20568 	/* Remember that there was a reference to this entity.  */
20569 	if (DECL_P (object)
20570 	    && !mark_used (object, complain) && !(complain & tf_error))
20571 	  RETURN (error_mark_node);
20572 	object_type = TREE_TYPE (object);
20573 
20574 	member = TREE_OPERAND (t, 1);
20575 	if (BASELINK_P (member))
20576 	  member = tsubst_baselink (member,
20577 				    non_reference (TREE_TYPE (object)),
20578 				    args, complain, in_decl);
20579 	else
20580 	  member = tsubst_copy (member, args, complain, in_decl);
20581 	if (member == error_mark_node)
20582 	  RETURN (error_mark_node);
20583 
20584 	if (TREE_CODE (member) == FIELD_DECL)
20585 	  {
20586 	    r = finish_non_static_data_member (member, object, NULL_TREE);
20587 	    if (TREE_CODE (r) == COMPONENT_REF)
20588 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20589 	    RETURN (r);
20590 	  }
20591 	else if (type_dependent_expression_p (object))
20592 	  /* We can't do much here.  */;
20593 	else if (!CLASS_TYPE_P (object_type))
20594 	  {
20595 	    if (scalarish_type_p (object_type))
20596 	      {
20597 		tree s = NULL_TREE;
20598 		tree dtor = member;
20599 
20600 		if (TREE_CODE (dtor) == SCOPE_REF)
20601 		  {
20602 		    s = TREE_OPERAND (dtor, 0);
20603 		    dtor = TREE_OPERAND (dtor, 1);
20604 		  }
20605 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
20606 		  {
20607 		    dtor = TREE_OPERAND (dtor, 0);
20608 		    if (TYPE_P (dtor))
20609 		      RETURN (finish_pseudo_destructor_expr
20610 			      (object, s, dtor, input_location));
20611 		  }
20612 	      }
20613 	  }
20614 	else if (TREE_CODE (member) == SCOPE_REF
20615 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
20616 	  {
20617 	    /* Lookup the template functions now that we know what the
20618 	       scope is.  */
20619 	    tree scope = TREE_OPERAND (member, 0);
20620 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
20621 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
20622 	    member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
20623 					    /*complain=*/false);
20624 	    if (BASELINK_P (member))
20625 	      {
20626 		BASELINK_FUNCTIONS (member)
20627 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
20628 			      args);
20629 		member = (adjust_result_of_qualified_name_lookup
20630 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
20631 			   object_type));
20632 	      }
20633 	    else
20634 	      {
20635 		qualified_name_lookup_error (scope, tmpl, member,
20636 					     input_location);
20637 		RETURN (error_mark_node);
20638 	      }
20639 	  }
20640 	else if (TREE_CODE (member) == SCOPE_REF
20641 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
20642 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
20643 	  {
20644 	    if (complain & tf_error)
20645 	      {
20646 		if (TYPE_P (TREE_OPERAND (member, 0)))
20647 		  error ("%qT is not a class or namespace",
20648 			 TREE_OPERAND (member, 0));
20649 		else
20650 		  error ("%qD is not a class or namespace",
20651 			 TREE_OPERAND (member, 0));
20652 	      }
20653 	    RETURN (error_mark_node);
20654 	  }
20655 
20656 	r = finish_class_member_access_expr (object, member,
20657 					     /*template_p=*/false,
20658 					     complain);
20659 	if (TREE_CODE (r) == COMPONENT_REF)
20660 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20661 	RETURN (r);
20662       }
20663 
20664     case THROW_EXPR:
20665       RETURN (build_throw
20666        (input_location, RECUR (TREE_OPERAND (t, 0))));
20667 
20668     case CONSTRUCTOR:
20669       {
20670 	vec<constructor_elt, va_gc> *n;
20671 	constructor_elt *ce;
20672 	unsigned HOST_WIDE_INT idx;
20673 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20674 	bool process_index_p;
20675         int newlen;
20676         bool need_copy_p = false;
20677 	tree r;
20678 
20679 	if (type == error_mark_node)
20680 	  RETURN (error_mark_node);
20681 
20682 	/* We do not want to process the index of aggregate
20683 	   initializers as they are identifier nodes which will be
20684 	   looked up by digest_init.  */
20685 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
20686 
20687 	if (null_member_pointer_value_p (t))
20688 	  {
20689 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
20690 	    RETURN (t);
20691 	  }
20692 
20693 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
20694         newlen = vec_safe_length (n);
20695 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
20696 	  {
20697 	    if (ce->index && process_index_p
20698 		/* An identifier index is looked up in the type
20699 		   being initialized, not the current scope.  */
20700 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
20701 	      ce->index = RECUR (ce->index);
20702 
20703             if (PACK_EXPANSION_P (ce->value))
20704               {
20705                 /* Substitute into the pack expansion.  */
20706                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
20707                                                   in_decl);
20708 
20709 		if (ce->value == error_mark_node
20710 		    || PACK_EXPANSION_P (ce->value))
20711 		  ;
20712 		else if (TREE_VEC_LENGTH (ce->value) == 1)
20713                   /* Just move the argument into place.  */
20714                   ce->value = TREE_VEC_ELT (ce->value, 0);
20715                 else
20716                   {
20717                     /* Update the length of the final CONSTRUCTOR
20718                        arguments vector, and note that we will need to
20719                        copy.*/
20720                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
20721                     need_copy_p = true;
20722                   }
20723               }
20724             else
20725               ce->value = RECUR (ce->value);
20726 	  }
20727 
20728         if (need_copy_p)
20729           {
20730             vec<constructor_elt, va_gc> *old_n = n;
20731 
20732             vec_alloc (n, newlen);
20733             FOR_EACH_VEC_ELT (*old_n, idx, ce)
20734               {
20735                 if (TREE_CODE (ce->value) == TREE_VEC)
20736                   {
20737                     int i, len = TREE_VEC_LENGTH (ce->value);
20738                     for (i = 0; i < len; ++i)
20739                       CONSTRUCTOR_APPEND_ELT (n, 0,
20740                                               TREE_VEC_ELT (ce->value, i));
20741                   }
20742                 else
20743                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
20744               }
20745           }
20746 
20747 	r = build_constructor (init_list_type_node, n);
20748 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
20749 	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
20750 	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
20751 
20752 	if (TREE_HAS_CONSTRUCTOR (t))
20753 	  {
20754 	    fcl_t cl = fcl_functional;
20755 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
20756 	      cl = fcl_c99;
20757 	    RETURN (finish_compound_literal (type, r, complain, cl));
20758 	  }
20759 
20760 	TREE_TYPE (r) = type;
20761 	RETURN (r);
20762       }
20763 
20764     case TYPEID_EXPR:
20765       {
20766 	tree operand_0 = TREE_OPERAND (t, 0);
20767 	if (TYPE_P (operand_0))
20768 	  {
20769 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
20770 	    RETURN (get_typeid (operand_0, complain));
20771 	  }
20772 	else
20773 	  {
20774 	    operand_0 = RECUR (operand_0);
20775 	    RETURN (build_typeid (operand_0, complain));
20776 	  }
20777       }
20778 
20779     case VAR_DECL:
20780       if (!args)
20781 	RETURN (t);
20782       /* Fall through */
20783 
20784     case PARM_DECL:
20785       {
20786 	tree r = tsubst_copy (t, args, complain, in_decl);
20787 	/* ??? We're doing a subset of finish_id_expression here.  */
20788 	if (tree wrap = maybe_get_tls_wrapper_call (r))
20789 	  /* Replace an evaluated use of the thread_local variable with
20790 	     a call to its wrapper.  */
20791 	  r = wrap;
20792 	else if (outer_automatic_var_p (r))
20793 	  r = process_outer_var_ref (r, complain);
20794 
20795 	if (!TYPE_REF_P (TREE_TYPE (t)))
20796 	  /* If the original type was a reference, we'll be wrapped in
20797 	     the appropriate INDIRECT_REF.  */
20798 	  r = convert_from_reference (r);
20799 	RETURN (r);
20800       }
20801 
20802     case VA_ARG_EXPR:
20803       {
20804 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20805 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20806 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
20807       }
20808 
20809     case OFFSETOF_EXPR:
20810       {
20811 	tree object_ptr
20812 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
20813 				   in_decl, /*function_p=*/false,
20814 				   /*integral_constant_expression_p=*/false);
20815 	RETURN (finish_offsetof (object_ptr,
20816 				 RECUR (TREE_OPERAND (t, 0)),
20817 				 EXPR_LOCATION (t)));
20818       }
20819 
20820     case ADDRESSOF_EXPR:
20821       RETURN (cp_build_addressof (EXPR_LOCATION (t),
20822 				  RECUR (TREE_OPERAND (t, 0)), complain));
20823 
20824     case TRAIT_EXPR:
20825       {
20826 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
20827 			     complain, in_decl);
20828 	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
20829 			     complain, in_decl);
20830 	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
20831 				   TRAIT_EXPR_KIND (t), type1, type2));
20832       }
20833 
20834     case STMT_EXPR:
20835       {
20836 	tree old_stmt_expr = cur_stmt_expr;
20837 	tree stmt_expr = begin_stmt_expr ();
20838 
20839 	cur_stmt_expr = stmt_expr;
20840 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
20841 		     integral_constant_expression_p);
20842 	stmt_expr = finish_stmt_expr (stmt_expr, false);
20843 	cur_stmt_expr = old_stmt_expr;
20844 
20845 	/* If the resulting list of expression statement is empty,
20846 	   fold it further into void_node.  */
20847 	if (empty_expr_stmt_p (stmt_expr))
20848 	  stmt_expr = void_node;
20849 
20850 	RETURN (stmt_expr);
20851       }
20852 
20853     case LAMBDA_EXPR:
20854       {
20855 	if (complain & tf_partial)
20856 	  {
20857 	    /* We don't have a full set of template arguments yet; don't touch
20858 	       the lambda at all.  */
20859 	    gcc_assert (processing_template_decl);
20860 	    return t;
20861 	  }
20862 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
20863 
20864 	RETURN (build_lambda_object (r));
20865       }
20866 
20867     case TARGET_EXPR:
20868       /* We can get here for a constant initializer of non-dependent type.
20869          FIXME stop folding in cp_parser_initializer_clause.  */
20870       {
20871 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
20872 					 complain);
20873 	RETURN (r);
20874       }
20875 
20876     case TRANSACTION_EXPR:
20877       RETURN (tsubst_expr(t, args, complain, in_decl,
20878 	     integral_constant_expression_p));
20879 
20880     case PAREN_EXPR:
20881       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
20882 
20883     case VEC_PERM_EXPR:
20884       {
20885 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20886 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20887 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20888 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
20889 				       complain));
20890       }
20891 
20892     case REQUIRES_EXPR:
20893       {
20894 	tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
20895 	RETURN (r);
20896       }
20897 
20898     case RANGE_EXPR:
20899       /* No need to substitute further, a RANGE_EXPR will always be built
20900 	 with constant operands.  */
20901       RETURN (t);
20902 
20903     case NON_LVALUE_EXPR:
20904     case VIEW_CONVERT_EXPR:
20905       if (location_wrapper_p (t))
20906 	/* We need to do this here as well as in tsubst_copy so we get the
20907 	   other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
20908 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
20909 					  EXPR_LOCATION (t)));
20910       /* fallthrough.  */
20911 
20912     default:
20913       /* Handle Objective-C++ constructs, if appropriate.  */
20914       {
20915 	tree subst
20916 	  = objcp_tsubst_copy_and_build (t, args, complain,
20917 					 in_decl, /*function_p=*/false);
20918 	if (subst)
20919 	  RETURN (subst);
20920       }
20921       RETURN (tsubst_copy (t, args, complain, in_decl));
20922     }
20923 
20924 #undef RECUR
20925 #undef RETURN
20926  out:
20927   input_location = save_loc;
20928   return retval;
20929 }
20930 
20931 /* Verify that the instantiated ARGS are valid. For type arguments,
20932    make sure that the type's linkage is ok. For non-type arguments,
20933    make sure they are constants if they are integral or enumerations.
20934    Emit an error under control of COMPLAIN, and return TRUE on error.  */
20935 
20936 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)20937 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
20938 {
20939   if (dependent_template_arg_p (t))
20940     return false;
20941   if (ARGUMENT_PACK_P (t))
20942     {
20943       tree vec = ARGUMENT_PACK_ARGS (t);
20944       int len = TREE_VEC_LENGTH (vec);
20945       bool result = false;
20946       int i;
20947 
20948       for (i = 0; i < len; ++i)
20949 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
20950 	  result = true;
20951       return result;
20952     }
20953   else if (TYPE_P (t))
20954     {
20955       /* [basic.link]: A name with no linkage (notably, the name
20956 	 of a class or enumeration declared in a local scope)
20957 	 shall not be used to declare an entity with linkage.
20958 	 This implies that names with no linkage cannot be used as
20959 	 template arguments
20960 
20961 	 DR 757 relaxes this restriction for C++0x.  */
20962       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
20963 		 : no_linkage_check (t, /*relaxed_p=*/false));
20964 
20965       if (nt)
20966 	{
20967 	  /* DR 488 makes use of a type with no linkage cause
20968 	     type deduction to fail.  */
20969 	  if (complain & tf_error)
20970 	    {
20971 	      if (TYPE_UNNAMED_P (nt))
20972 		error ("%qT is/uses unnamed type", t);
20973 	      else
20974 		error ("template argument for %qD uses local type %qT",
20975 		       tmpl, t);
20976 	    }
20977 	  return true;
20978 	}
20979       /* In order to avoid all sorts of complications, we do not
20980 	 allow variably-modified types as template arguments.  */
20981       else if (variably_modified_type_p (t, NULL_TREE))
20982 	{
20983 	  if (complain & tf_error)
20984 	    error ("%qT is a variably modified type", t);
20985 	  return true;
20986 	}
20987     }
20988   /* Class template and alias template arguments should be OK.  */
20989   else if (DECL_TYPE_TEMPLATE_P (t))
20990     ;
20991   /* A non-type argument of integral or enumerated type must be a
20992      constant.  */
20993   else if (TREE_TYPE (t)
20994 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
20995 	   && !REFERENCE_REF_P (t)
20996 	   && !TREE_CONSTANT (t))
20997     {
20998       if (complain & tf_error)
20999 	error ("integral expression %qE is not constant", t);
21000       return true;
21001     }
21002   return false;
21003 }
21004 
21005 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)21006 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21007 {
21008   int ix, len = DECL_NTPARMS (tmpl);
21009   bool result = false;
21010 
21011   for (ix = 0; ix != len; ix++)
21012     {
21013       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21014 	result = true;
21015     }
21016   if (result && (complain & tf_error))
21017     error ("  trying to instantiate %qD", tmpl);
21018   return result;
21019 }
21020 
21021 /* We're out of SFINAE context now, so generate diagnostics for the access
21022    errors we saw earlier when instantiating D from TMPL and ARGS.  */
21023 
21024 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)21025 recheck_decl_substitution (tree d, tree tmpl, tree args)
21026 {
21027   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21028   tree type = TREE_TYPE (pattern);
21029   location_t loc = input_location;
21030 
21031   push_access_scope (d);
21032   push_deferring_access_checks (dk_no_deferred);
21033   input_location = DECL_SOURCE_LOCATION (pattern);
21034   tsubst (type, args, tf_warning_or_error, d);
21035   input_location = loc;
21036   pop_deferring_access_checks ();
21037   pop_access_scope (d);
21038 }
21039 
21040 /* Instantiate the indicated variable, function, or alias template TMPL with
21041    the template arguments in TARG_PTR.  */
21042 
21043 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)21044 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
21045 {
21046   tree targ_ptr = orig_args;
21047   tree fndecl;
21048   tree gen_tmpl;
21049   tree spec;
21050   bool access_ok = true;
21051 
21052   if (tmpl == error_mark_node)
21053     return error_mark_node;
21054 
21055   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21056 
21057   if (modules_p ())
21058     lazy_load_pendings (tmpl);
21059 
21060   /* If this function is a clone, handle it specially.  */
21061   if (DECL_CLONED_FUNCTION_P (tmpl))
21062     {
21063       tree spec;
21064       tree clone;
21065 
21066       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21067 	 DECL_CLONED_FUNCTION.  */
21068       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21069 				   targ_ptr, complain);
21070       if (spec == error_mark_node)
21071 	return error_mark_node;
21072 
21073       /* Look for the clone.  */
21074       FOR_EACH_CLONE (clone, spec)
21075 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
21076 	  return clone;
21077       /* We should always have found the clone by now.  */
21078       gcc_unreachable ();
21079       return NULL_TREE;
21080     }
21081 
21082   if (targ_ptr == error_mark_node)
21083     return error_mark_node;
21084 
21085   /* Check to see if we already have this specialization.  */
21086   gen_tmpl = most_general_template (tmpl);
21087   if (TMPL_ARGS_DEPTH (targ_ptr)
21088       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21089     /* targ_ptr only has the innermost template args, so add the outer ones
21090        from tmpl, which could be either a partial instantiation or gen_tmpl (in
21091        the case of a non-dependent call within a template definition).  */
21092     targ_ptr = (add_outermost_template_args
21093 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21094 		 targ_ptr));
21095 
21096   /* It would be nice to avoid hashing here and then again in tsubst_decl,
21097      but it doesn't seem to be on the hot path.  */
21098   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
21099 
21100   gcc_checking_assert (tmpl == gen_tmpl
21101 		       || ((fndecl
21102 			    = retrieve_specialization (tmpl, orig_args, 0))
21103 			   == spec)
21104 		       || fndecl == NULL_TREE);
21105 
21106   if (spec != NULL_TREE)
21107     {
21108       if (FNDECL_HAS_ACCESS_ERRORS (spec))
21109 	{
21110 	  if (complain & tf_error)
21111 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21112 	  return error_mark_node;
21113 	}
21114       return spec;
21115     }
21116 
21117   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21118 			       complain))
21119     return error_mark_node;
21120 
21121   /* We are building a FUNCTION_DECL, during which the access of its
21122      parameters and return types have to be checked.  However this
21123      FUNCTION_DECL which is the desired context for access checking
21124      is not built yet.  We solve this chicken-and-egg problem by
21125      deferring all checks until we have the FUNCTION_DECL.  */
21126   push_deferring_access_checks (dk_deferred);
21127 
21128   /* Instantiation of the function happens in the context of the function
21129      template, not the context of the overload resolution we're doing.  */
21130   push_to_top_level ();
21131   /* If there are dependent arguments, e.g. because we're doing partial
21132      ordering, make sure processing_template_decl stays set.  */
21133   if (uses_template_parms (targ_ptr))
21134     ++processing_template_decl;
21135   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21136     {
21137       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21138 				   complain, gen_tmpl, true);
21139       push_nested_class (ctx);
21140     }
21141 
21142   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21143 
21144   fndecl = NULL_TREE;
21145   if (VAR_P (pattern))
21146     {
21147       /* We need to determine if we're using a partial or explicit
21148 	 specialization now, because the type of the variable could be
21149 	 different.  */
21150       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
21151       tree elt = most_specialized_partial_spec (tid, complain);
21152       if (elt == error_mark_node)
21153 	pattern = error_mark_node;
21154       else if (elt)
21155 	{
21156 	  tree partial_tmpl = TREE_VALUE (elt);
21157 	  tree partial_args = TREE_PURPOSE (elt);
21158 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21159 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
21160 	}
21161     }
21162 
21163   /* Substitute template parameters to obtain the specialization.  */
21164   if (fndecl == NULL_TREE)
21165     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
21166   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21167     pop_nested_class ();
21168   pop_from_top_level ();
21169 
21170   if (fndecl == error_mark_node)
21171     {
21172       pop_deferring_access_checks ();
21173       return error_mark_node;
21174     }
21175 
21176   /* The DECL_TI_TEMPLATE should always be the immediate parent
21177      template, not the most general template.  */
21178   DECL_TI_TEMPLATE (fndecl) = tmpl;
21179   DECL_TI_ARGS (fndecl) = targ_ptr;
21180 
21181   set_instantiating_module (fndecl);
21182 
21183   /* Now we know the specialization, compute access previously
21184      deferred.  Do no access control for inheriting constructors,
21185      as we already checked access for the inherited constructor.  */
21186   if (!(flag_new_inheriting_ctors
21187 	&& DECL_INHERITED_CTOR (fndecl)))
21188     {
21189       push_access_scope (fndecl);
21190       if (!perform_deferred_access_checks (complain))
21191 	access_ok = false;
21192       pop_access_scope (fndecl);
21193     }
21194   pop_deferring_access_checks ();
21195 
21196   /* If we've just instantiated the main entry point for a function,
21197      instantiate all the alternate entry points as well.  We do this
21198      by cloning the instantiation of the main entry point, not by
21199      instantiating the template clones.  */
21200   if (tree chain = DECL_CHAIN (gen_tmpl))
21201     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21202       clone_cdtor (fndecl, /*update_methods=*/false);
21203 
21204   if (!access_ok)
21205     {
21206       if (!(complain & tf_error))
21207 	{
21208 	  /* Remember to reinstantiate when we're out of SFINAE so the user
21209 	     can see the errors.  */
21210 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21211 	}
21212       return error_mark_node;
21213     }
21214   return fndecl;
21215 }
21216 
21217 /* Wrapper for instantiate_template_1.  */
21218 
21219 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)21220 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21221 {
21222   tree ret;
21223   timevar_push (TV_TEMPLATE_INST);
21224   ret = instantiate_template_1 (tmpl, orig_args,  complain);
21225   timevar_pop (TV_TEMPLATE_INST);
21226   return ret;
21227 }
21228 
21229 /* Instantiate the alias template TMPL with ARGS.  Also push a template
21230    instantiation level, which instantiate_template doesn't do because
21231    functions and variables have sufficient context established by the
21232    callers.  */
21233 
21234 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)21235 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21236 {
21237   if (tmpl == error_mark_node || args == error_mark_node)
21238     return error_mark_node;
21239 
21240   args =
21241     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21242 				     args, tmpl, complain,
21243 				     /*require_all_args=*/true,
21244 				     /*use_default_args=*/true);
21245 
21246   /* FIXME check for satisfaction in check_instantiated_args.  */
21247   if (flag_concepts
21248       && !any_dependent_template_arguments_p (args)
21249       && !constraints_satisfied_p (tmpl, args))
21250     {
21251       if (complain & tf_error)
21252 	{
21253 	  auto_diagnostic_group d;
21254 	  error ("template constraint failure for %qD", tmpl);
21255 	  diagnose_constraints (input_location, tmpl, args);
21256 	}
21257       return error_mark_node;
21258     }
21259 
21260   if (!push_tinst_level (tmpl, args))
21261     return error_mark_node;
21262   tree r = instantiate_template (tmpl, args, complain);
21263   pop_tinst_level ();
21264 
21265   if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21266     {
21267       /* An alias template specialization can be dependent
21268 	 even if its underlying type is not.  */
21269       TYPE_DEPENDENT_P (d) = true;
21270       TYPE_DEPENDENT_P_VALID (d) = true;
21271       /* Sometimes a dependent alias spec is equivalent to its expansion,
21272 	 sometimes not.  So always use structural_comptypes.  */
21273       SET_TYPE_STRUCTURAL_EQUALITY (d);
21274     }
21275 
21276   return r;
21277 }
21278 
21279 /* PARM is a template parameter pack for FN.  Returns true iff
21280    PARM is used in a deducible way in the argument list of FN.  */
21281 
21282 static bool
pack_deducible_p(tree parm,tree fn)21283 pack_deducible_p (tree parm, tree fn)
21284 {
21285   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21286   for (; t; t = TREE_CHAIN (t))
21287     {
21288       tree type = TREE_VALUE (t);
21289       tree packs;
21290       if (!PACK_EXPANSION_P (type))
21291 	continue;
21292       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21293 	   packs; packs = TREE_CHAIN (packs))
21294 	if (template_args_equal (TREE_VALUE (packs), parm))
21295 	  {
21296 	    /* The template parameter pack is used in a function parameter
21297 	       pack.  If this is the end of the parameter list, the
21298 	       template parameter pack is deducible.  */
21299 	    if (TREE_CHAIN (t) == void_list_node)
21300 	      return true;
21301 	    else
21302 	      /* Otherwise, not.  Well, it could be deduced from
21303 		 a non-pack parameter, but doing so would end up with
21304 		 a deduction mismatch, so don't bother.  */
21305 	      return false;
21306 	  }
21307     }
21308   /* The template parameter pack isn't used in any function parameter
21309      packs, but it might be used deeper, e.g. tuple<Args...>.  */
21310   return true;
21311 }
21312 
21313 /* Subroutine of fn_type_unification: check non-dependent parms for
21314    convertibility.  */
21315 
21316 static int
check_non_deducible_conversions(tree parms,const tree * args,unsigned nargs,tree fn,unification_kind_t strict,int flags,struct conversion ** convs,bool explain_p)21317 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21318 				 tree fn, unification_kind_t strict, int flags,
21319 				 struct conversion **convs, bool explain_p)
21320 {
21321   /* Non-constructor methods need to leave a conversion for 'this', which
21322      isn't included in nargs here.  */
21323   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21324 		     && !DECL_CONSTRUCTOR_P (fn));
21325 
21326   for (unsigned ia = 0;
21327        parms && parms != void_list_node && ia < nargs; )
21328     {
21329       tree parm = TREE_VALUE (parms);
21330 
21331       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21332 	  && (!TREE_CHAIN (parms)
21333 	      || TREE_CHAIN (parms) == void_list_node))
21334 	/* For a function parameter pack that occurs at the end of the
21335 	   parameter-declaration-list, the type A of each remaining
21336 	   argument of the call is compared with the type P of the
21337 	   declarator-id of the function parameter pack.  */
21338 	break;
21339 
21340       parms = TREE_CHAIN (parms);
21341 
21342       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21343 	/* For a function parameter pack that does not occur at the
21344 	   end of the parameter-declaration-list, the type of the
21345 	   parameter pack is a non-deduced context.  */
21346 	continue;
21347 
21348       if (!uses_template_parms (parm))
21349 	{
21350 	  tree arg = args[ia];
21351 	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
21352 	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
21353 
21354 	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
21355 					      conv_p, explain_p))
21356 	    return 1;
21357 	}
21358 
21359       ++ia;
21360     }
21361 
21362   return 0;
21363 }
21364 
21365 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
21366    NARGS elements of the arguments that are being used when calling
21367    it.  TARGS is a vector into which the deduced template arguments
21368    are placed.
21369 
21370    Returns either a FUNCTION_DECL for the matching specialization of FN or
21371    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
21372    true, diagnostics will be printed to explain why it failed.
21373 
21374    If FN is a conversion operator, or we are trying to produce a specific
21375    specialization, RETURN_TYPE is the return type desired.
21376 
21377    The EXPLICIT_TARGS are explicit template arguments provided via a
21378    template-id.
21379 
21380    The parameter STRICT is one of:
21381 
21382    DEDUCE_CALL:
21383      We are deducing arguments for a function call, as in
21384      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
21385      deducing arguments for a call to the result of a conversion
21386      function template, as in [over.call.object].
21387 
21388    DEDUCE_CONV:
21389      We are deducing arguments for a conversion function, as in
21390      [temp.deduct.conv].
21391 
21392    DEDUCE_EXACT:
21393      We are deducing arguments when doing an explicit instantiation
21394      as in [temp.explicit], when determining an explicit specialization
21395      as in [temp.expl.spec], or when taking the address of a function
21396      template, as in [temp.deduct.funcaddr].  */
21397 
21398 tree
fn_type_unification(tree fn,tree explicit_targs,tree targs,const tree * args,unsigned int nargs,tree return_type,unification_kind_t strict,int flags,struct conversion ** convs,bool explain_p,bool decltype_p)21399 fn_type_unification (tree fn,
21400 		     tree explicit_targs,
21401 		     tree targs,
21402 		     const tree *args,
21403 		     unsigned int nargs,
21404 		     tree return_type,
21405 		     unification_kind_t strict,
21406 		     int flags,
21407 		     struct conversion **convs,
21408 		     bool explain_p,
21409 		     bool decltype_p)
21410 {
21411   tree parms;
21412   tree fntype;
21413   tree decl = NULL_TREE;
21414   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21415   bool ok;
21416   static int deduction_depth;
21417   /* type_unification_real will pass back any access checks from default
21418      template argument substitution.  */
21419   vec<deferred_access_check, va_gc> *checks = NULL;
21420   /* We don't have all the template args yet.  */
21421   bool incomplete = true;
21422 
21423   tree orig_fn = fn;
21424   if (flag_new_inheriting_ctors)
21425     fn = strip_inheriting_ctors (fn);
21426 
21427   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
21428   tree r = error_mark_node;
21429 
21430   tree full_targs = targs;
21431   if (TMPL_ARGS_DEPTH (targs)
21432       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
21433     full_targs = (add_outermost_template_args
21434 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
21435 		   targs));
21436 
21437   if (decltype_p)
21438     complain |= tf_decltype;
21439 
21440   /* In C++0x, it's possible to have a function template whose type depends
21441      on itself recursively.  This is most obvious with decltype, but can also
21442      occur with enumeration scope (c++/48969).  So we need to catch infinite
21443      recursion and reject the substitution at deduction time; this function
21444      will return error_mark_node for any repeated substitution.
21445 
21446      This also catches excessive recursion such as when f<N> depends on
21447      f<N-1> across all integers, and returns error_mark_node for all the
21448      substitutions back up to the initial one.
21449 
21450      This is, of course, not reentrant.  */
21451   if (excessive_deduction_depth)
21452     return error_mark_node;
21453   ++deduction_depth;
21454 
21455   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
21456 
21457   fntype = TREE_TYPE (fn);
21458   if (explicit_targs)
21459     {
21460       /* [temp.deduct]
21461 
21462 	 The specified template arguments must match the template
21463 	 parameters in kind (i.e., type, nontype, template), and there
21464 	 must not be more arguments than there are parameters;
21465 	 otherwise type deduction fails.
21466 
21467 	 Nontype arguments must match the types of the corresponding
21468 	 nontype template parameters, or must be convertible to the
21469 	 types of the corresponding nontype parameters as specified in
21470 	 _temp.arg.nontype_, otherwise type deduction fails.
21471 
21472 	 All references in the function type of the function template
21473 	 to the corresponding template parameters are replaced by the
21474 	 specified template argument values.  If a substitution in a
21475 	 template parameter or in the function type of the function
21476 	 template results in an invalid type, type deduction fails.  */
21477       int i, len = TREE_VEC_LENGTH (tparms);
21478       location_t loc = input_location;
21479       incomplete = false;
21480 
21481       if (explicit_targs == error_mark_node)
21482 	goto fail;
21483 
21484       if (TMPL_ARGS_DEPTH (explicit_targs)
21485 	  < TMPL_ARGS_DEPTH (full_targs))
21486 	explicit_targs = add_outermost_template_args (full_targs,
21487 						      explicit_targs);
21488 
21489       /* Adjust any explicit template arguments before entering the
21490 	 substitution context.  */
21491       explicit_targs
21492 	= (coerce_template_parms (tparms, explicit_targs, fn,
21493 				  complain|tf_partial,
21494 				  /*require_all_args=*/false,
21495 				  /*use_default_args=*/false));
21496       if (explicit_targs == error_mark_node)
21497 	goto fail;
21498 
21499       /* Substitute the explicit args into the function type.  This is
21500 	 necessary so that, for instance, explicitly declared function
21501 	 arguments can match null pointed constants.  If we were given
21502 	 an incomplete set of explicit args, we must not do semantic
21503 	 processing during substitution as we could create partial
21504 	 instantiations.  */
21505       for (i = 0; i < len; i++)
21506         {
21507           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
21508           bool parameter_pack = false;
21509 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
21510 
21511           /* Dig out the actual parm.  */
21512           if (TREE_CODE (parm) == TYPE_DECL
21513               || TREE_CODE (parm) == TEMPLATE_DECL)
21514             {
21515               parm = TREE_TYPE (parm);
21516               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
21517             }
21518           else if (TREE_CODE (parm) == PARM_DECL)
21519             {
21520               parm = DECL_INITIAL (parm);
21521               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
21522             }
21523 
21524 	  if (targ == NULL_TREE)
21525 	    /* No explicit argument for this template parameter.  */
21526 	    incomplete = true;
21527 	  else if (parameter_pack && pack_deducible_p (parm, fn))
21528             {
21529               /* Mark the argument pack as "incomplete". We could
21530                  still deduce more arguments during unification.
21531 	         We remove this mark in type_unification_real.  */
21532 	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
21533 	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
21534 		= ARGUMENT_PACK_ARGS (targ);
21535 
21536               /* We have some incomplete argument packs.  */
21537               incomplete = true;
21538             }
21539         }
21540 
21541       if (incomplete)
21542 	{
21543 	  if (!push_tinst_level (fn, explicit_targs))
21544 	    {
21545 	      excessive_deduction_depth = true;
21546 	      goto fail;
21547 	    }
21548 	  ++processing_template_decl;
21549 	  input_location = DECL_SOURCE_LOCATION (fn);
21550 	  /* Ignore any access checks; we'll see them again in
21551 	     instantiate_template and they might have the wrong
21552 	     access path at this point.  */
21553 	  push_deferring_access_checks (dk_deferred);
21554 	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
21555 	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
21556 	  pop_deferring_access_checks ();
21557 	  input_location = loc;
21558 	  --processing_template_decl;
21559 	  pop_tinst_level ();
21560 
21561 	  if (fntype == error_mark_node)
21562 	    goto fail;
21563 	}
21564 
21565       /* Place the explicitly specified arguments in TARGS.  */
21566       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
21567       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
21568 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
21569       if (!incomplete && CHECKING_P
21570 	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21571 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
21572 	  (targs, NUM_TMPL_ARGS (explicit_targs));
21573     }
21574 
21575   if (return_type && strict != DEDUCE_CALL)
21576     {
21577       tree *new_args = XALLOCAVEC (tree, nargs + 1);
21578       new_args[0] = return_type;
21579       memcpy (new_args + 1, args, nargs * sizeof (tree));
21580       args = new_args;
21581       ++nargs;
21582     }
21583 
21584   if (!incomplete)
21585     goto deduced;
21586 
21587   /* Never do unification on the 'this' parameter.  */
21588   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
21589 
21590   if (return_type && strict == DEDUCE_CALL)
21591     {
21592       /* We're deducing for a call to the result of a template conversion
21593          function.  The parms we really want are in return_type.  */
21594       if (INDIRECT_TYPE_P (return_type))
21595 	return_type = TREE_TYPE (return_type);
21596       parms = TYPE_ARG_TYPES (return_type);
21597     }
21598   else if (return_type)
21599     {
21600       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
21601     }
21602 
21603   /* We allow incomplete unification without an error message here
21604      because the standard doesn't seem to explicitly prohibit it.  Our
21605      callers must be ready to deal with unification failures in any
21606      event.  */
21607 
21608   /* If we aren't explaining yet, push tinst context so we can see where
21609      any errors (e.g. from class instantiations triggered by instantiation
21610      of default template arguments) come from.  If we are explaining, this
21611      context is redundant.  */
21612   if (!explain_p && !push_tinst_level (fn, targs))
21613     {
21614       excessive_deduction_depth = true;
21615       goto fail;
21616     }
21617 
21618   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21619 			       full_targs, parms, args, nargs, /*subr=*/0,
21620 			       strict, &checks, explain_p);
21621   if (!explain_p)
21622     pop_tinst_level ();
21623   if (!ok)
21624     goto fail;
21625 
21626   /* Now that we have bindings for all of the template arguments,
21627      ensure that the arguments deduced for the template template
21628      parameters have compatible template parameter lists.  We cannot
21629      check this property before we have deduced all template
21630      arguments, because the template parameter types of a template
21631      template parameter might depend on prior template parameters
21632      deduced after the template template parameter.  The following
21633      ill-formed example illustrates this issue:
21634 
21635        template<typename T, template<T> class C> void f(C<5>, T);
21636 
21637        template<int N> struct X {};
21638 
21639        void g() {
21640          f(X<5>(), 5l); // error: template argument deduction fails
21641        }
21642 
21643      The template parameter list of 'C' depends on the template type
21644      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
21645      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
21646      time that we deduce 'C'.  */
21647   if (!template_template_parm_bindings_ok_p
21648            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
21649     {
21650       unify_inconsistent_template_template_parameters (explain_p);
21651       goto fail;
21652     }
21653 
21654  deduced:
21655 
21656   /* CWG2369: Check satisfaction before non-deducible conversions.  */
21657   if (!constraints_satisfied_p (fn, targs))
21658     {
21659       if (explain_p)
21660 	diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
21661       goto fail;
21662     }
21663 
21664   /* DR 1391: All parameters have args, now check non-dependent parms for
21665      convertibility.  We don't do this if all args were explicitly specified,
21666      as the standard says that we substitute explicit args immediately.  */
21667   if (incomplete
21668       && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
21669 					  convs, explain_p))
21670     goto fail;
21671 
21672   /* All is well so far.  Now, check:
21673 
21674      [temp.deduct]
21675 
21676      When all template arguments have been deduced, all uses of
21677      template parameters in nondeduced contexts are replaced with
21678      the corresponding deduced argument values.  If the
21679      substitution results in an invalid type, as described above,
21680      type deduction fails.  */
21681   if (!push_tinst_level (fn, targs))
21682     {
21683       excessive_deduction_depth = true;
21684       goto fail;
21685     }
21686 
21687   /* Also collect access checks from the instantiation.  */
21688   reopen_deferring_access_checks (checks);
21689 
21690   decl = instantiate_template (fn, targs, complain);
21691 
21692   checks = get_deferred_access_checks ();
21693   pop_deferring_access_checks ();
21694 
21695   pop_tinst_level ();
21696 
21697   if (decl == error_mark_node)
21698     goto fail;
21699 
21700   /* Now perform any access checks encountered during substitution.  */
21701   push_access_scope (decl);
21702   ok = perform_access_checks (checks, complain);
21703   pop_access_scope (decl);
21704   if (!ok)
21705     goto fail;
21706 
21707   /* If we're looking for an exact match, check that what we got
21708      is indeed an exact match.  It might not be if some template
21709      parameters are used in non-deduced contexts.  But don't check
21710      for an exact match if we have dependent template arguments;
21711      in that case we're doing partial ordering, and we already know
21712      that we have two candidates that will provide the actual type.  */
21713   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
21714     {
21715       tree substed = TREE_TYPE (decl);
21716       unsigned int i;
21717 
21718       tree sarg
21719 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
21720       if (return_type)
21721 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
21722       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
21723 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
21724 	  {
21725 	    unify_type_mismatch (explain_p, args[i],
21726 				 TREE_VALUE (sarg));
21727 	    goto fail;
21728 	  }
21729     }
21730 
21731   /* After doing deduction with the inherited constructor, actually return an
21732      instantiation of the inheriting constructor.  */
21733   if (orig_fn != fn)
21734     decl = instantiate_template (orig_fn, targs, complain);
21735 
21736   r = decl;
21737 
21738  fail:
21739   --deduction_depth;
21740   if (excessive_deduction_depth)
21741     {
21742       if (deduction_depth == 0)
21743 	/* Reset once we're all the way out.  */
21744 	excessive_deduction_depth = false;
21745     }
21746 
21747   return r;
21748 }
21749 
21750 /* Adjust types before performing type deduction, as described in
21751    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
21752    sections are symmetric.  PARM is the type of a function parameter
21753    or the return type of the conversion function.  ARG is the type of
21754    the argument passed to the call, or the type of the value
21755    initialized with the result of the conversion function.
21756    ARG_EXPR is the original argument expression, which may be null.  */
21757 
21758 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)21759 maybe_adjust_types_for_deduction (unification_kind_t strict,
21760 				  tree* parm,
21761 				  tree* arg,
21762 				  tree arg_expr)
21763 {
21764   int result = 0;
21765 
21766   switch (strict)
21767     {
21768     case DEDUCE_CALL:
21769       break;
21770 
21771     case DEDUCE_CONV:
21772       /* Swap PARM and ARG throughout the remainder of this
21773 	 function; the handling is precisely symmetric since PARM
21774 	 will initialize ARG rather than vice versa.  */
21775       std::swap (parm, arg);
21776       break;
21777 
21778     case DEDUCE_EXACT:
21779       /* Core issue #873: Do the DR606 thing (see below) for these cases,
21780 	 too, but here handle it by stripping the reference from PARM
21781 	 rather than by adding it to ARG.  */
21782       if (TYPE_REF_P (*parm)
21783 	  && TYPE_REF_IS_RVALUE (*parm)
21784 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21785 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21786 	  && TYPE_REF_P (*arg)
21787 	  && !TYPE_REF_IS_RVALUE (*arg))
21788 	*parm = TREE_TYPE (*parm);
21789       /* Nothing else to do in this case.  */
21790       return 0;
21791 
21792     default:
21793       gcc_unreachable ();
21794     }
21795 
21796   if (!TYPE_REF_P (*parm))
21797     {
21798       /* [temp.deduct.call]
21799 
21800 	 If P is not a reference type:
21801 
21802 	 --If A is an array type, the pointer type produced by the
21803 	 array-to-pointer standard conversion (_conv.array_) is
21804 	 used in place of A for type deduction; otherwise,
21805 
21806 	 --If A is a function type, the pointer type produced by
21807 	 the function-to-pointer standard conversion
21808 	 (_conv.func_) is used in place of A for type deduction;
21809 	 otherwise,
21810 
21811 	 --If A is a cv-qualified type, the top level
21812 	 cv-qualifiers of A's type are ignored for type
21813 	 deduction.  */
21814       if (TREE_CODE (*arg) == ARRAY_TYPE)
21815 	*arg = build_pointer_type (TREE_TYPE (*arg));
21816       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
21817 	*arg = build_pointer_type (*arg);
21818       else
21819 	*arg = TYPE_MAIN_VARIANT (*arg);
21820     }
21821 
21822   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
21823      reference to a cv-unqualified template parameter that does not represent a
21824      template parameter of a class template (during class template argument
21825      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
21826      an lvalue, the type "lvalue reference to A" is used in place of A for type
21827      deduction. */
21828   if (TYPE_REF_P (*parm)
21829       && TYPE_REF_IS_RVALUE (*parm)
21830       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21831       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
21832       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21833       && (arg_expr ? lvalue_p (arg_expr)
21834 	  /* try_one_overload doesn't provide an arg_expr, but
21835 	     functions are always lvalues.  */
21836 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
21837     *arg = build_reference_type (*arg);
21838 
21839   /* [temp.deduct.call]
21840 
21841      If P is a cv-qualified type, the top level cv-qualifiers
21842      of P's type are ignored for type deduction.  If P is a
21843      reference type, the type referred to by P is used for
21844      type deduction.  */
21845   *parm = TYPE_MAIN_VARIANT (*parm);
21846   if (TYPE_REF_P (*parm))
21847     {
21848       *parm = TREE_TYPE (*parm);
21849       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21850     }
21851 
21852   /* DR 322. For conversion deduction, remove a reference type on parm
21853      too (which has been swapped into ARG).  */
21854   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
21855     *arg = TREE_TYPE (*arg);
21856 
21857   return result;
21858 }
21859 
21860 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
21861    template which doesn't contain any deducible template parameters; check if
21862    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
21863    unify_one_argument.  */
21864 
21865 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,struct conversion ** conv_p,bool explain_p)21866 check_non_deducible_conversion (tree parm, tree arg, int strict,
21867 				int flags, struct conversion **conv_p,
21868 				bool explain_p)
21869 {
21870   tree type;
21871 
21872   if (!TYPE_P (arg))
21873     type = TREE_TYPE (arg);
21874   else
21875     type = arg;
21876 
21877   if (same_type_p (parm, type))
21878     return unify_success (explain_p);
21879 
21880   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21881   if (strict == DEDUCE_CONV)
21882     {
21883       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
21884 	return unify_success (explain_p);
21885     }
21886   else if (strict != DEDUCE_EXACT)
21887     {
21888       bool ok = false;
21889       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
21890       if (conv_p)
21891 	/* Avoid recalculating this in add_function_candidate.  */
21892 	ok = (*conv_p
21893 	      = good_conversion (parm, type, conv_arg, flags, complain));
21894       else
21895 	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
21896       if (ok)
21897 	return unify_success (explain_p);
21898     }
21899 
21900   if (strict == DEDUCE_EXACT)
21901     return unify_type_mismatch (explain_p, parm, arg);
21902   else
21903     return unify_arg_conversion (explain_p, parm, type, arg);
21904 }
21905 
21906 static bool uses_deducible_template_parms (tree type);
21907 
21908 /* Returns true iff the expression EXPR is one from which a template
21909    argument can be deduced.  In other words, if it's an undecorated
21910    use of a template non-type parameter.  */
21911 
21912 static bool
deducible_expression(tree expr)21913 deducible_expression (tree expr)
21914 {
21915   /* Strip implicit conversions and implicit INDIRECT_REFs.  */
21916   while (CONVERT_EXPR_P (expr)
21917 	 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
21918 	 || REFERENCE_REF_P (expr))
21919     expr = TREE_OPERAND (expr, 0);
21920   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
21921 }
21922 
21923 /* Returns true iff the array domain DOMAIN uses a template parameter in a
21924    deducible way; that is, if it has a max value of <PARM> - 1.  */
21925 
21926 static bool
deducible_array_bound(tree domain)21927 deducible_array_bound (tree domain)
21928 {
21929   if (domain == NULL_TREE)
21930     return false;
21931 
21932   tree max = TYPE_MAX_VALUE (domain);
21933   if (TREE_CODE (max) != MINUS_EXPR)
21934     return false;
21935 
21936   return deducible_expression (TREE_OPERAND (max, 0));
21937 }
21938 
21939 /* Returns true iff the template arguments ARGS use a template parameter
21940    in a deducible way.  */
21941 
21942 static bool
deducible_template_args(tree args)21943 deducible_template_args (tree args)
21944 {
21945   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
21946     {
21947       bool deducible;
21948       tree elt = TREE_VEC_ELT (args, i);
21949       if (ARGUMENT_PACK_P (elt))
21950 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
21951       else
21952 	{
21953 	  if (PACK_EXPANSION_P (elt))
21954 	    elt = PACK_EXPANSION_PATTERN (elt);
21955 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
21956 	    deducible = true;
21957 	  else if (TYPE_P (elt))
21958 	    deducible = uses_deducible_template_parms (elt);
21959 	  else
21960 	    deducible = deducible_expression (elt);
21961 	}
21962       if (deducible)
21963 	return true;
21964     }
21965   return false;
21966 }
21967 
21968 /* Returns true iff TYPE contains any deducible references to template
21969    parameters, as per 14.8.2.5.  */
21970 
21971 static bool
uses_deducible_template_parms(tree type)21972 uses_deducible_template_parms (tree type)
21973 {
21974   if (PACK_EXPANSION_P (type))
21975     type = PACK_EXPANSION_PATTERN (type);
21976 
21977   /* T
21978      cv-list T
21979      TT<T>
21980      TT<i>
21981      TT<> */
21982   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
21983       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
21984     return true;
21985 
21986   /* T*
21987      T&
21988      T&&  */
21989   if (INDIRECT_TYPE_P (type))
21990     return uses_deducible_template_parms (TREE_TYPE (type));
21991 
21992   /* T[integer-constant ]
21993      type [i]  */
21994   if (TREE_CODE (type) == ARRAY_TYPE)
21995     return (uses_deducible_template_parms (TREE_TYPE (type))
21996 	    || deducible_array_bound (TYPE_DOMAIN (type)));
21997 
21998   /* T type ::*
21999      type T::*
22000      T T::*
22001      T (type ::*)()
22002      type (T::*)()
22003      type (type ::*)(T)
22004      type (T::*)(T)
22005      T (type ::*)(T)
22006      T (T::*)()
22007      T (T::*)(T) */
22008   if (TYPE_PTRMEM_P (type))
22009     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22010 	    || (uses_deducible_template_parms
22011 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22012 
22013   /* template-name <T> (where template-name refers to a class template)
22014      template-name <i> (where template-name refers to a class template) */
22015   if (CLASS_TYPE_P (type)
22016       && CLASSTYPE_TEMPLATE_INFO (type)
22017       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22018     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22019 				    (CLASSTYPE_TI_ARGS (type)));
22020 
22021   /* type (T)
22022      T()
22023      T(T)  */
22024   if (FUNC_OR_METHOD_TYPE_P (type))
22025     {
22026       if (uses_deducible_template_parms (TREE_TYPE (type)))
22027 	return true;
22028       tree parm = TYPE_ARG_TYPES (type);
22029       if (TREE_CODE (type) == METHOD_TYPE)
22030 	parm = TREE_CHAIN (parm);
22031       for (; parm; parm = TREE_CHAIN (parm))
22032 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
22033 	  return true;
22034     }
22035 
22036   return false;
22037 }
22038 
22039 /* Subroutine of type_unification_real and unify_pack_expansion to
22040    handle unification of a single P/A pair.  Parameters are as
22041    for those functions.  */
22042 
22043 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)22044 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22045 		    int subr, unification_kind_t strict,
22046 		    bool explain_p)
22047 {
22048   tree arg_expr = NULL_TREE;
22049   int arg_strict;
22050 
22051   if (arg == error_mark_node || parm == error_mark_node)
22052     return unify_invalid (explain_p);
22053   if (arg == unknown_type_node)
22054     /* We can't deduce anything from this, but we might get all the
22055        template args from other function args.  */
22056     return unify_success (explain_p);
22057 
22058   /* Implicit conversions (Clause 4) will be performed on a function
22059      argument to convert it to the type of the corresponding function
22060      parameter if the parameter type contains no template-parameters that
22061      participate in template argument deduction.  */
22062   if (strict != DEDUCE_EXACT
22063       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22064     /* For function parameters with no deducible template parameters,
22065        just return.  We'll check non-dependent conversions later.  */
22066     return unify_success (explain_p);
22067 
22068   switch (strict)
22069     {
22070     case DEDUCE_CALL:
22071       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22072 		    | UNIFY_ALLOW_MORE_CV_QUAL
22073 		    | UNIFY_ALLOW_DERIVED);
22074       break;
22075 
22076     case DEDUCE_CONV:
22077       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22078       break;
22079 
22080     case DEDUCE_EXACT:
22081       arg_strict = UNIFY_ALLOW_NONE;
22082       break;
22083 
22084     default:
22085       gcc_unreachable ();
22086     }
22087 
22088   /* We only do these transformations if this is the top-level
22089      parameter_type_list in a call or declaration matching; in other
22090      situations (nested function declarators, template argument lists) we
22091      won't be comparing a type to an expression, and we don't do any type
22092      adjustments.  */
22093   if (!subr)
22094     {
22095       if (!TYPE_P (arg))
22096 	{
22097 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22098 	  if (type_unknown_p (arg))
22099 	    {
22100 	      /* [temp.deduct.type] A template-argument can be
22101 		 deduced from a pointer to function or pointer
22102 		 to member function argument if the set of
22103 		 overloaded functions does not contain function
22104 		 templates and at most one of a set of
22105 		 overloaded functions provides a unique
22106 		 match.  */
22107 	      resolve_overloaded_unification (tparms, targs, parm,
22108 					      arg, strict,
22109 					      arg_strict, explain_p);
22110 	      /* If a unique match was not found, this is a
22111 	         non-deduced context, so we still succeed. */
22112 	      return unify_success (explain_p);
22113 	    }
22114 
22115 	  arg_expr = arg;
22116 	  arg = unlowered_expr_type (arg);
22117 	  if (arg == error_mark_node)
22118 	    return unify_invalid (explain_p);
22119 	}
22120 
22121       arg_strict |=
22122 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
22123     }
22124   else
22125     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22126 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22127       return unify_template_argument_mismatch (explain_p, parm, arg);
22128 
22129   /* For deduction from an init-list we need the actual list.  */
22130   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22131     arg = arg_expr;
22132   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22133 }
22134 
22135 /* for_each_template_parm callback that always returns 0.  */
22136 
22137 static int
zero_r(tree,void *)22138 zero_r (tree, void *)
22139 {
22140   return 0;
22141 }
22142 
22143 /* for_each_template_parm any_fn callback to handle deduction of a template
22144    type argument from the type of an array bound.  */
22145 
22146 static int
array_deduction_r(tree t,void * data)22147 array_deduction_r (tree t, void *data)
22148 {
22149   tree_pair_p d = (tree_pair_p)data;
22150   tree &tparms = d->purpose;
22151   tree &targs = d->value;
22152 
22153   if (TREE_CODE (t) == ARRAY_TYPE)
22154     if (tree dom = TYPE_DOMAIN (t))
22155       if (tree max = TYPE_MAX_VALUE (dom))
22156 	{
22157 	  if (TREE_CODE (max) == MINUS_EXPR)
22158 	    max = TREE_OPERAND (max, 0);
22159 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22160 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
22161 		   UNIFY_ALLOW_NONE, /*explain*/false);
22162 	}
22163 
22164   /* Keep walking.  */
22165   return 0;
22166 }
22167 
22168 /* Try to deduce any not-yet-deduced template type arguments from the type of
22169    an array bound.  This is handled separately from unify because 14.8.2.5 says
22170    "The type of a type parameter is only deduced from an array bound if it is
22171    not otherwise deduced."  */
22172 
22173 static void
try_array_deduction(tree tparms,tree targs,tree parm)22174 try_array_deduction (tree tparms, tree targs, tree parm)
22175 {
22176   tree_pair_s data = { tparms, targs };
22177   hash_set<tree> visited;
22178   for_each_template_parm (parm, zero_r, &data, &visited,
22179 			  /*nondeduced*/false, array_deduction_r);
22180 }
22181 
22182 /* Most parms like fn_type_unification.
22183 
22184    If SUBR is 1, we're being called recursively (to unify the
22185    arguments of a function or method parameter of a function
22186    template).
22187 
22188    CHECKS is a pointer to a vector of access checks encountered while
22189    substituting default template arguments.  */
22190 
22191 static int
type_unification_real(tree tparms,tree full_targs,tree xparms,const tree * xargs,unsigned int xnargs,int subr,unification_kind_t strict,vec<deferred_access_check,va_gc> ** checks,bool explain_p)22192 type_unification_real (tree tparms,
22193 		       tree full_targs,
22194 		       tree xparms,
22195 		       const tree *xargs,
22196 		       unsigned int xnargs,
22197 		       int subr,
22198 		       unification_kind_t strict,
22199 		       vec<deferred_access_check, va_gc> **checks,
22200 		       bool explain_p)
22201 {
22202   tree parm, arg;
22203   int i;
22204   int ntparms = TREE_VEC_LENGTH (tparms);
22205   int saw_undeduced = 0;
22206   tree parms;
22207   const tree *args;
22208   unsigned int nargs;
22209   unsigned int ia;
22210 
22211   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22212   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22213   gcc_assert (ntparms > 0);
22214 
22215   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22216 
22217   /* Reset the number of non-defaulted template arguments contained
22218      in TARGS.  */
22219   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22220 
22221  again:
22222   parms = xparms;
22223   args = xargs;
22224   nargs = xnargs;
22225 
22226   ia = 0;
22227   while (parms && parms != void_list_node
22228 	 && ia < nargs)
22229     {
22230       parm = TREE_VALUE (parms);
22231 
22232       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22233 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
22234 	/* For a function parameter pack that occurs at the end of the
22235 	   parameter-declaration-list, the type A of each remaining
22236 	   argument of the call is compared with the type P of the
22237 	   declarator-id of the function parameter pack.  */
22238 	break;
22239 
22240       parms = TREE_CHAIN (parms);
22241 
22242       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22243 	/* For a function parameter pack that does not occur at the
22244 	   end of the parameter-declaration-list, the type of the
22245 	   parameter pack is a non-deduced context.  */
22246 	continue;
22247 
22248       arg = args[ia];
22249       ++ia;
22250 
22251       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22252 			      explain_p))
22253 	return 1;
22254     }
22255 
22256   if (parms
22257       && parms != void_list_node
22258       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22259     {
22260       /* Unify the remaining arguments with the pack expansion type.  */
22261       tree argvec;
22262       tree parmvec = make_tree_vec (1);
22263 
22264       /* Allocate a TREE_VEC and copy in all of the arguments */
22265       argvec = make_tree_vec (nargs - ia);
22266       for (i = 0; ia < nargs; ++ia, ++i)
22267 	TREE_VEC_ELT (argvec, i) = args[ia];
22268 
22269       /* Copy the parameter into parmvec.  */
22270       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22271       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22272                                 /*subr=*/subr, explain_p))
22273         return 1;
22274 
22275       /* Advance to the end of the list of parameters.  */
22276       parms = TREE_CHAIN (parms);
22277     }
22278 
22279   /* Fail if we've reached the end of the parm list, and more args
22280      are present, and the parm list isn't variadic.  */
22281   if (ia < nargs && parms == void_list_node)
22282     return unify_too_many_arguments (explain_p, nargs, ia);
22283   /* Fail if parms are left and they don't have default values and
22284      they aren't all deduced as empty packs (c++/57397).  This is
22285      consistent with sufficient_parms_p.  */
22286   if (parms && parms != void_list_node
22287       && TREE_PURPOSE (parms) == NULL_TREE)
22288     {
22289       unsigned int count = nargs;
22290       tree p = parms;
22291       bool type_pack_p;
22292       do
22293 	{
22294 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
22295 	  if (!type_pack_p)
22296 	    count++;
22297 	  p = TREE_CHAIN (p);
22298 	}
22299       while (p && p != void_list_node);
22300       if (count != nargs)
22301 	return unify_too_few_arguments (explain_p, ia, count,
22302 					type_pack_p);
22303     }
22304 
22305   if (!subr)
22306     {
22307       tsubst_flags_t complain = (explain_p
22308 				 ? tf_warning_or_error
22309 				 : tf_none);
22310       bool tried_array_deduction = (cxx_dialect < cxx17);
22311 
22312       for (i = 0; i < ntparms; i++)
22313 	{
22314 	  tree targ = TREE_VEC_ELT (targs, i);
22315 	  tree tparm = TREE_VEC_ELT (tparms, i);
22316 
22317 	  /* Clear the "incomplete" flags on all argument packs now so that
22318 	     substituting them into later default arguments works.  */
22319 	  if (targ && ARGUMENT_PACK_P (targ))
22320             {
22321               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
22322               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
22323             }
22324 
22325 	  if (targ || tparm == error_mark_node)
22326 	    continue;
22327 	  tparm = TREE_VALUE (tparm);
22328 
22329 	  if (TREE_CODE (tparm) == TYPE_DECL
22330 	      && !tried_array_deduction)
22331 	    {
22332 	      try_array_deduction (tparms, targs, xparms);
22333 	      tried_array_deduction = true;
22334 	      if (TREE_VEC_ELT (targs, i))
22335 		continue;
22336 	    }
22337 
22338 	  /* If this is an undeduced nontype parameter that depends on
22339 	     a type parameter, try another pass; its type may have been
22340 	     deduced from a later argument than the one from which
22341 	     this parameter can be deduced.  */
22342 	  if (TREE_CODE (tparm) == PARM_DECL
22343 	      && uses_template_parms (TREE_TYPE (tparm))
22344 	      && saw_undeduced < 2)
22345 	    {
22346 	      saw_undeduced = 1;
22347 	      continue;
22348 	    }
22349 
22350 	  /* Core issue #226 (C++0x) [temp.deduct]:
22351 
22352 	     If a template argument has not been deduced, its
22353 	     default template argument, if any, is used.
22354 
22355 	     When we are in C++98 mode, TREE_PURPOSE will either
22356 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
22357 	     to explicitly check cxx_dialect here.  */
22358 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
22359 	    /* OK, there is a default argument.  Wait until after the
22360 	       conversion check to do substitution.  */
22361 	    continue;
22362 
22363 	  /* If the type parameter is a parameter pack, then it will
22364 	     be deduced to an empty parameter pack.  */
22365 	  if (template_parameter_pack_p (tparm))
22366 	    {
22367 	      tree arg;
22368 
22369 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
22370 		{
22371 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
22372 		  TREE_CONSTANT (arg) = 1;
22373 		}
22374 	      else
22375 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
22376 
22377 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
22378 
22379 	      TREE_VEC_ELT (targs, i) = arg;
22380 	      continue;
22381 	    }
22382 
22383 	  return unify_parameter_deduction_failure (explain_p, tparm);
22384 	}
22385 
22386       /* Now substitute into the default template arguments.  */
22387       for (i = 0; i < ntparms; i++)
22388 	{
22389 	  tree targ = TREE_VEC_ELT (targs, i);
22390 	  tree tparm = TREE_VEC_ELT (tparms, i);
22391 
22392 	  if (targ || tparm == error_mark_node)
22393 	    continue;
22394 	  tree parm = TREE_VALUE (tparm);
22395 	  tree arg = TREE_PURPOSE (tparm);
22396 	  reopen_deferring_access_checks (*checks);
22397 	  location_t save_loc = input_location;
22398 	  if (DECL_P (parm))
22399 	    input_location = DECL_SOURCE_LOCATION (parm);
22400 
22401 	  if (saw_undeduced == 1
22402 	      && TREE_CODE (parm) == PARM_DECL
22403 	      && uses_template_parms (TREE_TYPE (parm)))
22404 	    {
22405 	      /* The type of this non-type parameter depends on undeduced
22406 		 parameters.  Don't try to use its default argument yet,
22407 		 since we might deduce an argument for it on the next pass,
22408 		 but do check whether the arguments we already have cause
22409 		 substitution failure, so that that happens before we try
22410 		 later default arguments (78489).  */
22411 	      ++processing_template_decl;
22412 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
22413 				  NULL_TREE);
22414 	      --processing_template_decl;
22415 	      if (type == error_mark_node)
22416 		arg = error_mark_node;
22417 	      else
22418 		arg = NULL_TREE;
22419 	    }
22420 	  else
22421 	    {
22422 	      /* Even if the call is happening in template context, getting
22423 		 here means it's non-dependent, and a default argument is
22424 		 considered a separate definition under [temp.decls], so we can
22425 		 do this substitution without processing_template_decl.  This
22426 		 is important if the default argument contains something that
22427 		 might be instantiation-dependent like access (87480).  */
22428 	      processing_template_decl_sentinel s;
22429 	      tree substed = NULL_TREE;
22430 	      if (saw_undeduced == 1)
22431 		{
22432 		  /* First instatiate in template context, in case we still
22433 		     depend on undeduced template parameters.  */
22434 		  ++processing_template_decl;
22435 		  substed = tsubst_template_arg (arg, full_targs, complain,
22436 						 NULL_TREE);
22437 		  --processing_template_decl;
22438 		  if (substed != error_mark_node
22439 		      && !uses_template_parms (substed))
22440 		    /* We replaced all the tparms, substitute again out of
22441 		       template context.  */
22442 		    substed = NULL_TREE;
22443 		}
22444 	      if (!substed)
22445 		substed = tsubst_template_arg (arg, full_targs, complain,
22446 					       NULL_TREE);
22447 
22448 	      if (!uses_template_parms (substed))
22449 		arg = convert_template_argument (parm, substed, full_targs,
22450 						 complain, i, NULL_TREE);
22451 	      else if (saw_undeduced == 1)
22452 		arg = NULL_TREE;
22453 	      else
22454 		arg = error_mark_node;
22455 	    }
22456 
22457 	  input_location = save_loc;
22458 	  *checks = get_deferred_access_checks ();
22459 	  pop_deferring_access_checks ();
22460 
22461 	  if (arg == error_mark_node)
22462 	    return 1;
22463 	  else if (arg)
22464 	    {
22465 	      TREE_VEC_ELT (targs, i) = arg;
22466 	      /* The position of the first default template argument,
22467 		 is also the number of non-defaulted arguments in TARGS.
22468 		 Record that.  */
22469 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22470 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
22471 	    }
22472 	}
22473 
22474       if (saw_undeduced++ == 1)
22475 	goto again;
22476     }
22477 
22478   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22479     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
22480 
22481   return unify_success (explain_p);
22482 }
22483 
22484 /* Subroutine of type_unification_real.  Args are like the variables
22485    at the call site.  ARG is an overloaded function (or template-id);
22486    we try deducing template args from each of the overloads, and if
22487    only one succeeds, we go with that.  Modifies TARGS and returns
22488    true on success.  */
22489 
22490 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)22491 resolve_overloaded_unification (tree tparms,
22492 				tree targs,
22493 				tree parm,
22494 				tree arg,
22495 				unification_kind_t strict,
22496 				int sub_strict,
22497 			        bool explain_p)
22498 {
22499   tree tempargs = copy_node (targs);
22500   int good = 0;
22501   tree goodfn = NULL_TREE;
22502   bool addr_p;
22503 
22504   if (TREE_CODE (arg) == ADDR_EXPR)
22505     {
22506       arg = TREE_OPERAND (arg, 0);
22507       addr_p = true;
22508     }
22509   else
22510     addr_p = false;
22511 
22512   if (TREE_CODE (arg) == COMPONENT_REF)
22513     /* Handle `&x' where `x' is some static or non-static member
22514        function name.  */
22515     arg = TREE_OPERAND (arg, 1);
22516 
22517   if (TREE_CODE (arg) == OFFSET_REF)
22518     arg = TREE_OPERAND (arg, 1);
22519 
22520   /* Strip baselink information.  */
22521   if (BASELINK_P (arg))
22522     arg = BASELINK_FUNCTIONS (arg);
22523 
22524   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
22525     {
22526       /* If we got some explicit template args, we need to plug them into
22527 	 the affected templates before we try to unify, in case the
22528 	 explicit args will completely resolve the templates in question.  */
22529 
22530       int ok = 0;
22531       tree expl_subargs = TREE_OPERAND (arg, 1);
22532       arg = TREE_OPERAND (arg, 0);
22533 
22534       for (lkp_iterator iter (arg); iter; ++iter)
22535 	{
22536 	  tree fn = *iter;
22537 	  tree subargs, elem;
22538 
22539 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22540 	    continue;
22541 
22542 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22543 					   expl_subargs, NULL_TREE, tf_none,
22544 					   /*require_all_args=*/true,
22545 					   /*use_default_args=*/true);
22546 	  if (subargs != error_mark_node
22547 	      && !any_dependent_template_arguments_p (subargs))
22548 	    {
22549 	      fn = instantiate_template (fn, subargs, tf_none);
22550 	      if (!constraints_satisfied_p (fn))
22551 		continue;
22552 	      if (undeduced_auto_decl (fn))
22553 		{
22554 		  /* Instantiate the function to deduce its return type.  */
22555 		  ++function_depth;
22556 		  instantiate_decl (fn, /*defer*/false, /*class*/false);
22557 		  --function_depth;
22558 		}
22559 
22560 	      if (flag_noexcept_type)
22561 		maybe_instantiate_noexcept (fn, tf_none);
22562 
22563 	      elem = TREE_TYPE (fn);
22564 	      if (try_one_overload (tparms, targs, tempargs, parm,
22565 				    elem, strict, sub_strict, addr_p, explain_p)
22566 		  && (!goodfn || !same_type_p (goodfn, elem)))
22567 		{
22568 		  goodfn = elem;
22569 		  ++good;
22570 		}
22571 	    }
22572 	  else if (subargs)
22573 	    ++ok;
22574 	}
22575       /* If no templates (or more than one) are fully resolved by the
22576 	 explicit arguments, this template-id is a non-deduced context; it
22577 	 could still be OK if we deduce all template arguments for the
22578 	 enclosing call through other arguments.  */
22579       if (good != 1)
22580 	good = ok;
22581     }
22582   else if (!OVL_P (arg))
22583     /* If ARG is, for example, "(0, &f)" then its type will be unknown
22584        -- but the deduction does not succeed because the expression is
22585        not just the function on its own.  */
22586     return false;
22587   else
22588     for (lkp_iterator iter (arg); iter; ++iter)
22589       {
22590 	tree fn = *iter;
22591 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
22592 			      strict, sub_strict, addr_p, explain_p)
22593 	    && (!goodfn || !decls_match (goodfn, fn)))
22594 	  {
22595 	    goodfn = fn;
22596 	    ++good;
22597 	  }
22598       }
22599 
22600   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22601      to function or pointer to member function argument if the set of
22602      overloaded functions does not contain function templates and at most
22603      one of a set of overloaded functions provides a unique match.
22604 
22605      So if we found multiple possibilities, we return success but don't
22606      deduce anything.  */
22607 
22608   if (good == 1)
22609     {
22610       int i = TREE_VEC_LENGTH (targs);
22611       for (; i--; )
22612 	if (TREE_VEC_ELT (tempargs, i))
22613 	  {
22614 	    tree old = TREE_VEC_ELT (targs, i);
22615 	    tree new_ = TREE_VEC_ELT (tempargs, i);
22616 	    if (new_ && old && ARGUMENT_PACK_P (old)
22617 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
22618 	      /* Don't forget explicit template arguments in a pack.  */
22619 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
22620 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
22621 	    TREE_VEC_ELT (targs, i) = new_;
22622 	  }
22623     }
22624   if (good)
22625     return true;
22626 
22627   return false;
22628 }
22629 
22630 /* Core DR 115: In contexts where deduction is done and fails, or in
22631    contexts where deduction is not done, if a template argument list is
22632    specified and it, along with any default template arguments, identifies
22633    a single function template specialization, then the template-id is an
22634    lvalue for the function template specialization.  */
22635 
22636 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)22637 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
22638 {
22639   tree expr, offset, baselink;
22640   bool addr;
22641 
22642   if (!type_unknown_p (orig_expr))
22643     return orig_expr;
22644 
22645   expr = orig_expr;
22646   addr = false;
22647   offset = NULL_TREE;
22648   baselink = NULL_TREE;
22649 
22650   if (TREE_CODE (expr) == ADDR_EXPR)
22651     {
22652       expr = TREE_OPERAND (expr, 0);
22653       addr = true;
22654     }
22655   if (TREE_CODE (expr) == OFFSET_REF)
22656     {
22657       offset = expr;
22658       expr = TREE_OPERAND (expr, 1);
22659     }
22660   if (BASELINK_P (expr))
22661     {
22662       baselink = expr;
22663       expr = BASELINK_FUNCTIONS (expr);
22664     }
22665 
22666   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
22667     {
22668       int good = 0;
22669       tree goodfn = NULL_TREE;
22670 
22671       /* If we got some explicit template args, we need to plug them into
22672 	 the affected templates before we try to unify, in case the
22673 	 explicit args will completely resolve the templates in question.  */
22674 
22675       tree expl_subargs = TREE_OPERAND (expr, 1);
22676       tree arg = TREE_OPERAND (expr, 0);
22677       tree badfn = NULL_TREE;
22678       tree badargs = NULL_TREE;
22679 
22680       for (lkp_iterator iter (arg); iter; ++iter)
22681 	{
22682 	  tree fn = *iter;
22683 	  tree subargs, elem;
22684 
22685 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22686 	    continue;
22687 
22688 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22689 					   expl_subargs, NULL_TREE, tf_none,
22690 					   /*require_all_args=*/true,
22691 					   /*use_default_args=*/true);
22692 	  if (subargs != error_mark_node
22693 	      && !any_dependent_template_arguments_p (subargs))
22694 	    {
22695 	      elem = instantiate_template (fn, subargs, tf_none);
22696 	      if (elem == error_mark_node)
22697 		{
22698 		  badfn = fn;
22699 		  badargs = subargs;
22700 		}
22701 	      else if (elem && (!goodfn || !decls_match (goodfn, elem))
22702 		       && constraints_satisfied_p (elem))
22703 		{
22704 		  goodfn = elem;
22705 		  ++good;
22706 		}
22707 	    }
22708 	}
22709       if (good == 1)
22710 	{
22711 	  mark_used (goodfn);
22712 	  expr = goodfn;
22713 	  if (baselink)
22714 	    expr = build_baselink (BASELINK_BINFO (baselink),
22715 				   BASELINK_ACCESS_BINFO (baselink),
22716 				   expr, BASELINK_OPTYPE (baselink));
22717 	  if (offset)
22718 	    {
22719 	      tree base
22720 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
22721 	      expr = build_offset_ref (base, expr, addr, complain);
22722 	    }
22723 	  if (addr)
22724 	    expr = cp_build_addr_expr (expr, complain);
22725 	  return expr;
22726 	}
22727       else if (good == 0 && badargs && (complain & tf_error))
22728 	/* There were no good options and at least one bad one, so let the
22729 	   user know what the problem is.  */
22730 	instantiate_template (badfn, badargs, complain);
22731     }
22732   return orig_expr;
22733 }
22734 
22735 /* As above, but error out if the expression remains overloaded.  */
22736 
22737 tree
resolve_nondeduced_context_or_error(tree exp,tsubst_flags_t complain)22738 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
22739 {
22740   exp = resolve_nondeduced_context (exp, complain);
22741   if (type_unknown_p (exp))
22742     {
22743       if (complain & tf_error)
22744 	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
22745       return error_mark_node;
22746     }
22747   return exp;
22748 }
22749 
22750 /* Subroutine of resolve_overloaded_unification; does deduction for a single
22751    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
22752    different overloads deduce different arguments for a given parm.
22753    ADDR_P is true if the expression for which deduction is being
22754    performed was of the form "& fn" rather than simply "fn".
22755 
22756    Returns 1 on success.  */
22757 
22758 static int
try_one_overload(tree tparms,tree orig_targs,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool addr_p,bool explain_p)22759 try_one_overload (tree tparms,
22760 		  tree orig_targs,
22761 		  tree targs,
22762 		  tree parm,
22763 		  tree arg,
22764 		  unification_kind_t strict,
22765 		  int sub_strict,
22766 		  bool addr_p,
22767 		  bool explain_p)
22768 {
22769   int nargs;
22770   tree tempargs;
22771   int i;
22772 
22773   if (arg == error_mark_node)
22774     return 0;
22775 
22776   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22777      to function or pointer to member function argument if the set of
22778      overloaded functions does not contain function templates and at most
22779      one of a set of overloaded functions provides a unique match.
22780 
22781      So if this is a template, just return success.  */
22782 
22783   if (uses_template_parms (arg))
22784     return 1;
22785 
22786   if (TREE_CODE (arg) == METHOD_TYPE)
22787     arg = build_ptrmemfunc_type (build_pointer_type (arg));
22788   else if (addr_p)
22789     arg = build_pointer_type (arg);
22790 
22791   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
22792 
22793   /* We don't copy orig_targs for this because if we have already deduced
22794      some template args from previous args, unify would complain when we
22795      try to deduce a template parameter for the same argument, even though
22796      there isn't really a conflict.  */
22797   nargs = TREE_VEC_LENGTH (targs);
22798   tempargs = make_tree_vec (nargs);
22799 
22800   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
22801     return 0;
22802 
22803   /* First make sure we didn't deduce anything that conflicts with
22804      explicitly specified args.  */
22805   for (i = nargs; i--; )
22806     {
22807       tree elt = TREE_VEC_ELT (tempargs, i);
22808       tree oldelt = TREE_VEC_ELT (orig_targs, i);
22809 
22810       if (!elt)
22811 	/*NOP*/;
22812       else if (uses_template_parms (elt))
22813 	/* Since we're unifying against ourselves, we will fill in
22814 	   template args used in the function parm list with our own
22815 	   template parms.  Discard them.  */
22816 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
22817       else if (oldelt && ARGUMENT_PACK_P (oldelt))
22818 	{
22819 	  /* Check that the argument at each index of the deduced argument pack
22820 	     is equivalent to the corresponding explicitly specified argument.
22821 	     We may have deduced more arguments than were explicitly specified,
22822 	     and that's OK.  */
22823 
22824 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
22825 	     that's wrong if we deduce the same argument pack from multiple
22826 	     function arguments: it's only incomplete the first time.  */
22827 
22828 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
22829 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
22830 
22831 	  if (TREE_VEC_LENGTH (deduced_pack)
22832 	      < TREE_VEC_LENGTH (explicit_pack))
22833 	    return 0;
22834 
22835 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
22836 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
22837 				      TREE_VEC_ELT (deduced_pack, j)))
22838 	      return 0;
22839 	}
22840       else if (oldelt && !template_args_equal (oldelt, elt))
22841 	return 0;
22842     }
22843 
22844   for (i = nargs; i--; )
22845     {
22846       tree elt = TREE_VEC_ELT (tempargs, i);
22847 
22848       if (elt)
22849 	TREE_VEC_ELT (targs, i) = elt;
22850     }
22851 
22852   return 1;
22853 }
22854 
22855 /* PARM is a template class (perhaps with unbound template
22856    parameters).  ARG is a fully instantiated type.  If ARG can be
22857    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
22858    TARGS are as for unify.  */
22859 
22860 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)22861 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
22862 		       bool explain_p)
22863 {
22864   tree copy_of_targs;
22865 
22866   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22867     return NULL_TREE;
22868   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22869     /* Matches anything.  */;
22870   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
22871 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
22872     return NULL_TREE;
22873 
22874   /* We need to make a new template argument vector for the call to
22875      unify.  If we used TARGS, we'd clutter it up with the result of
22876      the attempted unification, even if this class didn't work out.
22877      We also don't want to commit ourselves to all the unifications
22878      we've already done, since unification is supposed to be done on
22879      an argument-by-argument basis.  In other words, consider the
22880      following pathological case:
22881 
22882        template <int I, int J, int K>
22883        struct S {};
22884 
22885        template <int I, int J>
22886        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
22887 
22888        template <int I, int J, int K>
22889        void f(S<I, J, K>, S<I, I, I>);
22890 
22891        void g() {
22892 	 S<0, 0, 0> s0;
22893 	 S<0, 1, 2> s2;
22894 
22895 	 f(s0, s2);
22896        }
22897 
22898      Now, by the time we consider the unification involving `s2', we
22899      already know that we must have `f<0, 0, 0>'.  But, even though
22900      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
22901      because there are two ways to unify base classes of S<0, 1, 2>
22902      with S<I, I, I>.  If we kept the already deduced knowledge, we
22903      would reject the possibility I=1.  */
22904   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
22905 
22906   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22907     {
22908       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
22909 	return NULL_TREE;
22910       return arg;
22911     }
22912 
22913   /* If unification failed, we're done.  */
22914   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
22915 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
22916     return NULL_TREE;
22917 
22918   return arg;
22919 }
22920 
22921 /* Given a template type PARM and a class type ARG, find the unique
22922    base type in ARG that is an instance of PARM.  We do not examine
22923    ARG itself; only its base-classes.  If there is not exactly one
22924    appropriate base class, return NULL_TREE.  PARM may be the type of
22925    a partial specialization, as well as a plain template type.  Used
22926    by unify.  */
22927 
22928 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)22929 get_template_base (tree tparms, tree targs, tree parm, tree arg,
22930 		   bool explain_p, tree *result)
22931 {
22932   tree rval = NULL_TREE;
22933   tree binfo;
22934 
22935   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
22936 
22937   binfo = TYPE_BINFO (complete_type (arg));
22938   if (!binfo)
22939     {
22940       /* The type could not be completed.  */
22941       *result = NULL_TREE;
22942       return tbr_incomplete_type;
22943     }
22944 
22945   /* Walk in inheritance graph order.  The search order is not
22946      important, and this avoids multiple walks of virtual bases.  */
22947   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
22948     {
22949       tree r = try_class_unification (tparms, targs, parm,
22950 				      BINFO_TYPE (binfo), explain_p);
22951 
22952       if (r)
22953 	{
22954 	  /* If there is more than one satisfactory baseclass, then:
22955 
22956 	       [temp.deduct.call]
22957 
22958 	      If they yield more than one possible deduced A, the type
22959 	      deduction fails.
22960 
22961 	     applies.  */
22962 	  if (rval && !same_type_p (r, rval))
22963 	    {
22964 	      /* [temp.deduct.call]/4.3: If there is a class C that is a
22965 		 (direct or indirect) base class of D and derived (directly or
22966 		 indirectly) from a class B and that would be a valid deduced
22967 		 A, the deduced A cannot be B or pointer to B, respectively. */
22968 	      if (DERIVED_FROM_P (r, rval))
22969 		/* Ignore r.  */
22970 		continue;
22971 	      else if (DERIVED_FROM_P (rval, r))
22972 		/* Ignore rval.  */;
22973 	      else
22974 		{
22975 		  *result = NULL_TREE;
22976 		  return tbr_ambiguous_baseclass;
22977 		}
22978 	    }
22979 
22980 	  rval = r;
22981 	}
22982     }
22983 
22984   *result = rval;
22985   return tbr_success;
22986 }
22987 
22988 /* Returns the level of DECL, which declares a template parameter.  */
22989 
22990 static int
template_decl_level(tree decl)22991 template_decl_level (tree decl)
22992 {
22993   switch (TREE_CODE (decl))
22994     {
22995     case TYPE_DECL:
22996     case TEMPLATE_DECL:
22997       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
22998 
22999     case PARM_DECL:
23000       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23001 
23002     default:
23003       gcc_unreachable ();
23004     }
23005   return 0;
23006 }
23007 
23008 /* Decide whether ARG can be unified with PARM, considering only the
23009    cv-qualifiers of each type, given STRICT as documented for unify.
23010    Returns nonzero iff the unification is OK on that basis.  */
23011 
23012 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)23013 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23014 {
23015   int arg_quals = cp_type_quals (arg);
23016   int parm_quals = cp_type_quals (parm);
23017 
23018   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23019       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23020     {
23021       /*  Although a CVR qualifier is ignored when being applied to a
23022 	  substituted template parameter ([8.3.2]/1 for example), that
23023 	  does not allow us to unify "const T" with "int&" because both
23024 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23025 	  It is ok when we're allowing additional CV qualifiers
23026 	  at the outer level [14.8.2.1]/3,1st bullet.  */
23027       if ((TYPE_REF_P (arg)
23028 	   || FUNC_OR_METHOD_TYPE_P (arg))
23029 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23030 	return 0;
23031 
23032       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23033 	  && (parm_quals & TYPE_QUAL_RESTRICT))
23034 	return 0;
23035     }
23036 
23037   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23038       && (arg_quals & parm_quals) != parm_quals)
23039     return 0;
23040 
23041   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23042       && (parm_quals & arg_quals) != arg_quals)
23043     return 0;
23044 
23045   return 1;
23046 }
23047 
23048 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
23049 void
template_parm_level_and_index(tree parm,int * level,int * index)23050 template_parm_level_and_index (tree parm, int* level, int* index)
23051 {
23052   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23053       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23054       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23055     {
23056       *index = TEMPLATE_TYPE_IDX (parm);
23057       *level = TEMPLATE_TYPE_LEVEL (parm);
23058     }
23059   else
23060     {
23061       *index = TEMPLATE_PARM_IDX (parm);
23062       *level = TEMPLATE_PARM_LEVEL (parm);
23063     }
23064 }
23065 
23066 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
23067   do {									\
23068     if (unify (TP, TA, P, A, S, EP))					\
23069       return 1;								\
23070   } while (0)
23071 
23072 /* Unifies the remaining arguments in PACKED_ARGS with the pack
23073    expansion at the end of PACKED_PARMS. Returns 0 if the type
23074    deduction succeeds, 1 otherwise. STRICT is the same as in
23075    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23076    function call argument list. We'll need to adjust the arguments to make them
23077    types. SUBR tells us if this is from a recursive call to
23078    type_unification_real, or for comparing two template argument
23079    lists. */
23080 
23081 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)23082 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23083                       tree packed_args, unification_kind_t strict,
23084                       bool subr, bool explain_p)
23085 {
23086   tree parm
23087     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23088   tree pattern = PACK_EXPANSION_PATTERN (parm);
23089   tree pack, packs = NULL_TREE;
23090   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23091 
23092   /* Add in any args remembered from an earlier partial instantiation.  */
23093   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23094   int levels = TMPL_ARGS_DEPTH (targs);
23095 
23096   packed_args = expand_template_argument_pack (packed_args);
23097 
23098   int len = TREE_VEC_LENGTH (packed_args);
23099 
23100   /* Determine the parameter packs we will be deducing from the
23101      pattern, and record their current deductions.  */
23102   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23103        pack; pack = TREE_CHAIN (pack))
23104     {
23105       tree parm_pack = TREE_VALUE (pack);
23106       int idx, level;
23107 
23108       /* Only template parameter packs can be deduced, not e.g. function
23109 	 parameter packs or __bases or __integer_pack.  */
23110       if (!TEMPLATE_PARM_P (parm_pack))
23111 	continue;
23112 
23113       /* Determine the index and level of this parameter pack.  */
23114       template_parm_level_and_index (parm_pack, &level, &idx);
23115       if (level < levels)
23116 	continue;
23117 
23118       /* Keep track of the parameter packs and their corresponding
23119          argument packs.  */
23120       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23121       TREE_TYPE (packs) = make_tree_vec (len - start);
23122     }
23123 
23124   /* Loop through all of the arguments that have not yet been
23125      unified and unify each with the pattern.  */
23126   for (i = start; i < len; i++)
23127     {
23128       tree parm;
23129       bool any_explicit = false;
23130       tree arg = TREE_VEC_ELT (packed_args, i);
23131 
23132       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23133 	 or the element of its argument pack at the current index if
23134 	 this argument was explicitly specified.  */
23135       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23136         {
23137           int idx, level;
23138           tree arg, pargs;
23139           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23140 
23141           arg = NULL_TREE;
23142           if (TREE_VALUE (pack)
23143               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23144               && (i - start < TREE_VEC_LENGTH (pargs)))
23145             {
23146               any_explicit = true;
23147               arg = TREE_VEC_ELT (pargs, i - start);
23148             }
23149           TMPL_ARG (targs, level, idx) = arg;
23150         }
23151 
23152       /* If we had explicit template arguments, substitute them into the
23153 	 pattern before deduction.  */
23154       if (any_explicit)
23155 	{
23156 	  /* Some arguments might still be unspecified or dependent.  */
23157 	  bool dependent;
23158 	  ++processing_template_decl;
23159 	  dependent = any_dependent_template_arguments_p (targs);
23160 	  if (!dependent)
23161 	    --processing_template_decl;
23162 	  parm = tsubst (pattern, targs,
23163 			 explain_p ? tf_warning_or_error : tf_none,
23164 			 NULL_TREE);
23165 	  if (dependent)
23166 	    --processing_template_decl;
23167 	  if (parm == error_mark_node)
23168 	    return 1;
23169 	}
23170       else
23171 	parm = pattern;
23172 
23173       /* Unify the pattern with the current argument.  */
23174       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23175 			      explain_p))
23176 	return 1;
23177 
23178       /* For each parameter pack, collect the deduced value.  */
23179       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23180         {
23181           int idx, level;
23182           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23183 
23184           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
23185             TMPL_ARG (targs, level, idx);
23186         }
23187     }
23188 
23189   /* Verify that the results of unification with the parameter packs
23190      produce results consistent with what we've seen before, and make
23191      the deduced argument packs available.  */
23192   for (pack = packs; pack; pack = TREE_CHAIN (pack))
23193     {
23194       tree old_pack = TREE_VALUE (pack);
23195       tree new_args = TREE_TYPE (pack);
23196       int i, len = TREE_VEC_LENGTH (new_args);
23197       int idx, level;
23198       bool nondeduced_p = false;
23199 
23200       /* By default keep the original deduced argument pack.
23201 	 If necessary, more specific code is going to update the
23202 	 resulting deduced argument later down in this function.  */
23203       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23204       TMPL_ARG (targs, level, idx) = old_pack;
23205 
23206       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23207 	 actually deduce anything.  */
23208       for (i = 0; i < len && !nondeduced_p; ++i)
23209 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23210 	  nondeduced_p = true;
23211       if (nondeduced_p)
23212 	continue;
23213 
23214       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23215         {
23216           /* If we had fewer function args than explicit template args,
23217              just use the explicits.  */
23218           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23219           int explicit_len = TREE_VEC_LENGTH (explicit_args);
23220           if (len < explicit_len)
23221             new_args = explicit_args;
23222         }
23223 
23224       if (!old_pack)
23225         {
23226           tree result;
23227           /* Build the deduced *_ARGUMENT_PACK.  */
23228           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
23229             {
23230               result = make_node (NONTYPE_ARGUMENT_PACK);
23231               TREE_CONSTANT (result) = 1;
23232             }
23233           else
23234 	    result = cxx_make_type (TYPE_ARGUMENT_PACK);
23235 
23236           SET_ARGUMENT_PACK_ARGS (result, new_args);
23237 
23238           /* Note the deduced argument packs for this parameter
23239              pack.  */
23240           TMPL_ARG (targs, level, idx) = result;
23241         }
23242       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
23243                && (ARGUMENT_PACK_ARGS (old_pack)
23244                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
23245         {
23246           /* We only had the explicitly-provided arguments before, but
23247              now we have a complete set of arguments.  */
23248           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23249 
23250           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
23251           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
23252           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
23253         }
23254       else
23255 	{
23256 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23257 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23258 	  temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
23259 	  /* During template argument deduction for the aggregate deduction
23260 	     candidate, the number of elements in a trailing parameter pack
23261 	     is only deduced from the number of remaining function
23262 	     arguments if it is not otherwise deduced.  */
23263 	  if (cxx_dialect >= cxx20
23264 	      && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
23265 	      && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
23266 	    TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
23267 	  if (!comp_template_args (old_args, new_args,
23268 				   &bad_old_arg, &bad_new_arg))
23269 	    /* Inconsistent unification of this parameter pack.  */
23270 	    return unify_parameter_pack_inconsistent (explain_p,
23271 						      bad_old_arg,
23272 						      bad_new_arg);
23273 	}
23274     }
23275 
23276   return unify_success (explain_p);
23277 }
23278 
23279 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
23280    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
23281    parameters and return value are as for unify.  */
23282 
23283 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)23284 unify_array_domain (tree tparms, tree targs,
23285 		    tree parm_dom, tree arg_dom,
23286 		    bool explain_p)
23287 {
23288   tree parm_max;
23289   tree arg_max;
23290   bool parm_cst;
23291   bool arg_cst;
23292 
23293   /* Our representation of array types uses "N - 1" as the
23294      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
23295      not an integer constant.  We cannot unify arbitrarily
23296      complex expressions, so we eliminate the MINUS_EXPRs
23297      here.  */
23298   parm_max = TYPE_MAX_VALUE (parm_dom);
23299   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
23300   if (!parm_cst)
23301     {
23302       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
23303       parm_max = TREE_OPERAND (parm_max, 0);
23304     }
23305   arg_max = TYPE_MAX_VALUE (arg_dom);
23306   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
23307   if (!arg_cst)
23308     {
23309       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
23310 	 trying to unify the type of a variable with the type
23311 	 of a template parameter.  For example:
23312 
23313 	   template <unsigned int N>
23314 	   void f (char (&) [N]);
23315 	   int g();
23316 	   void h(int i) {
23317 	     char a[g(i)];
23318 	     f(a);
23319 	   }
23320 
23321 	 Here, the type of the ARG will be "int [g(i)]", and
23322 	 may be a SAVE_EXPR, etc.  */
23323       if (TREE_CODE (arg_max) != MINUS_EXPR)
23324 	return unify_vla_arg (explain_p, arg_dom);
23325       arg_max = TREE_OPERAND (arg_max, 0);
23326     }
23327 
23328   /* If only one of the bounds used a MINUS_EXPR, compensate
23329      by adding one to the other bound.  */
23330   if (parm_cst && !arg_cst)
23331     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
23332 				integer_type_node,
23333 				parm_max,
23334 				integer_one_node);
23335   else if (arg_cst && !parm_cst)
23336     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
23337 			       integer_type_node,
23338 			       arg_max,
23339 			       integer_one_node);
23340 
23341   return unify (tparms, targs, parm_max, arg_max,
23342 		UNIFY_ALLOW_INTEGER, explain_p);
23343 }
23344 
23345 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
23346 
23347 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
23348 
23349 static pa_kind_t
pa_kind(tree t)23350 pa_kind (tree t)
23351 {
23352   if (PACK_EXPANSION_P (t))
23353     t = PACK_EXPANSION_PATTERN (t);
23354   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
23355       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
23356       || DECL_TYPE_TEMPLATE_P (t))
23357     return pa_tmpl;
23358   else if (TYPE_P (t))
23359     return pa_type;
23360   else
23361     return pa_expr;
23362 }
23363 
23364 /* Deduce the value of template parameters.  TPARMS is the (innermost)
23365    set of template parameters to a template.  TARGS is the bindings
23366    for those template parameters, as determined thus far; TARGS may
23367    include template arguments for outer levels of template parameters
23368    as well.  PARM is a parameter to a template function, or a
23369    subcomponent of that parameter; ARG is the corresponding argument.
23370    This function attempts to match PARM with ARG in a manner
23371    consistent with the existing assignments in TARGS.  If more values
23372    are deduced, then TARGS is updated.
23373 
23374    Returns 0 if the type deduction succeeds, 1 otherwise.  The
23375    parameter STRICT is a bitwise or of the following flags:
23376 
23377      UNIFY_ALLOW_NONE:
23378        Require an exact match between PARM and ARG.
23379      UNIFY_ALLOW_MORE_CV_QUAL:
23380        Allow the deduced ARG to be more cv-qualified (by qualification
23381        conversion) than ARG.
23382      UNIFY_ALLOW_LESS_CV_QUAL:
23383        Allow the deduced ARG to be less cv-qualified than ARG.
23384      UNIFY_ALLOW_DERIVED:
23385        Allow the deduced ARG to be a template base class of ARG,
23386        or a pointer to a template base class of the type pointed to by
23387        ARG.
23388      UNIFY_ALLOW_INTEGER:
23389        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
23390        case for more information.
23391      UNIFY_ALLOW_OUTER_LEVEL:
23392        This is the outermost level of a deduction. Used to determine validity
23393        of qualification conversions. A valid qualification conversion must
23394        have const qualified pointers leading up to the inner type which
23395        requires additional CV quals, except at the outer level, where const
23396        is not required [conv.qual]. It would be normal to set this flag in
23397        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
23398      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
23399        This is the outermost level of a deduction, and PARM can be more CV
23400        qualified at this point.
23401      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
23402        This is the outermost level of a deduction, and PARM can be less CV
23403        qualified at this point.  */
23404 
23405 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)23406 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
23407        bool explain_p)
23408 {
23409   int idx;
23410   tree targ;
23411   tree tparm;
23412   int strict_in = strict;
23413   tsubst_flags_t complain = (explain_p
23414 			     ? tf_warning_or_error
23415 			     : tf_none);
23416 
23417   /* I don't think this will do the right thing with respect to types.
23418      But the only case I've seen it in so far has been array bounds, where
23419      signedness is the only information lost, and I think that will be
23420      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
23421      finish_id_expression_1, and are also OK.  */
23422   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
23423     parm = TREE_OPERAND (parm, 0);
23424 
23425   if (arg == error_mark_node)
23426     return unify_invalid (explain_p);
23427   if (arg == unknown_type_node
23428       || arg == init_list_type_node)
23429     /* We can't deduce anything from this, but we might get all the
23430        template args from other function args.  */
23431     return unify_success (explain_p);
23432 
23433   if (parm == any_targ_node || arg == any_targ_node)
23434     return unify_success (explain_p);
23435 
23436   /* If PARM uses template parameters, then we can't bail out here,
23437      even if ARG == PARM, since we won't record unifications for the
23438      template parameters.  We might need them if we're trying to
23439      figure out which of two things is more specialized.  */
23440   if (arg == parm && !uses_template_parms (parm))
23441     return unify_success (explain_p);
23442 
23443   /* Handle init lists early, so the rest of the function can assume
23444      we're dealing with a type. */
23445   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
23446     {
23447       tree elt, elttype;
23448       unsigned i;
23449       tree orig_parm = parm;
23450 
23451       if (!is_std_init_list (parm)
23452 	  && TREE_CODE (parm) != ARRAY_TYPE)
23453 	/* We can only deduce from an initializer list argument if the
23454 	   parameter is std::initializer_list or an array; otherwise this
23455 	   is a non-deduced context. */
23456 	return unify_success (explain_p);
23457 
23458       if (TREE_CODE (parm) == ARRAY_TYPE)
23459 	elttype = TREE_TYPE (parm);
23460       else
23461 	{
23462 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
23463 	  /* Deduction is defined in terms of a single type, so just punt
23464 	     on the (bizarre) std::initializer_list<T...>.  */
23465 	  if (PACK_EXPANSION_P (elttype))
23466 	    return unify_success (explain_p);
23467 	}
23468 
23469       if (strict != DEDUCE_EXACT
23470 	  && TYPE_P (elttype)
23471 	  && !uses_deducible_template_parms (elttype))
23472 	/* If ELTTYPE has no deducible template parms, skip deduction from
23473 	   the list elements.  */;
23474       else
23475 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
23476 	  {
23477 	    int elt_strict = strict;
23478 
23479 	    if (elt == error_mark_node)
23480 	      return unify_invalid (explain_p);
23481 
23482 	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
23483 	      {
23484 		tree type = TREE_TYPE (elt);
23485 		if (type == error_mark_node)
23486 		  return unify_invalid (explain_p);
23487 		/* It should only be possible to get here for a call.  */
23488 		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
23489 		elt_strict |= maybe_adjust_types_for_deduction
23490 		  (DEDUCE_CALL, &elttype, &type, elt);
23491 		elt = type;
23492 	      }
23493 
23494 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
23495 				   explain_p);
23496 	}
23497 
23498       if (TREE_CODE (parm) == ARRAY_TYPE
23499 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
23500 	{
23501 	  /* Also deduce from the length of the initializer list.  */
23502 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
23503 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
23504 	  if (idx == error_mark_node)
23505 	    return unify_invalid (explain_p);
23506 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23507 				     idx, explain_p);
23508 	}
23509 
23510       /* If the std::initializer_list<T> deduction worked, replace the
23511 	 deduced A with std::initializer_list<A>.  */
23512       if (orig_parm != parm)
23513 	{
23514 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
23515 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23516 	  targ = listify (targ);
23517 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
23518 	}
23519       return unify_success (explain_p);
23520     }
23521 
23522   /* If parm and arg aren't the same kind of thing (template, type, or
23523      expression), fail early.  */
23524   if (pa_kind (parm) != pa_kind (arg))
23525     return unify_invalid (explain_p);
23526 
23527   /* Immediately reject some pairs that won't unify because of
23528      cv-qualification mismatches.  */
23529   if (TREE_CODE (arg) == TREE_CODE (parm)
23530       && TYPE_P (arg)
23531       /* It is the elements of the array which hold the cv quals of an array
23532 	 type, and the elements might be template type parms. We'll check
23533 	 when we recurse.  */
23534       && TREE_CODE (arg) != ARRAY_TYPE
23535       /* We check the cv-qualifiers when unifying with template type
23536 	 parameters below.  We want to allow ARG `const T' to unify with
23537 	 PARM `T' for example, when computing which of two templates
23538 	 is more specialized, for example.  */
23539       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
23540       && !check_cv_quals_for_unify (strict_in, arg, parm))
23541     return unify_cv_qual_mismatch (explain_p, parm, arg);
23542 
23543   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
23544       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
23545     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
23546   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
23547   strict &= ~UNIFY_ALLOW_DERIVED;
23548   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
23549   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
23550 
23551   switch (TREE_CODE (parm))
23552     {
23553     case TYPENAME_TYPE:
23554     case SCOPE_REF:
23555     case UNBOUND_CLASS_TEMPLATE:
23556       /* In a type which contains a nested-name-specifier, template
23557 	 argument values cannot be deduced for template parameters used
23558 	 within the nested-name-specifier.  */
23559       return unify_success (explain_p);
23560 
23561     case TEMPLATE_TYPE_PARM:
23562     case TEMPLATE_TEMPLATE_PARM:
23563     case BOUND_TEMPLATE_TEMPLATE_PARM:
23564       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23565       if (error_operand_p (tparm))
23566 	return unify_invalid (explain_p);
23567 
23568       if (TEMPLATE_TYPE_LEVEL (parm)
23569 	  != template_decl_level (tparm))
23570 	/* The PARM is not one we're trying to unify.  Just check
23571 	   to see if it matches ARG.  */
23572 	{
23573 	  if (TREE_CODE (arg) == TREE_CODE (parm)
23574 	      && (is_auto (parm) ? is_auto (arg)
23575 		  : same_type_p (parm, arg)))
23576 	    return unify_success (explain_p);
23577 	  else
23578 	    return unify_type_mismatch (explain_p, parm, arg);
23579 	}
23580       idx = TEMPLATE_TYPE_IDX (parm);
23581       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23582       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
23583       if (error_operand_p (tparm))
23584 	return unify_invalid (explain_p);
23585 
23586       /* Check for mixed types and values.  */
23587       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23588 	   && TREE_CODE (tparm) != TYPE_DECL)
23589 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23590 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
23591 	gcc_unreachable ();
23592 
23593       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23594 	{
23595 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
23596 	      && CLASS_TYPE_P (arg))
23597 	    {
23598 	      /* First try to match ARG directly.  */
23599 	      tree t = try_class_unification (tparms, targs, parm, arg,
23600 					      explain_p);
23601 	      if (!t)
23602 		{
23603 		  /* Otherwise, look for a suitable base of ARG, as below.  */
23604 		  enum template_base_result r;
23605 		  r = get_template_base (tparms, targs, parm, arg,
23606 					 explain_p, &t);
23607 		  if (!t)
23608 		    return unify_no_common_base (explain_p, r, parm, arg);
23609 		  arg = t;
23610 		}
23611 	    }
23612 	  /* ARG must be constructed from a template class or a template
23613 	     template parameter.  */
23614 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
23615 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23616 	    return unify_template_deduction_failure (explain_p, parm, arg);
23617 
23618 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
23619 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
23620 	    return 1;
23621 
23622 	  arg = TYPE_TI_TEMPLATE (arg);
23623 
23624 	  /* Fall through to deduce template name.  */
23625 	}
23626 
23627       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23628 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23629 	{
23630 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
23631 
23632 	  /* Simple cases: Value already set, does match or doesn't.  */
23633 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
23634 	    return unify_success (explain_p);
23635 	  else if (targ)
23636 	    return unify_inconsistency (explain_p, parm, targ, arg);
23637 	}
23638       else
23639 	{
23640 	  /* If PARM is `const T' and ARG is only `int', we don't have
23641 	     a match unless we are allowing additional qualification.
23642 	     If ARG is `const int' and PARM is just `T' that's OK;
23643 	     that binds `const int' to `T'.  */
23644 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
23645 					 arg, parm))
23646 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23647 
23648 	  /* Consider the case where ARG is `const volatile int' and
23649 	     PARM is `const T'.  Then, T should be `volatile int'.  */
23650 	  arg = cp_build_qualified_type_real
23651 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
23652 	  if (arg == error_mark_node)
23653 	    return unify_invalid (explain_p);
23654 
23655 	  /* Simple cases: Value already set, does match or doesn't.  */
23656 	  if (targ != NULL_TREE && same_type_p (targ, arg))
23657 	    return unify_success (explain_p);
23658 	  else if (targ)
23659 	    return unify_inconsistency (explain_p, parm, targ, arg);
23660 
23661 	  /* Make sure that ARG is not a variable-sized array.  (Note
23662 	     that were talking about variable-sized arrays (like
23663 	     `int[n]'), rather than arrays of unknown size (like
23664 	     `int[]').)  We'll get very confused by such a type since
23665 	     the bound of the array is not constant, and therefore
23666 	     not mangleable.  Besides, such types are not allowed in
23667 	     ISO C++, so we can do as we please here.  We do allow
23668 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
23669 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
23670 	    return unify_vla_arg (explain_p, arg);
23671 
23672 	  /* Strip typedefs as in convert_template_argument.  */
23673 	  arg = canonicalize_type_argument (arg, tf_none);
23674 	}
23675 
23676       /* If ARG is a parameter pack or an expansion, we cannot unify
23677 	 against it unless PARM is also a parameter pack.  */
23678       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23679 	  && !template_parameter_pack_p (parm))
23680 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23681 
23682       /* If the argument deduction results is a METHOD_TYPE,
23683          then there is a problem.
23684          METHOD_TYPE doesn't map to any real C++ type the result of
23685 	 the deduction cannot be of that type.  */
23686       if (TREE_CODE (arg) == METHOD_TYPE)
23687 	return unify_method_type_error (explain_p, arg);
23688 
23689       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23690       return unify_success (explain_p);
23691 
23692     case TEMPLATE_PARM_INDEX:
23693       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23694       if (error_operand_p (tparm))
23695 	return unify_invalid (explain_p);
23696 
23697       if (TEMPLATE_PARM_LEVEL (parm)
23698 	  != template_decl_level (tparm))
23699 	{
23700 	  /* The PARM is not one we're trying to unify.  Just check
23701 	     to see if it matches ARG.  */
23702 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
23703 			 && cp_tree_equal (parm, arg));
23704 	  if (result)
23705 	    unify_expression_unequal (explain_p, parm, arg);
23706 	  return result;
23707 	}
23708 
23709       idx = TEMPLATE_PARM_IDX (parm);
23710       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23711 
23712       if (targ)
23713 	{
23714 	  if ((strict & UNIFY_ALLOW_INTEGER)
23715 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
23716 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
23717 	    /* We're deducing from an array bound, the type doesn't matter.  */
23718 	    arg = fold_convert (TREE_TYPE (targ), arg);
23719 	  int x = !cp_tree_equal (targ, arg);
23720 	  if (x)
23721 	    unify_inconsistency (explain_p, parm, targ, arg);
23722 	  return x;
23723 	}
23724 
23725       /* [temp.deduct.type] If, in the declaration of a function template
23726 	 with a non-type template-parameter, the non-type
23727 	 template-parameter is used in an expression in the function
23728 	 parameter-list and, if the corresponding template-argument is
23729 	 deduced, the template-argument type shall match the type of the
23730 	 template-parameter exactly, except that a template-argument
23731 	 deduced from an array bound may be of any integral type.
23732 	 The non-type parameter might use already deduced type parameters.  */
23733       tparm = TREE_TYPE (parm);
23734       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
23735 	/* We don't have enough levels of args to do any substitution.  This
23736 	   can happen in the context of -fnew-ttp-matching.  */;
23737       else
23738 	{
23739 	  ++processing_template_decl;
23740 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23741 	  --processing_template_decl;
23742 
23743 	  if (tree a = type_uses_auto (tparm))
23744 	    {
23745 	      tparm = do_auto_deduction (tparm, arg, a,
23746 					 complain, adc_unify, targs);
23747 	      if (tparm == error_mark_node)
23748 		return 1;
23749 	    }
23750 	}
23751 
23752       if (!TREE_TYPE (arg))
23753 	/* Template-parameter dependent expression.  Just accept it for now.
23754 	   It will later be processed in convert_template_argument.  */
23755 	;
23756       else if (same_type_ignoring_top_level_qualifiers_p
23757 	       (non_reference (TREE_TYPE (arg)),
23758 		non_reference (tparm)))
23759 	/* OK.  Ignore top-level quals here because a class-type template
23760 	   parameter object is const.  */;
23761       else if ((strict & UNIFY_ALLOW_INTEGER)
23762 	       && CP_INTEGRAL_TYPE_P (tparm))
23763 	/* Convert the ARG to the type of PARM; the deduced non-type
23764 	   template argument must exactly match the types of the
23765 	   corresponding parameter.  */
23766 	arg = fold (build_nop (tparm, arg));
23767       else if (uses_template_parms (tparm))
23768 	{
23769 	  /* We haven't deduced the type of this parameter yet.  */
23770 	  if (cxx_dialect >= cxx17
23771 	      /* We deduce from array bounds in try_array_deduction.  */
23772 	      && !(strict & UNIFY_ALLOW_INTEGER)
23773 	      && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
23774 	    {
23775 	      /* Deduce it from the non-type argument.  */
23776 	      tree atype = TREE_TYPE (arg);
23777 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
23778 				       tparm, atype,
23779 				       UNIFY_ALLOW_NONE, explain_p);
23780 	      /* Now check whether the type of this parameter is still
23781 		 dependent, and give up if so.  */
23782 	      ++processing_template_decl;
23783 	      tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23784 	      --processing_template_decl;
23785 	      if (uses_template_parms (tparm))
23786 		return unify_success (explain_p);
23787 	    }
23788 	  else
23789 	    /* Try again later.  */
23790 	    return unify_success (explain_p);
23791 	}
23792       else
23793 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
23794 
23795       /* If ARG is a parameter pack or an expansion, we cannot unify
23796 	 against it unless PARM is also a parameter pack.  */
23797       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23798 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
23799 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23800 
23801       {
23802 	bool removed_attr = false;
23803 	arg = strip_typedefs_expr (arg, &removed_attr);
23804       }
23805       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23806       return unify_success (explain_p);
23807 
23808     case PTRMEM_CST:
23809      {
23810 	/* A pointer-to-member constant can be unified only with
23811 	 another constant.  */
23812       if (TREE_CODE (arg) != PTRMEM_CST)
23813 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
23814 
23815       /* Just unify the class member. It would be useless (and possibly
23816 	 wrong, depending on the strict flags) to unify also
23817 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
23818 	 arg refer to the same variable, even if through different
23819 	 classes. For instance:
23820 
23821 	 struct A { int x; };
23822 	 struct B : A { };
23823 
23824 	 Unification of &A::x and &B::x must succeed.  */
23825       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
23826 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
23827      }
23828 
23829     case POINTER_TYPE:
23830       {
23831 	if (!TYPE_PTR_P (arg))
23832 	  return unify_type_mismatch (explain_p, parm, arg);
23833 
23834 	/* [temp.deduct.call]
23835 
23836 	   A can be another pointer or pointer to member type that can
23837 	   be converted to the deduced A via a qualification
23838 	   conversion (_conv.qual_).
23839 
23840 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
23841 	   This will allow for additional cv-qualification of the
23842 	   pointed-to types if appropriate.  */
23843 
23844 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
23845 	  /* The derived-to-base conversion only persists through one
23846 	     level of pointers.  */
23847 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
23848 
23849 	return unify (tparms, targs, TREE_TYPE (parm),
23850 		      TREE_TYPE (arg), strict, explain_p);
23851       }
23852 
23853     case REFERENCE_TYPE:
23854       if (!TYPE_REF_P (arg))
23855 	return unify_type_mismatch (explain_p, parm, arg);
23856       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23857 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23858 
23859     case ARRAY_TYPE:
23860       if (TREE_CODE (arg) != ARRAY_TYPE)
23861 	return unify_type_mismatch (explain_p, parm, arg);
23862       if ((TYPE_DOMAIN (parm) == NULL_TREE)
23863 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
23864 	return unify_type_mismatch (explain_p, parm, arg);
23865       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23866 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23867       if (TYPE_DOMAIN (parm) != NULL_TREE)
23868 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23869 				   TYPE_DOMAIN (arg), explain_p);
23870       return unify_success (explain_p);
23871 
23872     case REAL_TYPE:
23873     case COMPLEX_TYPE:
23874     case VECTOR_TYPE:
23875     case INTEGER_TYPE:
23876     case BOOLEAN_TYPE:
23877     case ENUMERAL_TYPE:
23878     case VOID_TYPE:
23879     case OPAQUE_TYPE:
23880     case NULLPTR_TYPE:
23881       if (TREE_CODE (arg) != TREE_CODE (parm))
23882 	return unify_type_mismatch (explain_p, parm, arg);
23883 
23884       /* We have already checked cv-qualification at the top of the
23885 	 function.  */
23886       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
23887 	return unify_type_mismatch (explain_p, parm, arg);
23888 
23889       /* As far as unification is concerned, this wins.	 Later checks
23890 	 will invalidate it if necessary.  */
23891       return unify_success (explain_p);
23892 
23893       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
23894       /* Type INTEGER_CST can come from ordinary constant template args.  */
23895     case INTEGER_CST:
23896       while (CONVERT_EXPR_P (arg))
23897 	arg = TREE_OPERAND (arg, 0);
23898 
23899       if (TREE_CODE (arg) != INTEGER_CST)
23900 	return unify_template_argument_mismatch (explain_p, parm, arg);
23901       return (tree_int_cst_equal (parm, arg)
23902 	      ? unify_success (explain_p)
23903 	      : unify_template_argument_mismatch (explain_p, parm, arg));
23904 
23905     case TREE_VEC:
23906       {
23907 	int i, len, argslen;
23908 	int parm_variadic_p = 0;
23909 
23910 	if (TREE_CODE (arg) != TREE_VEC)
23911 	  return unify_template_argument_mismatch (explain_p, parm, arg);
23912 
23913 	len = TREE_VEC_LENGTH (parm);
23914 	argslen = TREE_VEC_LENGTH (arg);
23915 
23916 	/* Check for pack expansions in the parameters.  */
23917 	for (i = 0; i < len; ++i)
23918 	  {
23919 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
23920 	      {
23921 		if (i == len - 1)
23922 		  /* We can unify against something with a trailing
23923 		     parameter pack.  */
23924 		  parm_variadic_p = 1;
23925 		else
23926 		  /* [temp.deduct.type]/9: If the template argument list of
23927 		     P contains a pack expansion that is not the last
23928 		     template argument, the entire template argument list
23929 		     is a non-deduced context.  */
23930 		  return unify_success (explain_p);
23931 	      }
23932 	  }
23933 
23934         /* If we don't have enough arguments to satisfy the parameters
23935            (not counting the pack expression at the end), or we have
23936            too many arguments for a parameter list that doesn't end in
23937            a pack expression, we can't unify.  */
23938 	if (parm_variadic_p
23939 	    ? argslen < len - parm_variadic_p
23940 	    : argslen != len)
23941 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
23942 
23943 	/* Unify all of the parameters that precede the (optional)
23944 	   pack expression.  */
23945 	for (i = 0; i < len - parm_variadic_p; ++i)
23946 	  {
23947 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
23948 				     TREE_VEC_ELT (parm, i),
23949 				     TREE_VEC_ELT (arg, i),
23950 				     UNIFY_ALLOW_NONE, explain_p);
23951 	  }
23952 	if (parm_variadic_p)
23953 	  return unify_pack_expansion (tparms, targs, parm, arg,
23954 				       DEDUCE_EXACT,
23955 				       /*subr=*/true, explain_p);
23956 	return unify_success (explain_p);
23957       }
23958 
23959     case RECORD_TYPE:
23960     case UNION_TYPE:
23961       if (TREE_CODE (arg) != TREE_CODE (parm))
23962 	return unify_type_mismatch (explain_p, parm, arg);
23963 
23964       if (TYPE_PTRMEMFUNC_P (parm))
23965 	{
23966 	  if (!TYPE_PTRMEMFUNC_P (arg))
23967 	    return unify_type_mismatch (explain_p, parm, arg);
23968 
23969 	  return unify (tparms, targs,
23970 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
23971 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
23972 			strict, explain_p);
23973 	}
23974       else if (TYPE_PTRMEMFUNC_P (arg))
23975 	return unify_type_mismatch (explain_p, parm, arg);
23976 
23977       if (CLASSTYPE_TEMPLATE_INFO (parm))
23978 	{
23979 	  tree t = NULL_TREE;
23980 
23981 	  if (strict_in & UNIFY_ALLOW_DERIVED)
23982 	    {
23983 	      /* First, we try to unify the PARM and ARG directly.  */
23984 	      t = try_class_unification (tparms, targs,
23985 					 parm, arg, explain_p);
23986 
23987 	      if (!t)
23988 		{
23989 		  /* Fallback to the special case allowed in
23990 		     [temp.deduct.call]:
23991 
23992 		       If P is a class, and P has the form
23993 		       template-id, then A can be a derived class of
23994 		       the deduced A.  Likewise, if P is a pointer to
23995 		       a class of the form template-id, A can be a
23996 		       pointer to a derived class pointed to by the
23997 		       deduced A.  */
23998 		  enum template_base_result r;
23999 		  r = get_template_base (tparms, targs, parm, arg,
24000 					 explain_p, &t);
24001 
24002 		  if (!t)
24003 		    {
24004 		      /* Don't give the derived diagnostic if we're
24005 			 already dealing with the same template.  */
24006 		      bool same_template
24007 			= (CLASSTYPE_TEMPLATE_INFO (arg)
24008 			   && (CLASSTYPE_TI_TEMPLATE (parm)
24009 			       == CLASSTYPE_TI_TEMPLATE (arg)));
24010 		      return unify_no_common_base (explain_p && !same_template,
24011 						   r, parm, arg);
24012 		    }
24013 		}
24014 	    }
24015 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
24016 		   && (CLASSTYPE_TI_TEMPLATE (parm)
24017 		       == CLASSTYPE_TI_TEMPLATE (arg)))
24018 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
24019 	       Then, we should unify `int' and `U'.  */
24020 	    t = arg;
24021 	  else
24022 	    /* There's no chance of unification succeeding.  */
24023 	    return unify_type_mismatch (explain_p, parm, arg);
24024 
24025 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24026 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
24027 	}
24028       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24029 	return unify_type_mismatch (explain_p, parm, arg);
24030       return unify_success (explain_p);
24031 
24032     case METHOD_TYPE:
24033     case FUNCTION_TYPE:
24034       {
24035 	unsigned int nargs;
24036 	tree *args;
24037 	tree a;
24038 	unsigned int i;
24039 
24040 	if (TREE_CODE (arg) != TREE_CODE (parm))
24041 	  return unify_type_mismatch (explain_p, parm, arg);
24042 
24043 	/* CV qualifications for methods can never be deduced, they must
24044 	   match exactly.  We need to check them explicitly here,
24045 	   because type_unification_real treats them as any other
24046 	   cv-qualified parameter.  */
24047 	if (TREE_CODE (parm) == METHOD_TYPE
24048 	    && (!check_cv_quals_for_unify
24049 		(UNIFY_ALLOW_NONE,
24050 		 class_of_this_parm (arg),
24051 		 class_of_this_parm (parm))))
24052 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24053 	if (TREE_CODE (arg) == FUNCTION_TYPE
24054 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
24055 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24056 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24057 	  return unify_type_mismatch (explain_p, parm, arg);
24058 
24059 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24060 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24061 
24062 	nargs = list_length (TYPE_ARG_TYPES (arg));
24063 	args = XALLOCAVEC (tree, nargs);
24064 	for (a = TYPE_ARG_TYPES (arg), i = 0;
24065 	     a != NULL_TREE && a != void_list_node;
24066 	     a = TREE_CHAIN (a), ++i)
24067 	  args[i] = TREE_VALUE (a);
24068 	nargs = i;
24069 
24070 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24071 				   args, nargs, 1, DEDUCE_EXACT,
24072 				   NULL, explain_p))
24073 	  return 1;
24074 
24075 	if (flag_noexcept_type)
24076 	  {
24077 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24078 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24079 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24080 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24081 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24082 		&& uses_template_parms (TREE_PURPOSE (pspec)))
24083 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24084 				       TREE_PURPOSE (aspec),
24085 				       UNIFY_ALLOW_NONE, explain_p);
24086 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
24087 	      return unify_type_mismatch (explain_p, parm, arg);
24088 	  }
24089 
24090 	return 0;
24091       }
24092 
24093     case OFFSET_TYPE:
24094       /* Unify a pointer to member with a pointer to member function, which
24095 	 deduces the type of the member as a function type. */
24096       if (TYPE_PTRMEMFUNC_P (arg))
24097 	{
24098 	  /* Check top-level cv qualifiers */
24099 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24100 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
24101 
24102 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24103 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24104 				   UNIFY_ALLOW_NONE, explain_p);
24105 
24106 	  /* Determine the type of the function we are unifying against. */
24107 	  tree fntype = static_fn_type (arg);
24108 
24109 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24110 	}
24111 
24112       if (TREE_CODE (arg) != OFFSET_TYPE)
24113 	return unify_type_mismatch (explain_p, parm, arg);
24114       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24115 			       TYPE_OFFSET_BASETYPE (arg),
24116 			       UNIFY_ALLOW_NONE, explain_p);
24117       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24118 		    strict, explain_p);
24119 
24120     case CONST_DECL:
24121       if (DECL_TEMPLATE_PARM_P (parm))
24122 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
24123       if (arg != scalar_constant_value (parm))
24124 	return unify_template_argument_mismatch (explain_p, parm, arg);
24125       return unify_success (explain_p);
24126 
24127     case FIELD_DECL:
24128     case TEMPLATE_DECL:
24129       /* Matched cases are handled by the ARG == PARM test above.  */
24130       return unify_template_argument_mismatch (explain_p, parm, arg);
24131 
24132     case VAR_DECL:
24133       /* We might get a variable as a non-type template argument in parm if the
24134 	 corresponding parameter is type-dependent.  Make any necessary
24135 	 adjustments based on whether arg is a reference.  */
24136       if (CONSTANT_CLASS_P (arg))
24137 	parm = fold_non_dependent_expr (parm, complain);
24138       else if (REFERENCE_REF_P (arg))
24139 	{
24140 	  tree sub = TREE_OPERAND (arg, 0);
24141 	  STRIP_NOPS (sub);
24142 	  if (TREE_CODE (sub) == ADDR_EXPR)
24143 	    arg = TREE_OPERAND (sub, 0);
24144 	}
24145       /* Now use the normal expression code to check whether they match.  */
24146       goto expr;
24147 
24148     case TYPE_ARGUMENT_PACK:
24149     case NONTYPE_ARGUMENT_PACK:
24150       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24151 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24152 
24153     case TYPEOF_TYPE:
24154     case DECLTYPE_TYPE:
24155     case UNDERLYING_TYPE:
24156       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24157 	 or UNDERLYING_TYPE nodes.  */
24158       return unify_success (explain_p);
24159 
24160     case ERROR_MARK:
24161       /* Unification fails if we hit an error node.  */
24162       return unify_invalid (explain_p);
24163 
24164     case INDIRECT_REF:
24165       if (REFERENCE_REF_P (parm))
24166 	{
24167 	  bool pexp = PACK_EXPANSION_P (arg);
24168 	  if (pexp)
24169 	    arg = PACK_EXPANSION_PATTERN (arg);
24170 	  if (REFERENCE_REF_P (arg))
24171 	    arg = TREE_OPERAND (arg, 0);
24172 	  if (pexp)
24173 	    arg = make_pack_expansion (arg, complain);
24174 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
24175 			strict, explain_p);
24176 	}
24177       /* FALLTHRU */
24178 
24179     default:
24180       /* An unresolved overload is a nondeduced context.  */
24181       if (is_overloaded_fn (parm) || type_unknown_p (parm))
24182 	return unify_success (explain_p);
24183       gcc_assert (EXPR_P (parm)
24184 		  || COMPOUND_LITERAL_P (parm)
24185 		  || TREE_CODE (parm) == TRAIT_EXPR);
24186     expr:
24187       /* We must be looking at an expression.  This can happen with
24188 	 something like:
24189 
24190 	   template <int I>
24191 	   void foo(S<I>, S<I + 2>);
24192 
24193 	 or
24194 
24195 	   template<typename T>
24196 	   void foo(A<T, T{}>);
24197 
24198 	 This is a "non-deduced context":
24199 
24200 	   [deduct.type]
24201 
24202 	   The non-deduced contexts are:
24203 
24204 	   --A non-type template argument or an array bound in which
24205 	     a subexpression references a template parameter.
24206 
24207 	 In these cases, we assume deduction succeeded, but don't
24208 	 actually infer any unifications.  */
24209 
24210       if (!uses_template_parms (parm)
24211 	  && !template_args_equal (parm, arg))
24212 	return unify_expression_unequal (explain_p, parm, arg);
24213       else
24214 	return unify_success (explain_p);
24215     }
24216 }
24217 #undef RECUR_AND_CHECK_FAILURE
24218 
24219 /* Note that DECL can be defined in this translation unit, if
24220    required.  */
24221 
24222 static void
mark_definable(tree decl)24223 mark_definable (tree decl)
24224 {
24225   tree clone;
24226   DECL_NOT_REALLY_EXTERN (decl) = 1;
24227   FOR_EACH_CLONE (clone, decl)
24228     DECL_NOT_REALLY_EXTERN (clone) = 1;
24229 }
24230 
24231 /* Called if RESULT is explicitly instantiated, or is a member of an
24232    explicitly instantiated class.  */
24233 
24234 void
mark_decl_instantiated(tree result,int extern_p)24235 mark_decl_instantiated (tree result, int extern_p)
24236 {
24237   SET_DECL_EXPLICIT_INSTANTIATION (result);
24238 
24239   /* If this entity has already been written out, it's too late to
24240      make any modifications.  */
24241   if (TREE_ASM_WRITTEN (result))
24242     return;
24243 
24244   /* consteval functions are never emitted.  */
24245   if (TREE_CODE (result) == FUNCTION_DECL
24246       && DECL_IMMEDIATE_FUNCTION_P (result))
24247     return;
24248 
24249   /* For anonymous namespace we don't need to do anything.  */
24250   if (decl_anon_ns_mem_p (result))
24251     {
24252       gcc_assert (!TREE_PUBLIC (result));
24253       return;
24254     }
24255 
24256   if (TREE_CODE (result) != FUNCTION_DECL)
24257     /* The TREE_PUBLIC flag for function declarations will have been
24258        set correctly by tsubst.  */
24259     TREE_PUBLIC (result) = 1;
24260 
24261   /* This might have been set by an earlier implicit instantiation.  */
24262   DECL_COMDAT (result) = 0;
24263 
24264   if (extern_p)
24265     {
24266       DECL_EXTERNAL (result) = 1;
24267       DECL_NOT_REALLY_EXTERN (result) = 0;
24268     }
24269   else
24270     {
24271       mark_definable (result);
24272       mark_needed (result);
24273       /* Always make artificials weak.  */
24274       if (DECL_ARTIFICIAL (result) && flag_weak)
24275 	comdat_linkage (result);
24276       /* For WIN32 we also want to put explicit instantiations in
24277 	 linkonce sections.  */
24278       else if (TREE_PUBLIC (result))
24279 	maybe_make_one_only (result);
24280       if (TREE_CODE (result) == FUNCTION_DECL
24281 	  && DECL_TEMPLATE_INSTANTIATED (result))
24282 	/* If the function has already been instantiated, clear DECL_EXTERNAL,
24283 	   since start_preparsed_function wouldn't have if we had an earlier
24284 	   extern explicit instantiation.  */
24285 	DECL_EXTERNAL (result) = 0;
24286     }
24287 
24288   /* If EXTERN_P, then this function will not be emitted -- unless
24289      followed by an explicit instantiation, at which point its linkage
24290      will be adjusted.  If !EXTERN_P, then this function will be
24291      emitted here.  In neither circumstance do we want
24292      import_export_decl to adjust the linkage.  */
24293   DECL_INTERFACE_KNOWN (result) = 1;
24294 }
24295 
24296 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
24297    important template arguments.  If any are missing, we check whether
24298    they're important by using error_mark_node for substituting into any
24299    args that were used for partial ordering (the ones between ARGS and END)
24300    and seeing if it bubbles up.  */
24301 
24302 static bool
check_undeduced_parms(tree targs,tree args,tree end)24303 check_undeduced_parms (tree targs, tree args, tree end)
24304 {
24305   bool found = false;
24306   int i;
24307   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
24308     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
24309       {
24310 	found = true;
24311 	TREE_VEC_ELT (targs, i) = error_mark_node;
24312       }
24313   if (found)
24314     {
24315       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
24316       if (substed == error_mark_node)
24317 	return true;
24318     }
24319   return false;
24320 }
24321 
24322 /* Given two function templates PAT1 and PAT2, return:
24323 
24324    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
24325    -1 if PAT2 is more specialized than PAT1.
24326    0 if neither is more specialized.
24327 
24328    LEN indicates the number of parameters we should consider
24329    (defaulted parameters should not be considered).
24330 
24331    The 1998 std underspecified function template partial ordering, and
24332    DR214 addresses the issue.  We take pairs of arguments, one from
24333    each of the templates, and deduce them against each other.  One of
24334    the templates will be more specialized if all the *other*
24335    template's arguments deduce against its arguments and at least one
24336    of its arguments *does* *not* deduce against the other template's
24337    corresponding argument.  Deduction is done as for class templates.
24338    The arguments used in deduction have reference and top level cv
24339    qualifiers removed.  Iff both arguments were originally reference
24340    types *and* deduction succeeds in both directions, an lvalue reference
24341    wins against an rvalue reference and otherwise the template
24342    with the more cv-qualified argument wins for that pairing (if
24343    neither is more cv-qualified, they both are equal).  Unlike regular
24344    deduction, after all the arguments have been deduced in this way,
24345    we do *not* verify the deduced template argument values can be
24346    substituted into non-deduced contexts.
24347 
24348    The logic can be a bit confusing here, because we look at deduce1 and
24349    targs1 to see if pat2 is at least as specialized, and vice versa; if we
24350    can find template arguments for pat1 to make arg1 look like arg2, that
24351    means that arg2 is at least as specialized as arg1.  */
24352 
24353 int
more_specialized_fn(tree pat1,tree pat2,int len)24354 more_specialized_fn (tree pat1, tree pat2, int len)
24355 {
24356   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
24357   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
24358   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
24359   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
24360   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
24361   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
24362   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
24363   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
24364   tree origs1, origs2;
24365   bool lose1 = false;
24366   bool lose2 = false;
24367 
24368   /* Remove the this parameter from non-static member functions.  If
24369      one is a non-static member function and the other is not a static
24370      member function, remove the first parameter from that function
24371      also.  This situation occurs for operator functions where we
24372      locate both a member function (with this pointer) and non-member
24373      operator (with explicit first operand).  */
24374   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
24375     {
24376       len--; /* LEN is the number of significant arguments for DECL1 */
24377       args1 = TREE_CHAIN (args1);
24378       if (!DECL_STATIC_FUNCTION_P (decl2))
24379 	args2 = TREE_CHAIN (args2);
24380     }
24381   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
24382     {
24383       args2 = TREE_CHAIN (args2);
24384       if (!DECL_STATIC_FUNCTION_P (decl1))
24385 	{
24386 	  len--;
24387 	  args1 = TREE_CHAIN (args1);
24388 	}
24389     }
24390 
24391   /* If only one is a conversion operator, they are unordered.  */
24392   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
24393     return 0;
24394 
24395   /* Consider the return type for a conversion function */
24396   if (DECL_CONV_FN_P (decl1))
24397     {
24398       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
24399       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
24400       len++;
24401     }
24402 
24403   processing_template_decl++;
24404 
24405   origs1 = args1;
24406   origs2 = args2;
24407 
24408   while (len--
24409 	 /* Stop when an ellipsis is seen.  */
24410 	 && args1 != NULL_TREE && args2 != NULL_TREE)
24411     {
24412       tree arg1 = TREE_VALUE (args1);
24413       tree arg2 = TREE_VALUE (args2);
24414       int deduce1, deduce2;
24415       int quals1 = -1;
24416       int quals2 = -1;
24417       int ref1 = 0;
24418       int ref2 = 0;
24419 
24420       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24421           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24422         {
24423           /* When both arguments are pack expansions, we need only
24424              unify the patterns themselves.  */
24425           arg1 = PACK_EXPANSION_PATTERN (arg1);
24426           arg2 = PACK_EXPANSION_PATTERN (arg2);
24427 
24428           /* This is the last comparison we need to do.  */
24429           len = 0;
24430         }
24431 
24432       if (TYPE_REF_P (arg1))
24433 	{
24434 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
24435 	  arg1 = TREE_TYPE (arg1);
24436 	  quals1 = cp_type_quals (arg1);
24437 	}
24438 
24439       if (TYPE_REF_P (arg2))
24440 	{
24441 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
24442 	  arg2 = TREE_TYPE (arg2);
24443 	  quals2 = cp_type_quals (arg2);
24444 	}
24445 
24446       arg1 = TYPE_MAIN_VARIANT (arg1);
24447       arg2 = TYPE_MAIN_VARIANT (arg2);
24448 
24449       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
24450         {
24451           int i, len2 = remaining_arguments (args2);
24452           tree parmvec = make_tree_vec (1);
24453           tree argvec = make_tree_vec (len2);
24454           tree ta = args2;
24455 
24456           /* Setup the parameter vector, which contains only ARG1.  */
24457           TREE_VEC_ELT (parmvec, 0) = arg1;
24458 
24459           /* Setup the argument vector, which contains the remaining
24460              arguments.  */
24461           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
24462             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24463 
24464           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
24465 					   argvec, DEDUCE_EXACT,
24466 					   /*subr=*/true, /*explain_p=*/false)
24467 		     == 0);
24468 
24469           /* We cannot deduce in the other direction, because ARG1 is
24470              a pack expansion but ARG2 is not.  */
24471           deduce2 = 0;
24472         }
24473       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24474         {
24475           int i, len1 = remaining_arguments (args1);
24476           tree parmvec = make_tree_vec (1);
24477           tree argvec = make_tree_vec (len1);
24478           tree ta = args1;
24479 
24480           /* Setup the parameter vector, which contains only ARG1.  */
24481           TREE_VEC_ELT (parmvec, 0) = arg2;
24482 
24483           /* Setup the argument vector, which contains the remaining
24484              arguments.  */
24485           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
24486             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24487 
24488           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
24489 					   argvec, DEDUCE_EXACT,
24490 					   /*subr=*/true, /*explain_p=*/false)
24491 		     == 0);
24492 
24493           /* We cannot deduce in the other direction, because ARG2 is
24494              a pack expansion but ARG1 is not.*/
24495           deduce1 = 0;
24496         }
24497 
24498       else
24499         {
24500           /* The normal case, where neither argument is a pack
24501              expansion.  */
24502           deduce1 = (unify (tparms1, targs1, arg1, arg2,
24503 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24504 		     == 0);
24505           deduce2 = (unify (tparms2, targs2, arg2, arg1,
24506 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24507 		     == 0);
24508         }
24509 
24510       /* If we couldn't deduce arguments for tparms1 to make arg1 match
24511 	 arg2, then arg2 is not as specialized as arg1.  */
24512       if (!deduce1)
24513 	lose2 = true;
24514       if (!deduce2)
24515 	lose1 = true;
24516 
24517       /* "If, for a given type, deduction succeeds in both directions
24518 	 (i.e., the types are identical after the transformations above)
24519 	 and both P and A were reference types (before being replaced with
24520 	 the type referred to above):
24521 	 - if the type from the argument template was an lvalue reference and
24522 	 the type from the parameter template was not, the argument type is
24523 	 considered to be more specialized than the other; otherwise,
24524 	 - if the type from the argument template is more cv-qualified
24525 	 than the type from the parameter template (as described above),
24526 	 the argument type is considered to be more specialized than the other;
24527 	 otherwise,
24528 	 - neither type is more specialized than the other."  */
24529 
24530       if (deduce1 && deduce2)
24531 	{
24532 	  if (ref1 && ref2 && ref1 != ref2)
24533 	    {
24534 	      if (ref1 > ref2)
24535 		lose1 = true;
24536 	      else
24537 		lose2 = true;
24538 	    }
24539 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
24540 	    {
24541 	      if ((quals1 & quals2) == quals2)
24542 		lose2 = true;
24543 	      if ((quals1 & quals2) == quals1)
24544 		lose1 = true;
24545 	    }
24546 	}
24547 
24548       if (lose1 && lose2)
24549 	/* We've failed to deduce something in either direction.
24550 	   These must be unordered.  */
24551 	break;
24552 
24553       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24554           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24555         /* We have already processed all of the arguments in our
24556            handing of the pack expansion type.  */
24557         len = 0;
24558 
24559       args1 = TREE_CHAIN (args1);
24560       args2 = TREE_CHAIN (args2);
24561     }
24562 
24563   /* "In most cases, all template parameters must have values in order for
24564      deduction to succeed, but for partial ordering purposes a template
24565      parameter may remain without a value provided it is not used in the
24566      types being used for partial ordering."
24567 
24568      Thus, if we are missing any of the targs1 we need to substitute into
24569      origs1, then pat2 is not as specialized as pat1.  This can happen when
24570      there is a nondeduced context.  */
24571   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
24572     lose2 = true;
24573   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
24574     lose1 = true;
24575 
24576   processing_template_decl--;
24577 
24578   /* If both deductions succeed, the partial ordering selects the more
24579      constrained template.  */
24580   /* P2113: If the corresponding template-parameters of the
24581      template-parameter-lists are not equivalent ([temp.over.link]) or if
24582      the function parameters that positionally correspond between the two
24583      templates are not of the same type, neither template is more
24584      specialized than the other.  */
24585   if (!lose1 && !lose2
24586       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
24587 			      DECL_TEMPLATE_PARMS (pat2))
24588       && compparms (origs1, origs2))
24589     {
24590       int winner = more_constrained (decl1, decl2);
24591       if (winner > 0)
24592 	lose2 = true;
24593       else if (winner < 0)
24594 	lose1 = true;
24595     }
24596 
24597   /* All things being equal, if the next argument is a pack expansion
24598      for one function but not for the other, prefer the
24599      non-variadic function.  FIXME this is bogus; see c++/41958.  */
24600   if (lose1 == lose2
24601       && args1 && TREE_VALUE (args1)
24602       && args2 && TREE_VALUE (args2))
24603     {
24604       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
24605       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
24606     }
24607 
24608   if (lose1 == lose2)
24609     return 0;
24610   else if (!lose1)
24611     return 1;
24612   else
24613     return -1;
24614 }
24615 
24616 /* Determine which of two partial specializations of TMPL is more
24617    specialized.
24618 
24619    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
24620    to the first partial specialization.  The TREE_PURPOSE is the
24621    innermost set of template parameters for the partial
24622    specialization.  PAT2 is similar, but for the second template.
24623 
24624    Return 1 if the first partial specialization is more specialized;
24625    -1 if the second is more specialized; 0 if neither is more
24626    specialized.
24627 
24628    See [temp.class.order] for information about determining which of
24629    two templates is more specialized.  */
24630 
24631 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)24632 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
24633 {
24634   tree targs;
24635   int winner = 0;
24636   bool any_deductions = false;
24637 
24638   tree tmpl1 = TREE_VALUE (pat1);
24639   tree tmpl2 = TREE_VALUE (pat2);
24640   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
24641   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
24642 
24643   /* Just like what happens for functions, if we are ordering between
24644      different template specializations, we may encounter dependent
24645      types in the arguments, and we need our dependency check functions
24646      to behave correctly.  */
24647   ++processing_template_decl;
24648   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
24649   if (targs)
24650     {
24651       --winner;
24652       any_deductions = true;
24653     }
24654 
24655   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
24656   if (targs)
24657     {
24658       ++winner;
24659       any_deductions = true;
24660     }
24661   --processing_template_decl;
24662 
24663   /* If both deductions succeed, the partial ordering selects the more
24664      constrained template.  */
24665   if (!winner && any_deductions)
24666     winner = more_constrained (tmpl1, tmpl2);
24667 
24668   /* In the case of a tie where at least one of the templates
24669      has a parameter pack at the end, the template with the most
24670      non-packed parameters wins.  */
24671   if (winner == 0
24672       && any_deductions
24673       && (template_args_variadic_p (TREE_PURPOSE (pat1))
24674           || template_args_variadic_p (TREE_PURPOSE (pat2))))
24675     {
24676       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
24677       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
24678       int len1 = TREE_VEC_LENGTH (args1);
24679       int len2 = TREE_VEC_LENGTH (args2);
24680 
24681       /* We don't count the pack expansion at the end.  */
24682       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
24683         --len1;
24684       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
24685         --len2;
24686 
24687       if (len1 > len2)
24688         return 1;
24689       else if (len1 < len2)
24690         return -1;
24691     }
24692 
24693   return winner;
24694 }
24695 
24696 /* Return the template arguments that will produce the function signature
24697    DECL from the function template FN, with the explicit template
24698    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
24699    also match.  Return NULL_TREE if no satisfactory arguments could be
24700    found.  */
24701 
24702 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)24703 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
24704 {
24705   int ntparms = DECL_NTPARMS (fn);
24706   tree targs = make_tree_vec (ntparms);
24707   tree decl_type = TREE_TYPE (decl);
24708   tree decl_arg_types;
24709   tree *args;
24710   unsigned int nargs, ix;
24711   tree arg;
24712 
24713   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
24714 
24715   /* Never do unification on the 'this' parameter.  */
24716   decl_arg_types = skip_artificial_parms_for (decl,
24717 					      TYPE_ARG_TYPES (decl_type));
24718 
24719   nargs = list_length (decl_arg_types);
24720   args = XALLOCAVEC (tree, nargs);
24721   for (arg = decl_arg_types, ix = 0;
24722        arg != NULL_TREE && arg != void_list_node;
24723        arg = TREE_CHAIN (arg), ++ix)
24724     args[ix] = TREE_VALUE (arg);
24725 
24726   if (fn_type_unification (fn, explicit_args, targs,
24727 			   args, ix,
24728 			   (check_rettype || DECL_CONV_FN_P (fn)
24729 			    ? TREE_TYPE (decl_type) : NULL_TREE),
24730 			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
24731 			   /*explain_p=*/false,
24732 			   /*decltype*/false)
24733       == error_mark_node)
24734     return NULL_TREE;
24735 
24736   return targs;
24737 }
24738 
24739 /* Return the innermost template arguments that, when applied to a partial
24740    specialization SPEC_TMPL of TMPL, yield the ARGS.
24741 
24742    For example, suppose we have:
24743 
24744      template <class T, class U> struct S {};
24745      template <class T> struct S<T*, int> {};
24746 
24747    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
24748    partial specialization and the ARGS will be {double*, int}.  The resulting
24749    vector will be {double}, indicating that `T' is bound to `double'.  */
24750 
24751 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)24752 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
24753 {
24754   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
24755   tree spec_args
24756     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
24757   int i, ntparms = TREE_VEC_LENGTH (tparms);
24758   tree deduced_args;
24759   tree innermost_deduced_args;
24760 
24761   innermost_deduced_args = make_tree_vec (ntparms);
24762   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24763     {
24764       deduced_args = copy_node (args);
24765       SET_TMPL_ARGS_LEVEL (deduced_args,
24766 			   TMPL_ARGS_DEPTH (deduced_args),
24767 			   innermost_deduced_args);
24768     }
24769   else
24770     deduced_args = innermost_deduced_args;
24771 
24772   bool tried_array_deduction = (cxx_dialect < cxx17);
24773  again:
24774   if (unify (tparms, deduced_args,
24775 	     INNERMOST_TEMPLATE_ARGS (spec_args),
24776 	     INNERMOST_TEMPLATE_ARGS (args),
24777 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
24778     return NULL_TREE;
24779 
24780   for (i =  0; i < ntparms; ++i)
24781     if (! TREE_VEC_ELT (innermost_deduced_args, i))
24782       {
24783 	if (!tried_array_deduction)
24784 	  {
24785 	    try_array_deduction (tparms, innermost_deduced_args,
24786 				 INNERMOST_TEMPLATE_ARGS (spec_args));
24787 	    tried_array_deduction = true;
24788 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
24789 	      goto again;
24790 	  }
24791 	return NULL_TREE;
24792       }
24793 
24794   if (!push_tinst_level (spec_tmpl, deduced_args))
24795     {
24796       excessive_deduction_depth = true;
24797       return NULL_TREE;
24798     }
24799 
24800   /* Verify that nondeduced template arguments agree with the type
24801      obtained from argument deduction.
24802 
24803      For example:
24804 
24805        struct A { typedef int X; };
24806        template <class T, class U> struct C {};
24807        template <class T> struct C<T, typename T::X> {};
24808 
24809      Then with the instantiation `C<A, int>', we can deduce that
24810      `T' is `A' but unify () does not check whether `typename T::X'
24811      is `int'.  */
24812   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
24813 
24814   if (spec_args != error_mark_node)
24815     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
24816 				       INNERMOST_TEMPLATE_ARGS (spec_args),
24817 				       tmpl, tf_none, false, false);
24818 
24819   pop_tinst_level ();
24820 
24821   if (spec_args == error_mark_node
24822       /* We only need to check the innermost arguments; the other
24823 	 arguments will always agree.  */
24824       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
24825 				     INNERMOST_TEMPLATE_ARGS (args)))
24826     return NULL_TREE;
24827 
24828   /* Now that we have bindings for all of the template arguments,
24829      ensure that the arguments deduced for the template template
24830      parameters have compatible template parameter lists.  See the use
24831      of template_template_parm_bindings_ok_p in fn_type_unification
24832      for more information.  */
24833   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
24834     return NULL_TREE;
24835 
24836   return deduced_args;
24837 }
24838 
24839 // Compare two function templates T1 and T2 by deducing bindings
24840 // from one against the other. If both deductions succeed, compare
24841 // constraints to see which is more constrained.
24842 static int
more_specialized_inst(tree t1,tree t2)24843 more_specialized_inst (tree t1, tree t2)
24844 {
24845   int fate = 0;
24846   int count = 0;
24847 
24848   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
24849     {
24850       --fate;
24851       ++count;
24852     }
24853 
24854   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
24855     {
24856       ++fate;
24857       ++count;
24858     }
24859 
24860   // If both deductions succeed, then one may be more constrained.
24861   if (count == 2 && fate == 0)
24862     fate = more_constrained (t1, t2);
24863 
24864   return fate;
24865 }
24866 
24867 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
24868    Return the TREE_LIST node with the most specialized template, if
24869    any.  If there is no most specialized template, the error_mark_node
24870    is returned.
24871 
24872    Note that this function does not look at, or modify, the
24873    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
24874    returned is one of the elements of INSTANTIATIONS, callers may
24875    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
24876    and retrieve it from the value returned.  */
24877 
24878 tree
most_specialized_instantiation(tree templates)24879 most_specialized_instantiation (tree templates)
24880 {
24881   tree fn, champ;
24882 
24883   ++processing_template_decl;
24884 
24885   champ = templates;
24886   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
24887     {
24888       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
24889       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
24890       if (fate == -1)
24891 	champ = fn;
24892       else if (!fate)
24893 	{
24894 	  /* Equally specialized, move to next function.  If there
24895 	     is no next function, nothing's most specialized.  */
24896 	  fn = TREE_CHAIN (fn);
24897 	  champ = fn;
24898 	  if (!fn)
24899 	    break;
24900 	}
24901     }
24902 
24903   if (champ)
24904     /* Now verify that champ is better than everything earlier in the
24905        instantiation list.  */
24906     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
24907       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
24908       {
24909         champ = NULL_TREE;
24910         break;
24911       }
24912     }
24913 
24914   processing_template_decl--;
24915 
24916   if (!champ)
24917     return error_mark_node;
24918 
24919   return champ;
24920 }
24921 
24922 /* If DECL is a specialization of some template, return the most
24923    general such template.  Otherwise, returns NULL_TREE.
24924 
24925    For example, given:
24926 
24927      template <class T> struct S { template <class U> void f(U); };
24928 
24929    if TMPL is `template <class U> void S<int>::f(U)' this will return
24930    the full template.  This function will not trace past partial
24931    specializations, however.  For example, given in addition:
24932 
24933      template <class T> struct S<T*> { template <class U> void f(U); };
24934 
24935    if TMPL is `template <class U> void S<int*>::f(U)' this will return
24936    `template <class T> template <class U> S<T*>::f(U)'.  */
24937 
24938 tree
most_general_template(tree decl)24939 most_general_template (tree decl)
24940 {
24941   if (TREE_CODE (decl) != TEMPLATE_DECL)
24942     {
24943       if (tree tinfo = get_template_info (decl))
24944 	decl = TI_TEMPLATE (tinfo);
24945       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
24946 	 template friend, or a FIELD_DECL for a capture pack.  */
24947       if (TREE_CODE (decl) != TEMPLATE_DECL)
24948 	return NULL_TREE;
24949     }
24950 
24951   /* Look for more and more general templates.  */
24952   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
24953     {
24954       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
24955 	 (See cp-tree.h for details.)  */
24956       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
24957 	break;
24958 
24959       if (CLASS_TYPE_P (TREE_TYPE (decl))
24960 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
24961 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
24962 	break;
24963 
24964       /* Stop if we run into an explicitly specialized class template.  */
24965       if (!DECL_NAMESPACE_SCOPE_P (decl)
24966 	  && DECL_CONTEXT (decl)
24967 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
24968 	break;
24969 
24970       decl = DECL_TI_TEMPLATE (decl);
24971     }
24972 
24973   return decl;
24974 }
24975 
24976 /* Return the most specialized of the template partial specializations
24977    which can produce TARGET, a specialization of some class or variable
24978    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
24979    a TEMPLATE_DECL node corresponding to the partial specialization, while
24980    the TREE_PURPOSE is the set of template arguments that must be
24981    substituted into the template pattern in order to generate TARGET.
24982 
24983    If the choice of partial specialization is ambiguous, a diagnostic
24984    is issued, and the error_mark_node is returned.  If there are no
24985    partial specializations matching TARGET, then NULL_TREE is
24986    returned, indicating that the primary template should be used.  */
24987 
24988 tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)24989 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
24990 {
24991   tree list = NULL_TREE;
24992   tree t;
24993   tree champ;
24994   int fate;
24995   bool ambiguous_p;
24996   tree outer_args = NULL_TREE;
24997   tree tmpl, args;
24998 
24999   if (TYPE_P (target))
25000     {
25001       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25002       tmpl = TI_TEMPLATE (tinfo);
25003       args = TI_ARGS (tinfo);
25004     }
25005   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25006     {
25007       tmpl = TREE_OPERAND (target, 0);
25008       args = TREE_OPERAND (target, 1);
25009     }
25010   else if (VAR_P (target))
25011     {
25012       tree tinfo = DECL_TEMPLATE_INFO (target);
25013       tmpl = TI_TEMPLATE (tinfo);
25014       args = TI_ARGS (tinfo);
25015     }
25016   else
25017     gcc_unreachable ();
25018 
25019   tree main_tmpl = most_general_template (tmpl);
25020 
25021   /* For determining which partial specialization to use, only the
25022      innermost args are interesting.  */
25023   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25024     {
25025       outer_args = strip_innermost_template_args (args, 1);
25026       args = INNERMOST_TEMPLATE_ARGS (args);
25027     }
25028 
25029   /* The caller hasn't called push_to_top_level yet, but we need
25030      get_partial_spec_bindings to be done in non-template context so that we'll
25031      fully resolve everything.  */
25032   processing_template_decl_sentinel ptds;
25033 
25034   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
25035     {
25036       const tree ospec_tmpl = TREE_VALUE (t);
25037 
25038       tree spec_tmpl;
25039       if (outer_args)
25040 	{
25041 	  /* Substitute in the template args from the enclosing class.  */
25042 	  ++processing_template_decl;
25043 	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25044 	  --processing_template_decl;
25045 	  if (spec_tmpl == error_mark_node)
25046 	    return error_mark_node;
25047 	}
25048       else
25049 	spec_tmpl = ospec_tmpl;
25050 
25051       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25052       if (spec_args)
25053 	{
25054 	  if (outer_args)
25055 	    spec_args = add_to_template_args (outer_args, spec_args);
25056 
25057           /* Keep the candidate only if the constraints are satisfied,
25058              or if we're not compiling with concepts.  */
25059           if (!flag_concepts
25060 	      || constraints_satisfied_p (ospec_tmpl, spec_args))
25061             {
25062 	      list = tree_cons (spec_args, ospec_tmpl, list);
25063               TREE_TYPE (list) = TREE_TYPE (t);
25064             }
25065 	}
25066     }
25067 
25068   if (! list)
25069     return NULL_TREE;
25070 
25071   ambiguous_p = false;
25072   t = list;
25073   champ = t;
25074   t = TREE_CHAIN (t);
25075   for (; t; t = TREE_CHAIN (t))
25076     {
25077       fate = more_specialized_partial_spec (tmpl, champ, t);
25078       if (fate == 1)
25079 	;
25080       else
25081 	{
25082 	  if (fate == 0)
25083 	    {
25084 	      t = TREE_CHAIN (t);
25085 	      if (! t)
25086 		{
25087 		  ambiguous_p = true;
25088 		  break;
25089 		}
25090 	    }
25091 	  champ = t;
25092 	}
25093     }
25094 
25095   if (!ambiguous_p)
25096     for (t = list; t && t != champ; t = TREE_CHAIN (t))
25097       {
25098 	fate = more_specialized_partial_spec (tmpl, champ, t);
25099 	if (fate != 1)
25100 	  {
25101 	    ambiguous_p = true;
25102 	    break;
25103 	  }
25104       }
25105 
25106   if (ambiguous_p)
25107     {
25108       const char *str;
25109       char *spaces = NULL;
25110       if (!(complain & tf_error))
25111 	return error_mark_node;
25112       if (TYPE_P (target))
25113 	error ("ambiguous template instantiation for %q#T", target);
25114       else
25115 	error ("ambiguous template instantiation for %q#D", target);
25116       str = ngettext ("candidate is:", "candidates are:", list_length (list));
25117       for (t = list; t; t = TREE_CHAIN (t))
25118         {
25119 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25120           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25121 		  "%s %#qS", spaces ? spaces : str, subst);
25122           spaces = spaces ? spaces : get_spaces (str);
25123         }
25124       free (spaces);
25125       return error_mark_node;
25126     }
25127 
25128   return champ;
25129 }
25130 
25131 /* Explicitly instantiate DECL.  */
25132 
25133 void
do_decl_instantiation(tree decl,tree storage)25134 do_decl_instantiation (tree decl, tree storage)
25135 {
25136   tree result = NULL_TREE;
25137   int extern_p = 0;
25138 
25139   if (!decl || decl == error_mark_node)
25140     /* An error occurred, for which grokdeclarator has already issued
25141        an appropriate message.  */
25142     return;
25143   else if (! DECL_LANG_SPECIFIC (decl))
25144     {
25145       error ("explicit instantiation of non-template %q#D", decl);
25146       return;
25147     }
25148   else if (DECL_DECLARED_CONCEPT_P (decl))
25149     {
25150       if (VAR_P (decl))
25151 	error ("explicit instantiation of variable concept %q#D", decl);
25152       else
25153 	error ("explicit instantiation of function concept %q#D", decl);
25154       return;
25155     }
25156 
25157   bool var_templ = (DECL_TEMPLATE_INFO (decl)
25158                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
25159 
25160   if (VAR_P (decl) && !var_templ)
25161     {
25162       /* There is an asymmetry here in the way VAR_DECLs and
25163 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
25164 	 the latter, the DECL we get back will be marked as a
25165 	 template instantiation, and the appropriate
25166 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
25167 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
25168 	 should handle VAR_DECLs as it currently handles
25169 	 FUNCTION_DECLs.  */
25170       if (!DECL_CLASS_SCOPE_P (decl))
25171 	{
25172 	  error ("%qD is not a static data member of a class template", decl);
25173 	  return;
25174 	}
25175       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
25176       if (!result || !VAR_P (result))
25177 	{
25178 	  error ("no matching template for %qD found", decl);
25179 	  return;
25180 	}
25181       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
25182 	{
25183 	  error ("type %qT for explicit instantiation %qD does not match "
25184 		 "declared type %qT", TREE_TYPE (result), decl,
25185 		 TREE_TYPE (decl));
25186 	  return;
25187 	}
25188     }
25189   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
25190     {
25191       error ("explicit instantiation of %q#D", decl);
25192       return;
25193     }
25194   else
25195     result = decl;
25196 
25197   /* Check for various error cases.  Note that if the explicit
25198      instantiation is valid the RESULT will currently be marked as an
25199      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
25200      until we get here.  */
25201 
25202   if (DECL_TEMPLATE_SPECIALIZATION (result))
25203     {
25204       /* DR 259 [temp.spec].
25205 
25206 	 Both an explicit instantiation and a declaration of an explicit
25207 	 specialization shall not appear in a program unless the explicit
25208 	 instantiation follows a declaration of the explicit specialization.
25209 
25210 	 For a given set of template parameters, if an explicit
25211 	 instantiation of a template appears after a declaration of an
25212 	 explicit specialization for that template, the explicit
25213 	 instantiation has no effect.  */
25214       return;
25215     }
25216   else if (DECL_EXPLICIT_INSTANTIATION (result))
25217     {
25218       /* [temp.spec]
25219 
25220 	 No program shall explicitly instantiate any template more
25221 	 than once.
25222 
25223 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
25224 	 the first instantiation was `extern' and the second is not,
25225 	 and EXTERN_P for the opposite case.  */
25226       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
25227 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
25228       /* If an "extern" explicit instantiation follows an ordinary
25229 	 explicit instantiation, the template is instantiated.  */
25230       if (extern_p)
25231 	return;
25232     }
25233   else if (!DECL_IMPLICIT_INSTANTIATION (result))
25234     {
25235       error ("no matching template for %qD found", result);
25236       return;
25237     }
25238   else if (!DECL_TEMPLATE_INFO (result))
25239     {
25240       permerror (input_location, "explicit instantiation of non-template %q#D", result);
25241       return;
25242     }
25243 
25244   if (storage == NULL_TREE)
25245     ;
25246   else if (storage == ridpointers[(int) RID_EXTERN])
25247     {
25248       if (cxx_dialect == cxx98)
25249 	pedwarn (input_location, OPT_Wpedantic,
25250 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
25251 		 "instantiations");
25252       extern_p = 1;
25253     }
25254   else
25255     error ("storage class %qD applied to template instantiation", storage);
25256 
25257   check_explicit_instantiation_namespace (result);
25258   mark_decl_instantiated (result, extern_p);
25259   if (! extern_p)
25260     instantiate_decl (result, /*defer_ok=*/true,
25261 		      /*expl_inst_class_mem_p=*/false);
25262 }
25263 
25264 static void
mark_class_instantiated(tree t,int extern_p)25265 mark_class_instantiated (tree t, int extern_p)
25266 {
25267   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25268   SET_CLASSTYPE_INTERFACE_KNOWN (t);
25269   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25270   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25271   if (! extern_p)
25272     {
25273       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
25274       rest_of_type_compilation (t, 1);
25275     }
25276 }
25277 
25278 /* Perform an explicit instantiation of template class T.  STORAGE, if
25279    non-null, is the RID for extern, inline or static.  COMPLAIN is
25280    nonzero if this is called from the parser, zero if called recursively,
25281    since the standard is unclear (as detailed below).  */
25282 
25283 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)25284 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
25285 {
25286   if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
25287     {
25288       if (tree ti = TYPE_TEMPLATE_INFO (t))
25289 	error ("explicit instantiation of non-class template %qD",
25290 	       TI_TEMPLATE (ti));
25291       else
25292 	error ("explicit instantiation of non-template type %qT", t);
25293       return;
25294     }
25295 
25296   complete_type (t);
25297 
25298   if (!COMPLETE_TYPE_P (t))
25299     {
25300       if (complain & tf_error)
25301 	error ("explicit instantiation of %q#T before definition of template",
25302 	       t);
25303       return;
25304     }
25305 
25306   /* At most one of these will be true.  */
25307   bool extern_p = false;
25308   bool nomem_p = false;
25309   bool static_p = false;
25310 
25311   if (storage != NULL_TREE)
25312     {
25313       if (storage == ridpointers[(int) RID_EXTERN])
25314 	{
25315 	  if (cxx_dialect == cxx98)
25316 	    pedwarn (input_location, OPT_Wpedantic,
25317 		     "ISO C++ 1998 forbids the use of %<extern%> on "
25318 		     "explicit instantiations");
25319 	}
25320       else
25321 	pedwarn (input_location, OPT_Wpedantic,
25322 		 "ISO C++ forbids the use of %qE"
25323 		 " on explicit instantiations", storage);
25324 
25325       if (storage == ridpointers[(int) RID_INLINE])
25326 	nomem_p = true;
25327       else if (storage == ridpointers[(int) RID_EXTERN])
25328 	extern_p = true;
25329       else if (storage == ridpointers[(int) RID_STATIC])
25330 	static_p = true;
25331       else
25332 	error ("storage class %qD applied to template instantiation",
25333 	       storage);
25334     }
25335 
25336   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
25337     /* DR 259 [temp.spec].
25338 
25339        Both an explicit instantiation and a declaration of an explicit
25340        specialization shall not appear in a program unless the
25341        explicit instantiation follows a declaration of the explicit
25342        specialization.
25343 
25344        For a given set of template parameters, if an explicit
25345        instantiation of a template appears after a declaration of an
25346        explicit specialization for that template, the explicit
25347        instantiation has no effect.  */
25348     return;
25349 
25350   if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
25351     {
25352       /* We've already instantiated the template.  */
25353 
25354       /* [temp.spec]
25355 
25356 	 No program shall explicitly instantiate any template more
25357 	 than once.
25358 
25359 	 If EXTERN_P then this is ok.  */
25360       if (!extern_p && (complain & tf_error))
25361 	permerror (input_location,
25362 		   "duplicate explicit instantiation of %q#T", t);
25363 
25364       return;
25365     }
25366 
25367   check_explicit_instantiation_namespace (TYPE_NAME (t));
25368   mark_class_instantiated (t, extern_p);
25369 
25370   if (nomem_p)
25371     return;
25372 
25373   /* In contrast to implicit instantiation, where only the
25374      declarations, and not the definitions, of members are
25375      instantiated, we have here:
25376 
25377 	 [temp.explicit]
25378 
25379 	 An explicit instantiation that names a class template
25380 	 specialization is also an explicit instantiation of the same
25381 	 kind (declaration or definition) of each of its members (not
25382 	 including members inherited from base classes and members
25383 	 that are templates) that has not been previously explicitly
25384 	 specialized in the translation unit containing the explicit
25385 	 instantiation, provided that the associated constraints, if
25386 	 any, of that member are satisfied by the template arguments
25387 	 of the explicit instantiation.  */
25388   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
25389     if ((VAR_P (fld)
25390 	 || (TREE_CODE (fld) == FUNCTION_DECL
25391 	     && !static_p
25392 	     && user_provided_p (fld)))
25393 	&& DECL_TEMPLATE_INSTANTIATION (fld)
25394 	&& constraints_satisfied_p (fld))
25395       {
25396 	mark_decl_instantiated (fld, extern_p);
25397 	if (! extern_p)
25398 	  instantiate_decl (fld, /*defer_ok=*/true,
25399 			    /*expl_inst_class_mem_p=*/true);
25400       }
25401     else if (DECL_IMPLICIT_TYPEDEF_P (fld))
25402       {
25403 	tree type = TREE_TYPE (fld);
25404 
25405 	if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
25406 	    && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
25407 	  do_type_instantiation (type, storage, 0);
25408       }
25409 }
25410 
25411 /* Given a function DECL, which is a specialization of TMPL, modify
25412    DECL to be a re-instantiation of TMPL with the same template
25413    arguments.  TMPL should be the template into which tsubst'ing
25414    should occur for DECL, not the most general template.
25415 
25416    One reason for doing this is a scenario like this:
25417 
25418      template <class T>
25419      void f(const T&, int i);
25420 
25421      void g() { f(3, 7); }
25422 
25423      template <class T>
25424      void f(const T& t, const int i) { }
25425 
25426    Note that when the template is first instantiated, with
25427    instantiate_template, the resulting DECL will have no name for the
25428    first parameter, and the wrong type for the second.  So, when we go
25429    to instantiate the DECL, we regenerate it.  */
25430 
25431 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)25432 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
25433 {
25434   /* The arguments used to instantiate DECL, from the most general
25435      template.  */
25436   tree code_pattern;
25437 
25438   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
25439 
25440   /* Make sure that we can see identifiers, and compute access
25441      correctly.  */
25442   push_access_scope (decl);
25443 
25444   if (TREE_CODE (decl) == FUNCTION_DECL)
25445     {
25446       tree specs;
25447       int args_depth;
25448       int parms_depth;
25449 
25450       args_depth = TMPL_ARGS_DEPTH (args);
25451       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
25452       if (args_depth > parms_depth)
25453 	args = get_innermost_template_args (args, parms_depth);
25454 
25455       /* Instantiate a dynamic exception-specification.  noexcept will be
25456 	 handled below.  */
25457       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
25458 	if (TREE_VALUE (raises))
25459 	  {
25460 	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
25461 						    args, tf_error, NULL_TREE,
25462 						    /*defer_ok*/false);
25463 	    if (specs && specs != error_mark_node)
25464 	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
25465 							  specs);
25466 	  }
25467 
25468       /* Merge parameter declarations.  */
25469       if (tree pattern_parm
25470 	  = skip_artificial_parms_for (code_pattern,
25471 				       DECL_ARGUMENTS (code_pattern)))
25472 	{
25473 	  tree *p = &DECL_ARGUMENTS (decl);
25474 	  for (int skip = num_artificial_parms_for (decl); skip; --skip)
25475 	    p = &DECL_CHAIN (*p);
25476 	  *p = tsubst_decl (pattern_parm, args, tf_error);
25477 	  for (tree t = *p; t; t = DECL_CHAIN (t))
25478 	    DECL_CONTEXT (t) = decl;
25479 	}
25480 
25481       /* Merge additional specifiers from the CODE_PATTERN.  */
25482       if (DECL_DECLARED_INLINE_P (code_pattern)
25483 	  && !DECL_DECLARED_INLINE_P (decl))
25484 	DECL_DECLARED_INLINE_P (decl) = 1;
25485 
25486       maybe_instantiate_noexcept (decl, tf_error);
25487     }
25488   else if (VAR_P (decl))
25489     {
25490       start_lambda_scope (decl);
25491       DECL_INITIAL (decl) =
25492 	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
25493 		     tf_error, DECL_TI_TEMPLATE (decl));
25494       finish_lambda_scope ();
25495       if (VAR_HAD_UNKNOWN_BOUND (decl))
25496 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
25497 				   tf_error, DECL_TI_TEMPLATE (decl));
25498     }
25499   else
25500     gcc_unreachable ();
25501 
25502   pop_access_scope (decl);
25503 }
25504 
25505 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
25506    substituted to get DECL.  */
25507 
25508 tree
template_for_substitution(tree decl)25509 template_for_substitution (tree decl)
25510 {
25511   tree tmpl = DECL_TI_TEMPLATE (decl);
25512 
25513   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
25514      for the instantiation.  This is not always the most general
25515      template.  Consider, for example:
25516 
25517 	template <class T>
25518 	struct S { template <class U> void f();
25519 		   template <> void f<int>(); };
25520 
25521      and an instantiation of S<double>::f<int>.  We want TD to be the
25522      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
25523   while (/* An instantiation cannot have a definition, so we need a
25524 	    more general template.  */
25525 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
25526 	   /* We must also deal with friend templates.  Given:
25527 
25528 		template <class T> struct S {
25529 		  template <class U> friend void f() {};
25530 		};
25531 
25532 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
25533 	      so far as the language is concerned, but that's still
25534 	      where we get the pattern for the instantiation from.  On
25535 	      other hand, if the definition comes outside the class, say:
25536 
25537 		template <class T> struct S {
25538 		  template <class U> friend void f();
25539 		};
25540 		template <class U> friend void f() {}
25541 
25542 	      we don't need to look any further.  That's what the check for
25543 	      DECL_INITIAL is for.  */
25544 	  || (TREE_CODE (decl) == FUNCTION_DECL
25545 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
25546 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
25547     {
25548       /* The present template, TD, should not be a definition.  If it
25549 	 were a definition, we should be using it!  Note that we
25550 	 cannot restructure the loop to just keep going until we find
25551 	 a template with a definition, since that might go too far if
25552 	 a specialization was declared, but not defined.  */
25553 
25554       /* Fetch the more general template.  */
25555       tmpl = DECL_TI_TEMPLATE (tmpl);
25556     }
25557 
25558   return tmpl;
25559 }
25560 
25561 /* Returns true if we need to instantiate this template instance even if we
25562    know we aren't going to emit it.  */
25563 
25564 bool
always_instantiate_p(tree decl)25565 always_instantiate_p (tree decl)
25566 {
25567   /* We always instantiate inline functions so that we can inline them.  An
25568      explicit instantiation declaration prohibits implicit instantiation of
25569      non-inline functions.  With high levels of optimization, we would
25570      normally inline non-inline functions -- but we're not allowed to do
25571      that for "extern template" functions.  Therefore, we check
25572      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
25573   return ((TREE_CODE (decl) == FUNCTION_DECL
25574 	   && (DECL_DECLARED_INLINE_P (decl)
25575 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
25576 	  /* And we need to instantiate static data members so that
25577 	     their initializers are available in integral constant
25578 	     expressions.  */
25579 	  || (VAR_P (decl)
25580 	      && decl_maybe_constant_var_p (decl)));
25581 }
25582 
25583 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
25584    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
25585    error, true otherwise.  */
25586 
25587 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)25588 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
25589 {
25590   if (fn == error_mark_node)
25591     return false;
25592 
25593   /* Don't instantiate a noexcept-specification from template context.  */
25594   if (processing_template_decl
25595       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
25596     return true;
25597 
25598   if (DECL_MAYBE_DELETED (fn))
25599     {
25600       if (fn == current_function_decl)
25601 	/* We're in start_preparsed_function, keep going.  */
25602 	return true;
25603 
25604       ++function_depth;
25605       synthesize_method (fn);
25606       --function_depth;
25607       return !DECL_MAYBE_DELETED (fn);
25608     }
25609 
25610   tree fntype = TREE_TYPE (fn);
25611   tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
25612 
25613   if (!spec || !TREE_PURPOSE (spec))
25614     return true;
25615 
25616   tree noex = TREE_PURPOSE (spec);
25617   if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
25618       && TREE_CODE (noex) != DEFERRED_PARSE)
25619     return true;
25620 
25621   tree orig_fn = NULL_TREE;
25622   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
25623      its FUNCTION_DECL for the rest of this function -- push_access_scope
25624      doesn't accept TEMPLATE_DECLs.  */
25625   if (DECL_FUNCTION_TEMPLATE_P (fn))
25626     {
25627       orig_fn = fn;
25628       fn = DECL_TEMPLATE_RESULT (fn);
25629     }
25630 
25631   if (DECL_CLONED_FUNCTION_P (fn))
25632     {
25633       tree prime = DECL_CLONED_FUNCTION (fn);
25634       if (!maybe_instantiate_noexcept (prime, complain))
25635 	return false;
25636       spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
25637     }
25638   else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
25639     {
25640       static hash_set<tree>* fns = new hash_set<tree>;
25641       bool added = false;
25642       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
25643 	{
25644 	  spec = get_defaulted_eh_spec (fn, complain);
25645 	  if (spec == error_mark_node)
25646 	    /* This might have failed because of an unparsed DMI, so
25647 	       let's try again later.  */
25648 	    return false;
25649 	}
25650       else if (!(added = !fns->add (fn)))
25651 	{
25652 	  /* If hash_set::add returns true, the element was already there.  */
25653 	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
25654 					    DECL_SOURCE_LOCATION (fn));
25655 	  error_at (loc,
25656 		    "exception specification of %qD depends on itself",
25657 		    fn);
25658 	  spec = noexcept_false_spec;
25659 	}
25660       else if (push_tinst_level (fn))
25661 	{
25662 	  push_to_top_level ();
25663 	  push_access_scope (fn);
25664 	  push_deferring_access_checks (dk_no_deferred);
25665 	  input_location = DECL_SOURCE_LOCATION (fn);
25666 
25667 	  if (!DECL_LOCAL_DECL_P (fn))
25668 	    {
25669 	      /* If needed, set current_class_ptr for the benefit of
25670 		 tsubst_copy/PARM_DECL.  The exception pattern will
25671 		 refer to the parm of the template, not the
25672 		 instantiation.  */
25673 	      tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
25674 	      if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
25675 		{
25676 		  tree this_parm = DECL_ARGUMENTS (tdecl);
25677 		  current_class_ptr = NULL_TREE;
25678 		  current_class_ref = cp_build_fold_indirect_ref (this_parm);
25679 		  current_class_ptr = this_parm;
25680 		}
25681 	    }
25682 
25683 	  /* If this function is represented by a TEMPLATE_DECL, then
25684 	     the deferred noexcept-specification might still contain
25685 	     dependent types, even after substitution.  And we need the
25686 	     dependency check functions to work in build_noexcept_spec.  */
25687 	  if (orig_fn)
25688 	    ++processing_template_decl;
25689 
25690 	  /* Do deferred instantiation of the noexcept-specifier.  */
25691 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
25692 					DEFERRED_NOEXCEPT_ARGS (noex),
25693 					tf_warning_or_error, fn,
25694 					/*function_p=*/false,
25695 					/*i_c_e_p=*/true);
25696 
25697 	  /* Build up the noexcept-specification.  */
25698 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
25699 
25700 	  if (orig_fn)
25701 	    --processing_template_decl;
25702 
25703 	  pop_deferring_access_checks ();
25704 	  pop_access_scope (fn);
25705 	  pop_tinst_level ();
25706 	  pop_from_top_level ();
25707 	}
25708       else
25709 	spec = noexcept_false_spec;
25710 
25711       if (added)
25712 	fns->remove (fn);
25713     }
25714 
25715   if (spec == error_mark_node)
25716     {
25717       /* This failed with a hard error, so let's go with false.  */
25718       gcc_assert (seen_error ());
25719       spec = noexcept_false_spec;
25720     }
25721 
25722   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
25723   if (orig_fn)
25724     TREE_TYPE (orig_fn) = TREE_TYPE (fn);
25725 
25726   return true;
25727 }
25728 
25729 /* We're starting to process the function INST, an instantiation of PATTERN;
25730    add their parameters to local_specializations.  */
25731 
25732 static void
register_parameter_specializations(tree pattern,tree inst)25733 register_parameter_specializations (tree pattern, tree inst)
25734 {
25735   tree tmpl_parm = DECL_ARGUMENTS (pattern);
25736   tree spec_parm = DECL_ARGUMENTS (inst);
25737   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
25738     {
25739       register_local_specialization (spec_parm, tmpl_parm);
25740       spec_parm = skip_artificial_parms_for (inst, spec_parm);
25741       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
25742     }
25743   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
25744     {
25745       if (!DECL_PACK_P (tmpl_parm))
25746 	{
25747 	  register_local_specialization (spec_parm, tmpl_parm);
25748 	  spec_parm = DECL_CHAIN (spec_parm);
25749 	}
25750       else
25751 	{
25752 	  /* Register the (value) argument pack as a specialization of
25753 	     TMPL_PARM, then move on.  */
25754 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
25755 	  register_local_specialization (argpack, tmpl_parm);
25756 	}
25757     }
25758   gcc_assert (!spec_parm);
25759 }
25760 
25761 /* Instantiate the body of D using PATTERN with ARGS.  We have
25762    already determined PATTERN is the correct template to use.
25763    NESTED_P is true if this is a nested function, in which case
25764    PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL.  */
25765 
25766 static void
instantiate_body(tree pattern,tree args,tree d,bool nested_p)25767 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
25768 {
25769   tree td = NULL_TREE;
25770   tree code_pattern = pattern;
25771 
25772   if (!nested_p)
25773     {
25774       td = pattern;
25775       code_pattern = DECL_TEMPLATE_RESULT (td);
25776     }
25777   else
25778     /* Only OMP reductions are nested.  */
25779     gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
25780 
25781   vec<tree> omp_privatization_save;
25782   if (current_function_decl)
25783     save_omp_privatization_clauses (omp_privatization_save);
25784 
25785   bool push_to_top
25786     = !(current_function_decl
25787 	&& !LAMBDA_FUNCTION_P (d)
25788 	&& decl_function_context (d) == current_function_decl);
25789 
25790   if (push_to_top)
25791     push_to_top_level ();
25792   else
25793     {
25794       gcc_assert (!processing_template_decl);
25795       push_function_context ();
25796       cp_unevaluated_operand = 0;
25797       c_inhibit_evaluation_warnings = 0;
25798     }
25799 
25800   if (VAR_P (d))
25801     {
25802       /* The variable might be a lambda's extra scope, and that
25803 	 lambda's visibility depends on D's.  */
25804       maybe_commonize_var (d);
25805       determine_visibility (d);
25806     }
25807 
25808   /* Mark D as instantiated so that recursive calls to
25809      instantiate_decl do not try to instantiate it again.  */
25810   DECL_TEMPLATE_INSTANTIATED (d) = 1;
25811 
25812   if (td)
25813     /* Regenerate the declaration in case the template has been modified
25814        by a subsequent redeclaration.  */
25815     regenerate_decl_from_template (d, td, args);
25816 
25817   /* We already set the file and line above.  Reset them now in case
25818      they changed as a result of calling regenerate_decl_from_template.  */
25819   input_location = DECL_SOURCE_LOCATION (d);
25820 
25821   if (VAR_P (d))
25822     {
25823       /* Clear out DECL_RTL; whatever was there before may not be right
25824 	 since we've reset the type of the declaration.  */
25825       SET_DECL_RTL (d, NULL);
25826       DECL_IN_AGGR_P (d) = 0;
25827 
25828       /* The initializer is placed in DECL_INITIAL by
25829 	 regenerate_decl_from_template so we don't need to
25830 	 push/pop_access_scope again here.  Pull it out so that
25831 	 cp_finish_decl can process it.  */
25832       bool const_init = false;
25833       tree init = DECL_INITIAL (d);
25834       DECL_INITIAL (d) = NULL_TREE;
25835       DECL_INITIALIZED_P (d) = 0;
25836 
25837       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
25838 	 initializer.  That function will defer actual emission until
25839 	 we have a chance to determine linkage.  */
25840       DECL_EXTERNAL (d) = 0;
25841 
25842       /* Enter the scope of D so that access-checking works correctly.  */
25843       bool enter_context = DECL_CLASS_SCOPE_P (d);
25844       if (enter_context)
25845         push_nested_class (DECL_CONTEXT (d));
25846 
25847       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25848       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
25849 
25850       if (enter_context)
25851         pop_nested_class ();
25852     }
25853   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
25854     synthesize_method (d);
25855   else if (TREE_CODE (d) == FUNCTION_DECL)
25856     {
25857       /* Set up the list of local specializations.  */
25858       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
25859       tree block = NULL_TREE;
25860 
25861       /* Set up context.  */
25862       if (nested_p)
25863 	block = push_stmt_list ();
25864       else
25865 	{
25866 	  start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
25867 
25868 	  perform_instantiation_time_access_checks (code_pattern, args);
25869 	}
25870 
25871       /* Create substitution entries for the parameters.  */
25872       register_parameter_specializations (code_pattern, d);
25873 
25874       /* Substitute into the body of the function.  */
25875       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25876 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
25877 			tf_warning_or_error, d);
25878       else
25879 	{
25880 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
25881 		       tf_warning_or_error, DECL_TI_TEMPLATE (d),
25882 		       /*integral_constant_expression_p=*/false);
25883 
25884 	  /* Set the current input_location to the end of the function
25885 	     so that finish_function knows where we are.  */
25886 	  input_location
25887 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
25888 
25889 	  /* Remember if we saw an infinite loop in the template.  */
25890 	  current_function_infinite_loop
25891 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
25892 	}
25893 
25894       /* Finish the function.  */
25895       if (nested_p)
25896 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
25897       else
25898 	{
25899 	  d = finish_function (/*inline_p=*/false);
25900 	  expand_or_defer_fn (d);
25901 	}
25902 
25903       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25904 	cp_check_omp_declare_reduction (d);
25905     }
25906 
25907   /* We're not deferring instantiation any more.  */
25908   if (!nested_p)
25909     TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
25910 
25911   if (push_to_top)
25912     pop_from_top_level ();
25913   else
25914     pop_function_context ();
25915 
25916   if (current_function_decl)
25917     restore_omp_privatization_clauses (omp_privatization_save);
25918 }
25919 
25920 /* Produce the definition of D, a _DECL generated from a template.  If
25921    DEFER_OK is true, then we don't have to actually do the
25922    instantiation now; we just have to do it sometime.  Normally it is
25923    an error if this is an explicit instantiation but D is undefined.
25924    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
25925    instantiated class template.  */
25926 
25927 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)25928 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
25929 {
25930   tree tmpl = DECL_TI_TEMPLATE (d);
25931   tree gen_args;
25932   tree args;
25933   tree td;
25934   tree code_pattern;
25935   tree spec;
25936   tree gen_tmpl;
25937   bool pattern_defined;
25938   location_t saved_loc = input_location;
25939   int saved_unevaluated_operand = cp_unevaluated_operand;
25940   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
25941   bool external_p;
25942   bool deleted_p;
25943 
25944   /* This function should only be used to instantiate templates for
25945      functions and static member variables.  */
25946   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
25947 
25948   /* A concept is never instantiated. */
25949   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
25950 
25951   gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
25952 
25953   if (modules_p ())
25954     /* We may have a pending instantiation of D itself.  */
25955     lazy_load_pendings (d);
25956 
25957   /* Variables are never deferred; if instantiation is required, they
25958      are instantiated right away.  That allows for better code in the
25959      case that an expression refers to the value of the variable --
25960      if the variable has a constant value the referring expression can
25961      take advantage of that fact.  */
25962   if (VAR_P (d))
25963     defer_ok = false;
25964 
25965   /* Don't instantiate cloned functions.  Instead, instantiate the
25966      functions they cloned.  */
25967   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
25968     d = DECL_CLONED_FUNCTION (d);
25969 
25970   if (DECL_TEMPLATE_INSTANTIATED (d)
25971       || TREE_TYPE (d) == error_mark_node
25972       || (TREE_CODE (d) == FUNCTION_DECL
25973 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
25974       || DECL_TEMPLATE_SPECIALIZATION (d))
25975     /* D has already been instantiated or explicitly specialized, so
25976        there's nothing for us to do here.
25977 
25978        It might seem reasonable to check whether or not D is an explicit
25979        instantiation, and, if so, stop here.  But when an explicit
25980        instantiation is deferred until the end of the compilation,
25981        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
25982        the instantiation.  */
25983     return d;
25984 
25985   /* Check to see whether we know that this template will be
25986      instantiated in some other file, as with "extern template"
25987      extension.  */
25988   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
25989 
25990   /* In general, we do not instantiate such templates.  */
25991   if (external_p && !always_instantiate_p (d))
25992     return d;
25993 
25994   gen_tmpl = most_general_template (tmpl);
25995   gen_args = DECL_TI_ARGS (d);
25996 
25997   /* We should already have the extra args.  */
25998   gcc_checking_assert (tmpl == gen_tmpl
25999 		       || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26000 			   == TMPL_ARGS_DEPTH (gen_args)));
26001   /* And what's in the hash table should match D.  */
26002   gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26003 		       == d
26004 		       || spec == NULL_TREE);
26005 
26006   /* This needs to happen before any tsubsting.  */
26007   if (! push_tinst_level (d))
26008     return d;
26009 
26010   timevar_push (TV_TEMPLATE_INST);
26011 
26012   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26013      for the instantiation.  */
26014   td = template_for_substitution (d);
26015   args = gen_args;
26016 
26017   if (VAR_P (d))
26018     {
26019       /* Look up an explicit specialization, if any.  */
26020       tree tid = lookup_template_variable (gen_tmpl, gen_args);
26021       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
26022       if (elt && elt != error_mark_node)
26023 	{
26024 	  td = TREE_VALUE (elt);
26025 	  args = TREE_PURPOSE (elt);
26026 	}
26027     }
26028 
26029   code_pattern = DECL_TEMPLATE_RESULT (td);
26030 
26031   /* We should never be trying to instantiate a member of a class
26032      template or partial specialization.  */
26033   gcc_assert (d != code_pattern);
26034 
26035   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26036       || DECL_TEMPLATE_SPECIALIZATION (td))
26037     /* In the case of a friend template whose definition is provided
26038        outside the class, we may have too many arguments.  Drop the
26039        ones we don't need.  The same is true for specializations.  */
26040     args = get_innermost_template_args
26041       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26042 
26043   if (TREE_CODE (d) == FUNCTION_DECL)
26044     {
26045       deleted_p = DECL_DELETED_FN (code_pattern);
26046       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26047 			  && DECL_INITIAL (code_pattern) != error_mark_node)
26048 			 || DECL_DEFAULTED_FN (code_pattern)
26049 			 || deleted_p);
26050     }
26051   else
26052     {
26053       deleted_p = false;
26054       if (DECL_CLASS_SCOPE_P (code_pattern))
26055 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26056       else
26057 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
26058     }
26059 
26060   /* We may be in the middle of deferred access check.  Disable it now.  */
26061   push_deferring_access_checks (dk_no_deferred);
26062 
26063   /* Unless an explicit instantiation directive has already determined
26064      the linkage of D, remember that a definition is available for
26065      this entity.  */
26066   if (pattern_defined
26067       && !DECL_INTERFACE_KNOWN (d)
26068       && !DECL_NOT_REALLY_EXTERN (d))
26069     mark_definable (d);
26070 
26071   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26072   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26073   input_location = DECL_SOURCE_LOCATION (d);
26074 
26075   /* If D is a member of an explicitly instantiated class template,
26076      and no definition is available, treat it like an implicit
26077      instantiation.  */
26078   if (!pattern_defined && expl_inst_class_mem_p
26079       && DECL_EXPLICIT_INSTANTIATION (d))
26080     {
26081       /* Leave linkage flags alone on instantiations with anonymous
26082 	 visibility.  */
26083       if (TREE_PUBLIC (d))
26084 	{
26085 	  DECL_NOT_REALLY_EXTERN (d) = 0;
26086 	  DECL_INTERFACE_KNOWN (d) = 0;
26087 	}
26088       SET_DECL_IMPLICIT_INSTANTIATION (d);
26089     }
26090 
26091   /* Defer all other templates, unless we have been explicitly
26092      forbidden from doing so.  */
26093   if (/* If there is no definition, we cannot instantiate the
26094 	 template.  */
26095       ! pattern_defined
26096       /* If it's OK to postpone instantiation, do so.  */
26097       || defer_ok
26098       /* If this is a static data member that will be defined
26099 	 elsewhere, we don't want to instantiate the entire data
26100 	 member, but we do want to instantiate the initializer so that
26101 	 we can substitute that elsewhere.  */
26102       || (external_p && VAR_P (d))
26103       /* Handle here a deleted function too, avoid generating
26104 	 its body (c++/61080).  */
26105       || deleted_p)
26106     {
26107       /* The definition of the static data member is now required so
26108 	 we must substitute the initializer.  */
26109       if (VAR_P (d)
26110 	  && !DECL_INITIAL (d)
26111 	  && DECL_INITIAL (code_pattern))
26112 	{
26113 	  tree ns;
26114 	  tree init;
26115 	  bool const_init = false;
26116 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
26117 
26118 	  ns = decl_namespace_context (d);
26119 	  push_nested_namespace (ns);
26120 	  if (enter_context)
26121 	    push_nested_class (DECL_CONTEXT (d));
26122 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
26123 			      args,
26124 			      tf_warning_or_error, NULL_TREE,
26125 			      /*integral_constant_expression_p=*/false);
26126 	  /* If instantiating the initializer involved instantiating this
26127 	     again, don't call cp_finish_decl twice.  */
26128 	  if (!DECL_INITIAL (d))
26129 	    {
26130 	      /* Make sure the initializer is still constant, in case of
26131 		 circular dependency (template/instantiate6.C). */
26132 	      const_init
26133 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26134 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26135 			      /*asmspec_tree=*/NULL_TREE,
26136 			      LOOKUP_ONLYCONVERTING);
26137 	    }
26138 	  if (enter_context)
26139 	    pop_nested_class ();
26140 	  pop_nested_namespace (ns);
26141 	}
26142 
26143       /* We restore the source position here because it's used by
26144 	 add_pending_template.  */
26145       input_location = saved_loc;
26146 
26147       if (at_eof && !pattern_defined
26148 	  && DECL_EXPLICIT_INSTANTIATION (d)
26149 	  && DECL_NOT_REALLY_EXTERN (d))
26150 	/* [temp.explicit]
26151 
26152 	   The definition of a non-exported function template, a
26153 	   non-exported member function template, or a non-exported
26154 	   member function or static data member of a class template
26155 	   shall be present in every translation unit in which it is
26156 	   explicitly instantiated.  */
26157 	permerror (input_location,  "explicit instantiation of %qD "
26158 		   "but no definition available", d);
26159 
26160       /* If we're in unevaluated context, we just wanted to get the
26161 	 constant value; this isn't an odr use, so don't queue
26162 	 a full instantiation.  */
26163       if (!cp_unevaluated_operand
26164 	  /* ??? Historically, we have instantiated inline functions, even
26165 	     when marked as "extern template".  */
26166 	  && !(external_p && VAR_P (d)))
26167 	add_pending_template (d);
26168     }
26169   else
26170     {
26171       set_instantiating_module (d);
26172       if (variable_template_p (gen_tmpl))
26173 	note_variable_template_instantiation (d);
26174       instantiate_body (td, args, d, false);
26175     }
26176 
26177   pop_deferring_access_checks ();
26178   timevar_pop (TV_TEMPLATE_INST);
26179   pop_tinst_level ();
26180   input_location = saved_loc;
26181   cp_unevaluated_operand = saved_unevaluated_operand;
26182   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26183 
26184   return d;
26185 }
26186 
26187 /* Run through the list of templates that we wish we could
26188    instantiate, and instantiate any we can.  RETRIES is the
26189    number of times we retry pending template instantiation.  */
26190 
26191 void
instantiate_pending_templates(int retries)26192 instantiate_pending_templates (int retries)
26193 {
26194   int reconsider;
26195   location_t saved_loc = input_location;
26196 
26197   /* Instantiating templates may trigger vtable generation.  This in turn
26198      may require further template instantiations.  We place a limit here
26199      to avoid infinite loop.  */
26200   if (pending_templates && retries >= max_tinst_depth)
26201     {
26202       tree decl = pending_templates->tinst->maybe_get_node ();
26203 
26204       fatal_error (input_location,
26205 		   "template instantiation depth exceeds maximum of %d"
26206 		   " instantiating %q+D, possibly from virtual table generation"
26207 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
26208 		   max_tinst_depth, decl);
26209       if (TREE_CODE (decl) == FUNCTION_DECL)
26210 	/* Pretend that we defined it.  */
26211 	DECL_INITIAL (decl) = error_mark_node;
26212       return;
26213     }
26214 
26215   do
26216     {
26217       struct pending_template **t = &pending_templates;
26218       struct pending_template *last = NULL;
26219       reconsider = 0;
26220       while (*t)
26221 	{
26222 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
26223 	  bool complete = false;
26224 
26225 	  if (TYPE_P (instantiation))
26226 	    {
26227 	      if (!COMPLETE_TYPE_P (instantiation))
26228 		{
26229 		  instantiate_class_template (instantiation);
26230 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26231 		    for (tree fld = TYPE_FIELDS (instantiation);
26232 			 fld; fld = TREE_CHAIN (fld))
26233 		      if ((VAR_P (fld)
26234 			   || (TREE_CODE (fld) == FUNCTION_DECL
26235 			       && !DECL_ARTIFICIAL (fld)))
26236 			  && DECL_TEMPLATE_INSTANTIATION (fld))
26237 			instantiate_decl (fld,
26238 					  /*defer_ok=*/false,
26239 					  /*expl_inst_class_mem_p=*/false);
26240 
26241 		  if (COMPLETE_TYPE_P (instantiation))
26242 		    reconsider = 1;
26243 		}
26244 
26245 	      complete = COMPLETE_TYPE_P (instantiation);
26246 	    }
26247 	  else
26248 	    {
26249 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26250 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26251 		{
26252 		  instantiation
26253 		    = instantiate_decl (instantiation,
26254 					/*defer_ok=*/false,
26255 					/*expl_inst_class_mem_p=*/false);
26256 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26257 		    reconsider = 1;
26258 		}
26259 
26260 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26261 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
26262 	    }
26263 
26264 	  if (complete)
26265 	    {
26266 	      /* If INSTANTIATION has been instantiated, then we don't
26267 		 need to consider it again in the future.  */
26268 	      struct pending_template *drop = *t;
26269 	      *t = (*t)->next;
26270 	      set_refcount_ptr (drop->tinst);
26271 	      pending_template_freelist ().free (drop);
26272 	    }
26273 	  else
26274 	    {
26275 	      last = *t;
26276 	      t = &(*t)->next;
26277 	    }
26278 	  tinst_depth = 0;
26279 	  set_refcount_ptr (current_tinst_level);
26280 	}
26281       last_pending_template = last;
26282     }
26283   while (reconsider);
26284 
26285   input_location = saved_loc;
26286 }
26287 
26288 /* Substitute ARGVEC into T, which is a list of initializers for
26289    either base class or a non-static data member.  The TREE_PURPOSEs
26290    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
26291    instantiate_decl.  */
26292 
26293 static tree
tsubst_initializer_list(tree t,tree argvec)26294 tsubst_initializer_list (tree t, tree argvec)
26295 {
26296   tree inits = NULL_TREE;
26297   tree target_ctor = error_mark_node;
26298 
26299   for (; t; t = TREE_CHAIN (t))
26300     {
26301       tree decl;
26302       tree init;
26303       tree expanded_bases = NULL_TREE;
26304       tree expanded_arguments = NULL_TREE;
26305       int i, len = 1;
26306 
26307       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
26308         {
26309           tree expr;
26310           tree arg;
26311 
26312           /* Expand the base class expansion type into separate base
26313              classes.  */
26314           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
26315                                                  tf_warning_or_error,
26316                                                  NULL_TREE);
26317           if (expanded_bases == error_mark_node)
26318             continue;
26319 
26320           /* We'll be building separate TREE_LISTs of arguments for
26321              each base.  */
26322           len = TREE_VEC_LENGTH (expanded_bases);
26323           expanded_arguments = make_tree_vec (len);
26324           for (i = 0; i < len; i++)
26325             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
26326 
26327           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
26328              expand each argument in the TREE_VALUE of t.  */
26329           expr = make_node (EXPR_PACK_EXPANSION);
26330 	  PACK_EXPANSION_LOCAL_P (expr) = true;
26331           PACK_EXPANSION_PARAMETER_PACKS (expr) =
26332             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
26333 
26334 	  if (TREE_VALUE (t) == void_type_node)
26335 	    /* VOID_TYPE_NODE is used to indicate
26336 	       value-initialization.  */
26337 	    {
26338 	      for (i = 0; i < len; i++)
26339 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
26340 	    }
26341 	  else
26342 	    {
26343 	      /* Substitute parameter packs into each argument in the
26344 		 TREE_LIST.  */
26345 	      in_base_initializer = 1;
26346 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
26347 		{
26348 		  tree expanded_exprs;
26349 
26350 		  /* Expand the argument.  */
26351 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
26352 		  expanded_exprs
26353 		    = tsubst_pack_expansion (expr, argvec,
26354 					     tf_warning_or_error,
26355 					     NULL_TREE);
26356 		  if (expanded_exprs == error_mark_node)
26357 		    continue;
26358 
26359 		  /* Prepend each of the expanded expressions to the
26360 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
26361 		  for (i = 0; i < len; i++)
26362 		    {
26363 		      TREE_VEC_ELT (expanded_arguments, i) =
26364 			tree_cons (NULL_TREE,
26365 				   TREE_VEC_ELT (expanded_exprs, i),
26366 				   TREE_VEC_ELT (expanded_arguments, i));
26367 		    }
26368 		}
26369 	      in_base_initializer = 0;
26370 
26371 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
26372 		 since we built them backwards.  */
26373 	      for (i = 0; i < len; i++)
26374 		{
26375 		  TREE_VEC_ELT (expanded_arguments, i) =
26376 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
26377 		}
26378 	    }
26379         }
26380 
26381       for (i = 0; i < len; ++i)
26382         {
26383           if (expanded_bases)
26384             {
26385               decl = TREE_VEC_ELT (expanded_bases, i);
26386               decl = expand_member_init (decl);
26387               init = TREE_VEC_ELT (expanded_arguments, i);
26388             }
26389           else
26390             {
26391 	      tree tmp;
26392               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
26393                                   tf_warning_or_error, NULL_TREE);
26394 
26395               decl = expand_member_init (decl);
26396               if (decl && !DECL_P (decl))
26397                 in_base_initializer = 1;
26398 
26399 	      init = TREE_VALUE (t);
26400 	      tmp = init;
26401 	      if (init != void_type_node)
26402 		init = tsubst_expr (init, argvec,
26403 				    tf_warning_or_error, NULL_TREE,
26404 				    /*integral_constant_expression_p=*/false);
26405 	      if (init == NULL_TREE && tmp != NULL_TREE)
26406 		/* If we had an initializer but it instantiated to nothing,
26407 		   value-initialize the object.  This will only occur when
26408 		   the initializer was a pack expansion where the parameter
26409 		   packs used in that expansion were of length zero.  */
26410 		init = void_type_node;
26411               in_base_initializer = 0;
26412             }
26413 
26414 	  if (target_ctor != error_mark_node
26415 	      && init != error_mark_node)
26416 	    {
26417 	      error ("mem-initializer for %qD follows constructor delegation",
26418 		     decl);
26419 	      return inits;
26420 	    }
26421 	  /* Look for a target constructor. */
26422 	  if (init != error_mark_node
26423 	      && decl && CLASS_TYPE_P (decl)
26424 	      && same_type_p (decl, current_class_type))
26425 	    {
26426 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
26427 	      if (inits)
26428 		{
26429 		  error ("constructor delegation follows mem-initializer for %qD",
26430 			 TREE_PURPOSE (inits));
26431 		  continue;
26432 		}
26433 	      target_ctor = init;
26434 	    }
26435 
26436           if (decl)
26437             {
26438               init = build_tree_list (decl, init);
26439 	      /* Carry over the dummy TREE_TYPE node containing the source
26440 		 location.  */
26441 	      TREE_TYPE (init) = TREE_TYPE (t);
26442               TREE_CHAIN (init) = inits;
26443               inits = init;
26444             }
26445         }
26446     }
26447   return inits;
26448 }
26449 
26450 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
26451    is the instantiation (which should have been created with
26452    start_enum) and ARGS are the template arguments to use.  */
26453 
26454 static void
tsubst_enum(tree tag,tree newtag,tree args)26455 tsubst_enum (tree tag, tree newtag, tree args)
26456 {
26457   tree e;
26458 
26459   if (SCOPED_ENUM_P (newtag))
26460     begin_scope (sk_scoped_enum, newtag);
26461 
26462   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
26463     {
26464       tree value;
26465       tree decl;
26466 
26467       decl = TREE_VALUE (e);
26468       /* Note that in a template enum, the TREE_VALUE is the
26469 	 CONST_DECL, not the corresponding INTEGER_CST.  */
26470       value = tsubst_expr (DECL_INITIAL (decl),
26471 			   args, tf_warning_or_error, NULL_TREE,
26472 			   /*integral_constant_expression_p=*/true);
26473 
26474       /* Give this enumeration constant the correct access.  */
26475       set_current_access_from_decl (decl);
26476 
26477       /* Actually build the enumerator itself.  Here we're assuming that
26478 	 enumerators can't have dependent attributes.  */
26479       build_enumerator (DECL_NAME (decl), value, newtag,
26480 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
26481     }
26482 
26483   if (SCOPED_ENUM_P (newtag))
26484     finish_scope ();
26485 
26486   finish_enum_value_list (newtag);
26487   finish_enum (newtag);
26488 
26489   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
26490     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
26491 }
26492 
26493 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
26494    its type -- but without substituting the innermost set of template
26495    arguments.  So, innermost set of template parameters will appear in
26496    the type.  */
26497 
26498 tree
get_mostly_instantiated_function_type(tree decl)26499 get_mostly_instantiated_function_type (tree decl)
26500 {
26501   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
26502   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
26503 }
26504 
26505 /* Return truthvalue if we're processing a template different from
26506    the last one involved in diagnostics.  */
26507 bool
problematic_instantiation_changed(void)26508 problematic_instantiation_changed (void)
26509 {
26510   return current_tinst_level != last_error_tinst_level;
26511 }
26512 
26513 /* Remember current template involved in diagnostics.  */
26514 void
record_last_problematic_instantiation(void)26515 record_last_problematic_instantiation (void)
26516 {
26517   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
26518 }
26519 
26520 struct tinst_level *
current_instantiation(void)26521 current_instantiation (void)
26522 {
26523   return current_tinst_level;
26524 }
26525 
26526 /* Return TRUE if current_function_decl is being instantiated, false
26527    otherwise.  */
26528 
26529 bool
instantiating_current_function_p(void)26530 instantiating_current_function_p (void)
26531 {
26532   return (current_instantiation ()
26533 	  && (current_instantiation ()->maybe_get_node ()
26534 	      == current_function_decl));
26535 }
26536 
26537 /* [temp.param] Check that template non-type parm TYPE is of an allowable
26538    type.  Return false for ok, true for disallowed.  Issue error and
26539    inform messages under control of COMPLAIN.  */
26540 
26541 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)26542 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
26543 {
26544   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
26545     return false;
26546   else if (TYPE_PTR_P (type))
26547     return false;
26548   else if (TYPE_REF_P (type)
26549 	   && !TYPE_REF_IS_RVALUE (type))
26550     return false;
26551   else if (TYPE_PTRMEM_P (type))
26552     return false;
26553   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
26554     {
26555       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
26556 	{
26557 	  if (complain & tf_error)
26558 	    error ("non-type template parameters of deduced class type only "
26559 		   "available with %<-std=c++20%> or %<-std=gnu++20%>");
26560 	  return true;
26561 	}
26562       return false;
26563     }
26564   else if (TREE_CODE (type) == TYPENAME_TYPE)
26565     return false;
26566   else if (TREE_CODE (type) == DECLTYPE_TYPE)
26567     return false;
26568   else if (TREE_CODE (type) == NULLPTR_TYPE)
26569     return false;
26570   /* A bound template template parm could later be instantiated to have a valid
26571      nontype parm type via an alias template.  */
26572   else if (cxx_dialect >= cxx11
26573 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26574     return false;
26575   else if (TREE_CODE (type) == COMPLEX_TYPE)
26576     /* Fall through.  */;
26577   else if (VOID_TYPE_P (type))
26578     /* Fall through.  */;
26579   else if (cxx_dialect >= cxx20)
26580     {
26581       if (dependent_type_p (type))
26582 	return false;
26583       if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
26584 	return true;
26585       if (structural_type_p (type))
26586 	return false;
26587       if (complain & tf_error)
26588 	{
26589 	  auto_diagnostic_group d;
26590 	  error ("%qT is not a valid type for a template non-type "
26591 		 "parameter because it is not structural", type);
26592 	  structural_type_p (type, true);
26593 	}
26594       return true;
26595     }
26596   else if (CLASS_TYPE_P (type))
26597     {
26598       if (complain & tf_error)
26599 	error ("non-type template parameters of class type only available "
26600 	       "with %<-std=c++20%> or %<-std=gnu++20%>");
26601       return true;
26602     }
26603 
26604   if (complain & tf_error)
26605     {
26606       if (type == error_mark_node)
26607 	inform (input_location, "invalid template non-type parameter");
26608       else
26609 	error ("%q#T is not a valid type for a template non-type parameter",
26610 	       type);
26611     }
26612   return true;
26613 }
26614 
26615 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
26616    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
26617 
26618 static bool
dependent_type_p_r(tree type)26619 dependent_type_p_r (tree type)
26620 {
26621   tree scope;
26622 
26623   /* [temp.dep.type]
26624 
26625      A type is dependent if it is:
26626 
26627      -- a template parameter. Template template parameters are types
26628 	for us (since TYPE_P holds true for them) so we handle
26629 	them here.  */
26630   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26631       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
26632     return true;
26633   /* -- a qualified-id with a nested-name-specifier which contains a
26634 	class-name that names a dependent type or whose unqualified-id
26635 	names a dependent type.  */
26636   if (TREE_CODE (type) == TYPENAME_TYPE)
26637     return true;
26638 
26639   /* An alias template specialization can be dependent even if the
26640      resulting type is not.  */
26641   if (dependent_alias_template_spec_p (type, nt_transparent))
26642     return true;
26643 
26644   /* -- a cv-qualified type where the cv-unqualified type is
26645 	dependent.
26646      No code is necessary for this bullet; the code below handles
26647      cv-qualified types, and we don't want to strip aliases with
26648      TYPE_MAIN_VARIANT because of DR 1558.  */
26649   /* -- a compound type constructed from any dependent type.  */
26650   if (TYPE_PTRMEM_P (type))
26651     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
26652 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
26653 					   (type)));
26654   else if (INDIRECT_TYPE_P (type))
26655     return dependent_type_p (TREE_TYPE (type));
26656   else if (FUNC_OR_METHOD_TYPE_P (type))
26657     {
26658       tree arg_type;
26659 
26660       if (dependent_type_p (TREE_TYPE (type)))
26661 	return true;
26662       for (arg_type = TYPE_ARG_TYPES (type);
26663 	   arg_type;
26664 	   arg_type = TREE_CHAIN (arg_type))
26665 	if (dependent_type_p (TREE_VALUE (arg_type)))
26666 	  return true;
26667       if (cxx_dialect >= cxx17)
26668 	/* A value-dependent noexcept-specifier makes the type dependent.  */
26669 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
26670 	  if (tree noex = TREE_PURPOSE (spec))
26671 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
26672 	       affect overload resolution and treating it as dependent breaks
26673 	       things.  Same for an unparsed noexcept expression.  */
26674 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26675 		&& TREE_CODE (noex) != DEFERRED_PARSE
26676 		&& value_dependent_expression_p (noex))
26677 	      return true;
26678       return false;
26679     }
26680   /* -- an array type constructed from any dependent type or whose
26681 	size is specified by a constant expression that is
26682 	value-dependent.
26683 
26684         We checked for type- and value-dependence of the bounds in
26685         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
26686   if (TREE_CODE (type) == ARRAY_TYPE)
26687     {
26688       if (TYPE_DOMAIN (type)
26689 	  && dependent_type_p (TYPE_DOMAIN (type)))
26690 	return true;
26691       return dependent_type_p (TREE_TYPE (type));
26692     }
26693 
26694   /* -- a template-id in which either the template name is a template
26695      parameter ...  */
26696   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26697     return true;
26698   /* ... or any of the template arguments is a dependent type or
26699 	an expression that is type-dependent or value-dependent.  */
26700   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26701 	   && (any_dependent_template_arguments_p
26702 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
26703     return true;
26704 
26705   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
26706      dependent; if the argument of the `typeof' expression is not
26707      type-dependent, then it should already been have resolved.  */
26708   if (TREE_CODE (type) == TYPEOF_TYPE
26709       || TREE_CODE (type) == DECLTYPE_TYPE
26710       || TREE_CODE (type) == UNDERLYING_TYPE)
26711     return true;
26712 
26713   /* A template argument pack is dependent if any of its packed
26714      arguments are.  */
26715   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
26716     {
26717       tree args = ARGUMENT_PACK_ARGS (type);
26718       int i, len = TREE_VEC_LENGTH (args);
26719       for (i = 0; i < len; ++i)
26720         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26721           return true;
26722     }
26723 
26724   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
26725      be template parameters.  */
26726   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
26727     return true;
26728 
26729   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
26730     return true;
26731 
26732   /* The standard does not specifically mention types that are local
26733      to template functions or local classes, but they should be
26734      considered dependent too.  For example:
26735 
26736        template <int I> void f() {
26737 	 enum E { a = I };
26738 	 S<sizeof (E)> s;
26739        }
26740 
26741      The size of `E' cannot be known until the value of `I' has been
26742      determined.  Therefore, `E' must be considered dependent.  */
26743   scope = TYPE_CONTEXT (type);
26744   if (scope && TYPE_P (scope))
26745     return dependent_type_p (scope);
26746   /* Don't use type_dependent_expression_p here, as it can lead
26747      to infinite recursion trying to determine whether a lambda
26748      nested in a lambda is dependent (c++/47687).  */
26749   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
26750 	   && DECL_LANG_SPECIFIC (scope)
26751 	   && DECL_TEMPLATE_INFO (scope)
26752 	   && (any_dependent_template_arguments_p
26753 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
26754     return true;
26755 
26756   /* Other types are non-dependent.  */
26757   return false;
26758 }
26759 
26760 /* Returns TRUE if TYPE is dependent, in the sense of
26761    [temp.dep.type].  Note that a NULL type is considered dependent.  */
26762 
26763 bool
dependent_type_p(tree type)26764 dependent_type_p (tree type)
26765 {
26766   /* If there are no template parameters in scope, then there can't be
26767      any dependent types.  */
26768   if (!processing_template_decl)
26769     {
26770       /* If we are not processing a template, then nobody should be
26771 	 providing us with a dependent type.  */
26772       gcc_assert (type);
26773       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
26774       return false;
26775     }
26776 
26777   /* If the type is NULL, we have not computed a type for the entity
26778      in question; in that case, the type is dependent.  */
26779   if (!type)
26780     return true;
26781 
26782   /* Erroneous types can be considered non-dependent.  */
26783   if (type == error_mark_node)
26784     return false;
26785 
26786   /* If we have not already computed the appropriate value for TYPE,
26787      do so now.  */
26788   if (!TYPE_DEPENDENT_P_VALID (type))
26789     {
26790       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
26791       TYPE_DEPENDENT_P_VALID (type) = 1;
26792     }
26793 
26794   return TYPE_DEPENDENT_P (type);
26795 }
26796 
26797 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
26798    lookup.  In other words, a dependent type that is not the current
26799    instantiation.  */
26800 
26801 bool
dependent_scope_p(tree scope)26802 dependent_scope_p (tree scope)
26803 {
26804   return (scope && TYPE_P (scope) && dependent_type_p (scope)
26805 	  && !currently_open_class (scope));
26806 }
26807 
26808 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
26809    an unknown base of 'this' (and is therefore instantiation-dependent).  */
26810 
26811 static bool
unknown_base_ref_p(tree t)26812 unknown_base_ref_p (tree t)
26813 {
26814   if (!current_class_ptr)
26815     return false;
26816 
26817   tree mem = TREE_OPERAND (t, 1);
26818   if (shared_member_p (mem))
26819     return false;
26820 
26821   tree cur = current_nonlambda_class_type ();
26822   if (!any_dependent_bases_p (cur))
26823     return false;
26824 
26825   tree ctx = TREE_OPERAND (t, 0);
26826   if (DERIVED_FROM_P (ctx, cur))
26827     return false;
26828 
26829   return true;
26830 }
26831 
26832 /* T is a SCOPE_REF; return whether we need to consider it
26833     instantiation-dependent so that we can check access at instantiation
26834     time even though we know which member it resolves to.  */
26835 
26836 static bool
instantiation_dependent_scope_ref_p(tree t)26837 instantiation_dependent_scope_ref_p (tree t)
26838 {
26839   if (DECL_P (TREE_OPERAND (t, 1))
26840       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
26841       && !unknown_base_ref_p (t)
26842       && accessible_in_template_p (TREE_OPERAND (t, 0),
26843 				   TREE_OPERAND (t, 1)))
26844     return false;
26845   else
26846     return true;
26847 }
26848 
26849 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
26850    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
26851    expression.  */
26852 
26853 /* Note that this predicate is not appropriate for general expressions;
26854    only constant expressions (that satisfy potential_constant_expression)
26855    can be tested for value dependence.  */
26856 
26857 bool
value_dependent_expression_p(tree expression)26858 value_dependent_expression_p (tree expression)
26859 {
26860   if (!processing_template_decl || expression == NULL_TREE)
26861     return false;
26862 
26863   /* A type-dependent expression is also value-dependent.  */
26864   if (type_dependent_expression_p (expression))
26865     return true;
26866 
26867   switch (TREE_CODE (expression))
26868     {
26869     case BASELINK:
26870       /* A dependent member function of the current instantiation.  */
26871       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
26872 
26873     case FUNCTION_DECL:
26874       /* A dependent member function of the current instantiation.  */
26875       if (DECL_CLASS_SCOPE_P (expression)
26876 	  && dependent_type_p (DECL_CONTEXT (expression)))
26877 	return true;
26878       break;
26879 
26880     case IDENTIFIER_NODE:
26881       /* A name that has not been looked up -- must be dependent.  */
26882       return true;
26883 
26884     case TEMPLATE_PARM_INDEX:
26885       /* A non-type template parm.  */
26886       return true;
26887 
26888     case CONST_DECL:
26889       /* A non-type template parm.  */
26890       if (DECL_TEMPLATE_PARM_P (expression))
26891 	return true;
26892       return value_dependent_expression_p (DECL_INITIAL (expression));
26893 
26894     case VAR_DECL:
26895        /* A constant with literal type and is initialized
26896 	  with an expression that is value-dependent.  */
26897       if (DECL_DEPENDENT_INIT_P (expression)
26898 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
26899 	  || TYPE_REF_P (TREE_TYPE (expression)))
26900 	return true;
26901       if (DECL_HAS_VALUE_EXPR_P (expression))
26902 	{
26903 	  tree value_expr = DECL_VALUE_EXPR (expression);
26904 	  if (value_dependent_expression_p (value_expr)
26905 	      /* __PRETTY_FUNCTION__ inside a template function is dependent
26906 		 on the name of the function.  */
26907 	      || (DECL_PRETTY_FUNCTION_P (expression)
26908 		  /* It might be used in a template, but not a template
26909 		     function, in which case its DECL_VALUE_EXPR will be
26910 		     "top level".  */
26911 		  && value_expr == error_mark_node))
26912 	    return true;
26913 	}
26914       return false;
26915 
26916     case DYNAMIC_CAST_EXPR:
26917     case STATIC_CAST_EXPR:
26918     case CONST_CAST_EXPR:
26919     case REINTERPRET_CAST_EXPR:
26920     case CAST_EXPR:
26921     case IMPLICIT_CONV_EXPR:
26922       /* These expressions are value-dependent if the type to which
26923 	 the cast occurs is dependent or the expression being casted
26924 	 is value-dependent.  */
26925       {
26926 	tree type = TREE_TYPE (expression);
26927 
26928 	if (dependent_type_p (type))
26929 	  return true;
26930 
26931 	/* A functional cast has a list of operands.  */
26932 	expression = TREE_OPERAND (expression, 0);
26933 	if (!expression)
26934 	  {
26935 	    /* If there are no operands, it must be an expression such
26936 	       as "int()". This should not happen for aggregate types
26937 	       because it would form non-constant expressions.  */
26938 	    gcc_assert (cxx_dialect >= cxx11
26939 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
26940 
26941 	    return false;
26942 	  }
26943 
26944 	if (TREE_CODE (expression) == TREE_LIST)
26945 	  return any_value_dependent_elements_p (expression);
26946 
26947 	return value_dependent_expression_p (expression);
26948       }
26949 
26950     case SIZEOF_EXPR:
26951       if (SIZEOF_EXPR_TYPE_P (expression))
26952 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
26953       /* FALLTHRU */
26954     case ALIGNOF_EXPR:
26955     case TYPEID_EXPR:
26956       /* A `sizeof' expression is value-dependent if the operand is
26957 	 type-dependent or is a pack expansion.  */
26958       expression = TREE_OPERAND (expression, 0);
26959       if (PACK_EXPANSION_P (expression))
26960         return true;
26961       else if (TYPE_P (expression))
26962 	return dependent_type_p (expression);
26963       return instantiation_dependent_uneval_expression_p (expression);
26964 
26965     case AT_ENCODE_EXPR:
26966       /* An 'encode' expression is value-dependent if the operand is
26967 	 type-dependent.  */
26968       expression = TREE_OPERAND (expression, 0);
26969       return dependent_type_p (expression);
26970 
26971     case NOEXCEPT_EXPR:
26972       expression = TREE_OPERAND (expression, 0);
26973       return instantiation_dependent_uneval_expression_p (expression);
26974 
26975     case SCOPE_REF:
26976       /* All instantiation-dependent expressions should also be considered
26977 	 value-dependent.  */
26978       return instantiation_dependent_scope_ref_p (expression);
26979 
26980     case COMPONENT_REF:
26981       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
26982 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
26983 
26984     case NONTYPE_ARGUMENT_PACK:
26985       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
26986          is value-dependent.  */
26987       {
26988         tree values = ARGUMENT_PACK_ARGS (expression);
26989         int i, len = TREE_VEC_LENGTH (values);
26990 
26991         for (i = 0; i < len; ++i)
26992           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
26993             return true;
26994 
26995         return false;
26996       }
26997 
26998     case TRAIT_EXPR:
26999       {
27000 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
27001 
27002 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
27003 	  return true;
27004 
27005 	if (!type2)
27006 	  return false;
27007 
27008 	if (TREE_CODE (type2) != TREE_LIST)
27009 	  return dependent_type_p (type2);
27010 
27011 	for (; type2; type2 = TREE_CHAIN (type2))
27012 	  if (dependent_type_p (TREE_VALUE (type2)))
27013 	    return true;
27014 
27015 	return false;
27016       }
27017 
27018     case MODOP_EXPR:
27019       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27020 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27021 
27022     case ARRAY_REF:
27023       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27024 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27025 
27026     case ADDR_EXPR:
27027       {
27028 	tree op = TREE_OPERAND (expression, 0);
27029 	return (value_dependent_expression_p (op)
27030 		|| has_value_dependent_address (op));
27031       }
27032 
27033     case REQUIRES_EXPR:
27034       /* Treat all requires-expressions as value-dependent so
27035          we don't try to fold them.  */
27036       return true;
27037 
27038     case TYPE_REQ:
27039       return dependent_type_p (TREE_OPERAND (expression, 0));
27040 
27041     case CALL_EXPR:
27042       {
27043 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27044 	  return true;
27045 	tree fn = get_callee_fndecl (expression);
27046 	int i, nargs;
27047 	nargs = call_expr_nargs (expression);
27048 	for (i = 0; i < nargs; ++i)
27049 	  {
27050 	    tree op = CALL_EXPR_ARG (expression, i);
27051 	    /* In a call to a constexpr member function, look through the
27052 	       implicit ADDR_EXPR on the object argument so that it doesn't
27053 	       cause the call to be considered value-dependent.  We also
27054 	       look through it in potential_constant_expression.  */
27055 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27056 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27057 		&& TREE_CODE (op) == ADDR_EXPR)
27058 	      op = TREE_OPERAND (op, 0);
27059 	    if (value_dependent_expression_p (op))
27060 	      return true;
27061 	  }
27062 	return false;
27063       }
27064 
27065     case TEMPLATE_ID_EXPR:
27066       return concept_definition_p (TREE_OPERAND (expression, 0))
27067 	&& any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
27068 
27069     case CONSTRUCTOR:
27070       {
27071 	unsigned ix;
27072 	tree val;
27073 	if (dependent_type_p (TREE_TYPE (expression)))
27074 	  return true;
27075 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27076 	  if (value_dependent_expression_p (val))
27077 	    return true;
27078 	return false;
27079       }
27080 
27081     case STMT_EXPR:
27082       /* Treat a GNU statement expression as dependent to avoid crashing
27083 	 under instantiate_non_dependent_expr; it can't be constant.  */
27084       return true;
27085 
27086     default:
27087       /* A constant expression is value-dependent if any subexpression is
27088 	 value-dependent.  */
27089       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27090 	{
27091 	case tcc_reference:
27092 	case tcc_unary:
27093 	case tcc_comparison:
27094 	case tcc_binary:
27095 	case tcc_expression:
27096 	case tcc_vl_exp:
27097 	  {
27098 	    int i, len = cp_tree_operand_length (expression);
27099 
27100 	    for (i = 0; i < len; i++)
27101 	      {
27102 		tree t = TREE_OPERAND (expression, i);
27103 
27104 		/* In some cases, some of the operands may be missing.
27105 		   (For example, in the case of PREDECREMENT_EXPR, the
27106 		   amount to increment by may be missing.)  That doesn't
27107 		   make the expression dependent.  */
27108 		if (t && value_dependent_expression_p (t))
27109 		  return true;
27110 	      }
27111 	  }
27112 	  break;
27113 	default:
27114 	  break;
27115 	}
27116       break;
27117     }
27118 
27119   /* The expression is not value-dependent.  */
27120   return false;
27121 }
27122 
27123 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
27124    [temp.dep.expr].  Note that an expression with no type is
27125    considered dependent.  Other parts of the compiler arrange for an
27126    expression with type-dependent subexpressions to have no type, so
27127    this function doesn't have to be fully recursive.  */
27128 
27129 bool
type_dependent_expression_p(tree expression)27130 type_dependent_expression_p (tree expression)
27131 {
27132   if (!processing_template_decl)
27133     return false;
27134 
27135   if (expression == NULL_TREE || expression == error_mark_node)
27136     return false;
27137 
27138   STRIP_ANY_LOCATION_WRAPPER (expression);
27139 
27140   /* An unresolved name is always dependent.  */
27141   if (identifier_p (expression)
27142       || TREE_CODE (expression) == USING_DECL
27143       || TREE_CODE (expression) == WILDCARD_DECL)
27144     return true;
27145 
27146   /* A lambda-expression in template context is dependent.  dependent_type_p is
27147      true for a lambda in the scope of a class or function template, but that
27148      doesn't cover all template contexts, like a default template argument.  */
27149   if (TREE_CODE (expression) == LAMBDA_EXPR)
27150     return true;
27151 
27152   /* A fold expression is type-dependent. */
27153   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
27154       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
27155       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
27156       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
27157     return true;
27158 
27159   /* Some expression forms are never type-dependent.  */
27160   if (TREE_CODE (expression) == SIZEOF_EXPR
27161       || TREE_CODE (expression) == ALIGNOF_EXPR
27162       || TREE_CODE (expression) == AT_ENCODE_EXPR
27163       || TREE_CODE (expression) == NOEXCEPT_EXPR
27164       || TREE_CODE (expression) == TRAIT_EXPR
27165       || TREE_CODE (expression) == TYPEID_EXPR
27166       || TREE_CODE (expression) == DELETE_EXPR
27167       || TREE_CODE (expression) == VEC_DELETE_EXPR
27168       || TREE_CODE (expression) == THROW_EXPR
27169       || TREE_CODE (expression) == REQUIRES_EXPR)
27170     return false;
27171 
27172   /* The types of these expressions depends only on the type to which
27173      the cast occurs.  */
27174   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
27175       || TREE_CODE (expression) == STATIC_CAST_EXPR
27176       || TREE_CODE (expression) == CONST_CAST_EXPR
27177       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
27178       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
27179       || TREE_CODE (expression) == CAST_EXPR)
27180     return dependent_type_p (TREE_TYPE (expression));
27181 
27182   /* The types of these expressions depends only on the type created
27183      by the expression.  */
27184   if (TREE_CODE (expression) == NEW_EXPR
27185       || TREE_CODE (expression) == VEC_NEW_EXPR)
27186     {
27187       /* For NEW_EXPR tree nodes created inside a template, either
27188 	 the object type itself or a TREE_LIST may appear as the
27189 	 operand 1.  */
27190       tree type = TREE_OPERAND (expression, 1);
27191       if (TREE_CODE (type) == TREE_LIST)
27192 	/* This is an array type.  We need to check array dimensions
27193 	   as well.  */
27194 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
27195 	       || value_dependent_expression_p
27196 		    (TREE_OPERAND (TREE_VALUE (type), 1));
27197       /* Array type whose dimension has to be deduced.  */
27198       else if (TREE_CODE (type) == ARRAY_TYPE
27199 	       && TREE_OPERAND (expression, 2) == NULL_TREE)
27200 	return true;
27201       else
27202 	return dependent_type_p (type);
27203     }
27204 
27205   if (TREE_CODE (expression) == SCOPE_REF)
27206     {
27207       tree scope = TREE_OPERAND (expression, 0);
27208       tree name = TREE_OPERAND (expression, 1);
27209 
27210       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
27211 	 contains an identifier associated by name lookup with one or more
27212 	 declarations declared with a dependent type, or...a
27213 	 nested-name-specifier or qualified-id that names a member of an
27214 	 unknown specialization.  */
27215       return (type_dependent_expression_p (name)
27216 	      || dependent_scope_p (scope));
27217     }
27218 
27219   if (TREE_CODE (expression) == TEMPLATE_DECL
27220       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27221     return uses_outer_template_parms (expression);
27222 
27223   if (TREE_CODE (expression) == STMT_EXPR)
27224     expression = stmt_expr_value_expr (expression);
27225 
27226   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
27227     {
27228       tree elt;
27229       unsigned i;
27230 
27231       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
27232 	{
27233 	  if (type_dependent_expression_p (elt))
27234 	    return true;
27235 	}
27236       return false;
27237     }
27238 
27239   /* A static data member of the current instantiation with incomplete
27240      array type is type-dependent, as the definition and specializations
27241      can have different bounds.  */
27242   if (VAR_P (expression)
27243       && DECL_CLASS_SCOPE_P (expression)
27244       && dependent_type_p (DECL_CONTEXT (expression))
27245       && VAR_HAD_UNKNOWN_BOUND (expression))
27246     return true;
27247 
27248   /* An array of unknown bound depending on a variadic parameter, eg:
27249 
27250      template<typename... Args>
27251        void foo (Args... args)
27252        {
27253          int arr[] = { args... };
27254        }
27255 
27256      template<int... vals>
27257        void bar ()
27258        {
27259          int arr[] = { vals... };
27260        }
27261 
27262      If the array has no length and has an initializer, it must be that
27263      we couldn't determine its length in cp_complete_array_type because
27264      it is dependent.  */
27265   if (VAR_P (expression)
27266       && TREE_TYPE (expression) != NULL_TREE
27267       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
27268       && !TYPE_DOMAIN (TREE_TYPE (expression))
27269       && DECL_INITIAL (expression))
27270    return true;
27271 
27272   /* A function or variable template-id is type-dependent if it has any
27273      dependent template arguments.  */
27274   if (VAR_OR_FUNCTION_DECL_P (expression)
27275       && DECL_LANG_SPECIFIC (expression)
27276       && DECL_TEMPLATE_INFO (expression))
27277     {
27278       /* Consider the innermost template arguments, since those are the ones
27279 	 that come from the template-id; the template arguments for the
27280 	 enclosing class do not make it type-dependent unless they are used in
27281 	 the type of the decl.  */
27282       if (instantiates_primary_template_p (expression)
27283 	  && (any_dependent_template_arguments_p
27284 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
27285 	return true;
27286     }
27287 
27288   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
27289      type-dependent.  Checking this is important for functions with auto return
27290      type, which looks like a dependent type.  */
27291   if (TREE_CODE (expression) == FUNCTION_DECL
27292       && !(DECL_CLASS_SCOPE_P (expression)
27293 	   && dependent_type_p (DECL_CONTEXT (expression)))
27294       && !(DECL_LANG_SPECIFIC (expression)
27295 	   && DECL_UNIQUE_FRIEND_P (expression)
27296 	   && (!DECL_FRIEND_CONTEXT (expression)
27297 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
27298       && !DECL_LOCAL_DECL_P (expression))
27299     {
27300       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
27301 		  || undeduced_auto_decl (expression));
27302       return false;
27303     }
27304 
27305   /* Always dependent, on the number of arguments if nothing else.  */
27306   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
27307     return true;
27308 
27309   if (TREE_TYPE (expression) == unknown_type_node)
27310     {
27311       if (TREE_CODE (expression) == ADDR_EXPR)
27312 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
27313       if (TREE_CODE (expression) == COMPONENT_REF
27314 	  || TREE_CODE (expression) == OFFSET_REF)
27315 	{
27316 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
27317 	    return true;
27318 	  expression = TREE_OPERAND (expression, 1);
27319 	  if (identifier_p (expression))
27320 	    return false;
27321 	}
27322       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
27323       if (TREE_CODE (expression) == SCOPE_REF)
27324 	return false;
27325 
27326       /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
27327       if (TREE_CODE (expression) == CO_AWAIT_EXPR
27328 	  || TREE_CODE (expression) == CO_YIELD_EXPR)
27329 	return true;
27330 
27331       if (BASELINK_P (expression))
27332 	{
27333 	  if (BASELINK_OPTYPE (expression)
27334 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
27335 	    return true;
27336 	  expression = BASELINK_FUNCTIONS (expression);
27337 	}
27338 
27339       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
27340 	{
27341 	  if (any_dependent_template_arguments_p
27342 	      (TREE_OPERAND (expression, 1)))
27343 	    return true;
27344 	  expression = TREE_OPERAND (expression, 0);
27345 	  if (identifier_p (expression))
27346 	    return true;
27347 	}
27348 
27349       gcc_assert (OVL_P (expression));
27350 
27351       for (lkp_iterator iter (expression); iter; ++iter)
27352 	if (type_dependent_expression_p (*iter))
27353 	  return true;
27354 
27355       return false;
27356     }
27357 
27358   /* The type of a non-type template parm declared with a placeholder type
27359      depends on the corresponding template argument, even though
27360      placeholders are not normally considered dependent.  */
27361   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
27362       && is_auto (TREE_TYPE (expression)))
27363     return true;
27364 
27365   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
27366 
27367   /* Dependent type attributes might not have made it from the decl to
27368      the type yet.  */
27369   if (DECL_P (expression)
27370       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
27371     return true;
27372 
27373   return (dependent_type_p (TREE_TYPE (expression)));
27374 }
27375 
27376 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
27377    type-dependent if the expression refers to a member of the current
27378    instantiation and the type of the referenced member is dependent, or the
27379    class member access expression refers to a member of an unknown
27380    specialization.
27381 
27382    This function returns true if the OBJECT in such a class member access
27383    expression is of an unknown specialization.  */
27384 
27385 bool
type_dependent_object_expression_p(tree object)27386 type_dependent_object_expression_p (tree object)
27387 {
27388   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
27389      dependent.  */
27390   if (TREE_CODE (object) == IDENTIFIER_NODE)
27391     return true;
27392   tree scope = TREE_TYPE (object);
27393   return (!scope || dependent_scope_p (scope));
27394 }
27395 
27396 /* walk_tree callback function for instantiation_dependent_expression_p,
27397    below.  Returns non-zero if a dependent subexpression is found.  */
27398 
27399 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)27400 instantiation_dependent_r (tree *tp, int *walk_subtrees,
27401 			   void * /*data*/)
27402 {
27403   if (TYPE_P (*tp))
27404     {
27405       /* We don't have to worry about decltype currently because decltype
27406 	 of an instantiation-dependent expr is a dependent type.  This
27407 	 might change depending on the resolution of DR 1172.  */
27408       *walk_subtrees = false;
27409       return NULL_TREE;
27410     }
27411   enum tree_code code = TREE_CODE (*tp);
27412   switch (code)
27413     {
27414       /* Don't treat an argument list as dependent just because it has no
27415 	 TREE_TYPE.  */
27416     case TREE_LIST:
27417     case TREE_VEC:
27418     case NONTYPE_ARGUMENT_PACK:
27419       return NULL_TREE;
27420 
27421     case TEMPLATE_PARM_INDEX:
27422       if (dependent_type_p (TREE_TYPE (*tp)))
27423 	return *tp;
27424       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
27425 	return *tp;
27426       /* We'll check value-dependence separately.  */
27427       return NULL_TREE;
27428 
27429       /* Handle expressions with type operands.  */
27430     case SIZEOF_EXPR:
27431     case ALIGNOF_EXPR:
27432     case TYPEID_EXPR:
27433     case AT_ENCODE_EXPR:
27434       {
27435 	tree op = TREE_OPERAND (*tp, 0);
27436 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
27437 	  op = TREE_TYPE (op);
27438 	if (TYPE_P (op))
27439 	  {
27440 	    if (dependent_type_p (op))
27441 	      return *tp;
27442 	    else
27443 	      {
27444 		*walk_subtrees = false;
27445 		return NULL_TREE;
27446 	      }
27447 	  }
27448 	break;
27449       }
27450 
27451     case COMPONENT_REF:
27452       if (identifier_p (TREE_OPERAND (*tp, 1)))
27453 	/* In a template, finish_class_member_access_expr creates a
27454 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
27455 	   type-dependent, so that we can check access control at
27456 	   instantiation time (PR 42277).  See also Core issue 1273.  */
27457 	return *tp;
27458       break;
27459 
27460     case SCOPE_REF:
27461       if (instantiation_dependent_scope_ref_p (*tp))
27462 	return *tp;
27463       else
27464 	break;
27465 
27466       /* Treat statement-expressions as dependent.  */
27467     case BIND_EXPR:
27468       return *tp;
27469 
27470       /* Treat requires-expressions as dependent. */
27471     case REQUIRES_EXPR:
27472       return *tp;
27473 
27474     case CONSTRUCTOR:
27475       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
27476 	return *tp;
27477       break;
27478 
27479     default:
27480       break;
27481     }
27482 
27483   if (type_dependent_expression_p (*tp))
27484     return *tp;
27485   else
27486     return NULL_TREE;
27487 }
27488 
27489 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
27490    sense defined by the ABI:
27491 
27492    "An expression is instantiation-dependent if it is type-dependent
27493    or value-dependent, or it has a subexpression that is type-dependent
27494    or value-dependent."
27495 
27496    Except don't actually check value-dependence for unevaluated expressions,
27497    because in sizeof(i) we don't care about the value of i.  Checking
27498    type-dependence will in turn check value-dependence of array bounds/template
27499    arguments as needed.  */
27500 
27501 bool
instantiation_dependent_uneval_expression_p(tree expression)27502 instantiation_dependent_uneval_expression_p (tree expression)
27503 {
27504   tree result;
27505 
27506   if (!processing_template_decl)
27507     return false;
27508 
27509   if (expression == error_mark_node)
27510     return false;
27511 
27512   result = cp_walk_tree_without_duplicates (&expression,
27513 					    instantiation_dependent_r, NULL);
27514   return result != NULL_TREE;
27515 }
27516 
27517 /* As above, but also check value-dependence of the expression as a whole.  */
27518 
27519 bool
instantiation_dependent_expression_p(tree expression)27520 instantiation_dependent_expression_p (tree expression)
27521 {
27522   return (instantiation_dependent_uneval_expression_p (expression)
27523 	  || (processing_template_decl
27524 	      && potential_constant_expression (expression)
27525 	      && value_dependent_expression_p (expression)));
27526 }
27527 
27528 /* Like type_dependent_expression_p, but it also works while not processing
27529    a template definition, i.e. during substitution or mangling.  */
27530 
27531 bool
type_dependent_expression_p_push(tree expr)27532 type_dependent_expression_p_push (tree expr)
27533 {
27534   bool b;
27535   ++processing_template_decl;
27536   b = type_dependent_expression_p (expr);
27537   --processing_template_decl;
27538   return b;
27539 }
27540 
27541 /* Returns TRUE if ARGS contains a type-dependent expression.  */
27542 
27543 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)27544 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
27545 {
27546   unsigned int i;
27547   tree arg;
27548 
27549   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
27550     {
27551       if (type_dependent_expression_p (arg))
27552 	return true;
27553     }
27554   return false;
27555 }
27556 
27557 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27558    expressions) contains any type-dependent expressions.  */
27559 
27560 bool
any_type_dependent_elements_p(const_tree list)27561 any_type_dependent_elements_p (const_tree list)
27562 {
27563   for (; list; list = TREE_CHAIN (list))
27564     if (type_dependent_expression_p (TREE_VALUE (list)))
27565       return true;
27566 
27567   return false;
27568 }
27569 
27570 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27571    expressions) contains any value-dependent expressions.  */
27572 
27573 bool
any_value_dependent_elements_p(const_tree list)27574 any_value_dependent_elements_p (const_tree list)
27575 {
27576   for (; list; list = TREE_CHAIN (list))
27577     if (value_dependent_expression_p (TREE_VALUE (list)))
27578       return true;
27579 
27580   return false;
27581 }
27582 
27583 /* Returns TRUE if the ARG (a template argument) is dependent.  */
27584 
27585 bool
dependent_template_arg_p(tree arg)27586 dependent_template_arg_p (tree arg)
27587 {
27588   if (!processing_template_decl)
27589     return false;
27590 
27591   /* Assume a template argument that was wrongly written by the user
27592      is dependent. This is consistent with what
27593      any_dependent_template_arguments_p [that calls this function]
27594      does.  */
27595   if (!arg || arg == error_mark_node)
27596     return true;
27597 
27598   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
27599     arg = argument_pack_select_arg (arg);
27600 
27601   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
27602     return true;
27603   if (TREE_CODE (arg) == TEMPLATE_DECL)
27604     {
27605       if (DECL_TEMPLATE_PARM_P (arg))
27606 	return true;
27607       /* A member template of a dependent class is not necessarily
27608 	 type-dependent, but it is a dependent template argument because it
27609 	 will be a member of an unknown specialization to that template.  */
27610       tree scope = CP_DECL_CONTEXT (arg);
27611       return TYPE_P (scope) && dependent_type_p (scope);
27612     }
27613   else if (ARGUMENT_PACK_P (arg))
27614     {
27615       tree args = ARGUMENT_PACK_ARGS (arg);
27616       int i, len = TREE_VEC_LENGTH (args);
27617       for (i = 0; i < len; ++i)
27618         {
27619           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27620             return true;
27621         }
27622 
27623       return false;
27624     }
27625   else if (TYPE_P (arg))
27626     return dependent_type_p (arg);
27627   else
27628     return value_dependent_expression_p (arg);
27629 }
27630 
27631 /* Returns true if ARGS (a collection of template arguments) contains
27632    any types that require structural equality testing.  */
27633 
27634 bool
any_template_arguments_need_structural_equality_p(tree args)27635 any_template_arguments_need_structural_equality_p (tree args)
27636 {
27637   int i;
27638   int j;
27639 
27640   if (!args)
27641     return false;
27642   if (args == error_mark_node)
27643     return true;
27644 
27645   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27646     {
27647       tree level = TMPL_ARGS_LEVEL (args, i + 1);
27648       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27649 	{
27650 	  tree arg = TREE_VEC_ELT (level, j);
27651 	  tree packed_args = NULL_TREE;
27652 	  int k, len = 1;
27653 
27654 	  if (ARGUMENT_PACK_P (arg))
27655 	    {
27656 	      /* Look inside the argument pack.  */
27657 	      packed_args = ARGUMENT_PACK_ARGS (arg);
27658 	      len = TREE_VEC_LENGTH (packed_args);
27659 	    }
27660 
27661 	  for (k = 0; k < len; ++k)
27662 	    {
27663 	      if (packed_args)
27664 		arg = TREE_VEC_ELT (packed_args, k);
27665 
27666 	      if (error_operand_p (arg))
27667 		return true;
27668 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
27669 		continue;
27670 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
27671 		return true;
27672 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
27673 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
27674 		return true;
27675 	    }
27676 	}
27677     }
27678 
27679   return false;
27680 }
27681 
27682 /* Returns true if ARGS (a collection of template arguments) contains
27683    any dependent arguments.  */
27684 
27685 bool
any_dependent_template_arguments_p(const_tree args)27686 any_dependent_template_arguments_p (const_tree args)
27687 {
27688   int i;
27689   int j;
27690 
27691   if (!args)
27692     return false;
27693   if (args == error_mark_node)
27694     return true;
27695 
27696   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27697     {
27698       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27699       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27700 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
27701 	  return true;
27702     }
27703 
27704   return false;
27705 }
27706 
27707 /* Returns true if ARGS contains any errors.  */
27708 
27709 bool
any_erroneous_template_args_p(const_tree args)27710 any_erroneous_template_args_p (const_tree args)
27711 {
27712   int i;
27713   int j;
27714 
27715   if (args == error_mark_node)
27716     return true;
27717 
27718   if (args && TREE_CODE (args) != TREE_VEC)
27719     {
27720       if (tree ti = get_template_info (args))
27721 	args = TI_ARGS (ti);
27722       else
27723 	args = NULL_TREE;
27724     }
27725 
27726   if (!args)
27727     return false;
27728 
27729   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27730     {
27731       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27732       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27733 	if (error_operand_p (TREE_VEC_ELT (level, j)))
27734 	  return true;
27735     }
27736 
27737   return false;
27738 }
27739 
27740 /* Returns TRUE if the template TMPL is type-dependent.  */
27741 
27742 bool
dependent_template_p(tree tmpl)27743 dependent_template_p (tree tmpl)
27744 {
27745   if (TREE_CODE (tmpl) == OVERLOAD)
27746     {
27747       for (lkp_iterator iter (tmpl); iter; ++iter)
27748 	if (dependent_template_p (*iter))
27749 	  return true;
27750       return false;
27751     }
27752 
27753   /* Template template parameters are dependent.  */
27754   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
27755       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
27756     return true;
27757   /* So are names that have not been looked up.  */
27758   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
27759     return true;
27760   return false;
27761 }
27762 
27763 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
27764 
27765 bool
dependent_template_id_p(tree tmpl,tree args)27766 dependent_template_id_p (tree tmpl, tree args)
27767 {
27768   return (dependent_template_p (tmpl)
27769 	  || any_dependent_template_arguments_p (args));
27770 }
27771 
27772 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
27773    are dependent.  */
27774 
27775 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)27776 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
27777 {
27778   int i;
27779 
27780   if (!processing_template_decl)
27781     return false;
27782 
27783   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
27784     {
27785       tree decl = TREE_VEC_ELT (declv, i);
27786       tree init = TREE_VEC_ELT (initv, i);
27787       tree cond = TREE_VEC_ELT (condv, i);
27788       tree incr = TREE_VEC_ELT (incrv, i);
27789 
27790       if (type_dependent_expression_p (decl)
27791 	  || TREE_CODE (decl) == SCOPE_REF)
27792 	return true;
27793 
27794       if (init && type_dependent_expression_p (init))
27795 	return true;
27796 
27797       if (cond == global_namespace)
27798 	return true;
27799 
27800       if (type_dependent_expression_p (cond))
27801 	return true;
27802 
27803       if (COMPARISON_CLASS_P (cond)
27804 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
27805 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
27806 	return true;
27807 
27808       if (TREE_CODE (incr) == MODOP_EXPR)
27809 	{
27810 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
27811 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
27812 	    return true;
27813 	}
27814       else if (type_dependent_expression_p (incr))
27815 	return true;
27816       else if (TREE_CODE (incr) == MODIFY_EXPR)
27817 	{
27818 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
27819 	    return true;
27820 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
27821 	    {
27822 	      tree t = TREE_OPERAND (incr, 1);
27823 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
27824 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
27825 		return true;
27826 
27827 	      /* If this loop has a class iterator with != comparison
27828 		 with increment other than i++/++i/i--/--i, make sure the
27829 		 increment is constant.  */
27830 	      if (CLASS_TYPE_P (TREE_TYPE (decl))
27831 		  && TREE_CODE (cond) == NE_EXPR)
27832 		{
27833 		  if (TREE_OPERAND (t, 0) == decl)
27834 		    t = TREE_OPERAND (t, 1);
27835 		  else
27836 		    t = TREE_OPERAND (t, 0);
27837 		  if (TREE_CODE (t) != INTEGER_CST)
27838 		    return true;
27839 		}
27840 	    }
27841 	}
27842     }
27843 
27844   return false;
27845 }
27846 
27847 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
27848    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
27849    no such TYPE can be found.  Note that this function peers inside
27850    uninstantiated templates and therefore should be used only in
27851    extremely limited situations.  ONLY_CURRENT_P restricts this
27852    peering to the currently open classes hierarchy (which is required
27853    when comparing types).  */
27854 
27855 tree
resolve_typename_type(tree type,bool only_current_p)27856 resolve_typename_type (tree type, bool only_current_p)
27857 {
27858   tree scope;
27859   tree name;
27860   tree decl;
27861   int quals;
27862   tree pushed_scope;
27863   tree result;
27864 
27865   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
27866 
27867   scope = TYPE_CONTEXT (type);
27868   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
27869   gcc_checking_assert (uses_template_parms (scope));
27870 
27871   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
27872      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
27873      TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
27874      representing the typedef. In that case TYPE_IDENTIFIER (type) is
27875      not the non-qualified identifier of the TYPENAME_TYPE anymore.
27876      So by getting the TYPE_IDENTIFIER of the _main declaration_ of
27877      the TYPENAME_TYPE instead, we avoid messing up with a possible
27878      typedef variant case.  */
27879   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
27880 
27881   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
27882      it first before we can figure out what NAME refers to.  */
27883   if (TREE_CODE (scope) == TYPENAME_TYPE)
27884     {
27885       if (TYPENAME_IS_RESOLVING_P (scope))
27886 	/* Given a class template A with a dependent base with nested type C,
27887 	   typedef typename A::C::C C will land us here, as trying to resolve
27888 	   the initial A::C leads to the local C typedef, which leads back to
27889 	   A::C::C.  So we break the recursion now.  */
27890 	return type;
27891       else
27892 	scope = resolve_typename_type (scope, only_current_p);
27893     }
27894   /* If we don't know what SCOPE refers to, then we cannot resolve the
27895      TYPENAME_TYPE.  */
27896   if (!CLASS_TYPE_P (scope))
27897     return type;
27898   /* If this is a typedef, we don't want to look inside (c++/11987).  */
27899   if (typedef_variant_p (type))
27900     return type;
27901   /* If SCOPE isn't the template itself, it will not have a valid
27902      TYPE_FIELDS list.  */
27903   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
27904     /* scope is either the template itself or a compatible instantiation
27905        like X<T>, so look up the name in the original template.  */
27906     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
27907   /* If scope has no fields, it can't be a current instantiation.  Check this
27908      before currently_open_class to avoid infinite recursion (71515).  */
27909   if (!TYPE_FIELDS (scope))
27910     return type;
27911   /* If the SCOPE is not the current instantiation, there's no reason
27912      to look inside it.  */
27913   if (only_current_p && !currently_open_class (scope))
27914     return type;
27915   /* Enter the SCOPE so that name lookup will be resolved as if we
27916      were in the class definition.  In particular, SCOPE will no
27917      longer be considered a dependent type.  */
27918   pushed_scope = push_scope (scope);
27919   /* Look up the declaration.  */
27920   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
27921 			tf_warning_or_error);
27922 
27923   result = NULL_TREE;
27924 
27925   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
27926      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
27927   tree fullname = TYPENAME_TYPE_FULLNAME (type);
27928   if (!decl)
27929     /*nop*/;
27930   else if (identifier_p (fullname)
27931 	   && TREE_CODE (decl) == TYPE_DECL)
27932     {
27933       result = TREE_TYPE (decl);
27934       if (result == error_mark_node)
27935 	result = NULL_TREE;
27936     }
27937   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
27938 	   && DECL_CLASS_TEMPLATE_P (decl))
27939     {
27940       /* Obtain the template and the arguments.  */
27941       tree tmpl = TREE_OPERAND (fullname, 0);
27942       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
27943 	{
27944 	  /* We get here with a plain identifier because a previous tentative
27945 	     parse of the nested-name-specifier as part of a ptr-operator saw
27946 	     ::template X<A>.  The use of ::template is necessary in a
27947 	     ptr-operator, but wrong in a declarator-id.
27948 
27949 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
27950 	     template shall not appear at the top level.  */
27951 	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
27952 		   "keyword %<template%> not allowed in declarator-id");
27953 	  tmpl = decl;
27954 	}
27955       tree args = TREE_OPERAND (fullname, 1);
27956       /* Instantiate the template.  */
27957       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
27958 				      /*entering_scope=*/true,
27959 				      tf_error | tf_user);
27960       if (result == error_mark_node)
27961 	result = NULL_TREE;
27962     }
27963 
27964   /* Leave the SCOPE.  */
27965   if (pushed_scope)
27966     pop_scope (pushed_scope);
27967 
27968   /* If we failed to resolve it, return the original typename.  */
27969   if (!result)
27970     return type;
27971 
27972   /* If lookup found a typename type, resolve that too.  */
27973   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
27974     {
27975       /* Ill-formed programs can cause infinite recursion here, so we
27976 	 must catch that.  */
27977       TYPENAME_IS_RESOLVING_P (result) = 1;
27978       result = resolve_typename_type (result, only_current_p);
27979       TYPENAME_IS_RESOLVING_P (result) = 0;
27980     }
27981 
27982   /* Qualify the resulting type.  */
27983   quals = cp_type_quals (type);
27984   if (quals)
27985     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
27986 
27987   return result;
27988 }
27989 
27990 /* EXPR is an expression which is not type-dependent.  Return a proxy
27991    for EXPR that can be used to compute the types of larger
27992    expressions containing EXPR.  */
27993 
27994 tree
build_non_dependent_expr(tree expr)27995 build_non_dependent_expr (tree expr)
27996 {
27997   tree orig_expr = expr;
27998   tree inner_expr;
27999 
28000   /* When checking, try to get a constant value for all non-dependent
28001      expressions in order to expose bugs in *_dependent_expression_p
28002      and constexpr.  This can affect code generation, see PR70704, so
28003      only do this for -fchecking=2.  */
28004   if (flag_checking > 1
28005       && cxx_dialect >= cxx11
28006       /* Don't do this during nsdmi parsing as it can lead to
28007 	 unexpected recursive instantiations.  */
28008       && !parsing_nsdmi ()
28009       /* Don't do this during concept processing either and for
28010          the same reason.  */
28011       && !processing_constraint_expression_p ())
28012     fold_non_dependent_expr (expr, tf_none);
28013 
28014   STRIP_ANY_LOCATION_WRAPPER (expr);
28015 
28016   /* Preserve OVERLOADs; the functions must be available to resolve
28017      types.  */
28018   inner_expr = expr;
28019   if (TREE_CODE (inner_expr) == STMT_EXPR)
28020     inner_expr = stmt_expr_value_expr (inner_expr);
28021   if (TREE_CODE (inner_expr) == ADDR_EXPR)
28022     inner_expr = TREE_OPERAND (inner_expr, 0);
28023   if (TREE_CODE (inner_expr) == COMPONENT_REF)
28024     inner_expr = TREE_OPERAND (inner_expr, 1);
28025   if (is_overloaded_fn (inner_expr)
28026       || TREE_CODE (inner_expr) == OFFSET_REF)
28027     return orig_expr;
28028   /* There is no need to return a proxy for a variable or enumerator.  */
28029   if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
28030     return orig_expr;
28031   /* Preserve string constants; conversions from string constants to
28032      "char *" are allowed, even though normally a "const char *"
28033      cannot be used to initialize a "char *".  */
28034   if (TREE_CODE (expr) == STRING_CST)
28035     return orig_expr;
28036   /* Preserve void and arithmetic constants, as an optimization -- there is no
28037      reason to create a new node.  */
28038   if (TREE_CODE (expr) == VOID_CST
28039       || TREE_CODE (expr) == INTEGER_CST
28040       || TREE_CODE (expr) == REAL_CST)
28041     return orig_expr;
28042   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
28043      There is at least one place where we want to know that a
28044      particular expression is a throw-expression: when checking a ?:
28045      expression, there are special rules if the second or third
28046      argument is a throw-expression.  */
28047   if (TREE_CODE (expr) == THROW_EXPR)
28048     return orig_expr;
28049 
28050   /* Don't wrap an initializer list, we need to be able to look inside.  */
28051   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
28052     return orig_expr;
28053 
28054   /* Don't wrap a dummy object, we need to be able to test for it.  */
28055   if (is_dummy_object (expr))
28056     return orig_expr;
28057 
28058   if (TREE_CODE (expr) == COND_EXPR)
28059     return build3 (COND_EXPR,
28060 		   TREE_TYPE (expr),
28061 		   build_non_dependent_expr (TREE_OPERAND (expr, 0)),
28062 		   (TREE_OPERAND (expr, 1)
28063 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
28064 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
28065 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
28066   if (TREE_CODE (expr) == COMPOUND_EXPR
28067       && !COMPOUND_EXPR_OVERLOADED (expr))
28068     return build2 (COMPOUND_EXPR,
28069 		   TREE_TYPE (expr),
28070 		   TREE_OPERAND (expr, 0),
28071 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
28072 
28073   /* If the type is unknown, it can't really be non-dependent */
28074   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
28075 
28076   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
28077   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
28078 		     TREE_TYPE (expr), expr);
28079 }
28080 
28081 /* ARGS is a vector of expressions as arguments to a function call.
28082    Replace the arguments with equivalent non-dependent expressions.
28083    This modifies ARGS in place.  */
28084 
28085 void
make_args_non_dependent(vec<tree,va_gc> * args)28086 make_args_non_dependent (vec<tree, va_gc> *args)
28087 {
28088   unsigned int ix;
28089   tree arg;
28090 
28091   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
28092     {
28093       tree newarg = build_non_dependent_expr (arg);
28094       if (newarg != arg)
28095 	(*args)[ix] = newarg;
28096     }
28097 }
28098 
28099 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
28100    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
28101    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
28102 
28103 static tree
make_auto_1(tree name,bool set_canonical)28104 make_auto_1 (tree name, bool set_canonical)
28105 {
28106   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28107   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28108   TYPE_STUB_DECL (au) = TYPE_NAME (au);
28109   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28110     (0, processing_template_decl + 1, processing_template_decl + 1,
28111      TYPE_NAME (au), NULL_TREE);
28112   if (set_canonical)
28113     TYPE_CANONICAL (au) = canonical_type_parameter (au);
28114   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28115   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28116   if (name == decltype_auto_identifier)
28117     AUTO_IS_DECLTYPE (au) = true;
28118 
28119   return au;
28120 }
28121 
28122 tree
make_decltype_auto(void)28123 make_decltype_auto (void)
28124 {
28125   return make_auto_1 (decltype_auto_identifier, true);
28126 }
28127 
28128 tree
make_auto(void)28129 make_auto (void)
28130 {
28131   return make_auto_1 (auto_identifier, true);
28132 }
28133 
28134 /* Return a C++17 deduction placeholder for class template TMPL.  */
28135 
28136 tree
make_template_placeholder(tree tmpl)28137 make_template_placeholder (tree tmpl)
28138 {
28139   tree t = make_auto_1 (auto_identifier, false);
28140   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
28141   /* Our canonical type depends on the placeholder.  */
28142   TYPE_CANONICAL (t) = canonical_type_parameter (t);
28143   return t;
28144 }
28145 
28146 /* True iff T is a C++17 class template deduction placeholder.  */
28147 
28148 bool
template_placeholder_p(tree t)28149 template_placeholder_p (tree t)
28150 {
28151   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
28152 }
28153 
28154 /* Make a "constrained auto" type-specifier. This is an auto or
28155   decltype(auto) type with constraints that must be associated after
28156   deduction.  The constraint is formed from the given concept CON
28157   and its optional sequence of template arguments ARGS.
28158 
28159   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28160 
28161 static tree
make_constrained_placeholder_type(tree type,tree con,tree args)28162 make_constrained_placeholder_type (tree type, tree con, tree args)
28163 {
28164   /* Build the constraint. */
28165   tree tmpl = DECL_TI_TEMPLATE (con);
28166   tree expr = tmpl;
28167   if (TREE_CODE (con) == FUNCTION_DECL)
28168     expr = ovl_make (tmpl);
28169   ++processing_template_decl;
28170   expr = build_concept_check (expr, type, args, tf_warning_or_error);
28171   --processing_template_decl;
28172 
28173   PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
28174     = build_tree_list (current_template_parms, expr);
28175 
28176   /* Our canonical type depends on the constraint.  */
28177   TYPE_CANONICAL (type) = canonical_type_parameter (type);
28178 
28179   /* Attach the constraint to the type declaration. */
28180   return TYPE_NAME (type);
28181 }
28182 
28183 /* Make a "constrained auto" type-specifier.  */
28184 
28185 tree
make_constrained_auto(tree con,tree args)28186 make_constrained_auto (tree con, tree args)
28187 {
28188   tree type = make_auto_1 (auto_identifier, false);
28189   return make_constrained_placeholder_type (type, con, args);
28190 }
28191 
28192 /* Make a "constrained decltype(auto)" type-specifier.  */
28193 
28194 tree
make_constrained_decltype_auto(tree con,tree args)28195 make_constrained_decltype_auto (tree con, tree args)
28196 {
28197   tree type = make_auto_1 (decltype_auto_identifier, false);
28198   return make_constrained_placeholder_type (type, con, args);
28199 }
28200 
28201 /* Returns true if the placeholder type constraint T has any dependent
28202    (explicit) template arguments.  */
28203 
28204 static bool
placeholder_type_constraint_dependent_p(tree t)28205 placeholder_type_constraint_dependent_p (tree t)
28206 {
28207   tree id = unpack_concept_check (t);
28208   tree args = TREE_OPERAND (id, 1);
28209   tree first = TREE_VEC_ELT (args, 0);
28210   if (ARGUMENT_PACK_P (first))
28211     {
28212       args = expand_template_argument_pack (args);
28213       first = TREE_VEC_ELT (args, 0);
28214     }
28215   gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
28216 		       || is_auto (first));
28217   for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
28218     if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
28219       return true;
28220   return false;
28221 }
28222 
28223 /* Build and return a concept definition. Like other templates, the
28224    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
28225    the TEMPLATE_DECL. */
28226 
28227 tree
finish_concept_definition(cp_expr id,tree init)28228 finish_concept_definition (cp_expr id, tree init)
28229 {
28230   gcc_assert (identifier_p (id));
28231   gcc_assert (processing_template_decl);
28232 
28233   location_t loc = id.get_location();
28234 
28235   /* A concept-definition shall not have associated constraints.  */
28236   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
28237     {
28238       error_at (loc, "a concept cannot be constrained");
28239       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
28240     }
28241 
28242   /* A concept-definition shall appear in namespace scope.  Templates
28243      aren't allowed in block scope, so we only need to check for class
28244      scope.  */
28245   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
28246     {
28247       error_at (loc, "concept %qE not in namespace scope", *id);
28248       return error_mark_node;
28249     }
28250 
28251   /* Initially build the concept declaration; its type is bool.  */
28252   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
28253   DECL_CONTEXT (decl) = current_scope ();
28254   DECL_INITIAL (decl) = init;
28255 
28256   set_originating_module (decl, false);
28257 
28258   /* Push the enclosing template.  */
28259   return push_template_decl (decl);
28260 }
28261 
28262 /* Given type ARG, return std::initializer_list<ARG>.  */
28263 
28264 static tree
listify(tree arg)28265 listify (tree arg)
28266 {
28267   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
28268 
28269   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
28270     {
28271       gcc_rich_location richloc (input_location);
28272       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
28273       error_at (&richloc,
28274 		"deducing from brace-enclosed initializer list"
28275 		" requires %<#include <initializer_list>%>");
28276 
28277       return error_mark_node;
28278     }
28279   tree argvec = make_tree_vec (1);
28280   TREE_VEC_ELT (argvec, 0) = arg;
28281 
28282   return lookup_template_class (std_init_list, argvec, NULL_TREE,
28283 				NULL_TREE, 0, tf_warning_or_error);
28284 }
28285 
28286 /* Replace auto in TYPE with std::initializer_list<auto>.  */
28287 
28288 static tree
listify_autos(tree type,tree auto_node)28289 listify_autos (tree type, tree auto_node)
28290 {
28291   tree init_auto = listify (strip_top_quals (auto_node));
28292   tree argvec = make_tree_vec (1);
28293   TREE_VEC_ELT (argvec, 0) = init_auto;
28294   if (processing_template_decl)
28295     argvec = add_to_template_args (current_template_args (), argvec);
28296   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
28297 }
28298 
28299 /* Hash traits for hashing possibly constrained 'auto'
28300    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
28301 
28302 struct auto_hash : default_hash_traits<tree>
28303 {
28304   static inline hashval_t hash (tree);
28305   static inline bool equal (tree, tree);
28306 };
28307 
28308 /* Hash the 'auto' T.  */
28309 
28310 inline hashval_t
hash(tree t)28311 auto_hash::hash (tree t)
28312 {
28313   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
28314     /* Matching constrained-type-specifiers denote the same template
28315        parameter, so hash the constraint.  */
28316     return hash_placeholder_constraint (c);
28317   else
28318     /* But unconstrained autos are all separate, so just hash the pointer.  */
28319     return iterative_hash_object (t, 0);
28320 }
28321 
28322 /* Compare two 'auto's.  */
28323 
28324 inline bool
equal(tree t1,tree t2)28325 auto_hash::equal (tree t1, tree t2)
28326 {
28327   if (t1 == t2)
28328     return true;
28329 
28330   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
28331   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
28332 
28333   /* Two unconstrained autos are distinct.  */
28334   if (!c1 || !c2)
28335     return false;
28336 
28337   return equivalent_placeholder_constraints (c1, c2);
28338 }
28339 
28340 /* for_each_template_parm callback for extract_autos: if t is a (possibly
28341    constrained) auto, add it to the vector.  */
28342 
28343 static int
extract_autos_r(tree t,void * data)28344 extract_autos_r (tree t, void *data)
28345 {
28346   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
28347   if (is_auto (t))
28348     {
28349       /* All the autos were built with index 0; fix that up now.  */
28350       tree *p = hash.find_slot (t, INSERT);
28351       unsigned idx;
28352       if (*p)
28353 	/* If this is a repeated constrained-type-specifier, use the index we
28354 	   chose before.  */
28355 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
28356       else
28357 	{
28358 	  /* Otherwise this is new, so use the current count.  */
28359 	  *p = t;
28360 	  idx = hash.elements () - 1;
28361 	}
28362       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
28363     }
28364 
28365   /* Always keep walking.  */
28366   return 0;
28367 }
28368 
28369 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
28370    says they can appear anywhere in the type.  */
28371 
28372 static tree
extract_autos(tree type)28373 extract_autos (tree type)
28374 {
28375   hash_set<tree> visited;
28376   hash_table<auto_hash> hash (2);
28377 
28378   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
28379 
28380   tree tree_vec = make_tree_vec (hash.elements());
28381   for (hash_table<auto_hash>::iterator iter = hash.begin();
28382        iter != hash.end(); ++iter)
28383     {
28384       tree elt = *iter;
28385       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
28386       TREE_VEC_ELT (tree_vec, i)
28387 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
28388     }
28389 
28390   return tree_vec;
28391 }
28392 
28393 /* The stem for deduction guide names.  */
28394 const char *const dguide_base = "__dguide_";
28395 
28396 /* Return the name for a deduction guide for class template TMPL.  */
28397 
28398 tree
dguide_name(tree tmpl)28399 dguide_name (tree tmpl)
28400 {
28401   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
28402   tree tname = TYPE_IDENTIFIER (type);
28403   char *buf = (char *) alloca (1 + strlen (dguide_base)
28404 			       + IDENTIFIER_LENGTH (tname));
28405   memcpy (buf, dguide_base, strlen (dguide_base));
28406   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
28407 	  IDENTIFIER_LENGTH (tname) + 1);
28408   tree dname = get_identifier (buf);
28409   TREE_TYPE (dname) = type;
28410   return dname;
28411 }
28412 
28413 /* True if NAME is the name of a deduction guide.  */
28414 
28415 bool
dguide_name_p(tree name)28416 dguide_name_p (tree name)
28417 {
28418   return (TREE_CODE (name) == IDENTIFIER_NODE
28419 	  && TREE_TYPE (name)
28420 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
28421 		       strlen (dguide_base)));
28422 }
28423 
28424 /* True if FN is a deduction guide.  */
28425 
28426 bool
deduction_guide_p(const_tree fn)28427 deduction_guide_p (const_tree fn)
28428 {
28429   if (DECL_P (fn))
28430     if (tree name = DECL_NAME (fn))
28431       return dguide_name_p (name);
28432   return false;
28433 }
28434 
28435 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
28436 
28437 bool
copy_guide_p(const_tree fn)28438 copy_guide_p (const_tree fn)
28439 {
28440   gcc_assert (deduction_guide_p (fn));
28441   if (!DECL_ARTIFICIAL (fn))
28442     return false;
28443   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
28444   return (TREE_CHAIN (parms) == void_list_node
28445 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
28446 }
28447 
28448 /* True if FN is a guide generated from a constructor template.  */
28449 
28450 bool
template_guide_p(const_tree fn)28451 template_guide_p (const_tree fn)
28452 {
28453   gcc_assert (deduction_guide_p (fn));
28454   if (!DECL_ARTIFICIAL (fn))
28455     return false;
28456   tree tmpl = DECL_TI_TEMPLATE (fn);
28457   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
28458     return PRIMARY_TEMPLATE_P (org);
28459   return false;
28460 }
28461 
28462 /* True if FN is an aggregate initialization guide or the copy deduction
28463    guide.  */
28464 
28465 bool
builtin_guide_p(const_tree fn)28466 builtin_guide_p (const_tree fn)
28467 {
28468   if (!deduction_guide_p (fn))
28469     return false;
28470   if (!DECL_ARTIFICIAL (fn))
28471     /* Explicitly declared.  */
28472     return false;
28473   if (DECL_ABSTRACT_ORIGIN (fn))
28474     /* Derived from a constructor.  */
28475     return false;
28476   return true;
28477 }
28478 
28479 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
28480    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
28481    template parameter types.  Note that the handling of template template
28482    parameters relies on current_template_parms being set appropriately for the
28483    new template.  */
28484 
28485 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)28486 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
28487 		       tree tsubst_args, tsubst_flags_t complain)
28488 {
28489   if (olddecl == error_mark_node)
28490     return error_mark_node;
28491 
28492   tree oldidx = get_template_parm_index (olddecl);
28493 
28494   tree newtype;
28495   if (TREE_CODE (olddecl) == TYPE_DECL
28496       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28497     {
28498       tree oldtype = TREE_TYPE (olddecl);
28499       newtype = cxx_make_type (TREE_CODE (oldtype));
28500       TYPE_MAIN_VARIANT (newtype) = newtype;
28501       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
28502 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
28503 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
28504     }
28505   else
28506     {
28507       newtype = TREE_TYPE (olddecl);
28508       if (type_uses_auto (newtype))
28509 	{
28510 	  // Substitute once to fix references to other template parameters.
28511 	  newtype = tsubst (newtype, tsubst_args,
28512 			    complain|tf_partial, NULL_TREE);
28513 	  // Now substitute again to reduce the level of the auto.
28514 	  newtype = tsubst (newtype, current_template_args (),
28515 			    complain, NULL_TREE);
28516 	}
28517       else
28518 	newtype = tsubst (newtype, tsubst_args,
28519 			  complain, NULL_TREE);
28520     }
28521 
28522   tree newdecl
28523     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
28524 		  DECL_NAME (olddecl), newtype);
28525   SET_DECL_TEMPLATE_PARM_P (newdecl);
28526 
28527   tree newidx;
28528   if (TREE_CODE (olddecl) == TYPE_DECL
28529       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28530     {
28531       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
28532 	= build_template_parm_index (index, level, level,
28533 				     newdecl, newtype);
28534       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28535 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28536       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
28537       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
28538 	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
28539       else
28540 	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
28541 
28542       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
28543 	{
28544 	  DECL_TEMPLATE_RESULT (newdecl)
28545 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
28546 			  DECL_NAME (olddecl), newtype);
28547 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
28548 	  // First create a copy (ttargs) of tsubst_args with an
28549 	  // additional level for the template template parameter's own
28550 	  // template parameters (ttparms).
28551 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
28552 			  (DECL_TEMPLATE_PARMS (olddecl)));
28553 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
28554 	  tree ttargs = make_tree_vec (depth + 1);
28555 	  for (int i = 0; i < depth; ++i)
28556 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
28557 	  TREE_VEC_ELT (ttargs, depth)
28558 	    = template_parms_level_to_args (ttparms);
28559 	  // Substitute ttargs into ttparms to fix references to
28560 	  // other template parameters.
28561 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28562 						 complain|tf_partial);
28563 	  // Now substitute again with args based on tparms, to reduce
28564 	  // the level of the ttparms.
28565 	  ttargs = current_template_args ();
28566 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28567 						 complain);
28568 	  // Finally, tack the adjusted parms onto tparms.
28569 	  ttparms = tree_cons (size_int (depth), ttparms,
28570 			       current_template_parms);
28571 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
28572 	}
28573     }
28574   else
28575     {
28576       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
28577       tree newconst
28578 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
28579 		      TREE_CODE (oldconst),
28580 		      DECL_NAME (oldconst), newtype);
28581       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
28582 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
28583       SET_DECL_TEMPLATE_PARM_P (newconst);
28584       newidx = build_template_parm_index (index, level, level,
28585 					  newconst, newtype);
28586       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28587 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28588       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
28589     }
28590 
28591   return newdecl;
28592 }
28593 
28594 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
28595    template parameter.  */
28596 
28597 static tree
rewrite_tparm_list(tree oldelt,unsigned index,unsigned level,tree targs,unsigned targs_index,tsubst_flags_t complain)28598 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
28599 		    tree targs, unsigned targs_index, tsubst_flags_t complain)
28600 {
28601   tree olddecl = TREE_VALUE (oldelt);
28602   tree newdecl = rewrite_template_parm (olddecl, index, level,
28603 					targs, complain);
28604   if (newdecl == error_mark_node)
28605     return error_mark_node;
28606   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
28607 				     targs, complain, NULL_TREE);
28608   tree list = build_tree_list (newdef, newdecl);
28609   TEMPLATE_PARM_CONSTRAINTS (list)
28610     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
28611 			      targs, complain, NULL_TREE);
28612   int depth = TMPL_ARGS_DEPTH (targs);
28613   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
28614   return list;
28615 }
28616 
28617 /* Returns a C++17 class deduction guide template based on the constructor
28618    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
28619    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
28620    aggregate initialization guide.  OUTER_ARGS are the template arguments
28621    for the enclosing scope of the class.  */
28622 
28623 static tree
build_deduction_guide(tree type,tree ctor,tree outer_args,tsubst_flags_t complain)28624 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
28625 {
28626   tree tparms, targs, fparms, fargs, ci;
28627   bool memtmpl = false;
28628   bool explicit_p;
28629   location_t loc;
28630   tree fn_tmpl = NULL_TREE;
28631 
28632   if (outer_args)
28633     {
28634       ++processing_template_decl;
28635       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
28636       --processing_template_decl;
28637     }
28638 
28639   if (!DECL_DECLARES_FUNCTION_P (ctor))
28640     {
28641       if (TYPE_P (ctor))
28642 	{
28643 	  bool copy_p = TYPE_REF_P (ctor);
28644 	  if (copy_p)
28645 	    fparms = tree_cons (NULL_TREE, type, void_list_node);
28646 	  else
28647 	    fparms = void_list_node;
28648 	}
28649       else if (TREE_CODE (ctor) == TREE_LIST)
28650 	fparms = ctor;
28651       else
28652 	gcc_unreachable ();
28653 
28654       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
28655       tparms = DECL_TEMPLATE_PARMS (ctmpl);
28656       targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
28657       ci = NULL_TREE;
28658       fargs = NULL_TREE;
28659       loc = DECL_SOURCE_LOCATION (ctmpl);
28660       explicit_p = false;
28661     }
28662   else
28663     {
28664       ++processing_template_decl;
28665       bool ok = true;
28666 
28667       fn_tmpl
28668 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
28669 	   : DECL_TI_TEMPLATE (ctor));
28670       if (outer_args)
28671 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
28672       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
28673 
28674       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
28675       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
28676 	 fully specialized args for the enclosing class.  Strip those off, as
28677 	 the deduction guide won't have those template parameters.  */
28678       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
28679 						TMPL_PARMS_DEPTH (tparms));
28680       /* Discard the 'this' parameter.  */
28681       fparms = FUNCTION_ARG_CHAIN (ctor);
28682       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
28683       ci = get_constraints (ctor);
28684       loc = DECL_SOURCE_LOCATION (ctor);
28685       explicit_p = DECL_NONCONVERTING_P (ctor);
28686 
28687       if (PRIMARY_TEMPLATE_P (fn_tmpl))
28688 	{
28689 	  memtmpl = true;
28690 
28691 	  /* For a member template constructor, we need to flatten the two
28692 	     template parameter lists into one, and then adjust the function
28693 	     signature accordingly.  This gets...complicated.  */
28694 	  tree save_parms = current_template_parms;
28695 
28696 	  /* For a member template we should have two levels of parms/args, one
28697 	     for the class and one for the constructor.  We stripped
28698 	     specialized args for further enclosing classes above.  */
28699 	  const int depth = 2;
28700 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
28701 
28702 	  /* Template args for translating references to the two-level template
28703 	     parameters into references to the one-level template parameters we
28704 	     are creating.  */
28705 	  tree tsubst_args = copy_node (targs);
28706 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
28707 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
28708 
28709 	  /* Template parms for the constructor template.  */
28710 	  tree ftparms = TREE_VALUE (tparms);
28711 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
28712 	  /* Template parms for the class template.  */
28713 	  tparms = TREE_CHAIN (tparms);
28714 	  tree ctparms = TREE_VALUE (tparms);
28715 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
28716 	  /* Template parms for the deduction guide start as a copy of the
28717 	     template parms for the class.  We set current_template_parms for
28718 	     lookup_template_class_1.  */
28719 	  current_template_parms = tparms = copy_node (tparms);
28720 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
28721 	  for (unsigned i = 0; i < clen; ++i)
28722 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
28723 
28724 	  /* Now we need to rewrite the constructor parms to append them to the
28725 	     class parms.  */
28726 	  for (unsigned i = 0; i < flen; ++i)
28727 	    {
28728 	      unsigned index = i + clen;
28729 	      unsigned level = 1;
28730 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
28731 	      tree newelt
28732 		= rewrite_tparm_list (oldelt, index, level,
28733 				      tsubst_args, i, complain);
28734 	      if (newelt == error_mark_node)
28735 		ok = false;
28736 	      TREE_VEC_ELT (new_vec, index) = newelt;
28737 	    }
28738 
28739 	  /* Now we have a final set of template parms to substitute into the
28740 	     function signature.  */
28741 	  targs = template_parms_to_args (tparms);
28742 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
28743 				     complain, ctor);
28744 	  if (fparms == error_mark_node)
28745 	    ok = false;
28746 	  if (ci)
28747 	    {
28748 	      if (outer_args)
28749 		/* FIXME: We'd like to avoid substituting outer template
28750 		   arguments into the constraint ahead of time, but the
28751 		   construction of tsubst_args assumes that outer arguments
28752 		   are already substituted in.  */
28753 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
28754 	      ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
28755 	    }
28756 
28757 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
28758 	     cp_unevaluated_operand.  */
28759 	  cp_evaluated ev;
28760 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
28761 	  current_template_parms = save_parms;
28762 	}
28763       else
28764 	{
28765 	  /* Substitute in the same arguments to rewrite class members into
28766 	     references to members of an unknown specialization.  */
28767 	  cp_evaluated ev;
28768 	  fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
28769 	  fargs = tsubst (fargs, targs, complain, ctor);
28770 	  if (ci)
28771 	    {
28772 	      if (outer_args)
28773 		/* FIXME: As above.  */
28774 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
28775 	      ci = tsubst_constraint_info (ci, targs, complain, ctor);
28776 	    }
28777 	}
28778 
28779       --processing_template_decl;
28780       if (!ok)
28781 	return error_mark_node;
28782     }
28783 
28784   if (!memtmpl)
28785     {
28786       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
28787       tparms = copy_node (tparms);
28788       INNERMOST_TEMPLATE_PARMS (tparms)
28789 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
28790     }
28791 
28792   tree fntype = build_function_type (type, fparms);
28793   tree ded_fn = build_lang_decl_loc (loc,
28794 				     FUNCTION_DECL,
28795 				     dguide_name (type), fntype);
28796   DECL_ARGUMENTS (ded_fn) = fargs;
28797   DECL_ARTIFICIAL (ded_fn) = true;
28798   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
28799   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
28800   DECL_ARTIFICIAL (ded_tmpl) = true;
28801   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
28802   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
28803   if (DECL_P (ctor))
28804     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
28805   if (ci)
28806     set_constraints (ded_tmpl, ci);
28807 
28808   return ded_tmpl;
28809 }
28810 
28811 /* Add to LIST the member types for the reshaped initializer CTOR.  */
28812 
28813 static tree
28814 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
28815 {
28816   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
28817   tree idx, val; unsigned i;
FOR_EACH_CONSTRUCTOR_ELT(v,i,idx,val)28818   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
28819     {
28820       tree ftype = elt ? elt : TREE_TYPE (idx);
28821       if (BRACE_ENCLOSED_INITIALIZER_P (val)
28822 	  && CONSTRUCTOR_BRACES_ELIDED_P (val))
28823 	{
28824 	  tree subelt = NULL_TREE;
28825 	  if (TREE_CODE (ftype) == ARRAY_TYPE)
28826 	    subelt = TREE_TYPE (ftype);
28827 	  list = collect_ctor_idx_types (val, list, subelt);
28828 	  continue;
28829 	}
28830       tree arg = NULL_TREE;
28831       if (i == v->length() - 1
28832 	  && PACK_EXPANSION_P (ftype))
28833 	/* Give the trailing pack expansion parameter a default argument to
28834 	   match aggregate initialization behavior, even if we deduce the
28835 	   length of the pack separately to more than we have initializers. */
28836 	arg = build_constructor (init_list_type_node, NULL);
28837       /* if ei is of array type and xi is a braced-init-list or string literal,
28838 	 Ti is an rvalue reference to the declared type of ei */
28839       STRIP_ANY_LOCATION_WRAPPER (val);
28840       if (TREE_CODE (ftype) == ARRAY_TYPE
28841 	  && (BRACE_ENCLOSED_INITIALIZER_P (val)
28842 	      || TREE_CODE (val) == STRING_CST))
28843 	{
28844 	  if (TREE_CODE (val) == STRING_CST)
28845 	    ftype = cp_build_qualified_type
28846 	      (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
28847 	  ftype = (cp_build_reference_type
28848 		   (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
28849 	}
28850       list = tree_cons (arg, ftype, list);
28851     }
28852 
28853   return list;
28854 }
28855 
28856 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
28857 
28858 static bool
is_spec_or_derived(tree etype,tree tmpl)28859 is_spec_or_derived (tree etype, tree tmpl)
28860 {
28861   if (!etype || !CLASS_TYPE_P (etype))
28862     return false;
28863 
28864   etype = cv_unqualified (etype);
28865   tree type = TREE_TYPE (tmpl);
28866   tree tparms = (INNERMOST_TEMPLATE_PARMS
28867 		 (DECL_TEMPLATE_PARMS (tmpl)));
28868   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
28869   int err = unify (tparms, targs, type, etype,
28870 		   UNIFY_ALLOW_DERIVED, /*explain*/false);
28871   ggc_free (targs);
28872   return !err;
28873 }
28874 
28875 static tree alias_ctad_tweaks (tree, tree);
28876 
28877 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
28878    INIT.  */
28879 
28880 static tree
maybe_aggr_guide(tree tmpl,tree init,vec<tree,va_gc> * args)28881 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
28882 {
28883   if (cxx_dialect < cxx20)
28884     return NULL_TREE;
28885 
28886   if (init == NULL_TREE)
28887     return NULL_TREE;
28888 
28889   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28890     {
28891       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28892       tree tinfo = get_template_info (under);
28893       if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
28894 	return alias_ctad_tweaks (tmpl, guide);
28895       return NULL_TREE;
28896     }
28897 
28898   /* We might be creating a guide for a class member template, e.g.,
28899 
28900        template<typename U> struct A {
28901 	 template<typename T> struct B { T t; };
28902        };
28903 
28904      At this point, A will have been instantiated.  Below, we need to
28905      use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types.  */
28906   const bool member_template_p
28907     = (DECL_TEMPLATE_INFO (tmpl)
28908        && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
28909   tree type = TREE_TYPE (tmpl);
28910   tree template_type = (member_template_p
28911 			? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
28912 			: type);
28913   if (!CP_AGGREGATE_TYPE_P (template_type))
28914     return NULL_TREE;
28915 
28916   /* No aggregate candidate for copy-initialization.  */
28917   if (args->length() == 1)
28918     {
28919       tree val = (*args)[0];
28920       if (is_spec_or_derived (TREE_TYPE (val), tmpl))
28921 	return NULL_TREE;
28922     }
28923 
28924   /* If we encounter a problem, we just won't add the candidate.  */
28925   tsubst_flags_t complain = tf_none;
28926 
28927   tree parms = NULL_TREE;
28928   if (BRACE_ENCLOSED_INITIALIZER_P (init))
28929     {
28930       init = reshape_init (template_type, init, complain);
28931       if (init == error_mark_node)
28932 	return NULL_TREE;
28933       parms = collect_ctor_idx_types (init, parms);
28934       /* If we're creating a deduction guide for a member class template,
28935 	 we've used the original template pattern type for the reshape_init
28936 	 above; this is done because we want PARMS to be a template parameter
28937 	 type, something that can be deduced when used as a function template
28938 	 parameter.  At this point the outer class template has already been
28939 	 partially instantiated (we deferred the deduction until the enclosing
28940 	 scope is non-dependent).  Therefore we have to partially instantiate
28941 	 PARMS, so that its template level is properly reduced and we don't get
28942 	 mismatches when deducing types using the guide with PARMS.  */
28943       if (member_template_p)
28944 	parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
28945     }
28946   else if (TREE_CODE (init) == TREE_LIST)
28947     {
28948       int len = list_length (init);
28949       for (tree field = TYPE_FIELDS (type);
28950 	   len;
28951 	   --len, field = DECL_CHAIN (field))
28952 	{
28953 	  field = next_initializable_field (field);
28954 	  if (!field)
28955 	    return NULL_TREE;
28956 	  tree ftype = finish_decltype_type (field, true, complain);
28957 	  parms = tree_cons (NULL_TREE, ftype, parms);
28958 	}
28959     }
28960   else
28961     /* Aggregate initialization doesn't apply to an initializer expression.  */
28962     return NULL_TREE;
28963 
28964   if (parms)
28965     {
28966       tree last = parms;
28967       parms = nreverse (parms);
28968       TREE_CHAIN (last) = void_list_node;
28969       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
28970       return guide;
28971     }
28972 
28973   return NULL_TREE;
28974 }
28975 
28976 /* UGUIDES are the deduction guides for the underlying template of alias
28977    template TMPL; adjust them to be deduction guides for TMPL.  */
28978 
28979 static tree
alias_ctad_tweaks(tree tmpl,tree uguides)28980 alias_ctad_tweaks (tree tmpl, tree uguides)
28981 {
28982   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
28983      class type (9.2.8.2) where the template-name names an alias template A,
28984      the defining-type-id of A must be of the form
28985 
28986      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28987 
28988      as specified in 9.2.8.2. The guides of A are the set of functions or
28989      function templates formed as follows. For each function or function
28990      template f in the guides of the template named by the simple-template-id
28991      of the defining-type-id, the template arguments of the return type of f
28992      are deduced from the defining-type-id of A according to the process in
28993      13.10.2.5 with the exception that deduction does not fail if not all
28994      template arguments are deduced. Let g denote the result of substituting
28995      these deductions into f. If substitution succeeds, form a function or
28996      function template f' with the following properties and add it to the set
28997      of guides of A:
28998 
28999      * The function type of f' is the function type of g.
29000 
29001      * If f is a function template, f' is a function template whose template
29002      parameter list consists of all the template parameters of A (including
29003      their default template arguments) that appear in the above deductions or
29004      (recursively) in their default template arguments, followed by the
29005      template parameters of f that were not deduced (including their default
29006      template arguments), otherwise f' is not a function template.
29007 
29008      * The associated constraints (13.5.2) are the conjunction of the
29009      associated constraints of g and a constraint that is satisfied if and only
29010      if the arguments of A are deducible (see below) from the return type.
29011 
29012      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29013      be so as well.
29014 
29015      * If f was generated from a deduction-guide (12.4.1.8), then f' is
29016      considered to be so as well.
29017 
29018      * The explicit-specifier of f' is the explicit-specifier of g (if
29019      any).  */
29020 
29021   /* This implementation differs from the above in two significant ways:
29022 
29023      1) We include all template parameters of A, not just some.
29024      2) The added constraint is same_type instead of deducible.
29025 
29026      I believe that while it's probably possible to construct a testcase that
29027      behaves differently with this simplification, it should have the same
29028      effect for real uses.  Including all template parameters means that we
29029      deduce all parameters of A when resolving the call, so when we're in the
29030      constraint we don't need to deduce them again, we can just check whether
29031      the deduction produced the desired result.  */
29032 
29033   tsubst_flags_t complain = tf_warning_or_error;
29034   tree atype = TREE_TYPE (tmpl);
29035   tree aguides = NULL_TREE;
29036   tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
29037   unsigned natparms = TREE_VEC_LENGTH (atparms);
29038   tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29039   for (ovl_iterator iter (uguides); iter; ++iter)
29040     {
29041       tree f = *iter;
29042       tree in_decl = f;
29043       location_t loc = DECL_SOURCE_LOCATION (f);
29044       tree ret = TREE_TYPE (TREE_TYPE (f));
29045       tree fprime = f;
29046       if (TREE_CODE (f) == TEMPLATE_DECL)
29047 	{
29048 	  processing_template_decl_sentinel ptds (/*reset*/false);
29049 	  ++processing_template_decl;
29050 
29051 	  /* Deduce template arguments for f from the type-id of A.  */
29052 	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29053 	  unsigned len = TREE_VEC_LENGTH (ftparms);
29054 	  tree targs = make_tree_vec (len);
29055 	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29056 	  if (err)
29057 	    continue;
29058 
29059 	  /* The number of parms for f' is the number of parms for A plus
29060 	     non-deduced parms of f.  */
29061 	  unsigned ndlen = 0;
29062 	  unsigned j;
29063 	  for (unsigned i = 0; i < len; ++i)
29064 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29065 	      ++ndlen;
29066 	  tree gtparms = make_tree_vec (natparms + ndlen);
29067 
29068 	  /* First copy over the parms of A.  */
29069 	  for (j = 0; j < natparms; ++j)
29070 	    TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
29071 	  /* Now rewrite the non-deduced parms of f.  */
29072 	  for (unsigned i = 0; ndlen && i < len; ++i)
29073 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29074 	      {
29075 		--ndlen;
29076 		unsigned index = j++;
29077 		unsigned level = 1;
29078 		tree oldlist = TREE_VEC_ELT (ftparms, i);
29079 		tree list = rewrite_tparm_list (oldlist, index, level,
29080 						targs, i, complain);
29081 		TREE_VEC_ELT (gtparms, index) = list;
29082 	      }
29083 	  gtparms = build_tree_list (size_one_node, gtparms);
29084 
29085 	  /* Substitute the deduced arguments plus the rewritten template
29086 	     parameters into f to get g.  This covers the type, copyness,
29087 	     guideness, and explicit-specifier.  */
29088 	  tree g;
29089 	    {
29090 	      /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
29091 		 if cp_unevaluated_operand.  */
29092 	      cp_evaluated ev;
29093 	      g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29094 	    }
29095 	  if (g == error_mark_node)
29096 	    continue;
29097 	  DECL_USE_TEMPLATE (g) = 0;
29098 	  fprime = build_template_decl (g, gtparms, false);
29099 	  DECL_TEMPLATE_RESULT (fprime) = g;
29100 	  TREE_TYPE (fprime) = TREE_TYPE (g);
29101 	  tree gtargs = template_parms_to_args (gtparms);
29102 	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
29103 	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
29104 
29105 	  /* Substitute the associated constraints.  */
29106 	  tree ci = get_constraints (f);
29107 	  if (ci)
29108 	    ci = tsubst_constraint_info (ci, targs, complain, in_decl);
29109 	  if (ci == error_mark_node)
29110 	    continue;
29111 
29112 	  /* Add a constraint that the return type matches the instantiation of
29113 	     A with the same template arguments.  */
29114 	  ret = TREE_TYPE (TREE_TYPE (fprime));
29115 	  if (!same_type_p (atype, ret)
29116 	      /* FIXME this should mean they don't compare as equivalent.  */
29117 	      || dependent_alias_template_spec_p (atype, nt_opaque))
29118 	    {
29119 	      tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
29120 	      ci = append_constraint (ci, same);
29121 	    }
29122 
29123 	  if (ci)
29124 	    {
29125 	      remove_constraints (fprime);
29126 	      set_constraints (fprime, ci);
29127 	    }
29128 	}
29129       else
29130 	{
29131 	  /* For a non-template deduction guide, if the arguments of A aren't
29132 	     deducible from the return type, don't add the candidate.  */
29133 	  tree targs = make_tree_vec (natparms);
29134 	  int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
29135 	  for (unsigned i = 0; !err && i < natparms; ++i)
29136 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29137 	      err = true;
29138 	  if (err)
29139 	    continue;
29140 	}
29141 
29142       aguides = lookup_add (fprime, aguides);
29143     }
29144 
29145   return aguides;
29146 }
29147 
29148 /* Return artificial deduction guides built from the constructors of class
29149    template TMPL.  */
29150 
29151 static tree
ctor_deduction_guides_for(tree tmpl,tsubst_flags_t complain)29152 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
29153 {
29154   tree type = TREE_TYPE (tmpl);
29155   tree outer_args = NULL_TREE;
29156   if (DECL_CLASS_SCOPE_P (tmpl)
29157       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
29158     {
29159       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
29160       type = TREE_TYPE (most_general_template (tmpl));
29161     }
29162 
29163   tree cands = NULL_TREE;
29164 
29165   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
29166     {
29167       /* Skip inherited constructors.  */
29168       if (iter.using_p ())
29169 	continue;
29170 
29171       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
29172       cands = lookup_add (guide, cands);
29173     }
29174 
29175   /* Add implicit default constructor deduction guide.  */
29176   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
29177     {
29178       tree guide = build_deduction_guide (type, type, outer_args,
29179 					  complain);
29180       cands = lookup_add (guide, cands);
29181     }
29182 
29183   /* Add copy guide.  */
29184   {
29185     tree gtype = build_reference_type (type);
29186     tree guide = build_deduction_guide (type, gtype, outer_args,
29187 					complain);
29188     cands = lookup_add (guide, cands);
29189   }
29190 
29191   return cands;
29192 }
29193 
29194 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
29195 
29196 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
29197    aggregate candidate is added separately because it depends on the
29198    initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
29199    guide.  */
29200 
29201 static tree
deduction_guides_for(tree tmpl,bool & any_dguides_p,tsubst_flags_t complain)29202 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
29203 {
29204   tree guides = NULL_TREE;
29205   if (DECL_ALIAS_TEMPLATE_P (tmpl))
29206     {
29207       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29208       tree tinfo = get_template_info (under);
29209       guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
29210 				     complain);
29211     }
29212   else
29213     {
29214       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
29215 				      dguide_name (tmpl),
29216 				      LOOK_want::NORMAL, /*complain*/false);
29217       if (guides == error_mark_node)
29218 	guides = NULL_TREE;
29219       else
29220 	any_dguides_p = true;
29221     }
29222 
29223   /* Cache the deduction guides for a template.  We also remember the result of
29224      lookup, and rebuild everything if it changes; should be very rare.  */
29225   tree_pair_p cache = NULL;
29226   if (tree_pair_p &r
29227       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
29228     {
29229       cache = r;
29230       if (cache->purpose == guides)
29231 	return cache->value;
29232     }
29233   else
29234     {
29235       r = cache = ggc_cleared_alloc<tree_pair_s> ();
29236       cache->purpose = guides;
29237     }
29238 
29239   tree cands = NULL_TREE;
29240   if (DECL_ALIAS_TEMPLATE_P (tmpl))
29241     cands = alias_ctad_tweaks (tmpl, guides);
29242   else
29243     {
29244       cands = ctor_deduction_guides_for (tmpl, complain);
29245       for (ovl_iterator it (guides); it; ++it)
29246 	cands = lookup_add (*it, cands);
29247     }
29248 
29249   cache->value = cands;
29250   return cands;
29251 }
29252 
29253 /* Return whether TMPL is a (class template argument-) deducible template.  */
29254 
29255 bool
ctad_template_p(tree tmpl)29256 ctad_template_p (tree tmpl)
29257 {
29258   /* A deducible template is either a class template or is an alias template
29259      whose defining-type-id is of the form
29260 
29261       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29262 
29263      where the nested-name-specifier (if any) is non-dependent and the
29264      template-name of the simple-template-id names a deducible template.  */
29265 
29266   if (DECL_CLASS_TEMPLATE_P (tmpl)
29267       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
29268     return true;
29269   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
29270     return false;
29271   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29272   if (tree tinfo = get_template_info (orig))
29273     return ctad_template_p (TI_TEMPLATE (tinfo));
29274   return false;
29275 }
29276 
29277 /* Deduce template arguments for the class template placeholder PTYPE for
29278    template TMPL based on the initializer INIT, and return the resulting
29279    type.  */
29280 
29281 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)29282 do_class_deduction (tree ptype, tree tmpl, tree init,
29283 		    int flags, tsubst_flags_t complain)
29284 {
29285   /* We should have handled this in the caller.  */
29286   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
29287     return ptype;
29288 
29289   /* Wait until the enclosing scope is non-dependent.  */
29290   if (DECL_CLASS_SCOPE_P (tmpl)
29291       && dependent_type_p (DECL_CONTEXT (tmpl)))
29292     return ptype;
29293 
29294   /* Initializing one placeholder from another.  */
29295   if (init
29296       && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
29297 	  || (TREE_CODE (init) == EXPR_PACK_EXPANSION
29298 	      && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
29299 		  == TEMPLATE_PARM_INDEX)))
29300       && is_auto (TREE_TYPE (init))
29301       && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
29302     return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
29303 
29304   /* Look through alias templates that just rename another template.  */
29305   tmpl = get_underlying_template (tmpl);
29306   if (!ctad_template_p (tmpl))
29307     {
29308       if (complain & tf_error)
29309 	error ("non-deducible template %qT used without template arguments", tmpl);
29310       return error_mark_node;
29311     }
29312   else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
29313     {
29314       if (complain & tf_error)
29315 	error ("alias template deduction only available "
29316 	       "with %<-std=c++20%> or %<-std=gnu++20%>");
29317       return error_mark_node;
29318     }
29319 
29320   /* Wait until the initializer is non-dependent.  */
29321   if (type_dependent_expression_p (init))
29322     return ptype;
29323 
29324   tree type = TREE_TYPE (tmpl);
29325 
29326   bool try_list_ctor = false;
29327   bool list_init_p = false;
29328 
29329   releasing_vec rv_args = NULL;
29330   vec<tree,va_gc> *&args = *&rv_args;
29331   if (init == NULL_TREE)
29332     args = make_tree_vector ();
29333   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
29334     {
29335       list_init_p = true;
29336       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
29337       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
29338 	{
29339 	  /* As an exception, the first phase in 16.3.1.7 (considering the
29340 	     initializer list as a single argument) is omitted if the
29341 	     initializer list consists of a single expression of type cv U,
29342 	     where U is a specialization of C or a class derived from a
29343 	     specialization of C.  */
29344 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
29345 	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
29346 	    try_list_ctor = false;
29347 	}
29348       if (try_list_ctor || is_std_init_list (type))
29349 	args = make_tree_vector_single (init);
29350       else
29351 	args = make_tree_vector_from_ctor (init);
29352     }
29353   else if (TREE_CODE (init) == TREE_LIST)
29354     args = make_tree_vector_from_list (init);
29355   else
29356     args = make_tree_vector_single (init);
29357 
29358   /* Do this now to avoid problems with erroneous args later on.  */
29359   args = resolve_args (args, complain);
29360   if (args == NULL)
29361     return error_mark_node;
29362 
29363   bool any_dguides_p = false;
29364   tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
29365   if (cands == error_mark_node)
29366     return error_mark_node;
29367 
29368   /* Prune explicit deduction guides in copy-initialization context (but
29369      not copy-list-initialization).  */
29370   bool elided = false;
29371   if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
29372     {
29373       for (lkp_iterator iter (cands); !elided && iter; ++iter)
29374 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29375 	  elided = true;
29376 
29377       if (elided)
29378 	{
29379 	  /* Found a nonconverting guide, prune the candidates.  */
29380 	  tree pruned = NULL_TREE;
29381 	  for (lkp_iterator iter (cands); iter; ++iter)
29382 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29383 	      pruned = lookup_add (*iter, pruned);
29384 
29385 	  cands = pruned;
29386 	}
29387     }
29388 
29389   if (!any_dguides_p)
29390     if (tree guide = maybe_aggr_guide (tmpl, init, args))
29391       cands = lookup_add (guide, cands);
29392 
29393   tree call = error_mark_node;
29394 
29395   /* If this is list-initialization and the class has a list constructor, first
29396      try deducing from the list as a single argument, as [over.match.list].  */
29397   tree list_cands = NULL_TREE;
29398   if (try_list_ctor && cands)
29399     for (lkp_iterator iter (cands); iter; ++iter)
29400       {
29401 	tree dg = *iter;
29402 	if (is_list_ctor (dg))
29403 	  list_cands = lookup_add (dg, list_cands);
29404       }
29405   if (list_cands)
29406     {
29407       ++cp_unevaluated_operand;
29408       call = build_new_function_call (list_cands, &args, tf_decltype);
29409       --cp_unevaluated_operand;
29410 
29411       if (call == error_mark_node)
29412 	{
29413 	  /* That didn't work, now try treating the list as a sequence of
29414 	     arguments.  */
29415 	  release_tree_vector (args);
29416 	  args = make_tree_vector_from_ctor (init);
29417 	}
29418     }
29419 
29420   if (elided && !cands)
29421     {
29422       error ("cannot deduce template arguments for copy-initialization"
29423 	     " of %qT, as it has no non-explicit deduction guides or "
29424 	     "user-declared constructors", type);
29425       return error_mark_node;
29426     }
29427   else if (!cands && call == error_mark_node)
29428     {
29429       error ("cannot deduce template arguments of %qT, as it has no viable "
29430 	     "deduction guides", type);
29431       return error_mark_node;
29432     }
29433 
29434   if (call == error_mark_node)
29435     {
29436       ++cp_unevaluated_operand;
29437       call = build_new_function_call (cands, &args, tf_decltype);
29438       --cp_unevaluated_operand;
29439     }
29440 
29441   if (call == error_mark_node)
29442     {
29443       if (complain & tf_warning_or_error)
29444 	{
29445 	  error ("class template argument deduction failed:");
29446 
29447 	  ++cp_unevaluated_operand;
29448 	  call = build_new_function_call (cands, &args,
29449 					  complain | tf_decltype);
29450 	  --cp_unevaluated_operand;
29451 
29452 	  if (elided)
29453 	    inform (input_location, "explicit deduction guides not considered "
29454 		    "for copy-initialization");
29455 	}
29456       return error_mark_node;
29457     }
29458   /* [over.match.list]/1: In copy-list-initialization, if an explicit
29459      constructor is chosen, the initialization is ill-formed.  */
29460   else if (flags & LOOKUP_ONLYCONVERTING)
29461     {
29462       tree fndecl = cp_get_callee_fndecl_nofold (call);
29463       if (fndecl && DECL_NONCONVERTING_P (fndecl))
29464 	{
29465 	  if (complain & tf_warning_or_error)
29466 	    {
29467 	      // TODO: Pass down location from cp_finish_decl.
29468 	      error ("class template argument deduction for %qT failed: "
29469 		     "explicit deduction guide selected in "
29470 		     "copy-list-initialization", type);
29471 	      inform (DECL_SOURCE_LOCATION (fndecl),
29472 		      "explicit deduction guide declared here");
29473 
29474 	    }
29475 	  return error_mark_node;
29476 	}
29477     }
29478 
29479   /* If CTAD succeeded but the type doesn't have any explicit deduction
29480      guides, this deduction might not be what the user intended.  */
29481   if (call != error_mark_node && !any_dguides_p)
29482     {
29483       tree fndecl = cp_get_callee_fndecl_nofold (call);
29484       if (fndecl != NULL_TREE
29485 	  && (!DECL_IN_SYSTEM_HEADER (fndecl)
29486 	      || global_dc->dc_warn_system_headers)
29487 	  && warning (OPT_Wctad_maybe_unsupported,
29488 		      "%qT may not intend to support class template argument "
29489 		      "deduction", type))
29490 	inform (input_location, "add a deduction guide to suppress this "
29491 		"warning");
29492     }
29493 
29494   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
29495 }
29496 
29497 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
29498    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
29499    The CONTEXT determines the context in which auto deduction is performed
29500    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
29501 
29502    OUTER_TARGS is used during template argument deduction (context == adc_unify)
29503    to properly substitute the result.  It's also used in the adc_unify and
29504    adc_requirement contexts to communicate the the necessary template arguments
29505    to satisfaction.  OUTER_TARGS is ignored in other contexts.
29506 
29507    For partial-concept-ids, extra args may be appended to the list of deduced
29508    template arguments prior to determining constraint satisfaction.  */
29509 
29510 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)29511 do_auto_deduction (tree type, tree init, tree auto_node,
29512                    tsubst_flags_t complain, auto_deduction_context context,
29513 		   tree outer_targs, int flags)
29514 {
29515   if (init == error_mark_node)
29516     return error_mark_node;
29517 
29518   if (init && type_dependent_expression_p (init)
29519       && context != adc_unify)
29520     /* Defining a subset of type-dependent expressions that we can deduce
29521        from ahead of time isn't worth the trouble.  */
29522     return type;
29523 
29524   /* Similarly, we can't deduce from another undeduced decl.  */
29525   if (init && undeduced_auto_decl (init))
29526     return type;
29527 
29528   /* We may be doing a partial substitution, but we still want to replace
29529      auto_node.  */
29530   complain &= ~tf_partial;
29531 
29532   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
29533     /* C++17 class template argument deduction.  */
29534     return do_class_deduction (type, tmpl, init, flags, complain);
29535 
29536   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
29537     /* Nothing we can do with this, even in deduction context.  */
29538     return type;
29539 
29540   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
29541      with either a new invented type template parameter U or, if the
29542      initializer is a braced-init-list (8.5.4), with
29543      std::initializer_list<U>.  */
29544   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29545     {
29546       if (!DIRECT_LIST_INIT_P (init))
29547 	type = listify_autos (type, auto_node);
29548       else if (CONSTRUCTOR_NELTS (init) == 1)
29549 	init = CONSTRUCTOR_ELT (init, 0)->value;
29550       else
29551 	{
29552           if (complain & tf_warning_or_error)
29553             {
29554 	      if (permerror (input_location, "direct-list-initialization of "
29555 			     "%<auto%> requires exactly one element"))
29556 	        inform (input_location,
29557 		        "for deduction to %<std::initializer_list%>, use copy-"
29558 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
29559             }
29560 	  type = listify_autos (type, auto_node);
29561 	}
29562     }
29563 
29564   if (type == error_mark_node)
29565     return error_mark_node;
29566 
29567   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29568     {
29569       /* We don't recurse here because we can't deduce from a nested
29570 	 initializer_list.  */
29571       if (CONSTRUCTOR_ELTS (init))
29572 	for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
29573 	  elt.value = resolve_nondeduced_context (elt.value, complain);
29574     }
29575   else
29576     init = resolve_nondeduced_context (init, complain);
29577 
29578   tree targs;
29579   if (context == adc_decomp_type
29580       && auto_node == type
29581       && init != error_mark_node
29582       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
29583     {
29584       /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
29585 	 and initializer has array type, deduce cv-qualified array type.  */
29586       targs = make_tree_vec (1);
29587       TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
29588     }
29589   else if (AUTO_IS_DECLTYPE (auto_node))
29590     {
29591       tree stripped_init = tree_strip_any_location_wrapper (init);
29592       if (REFERENCE_REF_P (stripped_init))
29593 	stripped_init = TREE_OPERAND (stripped_init, 0);
29594       bool id = (DECL_P (stripped_init)
29595 		 || ((TREE_CODE (init) == COMPONENT_REF
29596 		      || TREE_CODE (init) == SCOPE_REF)
29597 		     && !REF_PARENTHESIZED_P (init)));
29598       tree deduced = finish_decltype_type (init, id, complain);
29599       deduced = canonicalize_type_argument (deduced, complain);
29600       if (deduced == error_mark_node)
29601 	return error_mark_node;
29602       targs = make_tree_vec (1);
29603       TREE_VEC_ELT (targs, 0) = deduced;
29604       /* FIXME: These errors ought to be diagnosed at parse time. */
29605       if (type != auto_node)
29606 	{
29607           if (complain & tf_error)
29608 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
29609 	  return error_mark_node;
29610 	}
29611       else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
29612 	{
29613 	  if (complain & tf_error)
29614 	    error ("%<decltype(auto)%> cannot be cv-qualified");
29615 	  return error_mark_node;
29616 	}
29617     }
29618   else
29619     {
29620       if (error_operand_p (init))
29621 	return error_mark_node;
29622 
29623       tree parms = build_tree_list (NULL_TREE, type);
29624       tree tparms;
29625 
29626       if (flag_concepts)
29627 	tparms = extract_autos (type);
29628       else
29629 	{
29630 	  tparms = make_tree_vec (1);
29631 	  TREE_VEC_ELT (tparms, 0)
29632 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
29633 	}
29634 
29635       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29636       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
29637 				       DEDUCE_CALL,
29638 				       NULL, /*explain_p=*/false);
29639       if (val > 0)
29640 	{
29641 	  if (processing_template_decl)
29642 	    /* Try again at instantiation time.  */
29643 	    return type;
29644 	  if (type && type != error_mark_node
29645 	      && (complain & tf_error))
29646 	    /* If type is error_mark_node a diagnostic must have been
29647 	       emitted by now.  Also, having a mention to '<type error>'
29648 	       in the diagnostic is not really useful to the user.  */
29649 	    {
29650 	      if (cfun
29651 		  && FNDECL_USED_AUTO (current_function_decl)
29652 		  && (auto_node
29653 		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
29654 		  && LAMBDA_FUNCTION_P (current_function_decl))
29655 		error ("unable to deduce lambda return type from %qE", init);
29656 	      else
29657 		error ("unable to deduce %qT from %qE", type, init);
29658 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
29659 				     DEDUCE_CALL,
29660 				     NULL, /*explain_p=*/true);
29661 	    }
29662 	  return error_mark_node;
29663 	}
29664     }
29665 
29666   /* Check any placeholder constraints against the deduced type. */
29667   if (processing_template_decl && context == adc_unify)
29668     /* Constraints will be checked after deduction.  */;
29669   else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
29670     {
29671       if (processing_template_decl)
29672 	{
29673 	  gcc_checking_assert (context == adc_variable_type
29674 			       || context == adc_return_type
29675 			       || context == adc_decomp_type);
29676 	  gcc_checking_assert (!type_dependent_expression_p (init));
29677 	  /* If the constraint is dependent, we need to wait until
29678 	     instantiation time to resolve the placeholder.  */
29679 	  if (placeholder_type_constraint_dependent_p (constr))
29680 	    return type;
29681 	}
29682 
29683       if ((context == adc_return_type
29684 	   || context == adc_variable_type
29685 	   || context == adc_decomp_type)
29686 	  && current_function_decl
29687 	  && DECL_TEMPLATE_INFO (current_function_decl))
29688 	outer_targs = DECL_TI_ARGS (current_function_decl);
29689 
29690       tree full_targs = add_to_template_args (outer_targs, targs);
29691 
29692       /* HACK: Compensate for callers not always communicating all levels of
29693 	 outer template arguments by filling in the outermost missing levels
29694 	 with dummy levels before checking satisfaction.  We'll still crash
29695 	 if the constraint depends on a template argument belonging to one of
29696 	 these missing levels, but this hack otherwise allows us to handle a
29697 	 large subset of possible constraints (including all non-dependent
29698 	 constraints).  */
29699       if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
29700 				- TMPL_ARGS_DEPTH (full_targs)))
29701 	{
29702 	  tree dummy_levels = make_tree_vec (missing_levels);
29703 	  for (int i = 0; i < missing_levels; ++i)
29704 	    TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
29705 	  full_targs = add_to_template_args (dummy_levels, full_targs);
29706 	}
29707 
29708       if (!constraints_satisfied_p (auto_node, full_targs))
29709 	{
29710 	  if (complain & tf_warning_or_error)
29711 	    {
29712 	      auto_diagnostic_group d;
29713 	      switch (context)
29714 		{
29715 		case adc_unspecified:
29716 		case adc_unify:
29717 		  error("placeholder constraints not satisfied");
29718 		  break;
29719 		case adc_variable_type:
29720 		case adc_decomp_type:
29721 		  error ("deduced initializer does not satisfy "
29722 			 "placeholder constraints");
29723 		  break;
29724 		case adc_return_type:
29725 		  error ("deduced return type does not satisfy "
29726 			 "placeholder constraints");
29727 		  break;
29728 		case adc_requirement:
29729 		  error ("deduced expression type does not satisfy "
29730 			 "placeholder constraints");
29731 		  break;
29732 		}
29733 	      diagnose_constraints (input_location, auto_node, full_targs);
29734 	    }
29735 	  return error_mark_node;
29736 	}
29737     }
29738 
29739   if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
29740     /* The outer template arguments are already substituted into type
29741        (but we still may have used them for constraint checking above).  */;
29742   else if (context == adc_unify)
29743     targs = add_to_template_args (outer_targs, targs);
29744   else if (processing_template_decl)
29745     targs = add_to_template_args (current_template_args (), targs);
29746   return tsubst (type, targs, complain, NULL_TREE);
29747 }
29748 
29749 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
29750    result.  */
29751 
29752 tree
splice_late_return_type(tree type,tree late_return_type)29753 splice_late_return_type (tree type, tree late_return_type)
29754 {
29755   if (late_return_type)
29756     {
29757       gcc_assert (is_auto (type) || seen_error ());
29758       return late_return_type;
29759     }
29760 
29761   if (tree auto_node = find_type_usage (type, is_auto))
29762     if (TEMPLATE_TYPE_LEVEL (auto_node) <= processing_template_decl)
29763       {
29764 	/* In an abbreviated function template we didn't know we were dealing
29765 	   with a function template when we saw the auto return type, so rebuild
29766 	   the return type using an auto with the correct level.  */
29767 	tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
29768 	tree auto_vec = make_tree_vec (1);
29769 	TREE_VEC_ELT (auto_vec, 0) = new_auto;
29770 	tree targs = add_outermost_template_args (current_template_args (),
29771 						  auto_vec);
29772 	/* Also rebuild the constraint info in terms of the new auto.  */
29773 	if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
29774 	  PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
29775 	    = build_tree_list (current_template_parms,
29776 			       tsubst_constraint (TREE_VALUE (ci), targs,
29777 						  tf_none, NULL_TREE));
29778 	TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
29779 	return tsubst (type, targs, tf_none, NULL_TREE);
29780       }
29781   return type;
29782 }
29783 
29784 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
29785    'decltype(auto)' or a deduced class template.  */
29786 
29787 bool
is_auto(const_tree type)29788 is_auto (const_tree type)
29789 {
29790   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
29791       && (TYPE_IDENTIFIER (type) == auto_identifier
29792 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
29793     return true;
29794   else
29795     return false;
29796 }
29797 
29798 /* for_each_template_parm callback for type_uses_auto.  */
29799 
29800 int
is_auto_r(tree tp,void *)29801 is_auto_r (tree tp, void */*data*/)
29802 {
29803   return is_auto (tp);
29804 }
29805 
29806 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
29807    a use of `auto'.  Returns NULL_TREE otherwise.  */
29808 
29809 tree
type_uses_auto(tree type)29810 type_uses_auto (tree type)
29811 {
29812   if (type == NULL_TREE)
29813     return NULL_TREE;
29814   else if (flag_concepts)
29815     {
29816       /* The Concepts TS allows multiple autos in one type-specifier; just
29817 	 return the first one we find, do_auto_deduction will collect all of
29818 	 them.  */
29819       if (uses_template_parms (type))
29820 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
29821 				       /*visited*/NULL, /*nondeduced*/false);
29822       else
29823 	return NULL_TREE;
29824     }
29825   else
29826     return find_type_usage (type, is_auto);
29827 }
29828 
29829 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
29830    concepts are enabled, auto is acceptable in template arguments, but
29831    only when TEMPL identifies a template class.  Return TRUE if any
29832    such errors were reported.  */
29833 
29834 bool
check_auto_in_tmpl_args(tree tmpl,tree args)29835 check_auto_in_tmpl_args (tree tmpl, tree args)
29836 {
29837   /* If there were previous errors, nevermind.  */
29838   if (!args || TREE_CODE (args) != TREE_VEC)
29839     return false;
29840 
29841   /* If TMPL is an identifier, we're parsing and we can't tell yet
29842      whether TMPL is supposed to be a type, a function or a variable.
29843      We'll only be able to tell during template substitution, so we
29844      expect to be called again then.  If concepts are enabled and we
29845      know we have a type, we're ok.  */
29846   if (flag_concepts
29847       && (identifier_p (tmpl)
29848 	  || (DECL_P (tmpl)
29849 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
29850 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
29851     return false;
29852 
29853   /* Quickly search for any occurrences of auto; usually there won't
29854      be any, and then we'll avoid allocating the vector.  */
29855   if (!type_uses_auto (args))
29856     return false;
29857 
29858   bool errors = false;
29859 
29860   tree vec = extract_autos (args);
29861   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
29862     {
29863       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
29864       error_at (DECL_SOURCE_LOCATION (xauto),
29865 		"invalid use of %qT in template argument", xauto);
29866       errors = true;
29867     }
29868 
29869   return errors;
29870 }
29871 
29872 /* Recursively walk over && expressions searching for EXPR. Return a reference
29873    to that expression.  */
29874 
find_template_requirement(tree * t,tree key)29875 static tree *find_template_requirement (tree *t, tree key)
29876 {
29877   if (*t == key)
29878     return t;
29879   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
29880     {
29881       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
29882 	return p;
29883       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
29884 	return p;
29885     }
29886   return 0;
29887 }
29888 
29889 /* Convert the generic type parameters in PARM that match the types given in the
29890    range [START_IDX, END_IDX) from the current_template_parms into generic type
29891    packs.  */
29892 
29893 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)29894 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
29895 {
29896   tree current = current_template_parms;
29897   int depth = TMPL_PARMS_DEPTH (current);
29898   current = INNERMOST_TEMPLATE_PARMS (current);
29899   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
29900 
29901   for (int i = 0; i < start_idx; ++i)
29902     TREE_VEC_ELT (replacement, i)
29903       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29904 
29905   for (int i = start_idx; i < end_idx; ++i)
29906     {
29907       /* Create a distinct parameter pack type from the current parm and add it
29908 	 to the replacement args to tsubst below into the generic function
29909 	 parameter.  */
29910       tree node = TREE_VEC_ELT (current, i);
29911       tree o = TREE_TYPE (TREE_VALUE (node));
29912       tree t = copy_type (o);
29913       TEMPLATE_TYPE_PARM_INDEX (t)
29914 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
29915 				      t, 0, 0, tf_none);
29916       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
29917       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
29918       TYPE_MAIN_VARIANT (t) = t;
29919       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
29920       TYPE_CANONICAL (t) = canonical_type_parameter (t);
29921       TREE_VEC_ELT (replacement, i) = t;
29922 
29923       /* Replace the current template parameter with new pack.  */
29924       TREE_VALUE (node) = TREE_CHAIN (t);
29925 
29926       /* Surgically adjust the associated constraint of adjusted parameter
29927          and it's corresponding contribution to the current template
29928          requirements.  */
29929       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
29930 	{
29931 	  tree id = unpack_concept_check (constr);
29932 	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
29933 	  tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
29934 	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
29935 
29936 	  /* If there was a constraint, we also need to replace that in
29937 	     the template requirements, which we've already built.  */
29938 	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
29939 	  reqs = find_template_requirement (reqs, constr);
29940 	  *reqs = fold;
29941 	}
29942     }
29943 
29944   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
29945     TREE_VEC_ELT (replacement, i)
29946       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29947 
29948   /* If there are more levels then build up the replacement with the outer
29949      template parms.  */
29950   if (depth > 1)
29951     replacement = add_to_template_args (template_parms_to_args
29952 					(TREE_CHAIN (current_template_parms)),
29953 					replacement);
29954 
29955   return tsubst (parm, replacement, tf_none, NULL_TREE);
29956 }
29957 
29958 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
29959    0..N-1.  */
29960 
29961 void
declare_integer_pack(void)29962 declare_integer_pack (void)
29963 {
29964   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
29965 			       build_function_type_list (integer_type_node,
29966 							 integer_type_node,
29967 							 NULL_TREE),
29968 			       NULL_TREE, ECF_CONST);
29969   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
29970   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
29971 			      CP_BUILT_IN_INTEGER_PACK);
29972 }
29973 
29974 /* Walk the decl or type specialization table calling FN on each
29975    entry.  */
29976 
29977 void
walk_specializations(bool decls_p,void (* fn)(bool decls_p,spec_entry * entry,void * data),void * data)29978 walk_specializations (bool decls_p,
29979 		      void (*fn) (bool decls_p, spec_entry *entry, void *data),
29980 		      void *data)
29981 {
29982   spec_hash_table *table = decls_p ? decl_specializations
29983     : type_specializations;
29984   spec_hash_table::iterator end (table->end ());
29985   for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
29986     fn (decls_p, *iter, data);
29987 }
29988 
29989 /* Lookup the specialization of *ELT, in the decl or type
29990    specialization table.  Return the SPEC that's already there, or
29991    NULL if nothing.  */
29992 
29993 tree
match_mergeable_specialization(bool decl_p,spec_entry * elt)29994 match_mergeable_specialization (bool decl_p, spec_entry *elt)
29995 {
29996   hash_table<spec_hasher> *specializations
29997     = decl_p ? decl_specializations : type_specializations;
29998   hashval_t hash = spec_hasher::hash (elt);
29999   auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
30000 
30001   if (slot)
30002     return (*slot)->spec;
30003 
30004   return NULL_TREE;
30005 }
30006 
30007 /* Return flags encoding whether SPEC is on the instantiation and/or
30008    specialization lists of TMPL.  */
30009 
30010 unsigned
get_mergeable_specialization_flags(tree tmpl,tree decl)30011 get_mergeable_specialization_flags (tree tmpl, tree decl)
30012 {
30013   unsigned flags = 0;
30014 
30015   for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
30016        inst; inst = TREE_CHAIN (inst))
30017     if (TREE_VALUE (inst) == decl)
30018       {
30019 	flags |= 1;
30020 	break;
30021       }
30022 
30023   if (CLASS_TYPE_P (TREE_TYPE (decl))
30024       && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
30025       && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
30026     /* Only need to search if DECL is a partial specialization.  */
30027     for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
30028 	 part; part = TREE_CHAIN (part))
30029       if (TREE_VALUE (part) == decl)
30030 	{
30031 	  flags |= 2;
30032 	  break;
30033 	}
30034 
30035   return flags;
30036 }
30037 
30038 /* Add a new specialization described by SPEC.  DECL is the
30039    maybe-template decl and FLAGS is as returned from
30040    get_mergeable_specialization_flags.  */
30041 
30042 void
add_mergeable_specialization(bool decl_p,bool alias_p,spec_entry * elt,tree decl,unsigned flags)30043 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
30044 			      tree decl, unsigned flags)
30045 {
30046   hashval_t hash = spec_hasher::hash (elt);
30047   if (decl_p)
30048     {
30049       auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
30050 
30051       gcc_checking_assert (!*slot);
30052       auto entry = ggc_alloc<spec_entry> ();
30053       *entry = *elt;
30054       *slot = entry;
30055 
30056       if (alias_p)
30057 	{
30058 	  elt->spec = TREE_TYPE (elt->spec);
30059 	  gcc_checking_assert (elt->spec);
30060 	}
30061     }
30062 
30063   if (!decl_p || alias_p)
30064     {
30065       auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
30066 
30067       /* We don't distinguish different constrained partial type
30068 	 specializations, so there could be duplicates.  Everything else
30069 	 must be new.   */
30070       if (!(flags & 2 && *slot))
30071 	{
30072 	  gcc_checking_assert (!*slot);
30073 
30074 	  auto entry = ggc_alloc<spec_entry> ();
30075 	  *entry = *elt;
30076 	  *slot = entry;
30077 	}
30078     }
30079 
30080   if (flags & 1)
30081     DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
30082       = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
30083 
30084   if (flags & 2)
30085     {
30086       /* A partial specialization.  */
30087       tree cons = tree_cons (elt->args, decl,
30088 			     DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
30089       TREE_TYPE (cons) = elt->spec;
30090       DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
30091     }
30092 }
30093 
30094 /* Set up the hash tables for template instantiations.  */
30095 
30096 void
init_template_processing(void)30097 init_template_processing (void)
30098 {
30099   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
30100   type_specializations = hash_table<spec_hasher>::create_ggc (37);
30101 
30102   if (cxx_dialect >= cxx11)
30103     declare_integer_pack ();
30104 }
30105 
30106 /* Print stats about the template hash tables for -fstats.  */
30107 
30108 void
print_template_statistics(void)30109 print_template_statistics (void)
30110 {
30111   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
30112 	   "%f collisions\n", (long) decl_specializations->size (),
30113 	   (long) decl_specializations->elements (),
30114 	   decl_specializations->collisions ());
30115   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
30116 	   "%f collisions\n", (long) type_specializations->size (),
30117 	   (long) type_specializations->elements (),
30118 	   type_specializations->collisions ());
30119 }
30120 
30121 #if CHECKING_P
30122 
30123 namespace selftest {
30124 
30125 /* Verify that build_non_dependent_expr () works, for various expressions,
30126    and that location wrappers don't affect the results.  */
30127 
30128 static void
test_build_non_dependent_expr()30129 test_build_non_dependent_expr ()
30130 {
30131   location_t loc = BUILTINS_LOCATION;
30132 
30133   /* Verify constants, without and with location wrappers.  */
30134   tree int_cst = build_int_cst (integer_type_node, 42);
30135   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
30136 
30137   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
30138   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
30139   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
30140 
30141   tree string_lit = build_string (4, "foo");
30142   TREE_TYPE (string_lit) = char_array_type_node;
30143   string_lit = fix_string_type (string_lit);
30144   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
30145 
30146   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
30147   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
30148   ASSERT_EQ (wrapped_string_lit,
30149 	     build_non_dependent_expr (wrapped_string_lit));
30150 }
30151 
30152 /* Verify that type_dependent_expression_p () works correctly, even
30153    in the presence of location wrapper nodes.  */
30154 
30155 static void
test_type_dependent_expression_p()30156 test_type_dependent_expression_p ()
30157 {
30158   location_t loc = BUILTINS_LOCATION;
30159 
30160   tree name = get_identifier ("foo");
30161 
30162   /* If no templates are involved, nothing is type-dependent.  */
30163   gcc_assert (!processing_template_decl);
30164   ASSERT_FALSE (type_dependent_expression_p (name));
30165 
30166   ++processing_template_decl;
30167 
30168   /* Within a template, an unresolved name is always type-dependent.  */
30169   ASSERT_TRUE (type_dependent_expression_p (name));
30170 
30171   /* Ensure it copes with NULL_TREE and errors.  */
30172   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
30173   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
30174 
30175   /* A USING_DECL in a template should be type-dependent, even if wrapped
30176      with a location wrapper (PR c++/83799).  */
30177   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
30178   TREE_TYPE (using_decl) = integer_type_node;
30179   ASSERT_TRUE (type_dependent_expression_p (using_decl));
30180   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
30181   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
30182   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
30183 
30184   --processing_template_decl;
30185 }
30186 
30187 /* Run all of the selftests within this file.  */
30188 
30189 void
cp_pt_c_tests()30190 cp_pt_c_tests ()
30191 {
30192   test_build_non_dependent_expr ();
30193   test_type_dependent_expression_p ();
30194 }
30195 
30196 } // namespace selftest
30197 
30198 #endif /* #if CHECKING_P */
30199 
30200 #include "gt-cp-pt.h"
30201