1/* Handle parameterized types (templates) for GNU -*- C++ -*-.
2   Copyright (C) 1992-2022 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
6This file is part of GCC.
7
8GCC is free software; you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation; either version 3, or (at your option)
11any later version.
12
13GCC is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along 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.  */
51typedef 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.  */
56struct GTY ((chain_next ("%h.next"))) pending_template
57{
58  struct pending_template *next;
59  struct tinst_level *tinst;
60};
61
62static GTY(()) struct pending_template *pending_templates;
63static GTY(()) struct pending_template *last_pending_template;
64
65int processing_template_parmlist;
66static int template_header_count;
67
68static vec<int> inline_parm_levels;
69
70static GTY(()) struct tinst_level *current_tinst_level;
71
72static 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.  */
77static tree cur_stmt_expr;
78
79// -------------------------------------------------------------------------- //
80// Local Specialization Stack
81//
82// Implementation of the RAII helper for creating new local
83// specializations.
84local_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
95local_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.  */
105static bool excessive_deduction_depth;
106
107struct 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.  */
114typedef hash_table<spec_hasher> spec_hash_table;
115static GTY (()) spec_hash_table *decl_specializations;
116static 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.  */
122static 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
133enum template_base_result {
134  tbr_incomplete_type,
135  tbr_ambiguous_baseclass,
136  tbr_success
137};
138
139static bool resolve_overloaded_unification (tree, tree, tree, tree,
140					    unification_kind_t, int,
141					    bool);
142static int try_one_overload (tree, tree, tree, tree, tree,
143			     unification_kind_t, int, bool, bool);
144static int unify (tree, tree, tree, tree, int, bool);
145static void add_pending_template (tree);
146static tree reopen_tinst_level (struct tinst_level *);
147static tree tsubst_initializer_list (tree, tree);
148static tree get_partial_spec_bindings (tree, tree, tree);
149static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
150				   bool, bool);
151static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
152					      bool, bool);
153static void tsubst_enum	(tree, tree, tree);
154static bool check_instantiated_args (tree, tree, tsubst_flags_t);
155static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
156					   struct conversion **, bool);
157static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
158					     tree*, tree*, tree);
159static 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);
163static void note_template_header (int);
164static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166static tree convert_template_argument (tree, tree, tree,
167				       tsubst_flags_t, int, tree);
168static tree for_each_template_parm (tree, tree_fn_t, void*,
169				    hash_set<tree> *, bool, tree_fn_t = NULL);
170static tree expand_template_argument_pack (tree);
171static tree build_template_parm_index (int, int, int, tree, tree);
172static bool inline_needs_template_parms (tree, bool);
173static void push_inline_template_parms_recursive (tree, int);
174static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175static int mark_template_parm (tree, void *);
176static int template_parm_this_level_p (tree, void *);
177static tree tsubst_friend_function (tree, tree);
178static tree tsubst_friend_class (tree, tree);
179static int can_complete_type_without_circularity (tree);
180static tree get_bindings (tree, tree, tree, bool);
181static int template_decl_level (tree);
182static int check_cv_quals_for_unify (int, tree, tree);
183static int unify_pack_expansion (tree, tree, tree,
184				 tree, unification_kind_t, bool, bool);
185static tree copy_template_args (tree);
186static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
188tree most_specialized_partial_spec (tree, tsubst_flags_t);
189static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
190static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
191static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
192static bool check_specialization_scope (void);
193static tree process_partial_specialization (tree);
194static enum template_base_result get_template_base (tree, tree, tree, tree,
195						    bool , tree *);
196static tree try_class_unification (tree, tree, tree, tree, bool);
197static bool class_nttp_const_wrapper_p (tree t);
198static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
199					   tree, tree);
200static bool template_template_parm_bindings_ok_p (tree, tree);
201static void tsubst_default_arguments (tree, tsubst_flags_t);
202static tree for_each_template_parm_r (tree *, int *, void *);
203static tree copy_default_args_to_explicit_spec_1 (tree, tree);
204static void copy_default_args_to_explicit_spec (tree);
205static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
206static bool dependent_template_arg_p (tree);
207static bool any_template_arguments_need_structural_equality_p (tree);
208static bool dependent_type_p_r (tree);
209static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
210static tree tsubst_decl (tree, tree, tsubst_flags_t);
211static void perform_instantiation_time_access_checks (tree, tree);
212static tree listify (tree);
213static tree listify_autos (tree, tree);
214static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
215static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
216static bool complex_alias_template_p (const_tree tmpl);
217static tree get_underlying_template (tree);
218static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
219static tree canonicalize_expr_argument (tree, tsubst_flags_t);
220static tree make_argument_pack (tree);
221static void register_parameter_specializations (tree, tree);
222static tree enclosing_instantiation_of (tree tctx);
223static void instantiate_body (tree pattern, tree args, tree d, bool nested);
224
225/* Make the current scope suitable for access checking when we are
226   processing T.  T can be FUNCTION_DECL for instantiated function
227   template, VAR_DECL for static member variable, or TYPE_DECL for
228   for a class or alias template (needed by instantiate_decl).  */
229
230void
231push_access_scope (tree t)
232{
233  gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
234	      || TREE_CODE (t) == TYPE_DECL);
235
236  if (DECL_FRIEND_CONTEXT (t))
237    push_nested_class (DECL_FRIEND_CONTEXT (t));
238  else if (DECL_IMPLICIT_TYPEDEF_P (t)
239	   && CLASS_TYPE_P (TREE_TYPE (t)))
240    push_nested_class (TREE_TYPE (t));
241  else if (DECL_CLASS_SCOPE_P (t))
242    push_nested_class (DECL_CONTEXT (t));
243  else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
244    /* An artificial deduction guide should have the same access as
245       the constructor.  */
246    push_nested_class (TREE_TYPE (TREE_TYPE (t)));
247  else
248    push_to_top_level ();
249
250  if (TREE_CODE (t) == FUNCTION_DECL)
251    {
252      vec_safe_push (saved_access_scope, current_function_decl);
253      current_function_decl = t;
254    }
255}
256
257/* Restore the scope set up by push_access_scope.  T is the node we
258   are processing.  */
259
260void
261pop_access_scope (tree t)
262{
263  if (TREE_CODE (t) == FUNCTION_DECL)
264    current_function_decl = saved_access_scope->pop();
265
266  if (DECL_FRIEND_CONTEXT (t)
267      || (DECL_IMPLICIT_TYPEDEF_P (t)
268	  && CLASS_TYPE_P (TREE_TYPE (t)))
269      || DECL_CLASS_SCOPE_P (t)
270      || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
271    pop_nested_class ();
272  else
273    pop_from_top_level ();
274}
275
276/* Do any processing required when DECL (a member template
277   declaration) is finished.  Returns the TEMPLATE_DECL corresponding
278   to DECL, unless it is a specialization, in which case the DECL
279   itself is returned.  */
280
281tree
282finish_member_template_decl (tree decl)
283{
284  if (decl == error_mark_node)
285    return error_mark_node;
286
287  gcc_assert (DECL_P (decl));
288
289  if (TREE_CODE (decl) == TYPE_DECL)
290    {
291      tree type;
292
293      type = TREE_TYPE (decl);
294      if (type == error_mark_node)
295	return error_mark_node;
296      if (MAYBE_CLASS_TYPE_P (type)
297	  && CLASSTYPE_TEMPLATE_INFO (type)
298	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
299	{
300	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
301	  check_member_template (tmpl);
302	  return tmpl;
303	}
304      return NULL_TREE;
305    }
306  else if (TREE_CODE (decl) == FIELD_DECL)
307    error_at (DECL_SOURCE_LOCATION (decl),
308	      "data member %qD cannot be a member template", decl);
309  else if (DECL_TEMPLATE_INFO (decl))
310    {
311      if (!DECL_TEMPLATE_SPECIALIZATION (decl))
312	{
313	  check_member_template (DECL_TI_TEMPLATE (decl));
314	  return DECL_TI_TEMPLATE (decl);
315	}
316      else
317	return decl;
318    }
319  else
320    error_at (DECL_SOURCE_LOCATION (decl),
321	      "invalid member template declaration %qD", decl);
322
323  return error_mark_node;
324}
325
326/* Create a template info node.  */
327
328tree
329build_template_info (tree template_decl, tree template_args)
330{
331  tree result = make_node (TEMPLATE_INFO);
332  TI_TEMPLATE (result) = template_decl;
333  TI_ARGS (result) = template_args;
334  return result;
335}
336
337/* Return the template info node corresponding to T, whatever T is.  */
338
339tree
340get_template_info (const_tree t)
341{
342  tree tinfo = NULL_TREE;
343
344  if (!t || t == error_mark_node)
345    return NULL;
346
347  if (TREE_CODE (t) == NAMESPACE_DECL
348      || TREE_CODE (t) == PARM_DECL)
349    return NULL;
350
351  if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
352    tinfo = DECL_TEMPLATE_INFO (t);
353
354  if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
355    t = TREE_TYPE (t);
356
357  if (OVERLOAD_TYPE_P (t))
358    tinfo = TYPE_TEMPLATE_INFO (t);
359  else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
360    tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
361
362  return tinfo;
363}
364
365/* Returns the template nesting level of the indicated class TYPE.
366
367   For example, in:
368     template <class T>
369     struct A
370     {
371       template <class U>
372       struct B {};
373     };
374
375   A<T>::B<U> has depth two, while A<T> has depth one.
376   Both A<T>::B<int> and A<int>::B<U> have depth one, if
377   they are instantiations, not specializations.
378
379   This function is guaranteed to return 0 if passed NULL_TREE so
380   that, for example, `template_class_depth (current_class_type)' is
381   always safe.  */
382
383int
384template_class_depth (tree type)
385{
386  int depth;
387
388  for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
389    {
390      tree tinfo = get_template_info (type);
391
392      if (tinfo
393	  && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
394	  && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
395	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
396	++depth;
397
398      if (DECL_P (type))
399	{
400	  if (tree fctx = DECL_FRIEND_CONTEXT (type))
401	    type = fctx;
402	  else
403	    type = CP_DECL_CONTEXT (type);
404	}
405      else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
406	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
407      else
408	type = CP_TYPE_CONTEXT (type);
409    }
410
411  return depth;
412}
413
414/* Return TRUE if NODE instantiates a template that has arguments of
415   its own, be it directly a primary template or indirectly through a
416   partial specializations.  */
417static bool
418instantiates_primary_template_p (tree node)
419{
420  tree tinfo = get_template_info (node);
421  if (!tinfo)
422    return false;
423
424  tree tmpl = TI_TEMPLATE (tinfo);
425  if (PRIMARY_TEMPLATE_P (tmpl))
426    return true;
427
428  if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
429    return false;
430
431  /* So now we know we have a specialization, but it could be a full
432     or a partial specialization.  To tell which, compare the depth of
433     its template arguments with those of its context.  */
434
435  tree ctxt = DECL_CONTEXT (tmpl);
436  tree ctinfo = get_template_info (ctxt);
437  if (!ctinfo)
438    return true;
439
440  return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
441	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
442}
443
444/* Subroutine of maybe_begin_member_template_processing.
445   Returns true if processing DECL needs us to push template parms.  */
446
447static bool
448inline_needs_template_parms (tree decl, bool nsdmi)
449{
450  if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
451    return false;
452
453  return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
454	  > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
455}
456
457/* Subroutine of maybe_begin_member_template_processing.
458   Push the template parms in PARMS, starting from LEVELS steps into the
459   chain, and ending at the beginning, since template parms are listed
460   innermost first.  */
461
462static void
463push_inline_template_parms_recursive (tree parmlist, int levels)
464{
465  tree parms = TREE_VALUE (parmlist);
466  int i;
467
468  if (levels > 1)
469    push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
470
471  ++processing_template_decl;
472  current_template_parms
473    = tree_cons (size_int (current_template_depth + 1),
474		 parms, current_template_parms);
475  TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
476
477  begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
478	       NULL);
479  for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
480    {
481      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
482
483      if (error_operand_p (parm))
484	continue;
485
486      gcc_assert (DECL_P (parm));
487
488      switch (TREE_CODE (parm))
489	{
490	case TYPE_DECL:
491	case TEMPLATE_DECL:
492	  pushdecl (parm);
493	  break;
494
495	case PARM_DECL:
496	  /* Push the CONST_DECL.  */
497	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
498	  break;
499
500	default:
501	  gcc_unreachable ();
502	}
503    }
504}
505
506/* Restore the template parameter context for a member template, a
507   friend template defined in a class definition, or a non-template
508   member of template class.  */
509
510void
511maybe_begin_member_template_processing (tree decl)
512{
513  tree parms;
514  int levels = 0;
515  bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
516
517  if (nsdmi)
518    {
519      tree ctx = DECL_CONTEXT (decl);
520      decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
521	      /* Disregard full specializations (c++/60999).  */
522	      && uses_template_parms (ctx)
523	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
524    }
525
526  if (inline_needs_template_parms (decl, nsdmi))
527    {
528      parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
529      levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
530
531      if (DECL_TEMPLATE_SPECIALIZATION (decl))
532	{
533	  --levels;
534	  parms = TREE_CHAIN (parms);
535	}
536
537      push_inline_template_parms_recursive (parms, levels);
538    }
539
540  /* Remember how many levels of template parameters we pushed so that
541     we can pop them later.  */
542  inline_parm_levels.safe_push (levels);
543}
544
545/* Undo the effects of maybe_begin_member_template_processing.  */
546
547void
548maybe_end_member_template_processing (void)
549{
550  int i;
551  int last;
552
553  if (inline_parm_levels.length () == 0)
554    return;
555
556  last = inline_parm_levels.pop ();
557  for (i = 0; i < last; ++i)
558    {
559      --processing_template_decl;
560      current_template_parms = TREE_CHAIN (current_template_parms);
561      poplevel (0, 0, 0);
562    }
563}
564
565/* Return a new template argument vector which contains all of ARGS,
566   but has as its innermost set of arguments the EXTRA_ARGS.  */
567
568tree
569add_to_template_args (tree args, tree extra_args)
570{
571  tree new_args;
572  int extra_depth;
573  int i;
574  int j;
575
576  if (args == NULL_TREE || extra_args == error_mark_node)
577    return extra_args;
578
579  extra_depth = TMPL_ARGS_DEPTH (extra_args);
580  new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
581
582  for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
583    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
584
585  for (j = 1; j <= extra_depth; ++j, ++i)
586    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
587
588  return new_args;
589}
590
591/* Like add_to_template_args, but only the outermost ARGS are added to
592   the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
593   (EXTRA_ARGS) levels are added.  This function is used to combine
594   the template arguments from a partial instantiation with the
595   template arguments used to attain the full instantiation from the
596   partial instantiation.
597
598   If ARGS is a TEMPLATE_DECL, use its parameters as args.  */
599
600tree
601add_outermost_template_args (tree args, tree extra_args)
602{
603  tree new_args;
604
605  if (!args)
606    return extra_args;
607  if (TREE_CODE (args) == TEMPLATE_DECL)
608    {
609      tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
610      args = TI_ARGS (ti);
611    }
612
613  /* If there are more levels of EXTRA_ARGS than there are ARGS,
614     something very fishy is going on.  */
615  gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
616
617  /* If *all* the new arguments will be the EXTRA_ARGS, just return
618     them.  */
619  if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
620    return extra_args;
621
622  /* For the moment, we make ARGS look like it contains fewer levels.  */
623  TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
624
625  new_args = add_to_template_args (args, extra_args);
626
627  /* Now, we restore ARGS to its full dimensions.  */
628  TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
629
630  return new_args;
631}
632
633/* Return the N levels of innermost template arguments from the ARGS.  */
634
635tree
636get_innermost_template_args (tree args, int n)
637{
638  tree new_args;
639  int extra_levels;
640  int i;
641
642  gcc_assert (n >= 0);
643
644  /* If N is 1, just return the innermost set of template arguments.  */
645  if (n == 1)
646    return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
647
648  /* If we're not removing anything, just return the arguments we were
649     given.  */
650  extra_levels = TMPL_ARGS_DEPTH (args) - n;
651  gcc_assert (extra_levels >= 0);
652  if (extra_levels == 0)
653    return args;
654
655  /* Make a new set of arguments, not containing the outer arguments.  */
656  new_args = make_tree_vec (n);
657  for (i = 1; i <= n; ++i)
658    SET_TMPL_ARGS_LEVEL (new_args, i,
659			 TMPL_ARGS_LEVEL (args, i + extra_levels));
660
661  return new_args;
662}
663
664/* The inverse of get_innermost_template_args: Return all but the innermost
665   EXTRA_LEVELS levels of template arguments from the ARGS.  */
666
667static tree
668strip_innermost_template_args (tree args, int extra_levels)
669{
670  tree new_args;
671  int n = TMPL_ARGS_DEPTH (args) - extra_levels;
672  int i;
673
674  gcc_assert (n >= 0);
675
676  /* If N is 1, just return the outermost set of template arguments.  */
677  if (n == 1)
678    return TMPL_ARGS_LEVEL (args, 1);
679
680  /* If we're not removing anything, just return the arguments we were
681     given.  */
682  gcc_assert (extra_levels >= 0);
683  if (extra_levels == 0)
684    return args;
685
686  /* Make a new set of arguments, not containing the inner arguments.  */
687  new_args = make_tree_vec (n);
688  for (i = 1; i <= n; ++i)
689    SET_TMPL_ARGS_LEVEL (new_args, i,
690			 TMPL_ARGS_LEVEL (args, i));
691
692  return new_args;
693}
694
695/* We've got a template header coming up; push to a new level for storing
696   the parms.  */
697
698void
699begin_template_parm_list (void)
700{
701  /* We use a non-tag-transparent scope here, which causes pushtag to
702     put tags in this scope, rather than in the enclosing class or
703     namespace scope.  This is the right thing, since we want
704     TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
705     global template class, push_template_decl handles putting the
706     TEMPLATE_DECL into top-level scope.  For a nested template class,
707     e.g.:
708
709       template <class T> struct S1 {
710	 template <class T> struct S2 {};
711       };
712
713     pushtag contains special code to insert the TEMPLATE_DECL for S2
714     at the right scope.  */
715  begin_scope (sk_template_parms, NULL);
716  ++processing_template_decl;
717  ++processing_template_parmlist;
718  note_template_header (0);
719
720  /* Add a dummy parameter level while we process the parameter list.  */
721  current_template_parms
722    = tree_cons (size_int (current_template_depth + 1),
723		 make_tree_vec (0),
724		 current_template_parms);
725}
726
727/* This routine is called when a specialization is declared.  If it is
728   invalid to declare a specialization here, an error is reported and
729   false is returned, otherwise this routine will return true.  */
730
731static bool
732check_specialization_scope (void)
733{
734  tree scope = current_scope ();
735
736  /* [temp.expl.spec]
737
738     An explicit specialization shall be declared in the namespace of
739     which the template is a member, or, for member templates, in the
740     namespace of which the enclosing class or enclosing class
741     template is a member.  An explicit specialization of a member
742     function, member class or static data member of a class template
743     shall be declared in the namespace of which the class template
744     is a member.  */
745  if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
746    {
747      error ("explicit specialization in non-namespace scope %qD", scope);
748      return false;
749    }
750
751  /* [temp.expl.spec]
752
753     In an explicit specialization declaration for a member of a class
754     template or a member template that appears in namespace scope,
755     the member template and some of its enclosing class templates may
756     remain unspecialized, except that the declaration shall not
757     explicitly specialize a class member template if its enclosing
758     class templates are not explicitly specialized as well.  */
759  if (current_template_parms)
760    {
761      error ("enclosing class templates are not explicitly specialized");
762      return false;
763    }
764
765  return true;
766}
767
768/* We've just seen template <>.  */
769
770bool
771begin_specialization (void)
772{
773  begin_scope (sk_template_spec, NULL);
774  note_template_header (1);
775  return check_specialization_scope ();
776}
777
778/* Called at then end of processing a declaration preceded by
779   template<>.  */
780
781void
782end_specialization (void)
783{
784  finish_scope ();
785  reset_specialization ();
786}
787
788/* Any template <>'s that we have seen thus far are not referring to a
789   function specialization.  */
790
791void
792reset_specialization (void)
793{
794  processing_specialization = 0;
795  template_header_count = 0;
796}
797
798/* We've just seen a template header.  If SPECIALIZATION is nonzero,
799   it was of the form template <>.  */
800
801static void
802note_template_header (int specialization)
803{
804  processing_specialization = specialization;
805  template_header_count++;
806}
807
808/* We're beginning an explicit instantiation.  */
809
810void
811begin_explicit_instantiation (void)
812{
813  gcc_assert (!processing_explicit_instantiation);
814  processing_explicit_instantiation = true;
815}
816
817
818void
819end_explicit_instantiation (void)
820{
821  gcc_assert (processing_explicit_instantiation);
822  processing_explicit_instantiation = false;
823}
824
825/* An explicit specialization or partial specialization of TMPL is being
826   declared.  Check that the namespace in which the specialization is
827   occurring is permissible.  Returns false iff it is invalid to
828   specialize TMPL in the current namespace.  */
829
830static bool
831check_specialization_namespace (tree tmpl)
832{
833  tree tpl_ns = decl_namespace_context (tmpl);
834
835  /* [tmpl.expl.spec]
836
837     An explicit specialization shall be declared in a namespace enclosing the
838     specialized template. An explicit specialization whose declarator-id is
839     not qualified shall be declared in the nearest enclosing namespace of the
840     template, or, if the namespace is inline (7.3.1), any namespace from its
841     enclosing namespace set.  */
842  if (current_scope() != DECL_CONTEXT (tmpl)
843      && !at_namespace_scope_p ())
844    {
845      error ("specialization of %qD must appear at namespace scope", tmpl);
846      return false;
847    }
848
849  if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
850    /* Same or enclosing namespace.  */
851    return true;
852  else
853    {
854      auto_diagnostic_group d;
855      if (permerror (input_location,
856		     "specialization of %qD in different namespace", tmpl))
857	inform (DECL_SOURCE_LOCATION (tmpl),
858		"  from definition of %q#D", tmpl);
859      return false;
860    }
861}
862
863/* SPEC is an explicit instantiation.  Check that it is valid to
864   perform this explicit instantiation in the current namespace.  */
865
866static void
867check_explicit_instantiation_namespace (tree spec)
868{
869  tree ns;
870
871  /* DR 275: An explicit instantiation shall appear in an enclosing
872     namespace of its template.  */
873  ns = decl_namespace_context (spec);
874  if (!is_nested_namespace (current_namespace, ns))
875    permerror (input_location, "explicit instantiation of %qD in namespace %qD "
876	       "(which does not enclose namespace %qD)",
877	       spec, current_namespace, ns);
878}
879
880/* Returns true if TYPE is a new partial specialization that needs to be
881   set up.  This may also modify TYPE to point to the correct (new or
882   existing) constrained partial specialization.  */
883
884static bool
885maybe_new_partial_specialization (tree& type)
886{
887  /* An implicit instantiation of an incomplete type implies
888     the definition of a new class template.
889
890	template<typename T>
891	  struct S;
892
893	template<typename T>
894	  struct S<T*>;
895
896     Here, S<T*> is an implicit instantiation of S whose type
897     is incomplete.  */
898  if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
899    return true;
900
901  /* It can also be the case that TYPE is a completed specialization.
902     Continuing the previous example, suppose we also declare:
903
904	template<typename T>
905	  requires Integral<T>
906	    struct S<T*>;
907
908     Here, S<T*> refers to the specialization S<T*> defined
909     above. However, we need to differentiate definitions because
910     we intend to define a new partial specialization. In this case,
911     we rely on the fact that the constraints are different for
912     this declaration than that above.
913
914     Note that we also get here for injected class names and
915     late-parsed template definitions. We must ensure that we
916     do not create new type declarations for those cases.  */
917  if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
918    {
919      tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
920      tree args = CLASSTYPE_TI_ARGS (type);
921
922      /* If there are no template parameters, this cannot be a new
923	 partial template specialization?  */
924      if (!current_template_parms)
925	return false;
926
927      /* The injected-class-name is not a new partial specialization.  */
928      if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
929	return false;
930
931      /* If the constraints are not the same as those of the primary
932	 then, we can probably create a new specialization.  */
933      tree type_constr = current_template_constraints ();
934
935      if (type == TREE_TYPE (tmpl))
936	{
937	  tree main_constr = get_constraints (tmpl);
938	  if (equivalent_constraints (type_constr, main_constr))
939	    return false;
940	}
941
942      /* Also, if there's a pre-existing specialization with matching
943	 constraints, then this also isn't new.  */
944      tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
945      while (specs)
946        {
947          tree spec_tmpl = TREE_VALUE (specs);
948          tree spec_args = TREE_PURPOSE (specs);
949          tree spec_constr = get_constraints (spec_tmpl);
950          if (comp_template_args (args, spec_args)
951	      && equivalent_constraints (type_constr, spec_constr))
952	    {
953	      type = TREE_TYPE (spec_tmpl);
954	      return false;
955	    }
956          specs = TREE_CHAIN (specs);
957        }
958
959      /* Create a new type node (and corresponding type decl)
960	 for the newly declared specialization.  */
961      tree t = make_class_type (TREE_CODE (type));
962      CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
963      SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
964
965      /* We only need a separate type node for storing the definition of this
966	 partial specialization; uses of S<T*> are unconstrained, so all are
967	 equivalent.  So keep TYPE_CANONICAL the same.  */
968      TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
969
970      /* Build the corresponding type decl.  */
971      tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
972      DECL_CONTEXT (d) = TYPE_CONTEXT (t);
973      DECL_SOURCE_LOCATION (d) = input_location;
974      TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
975      TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
976
977      set_instantiating_module (d);
978      DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
979
980      type = t;
981      return true;
982    }
983
984  return false;
985}
986
987/* The TYPE is being declared.  If it is a template type, that means it
988   is a partial specialization.  Do appropriate error-checking.  */
989
990tree
991maybe_process_partial_specialization (tree type)
992{
993  tree context;
994
995  if (type == error_mark_node)
996    return error_mark_node;
997
998  /* A lambda that appears in specialization context is not itself a
999     specialization.  */
1000  if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1001    return type;
1002
1003  /* An injected-class-name is not a specialization.  */
1004  if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1005    return type;
1006
1007  if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1008    {
1009      error ("name of class shadows template template parameter %qD",
1010	     TYPE_NAME (type));
1011      return error_mark_node;
1012    }
1013
1014  context = TYPE_CONTEXT (type);
1015
1016  if (TYPE_ALIAS_P (type))
1017    {
1018      tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1019
1020      if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1021	error ("specialization of alias template %qD",
1022	       TI_TEMPLATE (tinfo));
1023      else
1024	error ("explicit specialization of non-template %qT", type);
1025      return error_mark_node;
1026    }
1027  else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1028    {
1029      /* This is for ordinary explicit specialization and partial
1030	 specialization of a template class such as:
1031
1032	   template <> class C<int>;
1033
1034	 or:
1035
1036	   template <class T> class C<T*>;
1037
1038	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1039
1040      if (maybe_new_partial_specialization (type))
1041	{
1042	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1043	      && !at_namespace_scope_p ())
1044	    return error_mark_node;
1045	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1046	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1047	  if (processing_template_decl)
1048	    {
1049	      tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1050	      if (decl == error_mark_node)
1051		return error_mark_node;
1052	      return TREE_TYPE (decl);
1053	    }
1054	}
1055      else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1056	error ("specialization of %qT after instantiation", type);
1057      else if (errorcount && !processing_specialization
1058	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1059	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1060	/* Trying to define a specialization either without a template<> header
1061	   or in an inappropriate place.  We've already given an error, so just
1062	   bail now so we don't actually define the specialization.  */
1063	return error_mark_node;
1064    }
1065  else if (CLASS_TYPE_P (type)
1066	   && !CLASSTYPE_USE_TEMPLATE (type)
1067	   && CLASSTYPE_TEMPLATE_INFO (type)
1068	   && context && CLASS_TYPE_P (context)
1069	   && CLASSTYPE_TEMPLATE_INFO (context))
1070    {
1071      /* This is for an explicit specialization of member class
1072	 template according to [temp.expl.spec/18]:
1073
1074	   template <> template <class U> class C<int>::D;
1075
1076	 The context `C<int>' must be an implicit instantiation.
1077	 Otherwise this is just a member class template declared
1078	 earlier like:
1079
1080	   template <> class C<int> { template <class U> class D; };
1081	   template <> template <class U> class C<int>::D;
1082
1083	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1084	 while in the second case, `C<int>::D' is a primary template
1085	 and `C<T>::D' may not exist.  */
1086
1087      if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1088	  && !COMPLETE_TYPE_P (type))
1089	{
1090	  tree t;
1091	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1092
1093	  if (current_namespace
1094	      != decl_namespace_context (tmpl))
1095	    {
1096	      if (permerror (input_location,
1097			     "specialization of %qD in different namespace",
1098			     type))
1099		inform (DECL_SOURCE_LOCATION (tmpl),
1100			"from definition of %q#D", tmpl);
1101	    }
1102
1103	  /* Check for invalid specialization after instantiation:
1104
1105	       template <> template <> class C<int>::D<int>;
1106	       template <> template <class U> class C<int>::D;  */
1107
1108	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1109	       t; t = TREE_CHAIN (t))
1110	    {
1111	      tree inst = TREE_VALUE (t);
1112	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1113		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1114		{
1115		  /* We already have a full specialization of this partial
1116		     instantiation, or a full specialization has been
1117		     looked up but not instantiated.  Reassign it to the
1118		     new member specialization template.  */
1119		  spec_entry elt;
1120		  spec_entry *entry;
1121
1122		  elt.tmpl = most_general_template (tmpl);
1123		  elt.args = CLASSTYPE_TI_ARGS (inst);
1124		  elt.spec = inst;
1125
1126		  type_specializations->remove_elt (&elt);
1127
1128		  elt.tmpl = tmpl;
1129		  CLASSTYPE_TI_ARGS (inst)
1130		    = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1131
1132		  spec_entry **slot
1133		    = type_specializations->find_slot (&elt, INSERT);
1134		  entry = ggc_alloc<spec_entry> ();
1135		  *entry = elt;
1136		  *slot = entry;
1137		}
1138	      else
1139		/* But if we've had an implicit instantiation, that's a
1140		   problem ([temp.expl.spec]/6).  */
1141		error ("specialization %qT after instantiation %qT",
1142		       type, inst);
1143	    }
1144
1145	  /* Mark TYPE as a specialization.  And as a result, we only
1146	     have one level of template argument for the innermost
1147	     class template.  */
1148	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1149	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1150	  CLASSTYPE_TI_ARGS (type)
1151	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1152	}
1153    }
1154  else if (processing_specialization)
1155    {
1156       /* Someday C++0x may allow for enum template specialization.  */
1157      if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1158	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1159	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1160		 "of %qD not allowed by ISO C++", type);
1161      else
1162	{
1163	  error ("explicit specialization of non-template %qT", type);
1164	  return error_mark_node;
1165	}
1166    }
1167
1168  return type;
1169}
1170
1171/* Returns nonzero if we can optimize the retrieval of specializations
1172   for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1173   do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1174
1175static inline bool
1176optimize_specialization_lookup_p (tree tmpl)
1177{
1178  return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1179	  && DECL_CLASS_SCOPE_P (tmpl)
1180	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1181	     parameter.  */
1182	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1183	  /* The optimized lookup depends on the fact that the
1184	     template arguments for the member function template apply
1185	     purely to the containing class, which is not true if the
1186	     containing class is an explicit or partial
1187	     specialization.  */
1188	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1189	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1190	  && !DECL_CONV_FN_P (tmpl)
1191	  /* It is possible to have a template that is not a member
1192	     template and is not a member of a template class:
1193
1194	     template <typename T>
1195	     struct S { friend A::f(); };
1196
1197	     Here, the friend function is a template, but the context does
1198	     not have template information.  The optimized lookup relies
1199	     on having ARGS be the template arguments for both the class
1200	     and the function template.  */
1201	  && !DECL_UNIQUE_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1202}
1203
1204/* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1205   gone through coerce_template_parms by now.  */
1206
1207static void
1208verify_unstripped_args_1 (tree inner)
1209{
1210  for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1211    {
1212      tree arg = TREE_VEC_ELT (inner, i);
1213      if (TREE_CODE (arg) == TEMPLATE_DECL)
1214	/* OK */;
1215      else if (TYPE_P (arg))
1216	gcc_assert (strip_typedefs (arg, NULL) == arg);
1217      else if (ARGUMENT_PACK_P (arg))
1218	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1219      else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1220	/* Allow typedefs on the type of a non-type argument, since a
1221	   parameter can have them.  */;
1222      else
1223	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1224    }
1225}
1226
1227static void
1228verify_unstripped_args (tree args)
1229{
1230  ++processing_template_decl;
1231  if (!any_dependent_template_arguments_p (args))
1232    verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1233  --processing_template_decl;
1234}
1235
1236/* Retrieve the specialization (in the sense of [temp.spec] - a
1237   specialization is either an instantiation or an explicit
1238   specialization) of TMPL for the given template ARGS.  If there is
1239   no such specialization, return NULL_TREE.  The ARGS are a vector of
1240   arguments, or a vector of vectors of arguments, in the case of
1241   templates with more than one level of parameters.
1242
1243   If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1244   then we search for a partial specialization matching ARGS.  This
1245   parameter is ignored if TMPL is not a class template.
1246
1247   We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1248   result is a NONTYPE_ARGUMENT_PACK.  */
1249
1250static tree
1251retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1252{
1253  if (tmpl == NULL_TREE)
1254    return NULL_TREE;
1255
1256  if (args == error_mark_node)
1257    return NULL_TREE;
1258
1259  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1260	      || TREE_CODE (tmpl) == FIELD_DECL);
1261
1262  /* There should be as many levels of arguments as there are
1263     levels of parameters.  */
1264  gcc_assert (TMPL_ARGS_DEPTH (args)
1265	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1266		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1267		  : template_class_depth (DECL_CONTEXT (tmpl))));
1268
1269  if (flag_checking)
1270    verify_unstripped_args (args);
1271
1272  /* Lambda functions in templates aren't instantiated normally, but through
1273     tsubst_lambda_expr.  */
1274  if (lambda_fn_in_template_p (tmpl))
1275    return NULL_TREE;
1276
1277  if (optimize_specialization_lookup_p (tmpl))
1278    {
1279      /* The template arguments actually apply to the containing
1280	 class.  Find the class specialization with those
1281	 arguments.  */
1282      tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1283      tree class_specialization
1284	= retrieve_specialization (class_template, args, 0);
1285      if (!class_specialization)
1286	return NULL_TREE;
1287
1288      /* Find the instance of TMPL.  */
1289      tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1290      for (ovl_iterator iter (fns); iter; ++iter)
1291	{
1292	  tree fn = *iter;
1293	  if (tree ti = get_template_info (fn))
1294	    if (TI_TEMPLATE (ti) == tmpl
1295		/* using-declarations can bring in a different
1296		   instantiation of tmpl as a member of a different
1297		   instantiation of tmpl's class.  We don't want those
1298		   here.  */
1299		&& DECL_CONTEXT (fn) == class_specialization)
1300	      return fn;
1301	}
1302      return NULL_TREE;
1303    }
1304  else
1305    {
1306      spec_entry *found;
1307      spec_entry elt;
1308      spec_hash_table *specializations;
1309
1310      elt.tmpl = tmpl;
1311      elt.args = args;
1312      elt.spec = NULL_TREE;
1313
1314      if (DECL_CLASS_TEMPLATE_P (tmpl))
1315	specializations = type_specializations;
1316      else
1317	specializations = decl_specializations;
1318
1319      if (hash == 0)
1320	hash = spec_hasher::hash (&elt);
1321      found = specializations->find_with_hash (&elt, hash);
1322      if (found)
1323	return found->spec;
1324    }
1325
1326  return NULL_TREE;
1327}
1328
1329/* Like retrieve_specialization, but for local declarations.  */
1330
1331tree
1332retrieve_local_specialization (tree tmpl)
1333{
1334  if (local_specializations == NULL)
1335    return NULL_TREE;
1336
1337  tree *slot = local_specializations->get (tmpl);
1338  return slot ? *slot : NULL_TREE;
1339}
1340
1341/* Returns nonzero iff DECL is a specialization of TMPL.  */
1342
1343int
1344is_specialization_of (tree decl, tree tmpl)
1345{
1346  tree t;
1347
1348  if (TREE_CODE (decl) == FUNCTION_DECL)
1349    {
1350      for (t = decl;
1351	   t != NULL_TREE;
1352	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1353	if (t == tmpl)
1354	  return 1;
1355    }
1356  else
1357    {
1358      gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1359
1360      for (t = TREE_TYPE (decl);
1361	   t != NULL_TREE;
1362	   t = CLASSTYPE_USE_TEMPLATE (t)
1363	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1364	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1365	  return 1;
1366    }
1367
1368  return 0;
1369}
1370
1371/* Returns nonzero iff DECL is a specialization of friend declaration
1372   FRIEND_DECL according to [temp.friend].  */
1373
1374bool
1375is_specialization_of_friend (tree decl, tree friend_decl)
1376{
1377  bool need_template = true;
1378  int template_depth;
1379
1380  gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1381	      || TREE_CODE (decl) == TYPE_DECL);
1382
1383  /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1384     of a template class, we want to check if DECL is a specialization
1385     if this.  */
1386  if (TREE_CODE (friend_decl) == FUNCTION_DECL
1387      && DECL_TEMPLATE_INFO (friend_decl)
1388      && !DECL_USE_TEMPLATE (friend_decl))
1389    {
1390      /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1391      friend_decl = DECL_TI_TEMPLATE (friend_decl);
1392      need_template = false;
1393    }
1394  else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1395	   && !PRIMARY_TEMPLATE_P (friend_decl))
1396    need_template = false;
1397
1398  /* There is nothing to do if this is not a template friend.  */
1399  if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1400    return false;
1401
1402  if (is_specialization_of (decl, friend_decl))
1403    return true;
1404
1405  /* [temp.friend/6]
1406     A member of a class template may be declared to be a friend of a
1407     non-template class.  In this case, the corresponding member of
1408     every specialization of the class template is a friend of the
1409     class granting friendship.
1410
1411     For example, given a template friend declaration
1412
1413       template <class T> friend void A<T>::f();
1414
1415     the member function below is considered a friend
1416
1417       template <> struct A<int> {
1418	 void f();
1419       };
1420
1421     For this type of template friend, TEMPLATE_DEPTH below will be
1422     nonzero.  To determine if DECL is a friend of FRIEND, we first
1423     check if the enclosing class is a specialization of another.  */
1424
1425  template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1426  if (template_depth
1427      && DECL_CLASS_SCOPE_P (decl)
1428      && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1429			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1430    {
1431      /* Next, we check the members themselves.  In order to handle
1432	 a few tricky cases, such as when FRIEND_DECL's are
1433
1434	   template <class T> friend void A<T>::g(T t);
1435	   template <class T> template <T t> friend void A<T>::h();
1436
1437	 and DECL's are
1438
1439	   void A<int>::g(int);
1440	   template <int> void A<int>::h();
1441
1442	 we need to figure out ARGS, the template arguments from
1443	 the context of DECL.  This is required for template substitution
1444	 of `T' in the function parameter of `g' and template parameter
1445	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1446
1447      tree context = DECL_CONTEXT (decl);
1448      tree args = NULL_TREE;
1449      int current_depth = 0;
1450
1451      while (current_depth < template_depth)
1452	{
1453	  if (CLASSTYPE_TEMPLATE_INFO (context))
1454	    {
1455	      if (current_depth == 0)
1456		args = TYPE_TI_ARGS (context);
1457	      else
1458		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1459	      current_depth++;
1460	    }
1461	  context = TYPE_CONTEXT (context);
1462	}
1463
1464      if (TREE_CODE (decl) == FUNCTION_DECL)
1465	{
1466	  bool is_template;
1467	  tree friend_type;
1468	  tree decl_type;
1469	  tree friend_args_type;
1470	  tree decl_args_type;
1471
1472	  /* Make sure that both DECL and FRIEND_DECL are templates or
1473	     non-templates.  */
1474	  is_template = DECL_TEMPLATE_INFO (decl)
1475			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1476	  if (need_template ^ is_template)
1477	    return false;
1478	  else if (is_template)
1479	    {
1480	      /* If both are templates, check template parameter list.  */
1481	      tree friend_parms
1482		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1483					 args, tf_none);
1484	      if (!comp_template_parms
1485		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1486		      friend_parms))
1487		return false;
1488
1489	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1490	    }
1491	  else
1492	    decl_type = TREE_TYPE (decl);
1493
1494	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1495					      tf_none, NULL_TREE);
1496	  if (friend_type == error_mark_node)
1497	    return false;
1498
1499	  /* Check if return types match.  */
1500	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1501	    return false;
1502
1503	  /* Check if function parameter types match, ignoring the
1504	     `this' parameter.  */
1505	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1506	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1507	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1508	    friend_args_type = TREE_CHAIN (friend_args_type);
1509	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1510	    decl_args_type = TREE_CHAIN (decl_args_type);
1511
1512	  return compparms (decl_args_type, friend_args_type);
1513	}
1514      else
1515	{
1516	  /* DECL is a TYPE_DECL */
1517	  bool is_template;
1518	  tree decl_type = TREE_TYPE (decl);
1519
1520	  /* Make sure that both DECL and FRIEND_DECL are templates or
1521	     non-templates.  */
1522	  is_template
1523	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1524	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1525
1526	  if (need_template ^ is_template)
1527	    return false;
1528	  else if (is_template)
1529	    {
1530	      tree friend_parms;
1531	      /* If both are templates, check the name of the two
1532		 TEMPLATE_DECL's first because is_friend didn't.  */
1533	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1534		  != DECL_NAME (friend_decl))
1535		return false;
1536
1537	      /* Now check template parameter list.  */
1538	      friend_parms
1539		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1540					 args, tf_none);
1541	      return comp_template_parms
1542		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1543		 friend_parms);
1544	    }
1545	  else
1546	    return (DECL_NAME (decl)
1547		    == DECL_NAME (friend_decl));
1548	}
1549    }
1550  return false;
1551}
1552
1553/* Register the specialization SPEC as a specialization of TMPL with
1554   the indicated ARGS.  IS_FRIEND indicates whether the specialization
1555   is actually just a friend declaration.  ATTRLIST is the list of
1556   attributes that the specialization is declared with or NULL when
1557   it isn't.  Returns SPEC, or an equivalent prior declaration, if
1558   available.
1559
1560   We also store instantiations of field packs in the hash table, even
1561   though they are not themselves templates, to make lookup easier.  */
1562
1563static tree
1564register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1565			 hashval_t hash)
1566{
1567  tree fn;
1568  spec_entry **slot = NULL;
1569  spec_entry elt;
1570
1571  gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1572	      || (TREE_CODE (tmpl) == FIELD_DECL
1573		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1574
1575  if (TREE_CODE (spec) == FUNCTION_DECL
1576      && uses_template_parms (DECL_TI_ARGS (spec)))
1577    /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1578       register it; we want the corresponding TEMPLATE_DECL instead.
1579       We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1580       the more obvious `uses_template_parms (spec)' to avoid problems
1581       with default function arguments.  In particular, given
1582       something like this:
1583
1584	  template <class T> void f(T t1, T t = T())
1585
1586       the default argument expression is not substituted for in an
1587       instantiation unless and until it is actually needed.  */
1588    return spec;
1589
1590  if (optimize_specialization_lookup_p (tmpl))
1591    /* We don't put these specializations in the hash table, but we might
1592       want to give an error about a mismatch.  */
1593    fn = retrieve_specialization (tmpl, args, 0);
1594  else
1595    {
1596      elt.tmpl = tmpl;
1597      elt.args = args;
1598      elt.spec = spec;
1599
1600      if (hash == 0)
1601	hash = spec_hasher::hash (&elt);
1602
1603      slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1604      if (*slot)
1605	fn = (*slot)->spec;
1606      else
1607	fn = NULL_TREE;
1608    }
1609
1610  /* We can sometimes try to re-register a specialization that we've
1611     already got.  In particular, regenerate_decl_from_template calls
1612     duplicate_decls which will update the specialization list.  But,
1613     we'll still get called again here anyhow.  It's more convenient
1614     to simply allow this than to try to prevent it.  */
1615  if (fn == spec)
1616    return spec;
1617  else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1618    {
1619      if (DECL_TEMPLATE_INSTANTIATION (fn))
1620	{
1621	  if (DECL_ODR_USED (fn)
1622	      || DECL_EXPLICIT_INSTANTIATION (fn))
1623	    {
1624	      error ("specialization of %qD after instantiation",
1625		     fn);
1626	      return error_mark_node;
1627	    }
1628	  else
1629	    {
1630	      tree clone;
1631	      /* This situation should occur only if the first
1632		 specialization is an implicit instantiation, the
1633		 second is an explicit specialization, and the
1634		 implicit instantiation has not yet been used.  That
1635		 situation can occur if we have implicitly
1636		 instantiated a member function and then specialized
1637		 it later.
1638
1639		 We can also wind up here if a friend declaration that
1640		 looked like an instantiation turns out to be a
1641		 specialization:
1642
1643		   template <class T> void foo(T);
1644		   class S { friend void foo<>(int) };
1645		   template <> void foo(int);
1646
1647		 We transform the existing DECL in place so that any
1648		 pointers to it become pointers to the updated
1649		 declaration.
1650
1651		 If there was a definition for the template, but not
1652		 for the specialization, we want this to look as if
1653		 there were no definition, and vice versa.  */
1654	      DECL_INITIAL (fn) = NULL_TREE;
1655	      duplicate_decls (spec, fn, /*hiding=*/is_friend);
1656	      /* The call to duplicate_decls will have applied
1657		 [temp.expl.spec]:
1658
1659		   An explicit specialization of a function template
1660		   is inline only if it is explicitly declared to be,
1661		   and independently of whether its function template
1662		   is.
1663
1664		to the primary function; now copy the inline bits to
1665		the various clones.  */
1666	      FOR_EACH_CLONE (clone, fn)
1667		{
1668		  DECL_DECLARED_INLINE_P (clone)
1669		    = DECL_DECLARED_INLINE_P (fn);
1670		  DECL_SOURCE_LOCATION (clone)
1671		    = DECL_SOURCE_LOCATION (fn);
1672		  DECL_DELETED_FN (clone)
1673		    = DECL_DELETED_FN (fn);
1674		}
1675	      check_specialization_namespace (tmpl);
1676
1677	      return fn;
1678	    }
1679	}
1680      else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1681	{
1682	  tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1683	  if (dd == error_mark_node)
1684	    /* We've already complained in duplicate_decls.  */
1685	    return error_mark_node;
1686
1687	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1688	    /* Dup decl failed, but this is a new definition. Set the
1689	       line number so any errors match this new
1690	       definition.  */
1691	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1692
1693	  return fn;
1694	}
1695    }
1696  else if (fn)
1697    return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1698
1699  /* A specialization must be declared in the same namespace as the
1700     template it is specializing.  */
1701  if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1702      && !check_specialization_namespace (tmpl))
1703    DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1704
1705  if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1706    {
1707      spec_entry *entry = ggc_alloc<spec_entry> ();
1708      gcc_assert (tmpl && args && spec);
1709      *entry = elt;
1710      *slot = entry;
1711      if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1712	   && PRIMARY_TEMPLATE_P (tmpl)
1713	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1714	  || variable_template_p (tmpl))
1715	/* If TMPL is a forward declaration of a template function, keep a list
1716	   of all specializations in case we need to reassign them to a friend
1717	   template later in tsubst_friend_function.
1718
1719	   Also keep a list of all variable template instantiations so that
1720	   process_partial_specialization can check whether a later partial
1721	   specialization would have used it.  */
1722	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1723	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1724    }
1725
1726  return spec;
1727}
1728
1729/* Restricts tree and type comparisons.  */
1730int comparing_specializations;
1731int comparing_dependent_aliases;
1732
1733/* Returns true iff two spec_entry nodes are equivalent.  */
1734
1735bool
1736spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1737{
1738  int equal;
1739
1740  ++comparing_specializations;
1741  ++comparing_dependent_aliases;
1742  ++processing_template_decl;
1743  equal = (e1->tmpl == e2->tmpl
1744	   && comp_template_args (e1->args, e2->args));
1745  if (equal && flag_concepts
1746      /* tmpl could be a FIELD_DECL for a capture pack.  */
1747      && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1748      && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1749      && uses_template_parms (e1->args))
1750    {
1751      /* Partial specializations of a variable template can be distinguished by
1752	 constraints.  */
1753      tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1754      tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1755      equal = equivalent_constraints (c1, c2);
1756    }
1757  --processing_template_decl;
1758  --comparing_dependent_aliases;
1759  --comparing_specializations;
1760
1761  return equal;
1762}
1763
1764/* Returns a hash for a template TMPL and template arguments ARGS.  */
1765
1766static hashval_t
1767hash_tmpl_and_args (tree tmpl, tree args)
1768{
1769  hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1770  return iterative_hash_template_arg (args, val);
1771}
1772
1773/* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1774   ignoring SPEC.  */
1775
1776hashval_t
1777spec_hasher::hash (spec_entry *e)
1778{
1779  return hash_tmpl_and_args (e->tmpl, e->args);
1780}
1781
1782/* Recursively calculate a hash value for a template argument ARG, for use
1783   in the hash tables of template specializations.   We must be
1784   careful to (at least) skip the same entities template_args_equal
1785   does.  */
1786
1787hashval_t
1788iterative_hash_template_arg (tree arg, hashval_t val)
1789{
1790  if (arg == NULL_TREE)
1791    return iterative_hash_object (arg, val);
1792
1793  if (!TYPE_P (arg))
1794    /* Strip nop-like things, but not the same as STRIP_NOPS.  */
1795    while (CONVERT_EXPR_P (arg)
1796	   || TREE_CODE (arg) == NON_LVALUE_EXPR
1797	   || class_nttp_const_wrapper_p (arg))
1798      arg = TREE_OPERAND (arg, 0);
1799
1800  enum tree_code code = TREE_CODE (arg);
1801
1802  val = iterative_hash_object (code, val);
1803
1804  switch (code)
1805    {
1806    case ARGUMENT_PACK_SELECT:
1807      /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1808	 preserving it in a hash table, which is bad because it will change
1809	 meaning when gen_elem_of_pack_expansion_instantiation changes the
1810	 ARGUMENT_PACK_SELECT_INDEX.  */
1811      gcc_unreachable ();
1812
1813    case ERROR_MARK:
1814      return val;
1815
1816    case IDENTIFIER_NODE:
1817      return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1818
1819    case TREE_VEC:
1820      for (int i = 0, len = TREE_VEC_LENGTH (arg); i < len; ++i)
1821	val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1822      return val;
1823
1824    case TYPE_PACK_EXPANSION:
1825    case EXPR_PACK_EXPANSION:
1826      val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1827      return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1828
1829    case TYPE_ARGUMENT_PACK:
1830    case NONTYPE_ARGUMENT_PACK:
1831      return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1832
1833    case TREE_LIST:
1834      for (; arg; arg = TREE_CHAIN (arg))
1835	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1836      return val;
1837
1838    case OVERLOAD:
1839      for (lkp_iterator iter (arg); iter; ++iter)
1840	val = iterative_hash_template_arg (*iter, val);
1841      return val;
1842
1843    case CONSTRUCTOR:
1844      {
1845	iterative_hash_template_arg (TREE_TYPE (arg), val);
1846	for (auto &e: CONSTRUCTOR_ELTS (arg))
1847	  {
1848	    val = iterative_hash_template_arg (e.index, val);
1849	    val = iterative_hash_template_arg (e.value, val);
1850	  }
1851	return val;
1852      }
1853
1854    case PARM_DECL:
1855      if (!DECL_ARTIFICIAL (arg))
1856	{
1857	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1858	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1859	}
1860      return iterative_hash_template_arg (TREE_TYPE (arg), val);
1861
1862    case TARGET_EXPR:
1863      return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1864
1865    case PTRMEM_CST:
1866      val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1867      return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1868
1869    case TEMPLATE_PARM_INDEX:
1870      val = iterative_hash_template_arg
1871	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1872      val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1873      return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1874
1875    case TRAIT_EXPR:
1876      val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1877      val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1878      return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1879
1880    case BASELINK:
1881      val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1882					 val);
1883      return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1884					  val);
1885
1886    case MODOP_EXPR:
1887      val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1888      code = TREE_CODE (TREE_OPERAND (arg, 1));
1889      val = iterative_hash_object (code, val);
1890      return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1891
1892    case LAMBDA_EXPR:
1893      /* [temp.over.link] Two lambda-expressions are never considered
1894	 equivalent.
1895
1896         So just hash the closure type.  */
1897      return iterative_hash_template_arg (TREE_TYPE (arg), val);
1898
1899    case CAST_EXPR:
1900    case IMPLICIT_CONV_EXPR:
1901    case STATIC_CAST_EXPR:
1902    case REINTERPRET_CAST_EXPR:
1903    case CONST_CAST_EXPR:
1904    case DYNAMIC_CAST_EXPR:
1905    case NEW_EXPR:
1906      val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1907      /* Now hash operands as usual.  */
1908      break;
1909
1910    case CALL_EXPR:
1911      {
1912	tree fn = CALL_EXPR_FN (arg);
1913	if (tree name = call_expr_dependent_name (arg))
1914	  {
1915	    if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1916	      val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1917	    fn = name;
1918	  }
1919	val = iterative_hash_template_arg (fn, val);
1920	call_expr_arg_iterator ai;
1921	for (tree x = first_call_expr_arg (arg, &ai); x;
1922	     x = next_call_expr_arg (&ai))
1923	  val = iterative_hash_template_arg (x, val);
1924	return val;
1925      }
1926
1927    default:
1928      break;
1929    }
1930
1931  char tclass = TREE_CODE_CLASS (code);
1932  switch (tclass)
1933    {
1934    case tcc_type:
1935      if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1936	{
1937	  // We want an alias specialization that survived strip_typedefs
1938	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1939	  // collisions that compare as different in template_args_equal.
1940	  // These could be dependent specializations that strip_typedefs
1941	  // left alone, or untouched specializations because
1942	  // coerce_template_parms returns the unconverted template
1943	  // arguments if it sees incomplete argument packs.
1944	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1945	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1946	}
1947
1948      switch (TREE_CODE (arg))
1949	{
1950	case TEMPLATE_TEMPLATE_PARM:
1951	  {
1952	    tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1953
1954	    /* Do not recurse with TPI directly, as that is unbounded
1955	       recursion.  */
1956	    val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1957	    val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1958	  }
1959	  break;
1960
1961	case  DECLTYPE_TYPE:
1962	  val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1963	  break;
1964
1965	default:
1966	  if (tree canonical = TYPE_CANONICAL (arg))
1967	    val = iterative_hash_object (TYPE_HASH (canonical), val);
1968	  break;
1969	}
1970
1971      return val;
1972
1973    case tcc_declaration:
1974    case tcc_constant:
1975      return iterative_hash_expr (arg, val);
1976
1977    default:
1978      gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1979      for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1980	val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1981      return val;
1982    }
1983}
1984
1985/* Unregister the specialization SPEC as a specialization of TMPL.
1986   Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1987   if the SPEC was listed as a specialization of TMPL.
1988
1989   Note that SPEC has been ggc_freed, so we can't look inside it.  */
1990
1991bool
1992reregister_specialization (tree spec, tree tinfo, tree new_spec)
1993{
1994  spec_entry *entry;
1995  spec_entry elt;
1996
1997  elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1998  elt.args = TI_ARGS (tinfo);
1999  elt.spec = NULL_TREE;
2000
2001  entry = decl_specializations->find (&elt);
2002  if (entry != NULL)
2003    {
2004      gcc_assert (entry->spec == spec || entry->spec == new_spec);
2005      gcc_assert (new_spec != NULL_TREE);
2006      entry->spec = new_spec;
2007      return 1;
2008    }
2009
2010  return 0;
2011}
2012
2013/* Like register_specialization, but for local declarations.  We are
2014   registering SPEC, an instantiation of TMPL.  */
2015
2016void
2017register_local_specialization (tree spec, tree tmpl)
2018{
2019  gcc_assert (tmpl != spec);
2020  local_specializations->put (tmpl, spec);
2021}
2022
2023/* TYPE is a class type.  Returns true if TYPE is an explicitly
2024   specialized class.  */
2025
2026bool
2027explicit_class_specialization_p (tree type)
2028{
2029  if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2030    return false;
2031  return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2032}
2033
2034/* Print the list of functions at FNS, going through all the overloads
2035   for each element of the list.  Alternatively, FNS cannot be a
2036   TREE_LIST, in which case it will be printed together with all the
2037   overloads.
2038
2039   MORE and *STR should respectively be FALSE and NULL when the function
2040   is called from the outside.  They are used internally on recursive
2041   calls.  print_candidates manages the two parameters and leaves NULL
2042   in *STR when it ends.  */
2043
2044static void
2045print_candidates_1 (tree fns, char **str, bool more = false)
2046{
2047  if (TREE_CODE (fns) == TREE_LIST)
2048    for (; fns; fns = TREE_CHAIN (fns))
2049      print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2050  else
2051    for (lkp_iterator iter (fns); iter;)
2052      {
2053	tree cand = *iter;
2054	++iter;
2055
2056	const char *pfx = *str;
2057	if (!pfx)
2058	  {
2059	    if (more || iter)
2060	      pfx = _("candidates are:");
2061	    else
2062	      pfx = _("candidate is:");
2063	    *str = get_spaces (pfx);
2064	  }
2065	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2066      }
2067}
2068
2069/* Print the list of candidate FNS in an error message.  FNS can also
2070   be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2071
2072void
2073print_candidates (tree fns)
2074{
2075  char *str = NULL;
2076  print_candidates_1 (fns, &str);
2077  free (str);
2078}
2079
2080/* Get a (possibly) constrained template declaration for the
2081   purpose of ordering candidates.  */
2082static tree
2083get_template_for_ordering (tree list)
2084{
2085  gcc_assert (TREE_CODE (list) == TREE_LIST);
2086  tree f = TREE_VALUE (list);
2087  if (tree ti = DECL_TEMPLATE_INFO (f))
2088    return TI_TEMPLATE (ti);
2089  return f;
2090}
2091
2092/* Among candidates having the same signature, return the
2093   most constrained or NULL_TREE if there is no best candidate.
2094   If the signatures of candidates vary (e.g., template
2095   specialization vs. member function), then there can be no
2096   most constrained.
2097
2098   Note that we don't compare constraints on the functions
2099   themselves, but rather those of their templates. */
2100static tree
2101most_constrained_function (tree candidates)
2102{
2103  // Try to find the best candidate in a first pass.
2104  tree champ = candidates;
2105  for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2106    {
2107      int winner = more_constrained (get_template_for_ordering (champ),
2108                                     get_template_for_ordering (c));
2109      if (winner == -1)
2110        champ = c; // The candidate is more constrained
2111      else if (winner == 0)
2112        return NULL_TREE; // Neither is more constrained
2113    }
2114
2115  // Verify that the champ is better than previous candidates.
2116  for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2117    if (!more_constrained (get_template_for_ordering (champ),
2118                           get_template_for_ordering (c)))
2119      return NULL_TREE;
2120  }
2121
2122  return champ;
2123}
2124
2125
2126/* Returns the template (one of the functions given by TEMPLATE_ID)
2127   which can be specialized to match the indicated DECL with the
2128   explicit template args given in TEMPLATE_ID.  The DECL may be
2129   NULL_TREE if none is available.  In that case, the functions in
2130   TEMPLATE_ID are non-members.
2131
2132   If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2133   specialization of a member template.
2134
2135   The TEMPLATE_COUNT is the number of references to qualifying
2136   template classes that appeared in the name of the function. See
2137   check_explicit_specialization for a more accurate description.
2138
2139   TSK indicates what kind of template declaration (if any) is being
2140   declared.  TSK_TEMPLATE indicates that the declaration given by
2141   DECL, though a FUNCTION_DECL, has template parameters, and is
2142   therefore a template function.
2143
2144   The template args (those explicitly specified and those deduced)
2145   are output in a newly created vector *TARGS_OUT.
2146
2147   If it is impossible to determine the result, an error message is
2148   issued.  The error_mark_node is returned to indicate failure.  */
2149
2150static tree
2151determine_specialization (tree template_id,
2152			  tree decl,
2153			  tree* targs_out,
2154			  int need_member_template,
2155			  int template_count,
2156			  tmpl_spec_kind tsk)
2157{
2158  tree fns;
2159  tree targs;
2160  tree explicit_targs;
2161  tree candidates = NULL_TREE;
2162
2163  /* A TREE_LIST of templates of which DECL may be a specialization.
2164     The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2165     corresponding TREE_PURPOSE is the set of template arguments that,
2166     when used to instantiate the template, would produce a function
2167     with the signature of DECL.  */
2168  tree templates = NULL_TREE;
2169  int header_count;
2170  cp_binding_level *b;
2171
2172  *targs_out = NULL_TREE;
2173
2174  if (template_id == error_mark_node || decl == error_mark_node)
2175    return error_mark_node;
2176
2177  /* We shouldn't be specializing a member template of an
2178     unspecialized class template; we already gave an error in
2179     check_specialization_scope, now avoid crashing.  */
2180  if (!VAR_P (decl)
2181      && template_count && DECL_CLASS_SCOPE_P (decl)
2182      && template_class_depth (DECL_CONTEXT (decl)) > 0)
2183    {
2184      gcc_assert (errorcount);
2185      return error_mark_node;
2186    }
2187
2188  fns = TREE_OPERAND (template_id, 0);
2189  explicit_targs = TREE_OPERAND (template_id, 1);
2190
2191  if (fns == error_mark_node)
2192    return error_mark_node;
2193
2194  /* Check for baselinks.  */
2195  if (BASELINK_P (fns))
2196    fns = BASELINK_FUNCTIONS (fns);
2197
2198  if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2199    {
2200      error_at (DECL_SOURCE_LOCATION (decl),
2201		"%qD is not a function template", fns);
2202      return error_mark_node;
2203    }
2204  else if (VAR_P (decl) && !variable_template_p (fns))
2205    {
2206      error ("%qD is not a variable template", fns);
2207      return error_mark_node;
2208    }
2209
2210  /* Count the number of template headers specified for this
2211     specialization.  */
2212  header_count = 0;
2213  for (b = current_binding_level;
2214       b->kind == sk_template_parms;
2215       b = b->level_chain)
2216    ++header_count;
2217
2218  tree orig_fns = fns;
2219  bool header_mismatch = false;
2220
2221  if (variable_template_p (fns))
2222    {
2223      tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2224      targs = coerce_template_parms (parms, explicit_targs, fns,
2225				     tf_warning_or_error,
2226				     /*req_all*/true, /*use_defarg*/true);
2227      if (targs != error_mark_node
2228	  && constraints_satisfied_p (fns, targs))
2229        templates = tree_cons (targs, fns, templates);
2230    }
2231  else for (lkp_iterator iter (fns); iter; ++iter)
2232    {
2233      tree fn = *iter;
2234
2235      if (TREE_CODE (fn) == TEMPLATE_DECL)
2236	{
2237	  tree decl_arg_types;
2238	  tree fn_arg_types;
2239
2240	  /* In case of explicit specialization, we need to check if
2241	     the number of template headers appearing in the specialization
2242	     is correct. This is usually done in check_explicit_specialization,
2243	     but the check done there cannot be exhaustive when specializing
2244	     member functions. Consider the following code:
2245
2246	     template <> void A<int>::f(int);
2247	     template <> template <> void A<int>::f(int);
2248
2249	     Assuming that A<int> is not itself an explicit specialization
2250	     already, the first line specializes "f" which is a non-template
2251	     member function, whilst the second line specializes "f" which
2252	     is a template member function. So both lines are syntactically
2253	     correct, and check_explicit_specialization does not reject
2254	     them.
2255
2256	     Here, we can do better, as we are matching the specialization
2257	     against the declarations. We count the number of template
2258	     headers, and we check if they match TEMPLATE_COUNT + 1
2259	     (TEMPLATE_COUNT is the number of qualifying template classes,
2260	     plus there must be another header for the member template
2261	     itself).
2262
2263	     Notice that if header_count is zero, this is not a
2264	     specialization but rather a template instantiation, so there
2265	     is no check we can perform here.  */
2266	  if (header_count && header_count != template_count + 1)
2267	    {
2268	      header_mismatch = true;
2269	      continue;
2270	    }
2271
2272	  /* Check that the number of template arguments at the
2273	     innermost level for DECL is the same as for FN.  */
2274	  if (current_binding_level->kind == sk_template_parms
2275	      && !current_binding_level->explicit_spec_p
2276	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2277		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2278				      (current_template_parms))))
2279	    continue;
2280
2281	  /* DECL might be a specialization of FN.  */
2282	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2283	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2284
2285	  /* For a non-static member function, we need to make sure
2286	     that the const qualification is the same.  Since
2287	     get_bindings does not try to merge the "this" parameter,
2288	     we must do the comparison explicitly.  */
2289	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2290	    {
2291	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2292				TREE_VALUE (decl_arg_types)))
2293		continue;
2294
2295	      /* And the ref-qualification.  */
2296	      if (type_memfn_rqual (TREE_TYPE (decl))
2297		  != type_memfn_rqual (TREE_TYPE (fn)))
2298		continue;
2299	    }
2300
2301	  /* Skip the "this" parameter and, for constructors of
2302	     classes with virtual bases, the VTT parameter.  A
2303	     full specialization of a constructor will have a VTT
2304	     parameter, but a template never will.  */
2305	  decl_arg_types
2306	    = skip_artificial_parms_for (decl, decl_arg_types);
2307	  fn_arg_types
2308	    = skip_artificial_parms_for (fn, fn_arg_types);
2309
2310	  /* Function templates cannot be specializations; there are
2311	     no partial specializations of functions.  Therefore, if
2312	     the type of DECL does not match FN, there is no
2313	     match.
2314
2315             Note that it should never be the case that we have both
2316             candidates added here, and for regular member functions
2317             below. */
2318	  if (tsk == tsk_template)
2319	    {
2320	      if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2321					current_template_parms))
2322		continue;
2323	      if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2324				TREE_TYPE (TREE_TYPE (fn))))
2325		continue;
2326	      if (!compparms (fn_arg_types, decl_arg_types))
2327		continue;
2328
2329	      tree freq = get_constraints (fn);
2330	      tree dreq = get_constraints (decl);
2331	      if (!freq != !dreq)
2332		continue;
2333	      if (freq)
2334		{
2335		  /* C++20 CA104: Substitute directly into the
2336		     constraint-expression.  */
2337		  tree fargs = DECL_TI_ARGS (fn);
2338		  tsubst_flags_t complain = tf_none;
2339		  freq = tsubst_constraint_info (freq, fargs, complain, fn);
2340		  if (!cp_tree_equal (freq, dreq))
2341		    continue;
2342		}
2343
2344	      candidates = tree_cons (NULL_TREE, fn, candidates);
2345	      continue;
2346	    }
2347
2348	  /* See whether this function might be a specialization of this
2349	     template.  Suppress access control because we might be trying
2350	     to make this specialization a friend, and we have already done
2351	     access control for the declaration of the specialization.  */
2352	  push_deferring_access_checks (dk_no_check);
2353	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2354	  pop_deferring_access_checks ();
2355
2356	  if (!targs)
2357	    /* We cannot deduce template arguments that when used to
2358	       specialize TMPL will produce DECL.  */
2359	    continue;
2360
2361	  if (uses_template_parms (targs))
2362	    /* We deduced something involving 'auto', which isn't a valid
2363	       template argument.  */
2364	    continue;
2365
2366	  /* Save this template, and the arguments deduced.  */
2367	  templates = tree_cons (targs, fn, templates);
2368	}
2369      else if (need_member_template)
2370	/* FN is an ordinary member function, and we need a
2371	   specialization of a member template.  */
2372	;
2373      else if (TREE_CODE (fn) != FUNCTION_DECL)
2374	/* We can get IDENTIFIER_NODEs here in certain erroneous
2375	   cases.  */
2376	;
2377      else if (!DECL_FUNCTION_MEMBER_P (fn))
2378	/* This is just an ordinary non-member function.  Nothing can
2379	   be a specialization of that.  */
2380	;
2381      else if (DECL_ARTIFICIAL (fn))
2382	/* Cannot specialize functions that are created implicitly.  */
2383	;
2384      else
2385	{
2386	  tree decl_arg_types;
2387
2388	  /* This is an ordinary member function.  However, since
2389	     we're here, we can assume its enclosing class is a
2390	     template class.  For example,
2391
2392	       template <typename T> struct S { void f(); };
2393	       template <> void S<int>::f() {}
2394
2395	     Here, S<int>::f is a non-template, but S<int> is a
2396	     template class.  If FN has the same type as DECL, we
2397	     might be in business.  */
2398
2399	  if (!DECL_TEMPLATE_INFO (fn))
2400	    /* Its enclosing class is an explicit specialization
2401	       of a template class.  This is not a candidate.  */
2402	    continue;
2403
2404	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2405			    TREE_TYPE (TREE_TYPE (fn))))
2406	    /* The return types differ.  */
2407	    continue;
2408
2409	  /* Adjust the type of DECL in case FN is a static member.  */
2410	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2411	  if (DECL_STATIC_FUNCTION_P (fn)
2412	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2413	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2414
2415	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2416			 decl_arg_types))
2417            continue;
2418
2419	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2420	      && (type_memfn_rqual (TREE_TYPE (decl))
2421		  != type_memfn_rqual (TREE_TYPE (fn))))
2422	    continue;
2423
2424          // If the deduced arguments do not satisfy the constraints,
2425          // this is not a candidate.
2426          if (flag_concepts && !constraints_satisfied_p (fn))
2427            continue;
2428
2429          // Add the candidate.
2430          candidates = tree_cons (NULL_TREE, fn, candidates);
2431	}
2432    }
2433
2434  if (templates && TREE_CHAIN (templates))
2435    {
2436      /* We have:
2437
2438	   [temp.expl.spec]
2439
2440	   It is possible for a specialization with a given function
2441	   signature to be instantiated from more than one function
2442	   template.  In such cases, explicit specification of the
2443	   template arguments must be used to uniquely identify the
2444	   function template specialization being specialized.
2445
2446	 Note that here, there's no suggestion that we're supposed to
2447	 determine which of the candidate templates is most
2448	 specialized.  However, we, also have:
2449
2450	   [temp.func.order]
2451
2452	   Partial ordering of overloaded function template
2453	   declarations is used in the following contexts to select
2454	   the function template to which a function template
2455	   specialization refers:
2456
2457	   -- when an explicit specialization refers to a function
2458	      template.
2459
2460	 So, we do use the partial ordering rules, at least for now.
2461	 This extension can only serve to make invalid programs valid,
2462	 so it's safe.  And, there is strong anecdotal evidence that
2463	 the committee intended the partial ordering rules to apply;
2464	 the EDG front end has that behavior, and John Spicer claims
2465	 that the committee simply forgot to delete the wording in
2466	 [temp.expl.spec].  */
2467      tree tmpl = most_specialized_instantiation (templates);
2468      if (tmpl != error_mark_node)
2469	{
2470	  templates = tmpl;
2471	  TREE_CHAIN (templates) = NULL_TREE;
2472	}
2473    }
2474
2475  // Concepts allows multiple declarations of member functions
2476  // with the same signature. Like above, we need to rely on
2477  // on the partial ordering of those candidates to determine which
2478  // is the best.
2479  if (flag_concepts && candidates && TREE_CHAIN (candidates))
2480    {
2481      if (tree cand = most_constrained_function (candidates))
2482        {
2483          candidates = cand;
2484          TREE_CHAIN (cand) = NULL_TREE;
2485        }
2486    }
2487
2488  if (templates == NULL_TREE && candidates == NULL_TREE)
2489    {
2490      error ("template-id %qD for %q+D does not match any template "
2491	     "declaration", template_id, decl);
2492      if (header_mismatch)
2493	inform (DECL_SOURCE_LOCATION (decl),
2494		"saw %d %<template<>%>, need %d for "
2495		"specializing a member function template",
2496		header_count, template_count + 1);
2497      print_candidates (orig_fns);
2498      return error_mark_node;
2499    }
2500  else if ((templates && TREE_CHAIN (templates))
2501	   || (candidates && TREE_CHAIN (candidates))
2502	   || (templates && candidates))
2503    {
2504      error ("ambiguous template specialization %qD for %q+D",
2505	     template_id, decl);
2506      candidates = chainon (candidates, templates);
2507      print_candidates (candidates);
2508      return error_mark_node;
2509    }
2510
2511  /* We have one, and exactly one, match.  */
2512  if (candidates)
2513    {
2514      tree fn = TREE_VALUE (candidates);
2515      *targs_out = copy_node (DECL_TI_ARGS (fn));
2516
2517      /* Propagate the candidate's constraints to the declaration.  */
2518      if (tsk != tsk_template)
2519	set_constraints (decl, get_constraints (fn));
2520
2521      /* DECL is a re-declaration or partial instantiation of a template
2522	 function.  */
2523      if (TREE_CODE (fn) == TEMPLATE_DECL)
2524	return fn;
2525      /* It was a specialization of an ordinary member function in a
2526	 template class.  */
2527      return DECL_TI_TEMPLATE (fn);
2528    }
2529
2530  /* It was a specialization of a template.  */
2531  tree tmpl = TREE_VALUE (templates);
2532  *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2533
2534  /* Propagate the template's constraints to the declaration.  */
2535  if (tsk != tsk_template)
2536    set_constraints (decl, get_constraints (tmpl));
2537
2538  return tmpl;
2539}
2540
2541/* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2542   but with the default argument values filled in from those in the
2543   TMPL_TYPES.  */
2544
2545static tree
2546copy_default_args_to_explicit_spec_1 (tree spec_types,
2547				      tree tmpl_types)
2548{
2549  tree new_spec_types;
2550
2551  if (!spec_types)
2552    return NULL_TREE;
2553
2554  if (spec_types == void_list_node)
2555    return void_list_node;
2556
2557  /* Substitute into the rest of the list.  */
2558  new_spec_types =
2559    copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2560					  TREE_CHAIN (tmpl_types));
2561
2562  /* Add the default argument for this parameter.  */
2563  return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2564			 TREE_VALUE (spec_types),
2565			 new_spec_types);
2566}
2567
2568/* DECL is an explicit specialization.  Replicate default arguments
2569   from the template it specializes.  (That way, code like:
2570
2571     template <class T> void f(T = 3);
2572     template <> void f(double);
2573     void g () { f (); }
2574
2575   works, as required.)  An alternative approach would be to look up
2576   the correct default arguments at the call-site, but this approach
2577   is consistent with how implicit instantiations are handled.  */
2578
2579static void
2580copy_default_args_to_explicit_spec (tree decl)
2581{
2582  tree tmpl;
2583  tree spec_types;
2584  tree tmpl_types;
2585  tree new_spec_types;
2586  tree old_type;
2587  tree new_type;
2588  tree t;
2589  tree object_type = NULL_TREE;
2590  tree in_charge = NULL_TREE;
2591  tree vtt = NULL_TREE;
2592
2593  /* See if there's anything we need to do.  */
2594  tmpl = DECL_TI_TEMPLATE (decl);
2595  tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2596  for (t = tmpl_types; t; t = TREE_CHAIN (t))
2597    if (TREE_PURPOSE (t))
2598      break;
2599  if (!t)
2600    return;
2601
2602  old_type = TREE_TYPE (decl);
2603  spec_types = TYPE_ARG_TYPES (old_type);
2604
2605  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2606    {
2607      /* Remove the this pointer, but remember the object's type for
2608	 CV quals.  */
2609      object_type = TREE_TYPE (TREE_VALUE (spec_types));
2610      spec_types = TREE_CHAIN (spec_types);
2611      tmpl_types = TREE_CHAIN (tmpl_types);
2612
2613      if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2614	{
2615	  /* DECL may contain more parameters than TMPL due to the extra
2616	     in-charge parameter in constructors and destructors.  */
2617	  in_charge = spec_types;
2618	  spec_types = TREE_CHAIN (spec_types);
2619	}
2620      if (DECL_HAS_VTT_PARM_P (decl))
2621	{
2622	  vtt = spec_types;
2623	  spec_types = TREE_CHAIN (spec_types);
2624	}
2625    }
2626
2627  /* Compute the merged default arguments.  */
2628  new_spec_types =
2629    copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2630
2631  /* Compute the new FUNCTION_TYPE.  */
2632  if (object_type)
2633    {
2634      if (vtt)
2635	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2636					 TREE_VALUE (vtt),
2637					 new_spec_types);
2638
2639      if (in_charge)
2640	/* Put the in-charge parameter back.  */
2641	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2642					 TREE_VALUE (in_charge),
2643					 new_spec_types);
2644
2645      new_type = build_method_type_directly (object_type,
2646					     TREE_TYPE (old_type),
2647					     new_spec_types);
2648    }
2649  else
2650    new_type = build_function_type (TREE_TYPE (old_type),
2651				    new_spec_types);
2652  new_type = cp_build_type_attribute_variant (new_type,
2653					      TYPE_ATTRIBUTES (old_type));
2654  new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2655
2656  TREE_TYPE (decl) = new_type;
2657}
2658
2659/* Return the number of template headers we expect to see for a definition
2660   or specialization of CTYPE or one of its non-template members.  */
2661
2662int
2663num_template_headers_for_class (tree ctype)
2664{
2665  int num_templates = 0;
2666
2667  while (ctype && CLASS_TYPE_P (ctype))
2668    {
2669      /* You're supposed to have one `template <...>' for every
2670	 template class, but you don't need one for a full
2671	 specialization.  For example:
2672
2673	 template <class T> struct S{};
2674	 template <> struct S<int> { void f(); };
2675	 void S<int>::f () {}
2676
2677	 is correct; there shouldn't be a `template <>' for the
2678	 definition of `S<int>::f'.  */
2679      if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2680	/* If CTYPE does not have template information of any
2681	   kind,  then it is not a template, nor is it nested
2682	   within a template.  */
2683	break;
2684      if (explicit_class_specialization_p (ctype))
2685	break;
2686      if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2687	++num_templates;
2688
2689      ctype = TYPE_CONTEXT (ctype);
2690    }
2691
2692  return num_templates;
2693}
2694
2695/* Do a simple sanity check on the template headers that precede the
2696   variable declaration DECL.  */
2697
2698void
2699check_template_variable (tree decl)
2700{
2701  tree ctx = CP_DECL_CONTEXT (decl);
2702  int wanted = num_template_headers_for_class (ctx);
2703  if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2704      && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2705    {
2706      if (cxx_dialect < cxx14)
2707        pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2708		 "variable templates only available with "
2709		 "%<-std=c++14%> or %<-std=gnu++14%>");
2710
2711      // Namespace-scope variable templates should have a template header.
2712      ++wanted;
2713    }
2714  if (template_header_count > wanted)
2715    {
2716      auto_diagnostic_group d;
2717      bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2718			     "too many template headers for %qD "
2719	                     "(should be %d)",
2720			     decl, wanted);
2721      if (warned && CLASS_TYPE_P (ctx)
2722	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2723	inform (DECL_SOURCE_LOCATION (decl),
2724		"members of an explicitly specialized class are defined "
2725		"without a template header");
2726    }
2727}
2728
2729/* An explicit specialization whose declarator-id or class-head-name is not
2730   qualified shall be declared in the nearest enclosing namespace of the
2731   template, or, if the namespace is inline (7.3.1), any namespace from its
2732   enclosing namespace set.
2733
2734   If the name declared in the explicit instantiation is an unqualified name,
2735   the explicit instantiation shall appear in the namespace where its template
2736   is declared or, if that namespace is inline (7.3.1), any namespace from its
2737   enclosing namespace set.  */
2738
2739void
2740check_unqualified_spec_or_inst (tree t, location_t loc)
2741{
2742  tree tmpl = most_general_template (t);
2743  if (DECL_NAMESPACE_SCOPE_P (tmpl)
2744      && !is_nested_namespace (current_namespace,
2745			       CP_DECL_CONTEXT (tmpl), true))
2746    {
2747      if (processing_specialization)
2748	permerror (loc, "explicit specialization of %qD outside its "
2749		   "namespace must use a nested-name-specifier", tmpl);
2750      else if (processing_explicit_instantiation
2751	       && cxx_dialect >= cxx11)
2752	/* This was allowed in C++98, so only pedwarn.  */
2753	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2754		 "outside its namespace must use a nested-name-"
2755		 "specifier", tmpl);
2756    }
2757}
2758
2759/* Warn for a template specialization SPEC that is missing some of a set
2760   of function or type attributes that the template TEMPL is declared with.
2761   ATTRLIST is a list of additional attributes that SPEC should be taken
2762   to ultimately be declared with.  */
2763
2764static void
2765warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2766{
2767  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2768    tmpl = DECL_TEMPLATE_RESULT (tmpl);
2769
2770  /* Avoid warning if the difference between the primary and
2771     the specialization is not in one of the attributes below.  */
2772  const char* const blacklist[] = {
2773    "alloc_align", "alloc_size", "assume_aligned", "format",
2774    "format_arg", "malloc", "nonnull", NULL
2775  };
2776
2777  /* Put together a list of the black listed attributes that the primary
2778     template is declared with that the specialization is not, in case
2779     it's not apparent from the most recent declaration of the primary.  */
2780  pretty_printer str;
2781  unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2782						 blacklist, &str);
2783
2784  if (!nattrs)
2785    return;
2786
2787  auto_diagnostic_group d;
2788  if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2789		  "explicit specialization %q#D may be missing attributes",
2790		  spec))
2791    inform (DECL_SOURCE_LOCATION (tmpl),
2792	    nattrs > 1
2793	    ? G_("missing primary template attributes %s")
2794	    : G_("missing primary template attribute %s"),
2795	    pp_formatted_text (&str));
2796}
2797
2798/* Check to see if the function just declared, as indicated in
2799   DECLARATOR, and in DECL, is a specialization of a function
2800   template.  We may also discover that the declaration is an explicit
2801   instantiation at this point.
2802
2803   Returns DECL, or an equivalent declaration that should be used
2804   instead if all goes well.  Issues an error message if something is
2805   amiss.  Returns error_mark_node if the error is not easily
2806   recoverable.
2807
2808   FLAGS is a bitmask consisting of the following flags:
2809
2810   2: The function has a definition.
2811   4: The function is a friend.
2812
2813   The TEMPLATE_COUNT is the number of references to qualifying
2814   template classes that appeared in the name of the function.  For
2815   example, in
2816
2817     template <class T> struct S { void f(); };
2818     void S<int>::f();
2819
2820   the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2821   classes are not counted in the TEMPLATE_COUNT, so that in
2822
2823     template <class T> struct S {};
2824     template <> struct S<int> { void f(); }
2825     template <> void S<int>::f();
2826
2827   the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2828   invalid; there should be no template <>.)
2829
2830   If the function is a specialization, it is marked as such via
2831   DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2832   is set up correctly, and it is added to the list of specializations
2833   for that template.  */
2834
2835tree
2836check_explicit_specialization (tree declarator,
2837			       tree decl,
2838			       int template_count,
2839			       int flags,
2840			       tree attrlist)
2841{
2842  int have_def = flags & 2;
2843  int is_friend = flags & 4;
2844  bool is_concept = flags & 8;
2845  int specialization = 0;
2846  int explicit_instantiation = 0;
2847  int member_specialization = 0;
2848  tree ctype = DECL_CLASS_CONTEXT (decl);
2849  tree dname = DECL_NAME (decl);
2850  tmpl_spec_kind tsk;
2851
2852  if (is_friend)
2853    {
2854      if (!processing_specialization)
2855	tsk = tsk_none;
2856      else
2857	tsk = tsk_excessive_parms;
2858    }
2859  else
2860    tsk = current_tmpl_spec_kind (template_count);
2861
2862  switch (tsk)
2863    {
2864    case tsk_none:
2865      if (processing_specialization && !VAR_P (decl))
2866	{
2867	  specialization = 1;
2868	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2869	}
2870      else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2871	       || (DECL_LANG_SPECIFIC (decl)
2872		   && DECL_IMPLICIT_INSTANTIATION (decl)))
2873	{
2874	  if (is_friend)
2875	    /* This could be something like:
2876
2877	       template <class T> void f(T);
2878	       class S { friend void f<>(int); }  */
2879	    specialization = 1;
2880	  else
2881	    {
2882	      /* This case handles bogus declarations like template <>
2883		 template <class T> void f<int>(); */
2884
2885	      error_at (cp_expr_loc_or_input_loc (declarator),
2886			"template-id %qE in declaration of primary template",
2887			declarator);
2888	      return decl;
2889	    }
2890	}
2891      break;
2892
2893    case tsk_invalid_member_spec:
2894      /* The error has already been reported in
2895	 check_specialization_scope.  */
2896      return error_mark_node;
2897
2898    case tsk_invalid_expl_inst:
2899      error ("template parameter list used in explicit instantiation");
2900
2901      /* Fall through.  */
2902
2903    case tsk_expl_inst:
2904      if (have_def)
2905	error ("definition provided for explicit instantiation");
2906
2907      explicit_instantiation = 1;
2908      break;
2909
2910    case tsk_excessive_parms:
2911    case tsk_insufficient_parms:
2912      if (tsk == tsk_excessive_parms)
2913	error ("too many template parameter lists in declaration of %qD",
2914	       decl);
2915      else if (template_header_count)
2916	error("too few template parameter lists in declaration of %qD", decl);
2917      else
2918	error("explicit specialization of %qD must be introduced by "
2919	      "%<template <>%>", decl);
2920
2921      /* Fall through.  */
2922    case tsk_expl_spec:
2923      if (is_concept)
2924        error ("explicit specialization declared %<concept%>");
2925
2926      if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2927	/* In cases like template<> constexpr bool v = true;
2928	   We'll give an error in check_template_variable.  */
2929	break;
2930
2931      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2932      if (ctype)
2933	member_specialization = 1;
2934      else
2935	specialization = 1;
2936      break;
2937
2938    case tsk_template:
2939      if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2940	{
2941	  /* This case handles bogus declarations like template <>
2942	     template <class T> void f<int>(); */
2943
2944	  if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2945	    error_at (cp_expr_loc_or_input_loc (declarator),
2946		      "template-id %qE in declaration of primary template",
2947		      declarator);
2948	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2949	    {
2950	      /* Partial specialization of variable template.  */
2951	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2952	      specialization = 1;
2953	      goto ok;
2954	    }
2955	  else if (cxx_dialect < cxx14)
2956	    error_at (cp_expr_loc_or_input_loc (declarator),
2957		      "non-type partial specialization %qE "
2958		      "is not allowed", declarator);
2959	  else
2960	    error_at (cp_expr_loc_or_input_loc (declarator),
2961		      "non-class, non-variable partial specialization %qE "
2962		      "is not allowed", declarator);
2963	  return decl;
2964	ok:;
2965	}
2966
2967      if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2968	/* This is a specialization of a member template, without
2969	   specialization the containing class.  Something like:
2970
2971	     template <class T> struct S {
2972	       template <class U> void f (U);
2973	     };
2974	     template <> template <class U> void S<int>::f(U) {}
2975
2976	   That's a specialization -- but of the entire template.  */
2977	specialization = 1;
2978      break;
2979
2980    default:
2981      gcc_unreachable ();
2982    }
2983
2984  if ((specialization || member_specialization)
2985      /* This doesn't apply to variable templates.  */
2986      && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2987    {
2988      tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2989      for (; t; t = TREE_CHAIN (t))
2990	if (TREE_PURPOSE (t))
2991	  {
2992	    permerror (input_location,
2993		       "default argument specified in explicit specialization");
2994	    break;
2995	  }
2996    }
2997
2998  if (specialization || member_specialization || explicit_instantiation)
2999    {
3000      tree tmpl = NULL_TREE;
3001      tree targs = NULL_TREE;
3002      bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
3003      bool found_hidden = false;
3004
3005      /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
3006      if (!was_template_id)
3007	{
3008	  tree fns;
3009
3010	  gcc_assert (identifier_p (declarator));
3011	  if (ctype)
3012	    fns = dname;
3013	  else
3014	    {
3015	      /* If there is no class context, the explicit instantiation
3016		 must be at namespace scope.  */
3017	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
3018
3019	      /* Find the namespace binding, using the declaration
3020		 context.  */
3021	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3022					   LOOK_want::NORMAL, true);
3023	      if (fns == error_mark_node)
3024		{
3025		  /* If lookup fails, look for a friend declaration so we can
3026		     give a better diagnostic.  */
3027		  fns = (lookup_qualified_name
3028			 (CP_DECL_CONTEXT (decl), dname,
3029			  LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3030			  /*complain*/true));
3031		  found_hidden = true;
3032		}
3033
3034	      if (fns == error_mark_node || !is_overloaded_fn (fns))
3035		{
3036		  error ("%qD is not a template function", dname);
3037		  fns = error_mark_node;
3038		}
3039	    }
3040
3041	  declarator = lookup_template_function (fns, NULL_TREE);
3042	}
3043
3044      if (declarator == error_mark_node)
3045	return error_mark_node;
3046
3047      if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3048	{
3049	  if (!explicit_instantiation)
3050	    /* A specialization in class scope.  This is invalid,
3051	       but the error will already have been flagged by
3052	       check_specialization_scope.  */
3053	    return error_mark_node;
3054	  else
3055	    {
3056	      /* It's not valid to write an explicit instantiation in
3057		 class scope, e.g.:
3058
3059		   class C { template void f(); }
3060
3061		   This case is caught by the parser.  However, on
3062		   something like:
3063
3064		   template class C { void f(); };
3065
3066		   (which is invalid) we can get here.  The error will be
3067		   issued later.  */
3068	      ;
3069	    }
3070
3071	  return decl;
3072	}
3073      else if (ctype != NULL_TREE
3074	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3075	{
3076	  // We'll match variable templates in start_decl.
3077	  if (VAR_P (decl))
3078	    return decl;
3079
3080	  /* Find the list of functions in ctype that have the same
3081	     name as the declared function.  */
3082	  tree name = TREE_OPERAND (declarator, 0);
3083
3084	  if (constructor_name_p (name, ctype))
3085	    {
3086	      if (DECL_CONSTRUCTOR_P (decl)
3087		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3088		  : !CLASSTYPE_DESTRUCTOR (ctype))
3089		{
3090		  /* From [temp.expl.spec]:
3091
3092		     If such an explicit specialization for the member
3093		     of a class template names an implicitly-declared
3094		     special member function (clause _special_), the
3095		     program is ill-formed.
3096
3097		     Similar language is found in [temp.explicit].  */
3098		  error ("specialization of implicitly-declared special member function");
3099		  return error_mark_node;
3100		}
3101
3102	      name = DECL_NAME (decl);
3103	    }
3104
3105	  /* For a type-conversion operator, We might be looking for
3106	     `operator int' which will be a specialization of
3107	     `operator T'.  Grab all the conversion operators, and
3108	     then select from them.  */
3109	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3110					? conv_op_identifier : name);
3111
3112	  if (fns == NULL_TREE)
3113	    {
3114	      error ("no member function %qD declared in %qT", name, ctype);
3115	      return error_mark_node;
3116	    }
3117	  else
3118	    TREE_OPERAND (declarator, 0) = fns;
3119	}
3120
3121      /* Figure out what exactly is being specialized at this point.
3122	 Note that for an explicit instantiation, even one for a
3123	 member function, we cannot tell a priori whether the
3124	 instantiation is for a member template, or just a member
3125	 function of a template class.  Even if a member template is
3126	 being instantiated, the member template arguments may be
3127	 elided if they can be deduced from the rest of the
3128	 declaration.  */
3129      tmpl = determine_specialization (declarator, decl,
3130				       &targs,
3131				       member_specialization,
3132				       template_count,
3133				       tsk);
3134
3135      if (!tmpl || tmpl == error_mark_node)
3136	/* We couldn't figure out what this declaration was
3137	   specializing.  */
3138	return error_mark_node;
3139      else
3140	{
3141	  if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3142	    {
3143	      auto_diagnostic_group d;
3144	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3145			   "friend declaration %qD is not visible to "
3146			   "explicit specialization", tmpl))
3147		inform (DECL_SOURCE_LOCATION (tmpl),
3148			"friend declaration here");
3149	    }
3150
3151	  if (!ctype && !is_friend
3152	      && CP_DECL_CONTEXT (decl) == current_namespace)
3153	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3154
3155	  tree gen_tmpl = most_general_template (tmpl);
3156
3157	  if (explicit_instantiation)
3158	    {
3159	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3160		 is done by do_decl_instantiation later.  */
3161
3162	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3163	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3164
3165	      if (arg_depth > parm_depth)
3166		{
3167		  /* If TMPL is not the most general template (for
3168		     example, if TMPL is a friend template that is
3169		     injected into namespace scope), then there will
3170		     be too many levels of TARGS.  Remove some of them
3171		     here.  */
3172		  int i;
3173		  tree new_targs;
3174
3175		  new_targs = make_tree_vec (parm_depth);
3176		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3177		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3178		      = TREE_VEC_ELT (targs, i);
3179		  targs = new_targs;
3180		}
3181
3182	      return instantiate_template (tmpl, targs, tf_error);
3183	    }
3184
3185	  /* If we thought that the DECL was a member function, but it
3186	     turns out to be specializing a static member function,
3187	     make DECL a static member function as well.  */
3188	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3189	      && DECL_STATIC_FUNCTION_P (tmpl)
3190	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3191	    revert_static_member_fn (decl);
3192
3193	  /* If this is a specialization of a member template of a
3194	     template class, we want to return the TEMPLATE_DECL, not
3195	     the specialization of it.  */
3196	  if (tsk == tsk_template && !was_template_id)
3197	    {
3198	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3199	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3200	      DECL_INITIAL (result) = NULL_TREE;
3201	      if (have_def)
3202		{
3203		  tree parm;
3204		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3205		  DECL_SOURCE_LOCATION (result)
3206		    = DECL_SOURCE_LOCATION (decl);
3207		  /* We want to use the argument list specified in the
3208		     definition, not in the original declaration.  */
3209		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3210		  for (parm = DECL_ARGUMENTS (result); parm;
3211		       parm = DECL_CHAIN (parm))
3212		    DECL_CONTEXT (parm) = result;
3213		}
3214	      return register_specialization (tmpl, gen_tmpl, targs,
3215					      is_friend, 0);
3216	    }
3217
3218	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3219	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3220
3221	  if (was_template_id)
3222	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3223
3224	  /* Inherit default function arguments from the template
3225	     DECL is specializing.  */
3226	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3227	    copy_default_args_to_explicit_spec (decl);
3228
3229	  /* This specialization has the same protection as the
3230	     template it specializes.  */
3231	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3232	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3233
3234          /* 7.1.1-1 [dcl.stc]
3235
3236             A storage-class-specifier shall not be specified in an
3237             explicit specialization...
3238
3239             The parser rejects these, so unless action is taken here,
3240             explicit function specializations will always appear with
3241             global linkage.
3242
3243             The action recommended by the C++ CWG in response to C++
3244             defect report 605 is to make the storage class and linkage
3245             of the explicit specialization match the templated function:
3246
3247             http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3248           */
3249          if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3250            {
3251              tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3252              gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3253
3254              /* A concept cannot be specialized.  */
3255              if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3256                {
3257                  error ("explicit specialization of function concept %qD",
3258                         gen_tmpl);
3259                  return error_mark_node;
3260                }
3261
3262              /* This specialization has the same linkage and visibility as
3263                 the function template it specializes.  */
3264              TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3265	      if (! TREE_PUBLIC (decl))
3266		{
3267		  DECL_INTERFACE_KNOWN (decl) = 1;
3268		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3269		}
3270              DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3271              if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3272                {
3273                  DECL_VISIBILITY_SPECIFIED (decl) = 1;
3274                  DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3275                }
3276            }
3277
3278	  /* If DECL is a friend declaration, declared using an
3279	     unqualified name, the namespace associated with DECL may
3280	     have been set incorrectly.  For example, in:
3281
3282	       template <typename T> void f(T);
3283	       namespace N {
3284		 struct S { friend void f<int>(int); }
3285	       }
3286
3287	     we will have set the DECL_CONTEXT for the friend
3288	     declaration to N, rather than to the global namespace.  */
3289	  if (DECL_NAMESPACE_SCOPE_P (decl))
3290	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3291
3292	  if (is_friend && !have_def)
3293	    /* This is not really a declaration of a specialization.
3294	       It's just the name of an instantiation.  But, it's not
3295	       a request for an instantiation, either.  */
3296	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3297	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3298	    /* A specialization is not necessarily COMDAT.  */
3299	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3300				  && DECL_DECLARED_INLINE_P (decl));
3301	  else if (VAR_P (decl))
3302	    DECL_COMDAT (decl) = false;
3303
3304	  /* If this is a full specialization, register it so that we can find
3305	     it again.  Partial specializations will be registered in
3306	     process_partial_specialization.  */
3307	  if (!processing_template_decl)
3308	    {
3309	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3310
3311	      decl = register_specialization (decl, gen_tmpl, targs,
3312					      is_friend, 0);
3313	    }
3314
3315
3316	  /* A 'structor should already have clones.  */
3317	  gcc_assert (decl == error_mark_node
3318		      || variable_template_p (tmpl)
3319		      || !(DECL_CONSTRUCTOR_P (decl)
3320			   || DECL_DESTRUCTOR_P (decl))
3321		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3322	}
3323    }
3324
3325  return decl;
3326}
3327
3328/* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3329   parameters.  These are represented in the same format used for
3330   DECL_TEMPLATE_PARMS.  */
3331
3332int
3333comp_template_parms (const_tree parms1, const_tree parms2)
3334{
3335  const_tree p1;
3336  const_tree p2;
3337
3338  if (parms1 == parms2)
3339    return 1;
3340
3341  for (p1 = parms1, p2 = parms2;
3342       p1 != NULL_TREE && p2 != NULL_TREE;
3343       p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3344    {
3345      tree t1 = TREE_VALUE (p1);
3346      tree t2 = TREE_VALUE (p2);
3347      int i;
3348
3349      gcc_assert (TREE_CODE (t1) == TREE_VEC);
3350      gcc_assert (TREE_CODE (t2) == TREE_VEC);
3351
3352      if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3353	return 0;
3354
3355      for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3356	{
3357          tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3358          tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3359
3360          /* If either of the template parameters are invalid, assume
3361             they match for the sake of error recovery. */
3362          if (error_operand_p (parm1) || error_operand_p (parm2))
3363            return 1;
3364
3365	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3366	    return 0;
3367
3368	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3369              && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3370                  == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3371	    continue;
3372	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3373	    return 0;
3374	}
3375    }
3376
3377  if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3378    /* One set of parameters has more parameters lists than the
3379       other.  */
3380    return 0;
3381
3382  return 1;
3383}
3384
3385/* Returns true if two template parameters are declared with
3386   equivalent constraints.  */
3387
3388static bool
3389template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3390{
3391  tree req1 = TREE_TYPE (parm1);
3392  tree req2 = TREE_TYPE (parm2);
3393  if (!req1 != !req2)
3394    return false;
3395  if (req1)
3396    return cp_tree_equal (req1, req2);
3397  return true;
3398}
3399
3400/* Returns true when two template parameters are equivalent.  */
3401
3402static bool
3403template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3404{
3405  tree decl1 = TREE_VALUE (parm1);
3406  tree decl2 = TREE_VALUE (parm2);
3407
3408  /* If either of the template parameters are invalid, assume
3409     they match for the sake of error recovery. */
3410  if (error_operand_p (decl1) || error_operand_p (decl2))
3411    return true;
3412
3413  /* ... they declare parameters of the same kind.  */
3414  if (TREE_CODE (decl1) != TREE_CODE (decl2))
3415    return false;
3416
3417  /* ... one parameter was introduced by a parameter declaration, then
3418     both are. This case arises as a result of eagerly rewriting declarations
3419     during parsing.  */
3420  if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3421    return false;
3422
3423  /* ... if either declares a pack, they both do.  */
3424  if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3425    return false;
3426
3427  if (TREE_CODE (decl1) == PARM_DECL)
3428    {
3429      /* ... if they declare non-type parameters, the types are equivalent.  */
3430      if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3431	return false;
3432    }
3433  else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3434    {
3435      /* ... if they declare template template parameters, their template
3436	 parameter lists are equivalent.  */
3437      if (!template_heads_equivalent_p (decl1, decl2))
3438	return false;
3439    }
3440
3441  /* ... if they are declared with a qualified-concept name, they both
3442     are, and those names are equivalent.  */
3443  return template_parameter_constraints_equivalent_p (parm1, parm2);
3444}
3445
3446/* Returns true if two template parameters lists are equivalent.
3447   Two template parameter lists are equivalent if they have the
3448   same length and their corresponding parameters are equivalent.
3449
3450   PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3451   data structure returned by DECL_TEMPLATE_PARMS.
3452
3453   This is generally the same implementation as comp_template_parms
3454   except that it also the concept names and arguments used to
3455   introduce parameters.  */
3456
3457static bool
3458template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3459{
3460  if (parms1 == parms2)
3461    return true;
3462
3463  const_tree p1 = parms1;
3464  const_tree p2 = parms2;
3465  while (p1 != NULL_TREE && p2 != NULL_TREE)
3466    {
3467      tree list1 = TREE_VALUE (p1);
3468      tree list2 = TREE_VALUE (p2);
3469
3470      if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3471	return 0;
3472
3473      for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3474	{
3475	  tree parm1 = TREE_VEC_ELT (list1, i);
3476	  tree parm2 = TREE_VEC_ELT (list2, i);
3477	  if (!template_parameters_equivalent_p (parm1, parm2))
3478	    return false;
3479	}
3480
3481      p1 = TREE_CHAIN (p1);
3482      p2 = TREE_CHAIN (p2);
3483    }
3484
3485  if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3486    return false;
3487
3488  return true;
3489}
3490
3491/* Return true if the requires-clause of the template parameter lists are
3492   equivalent and false otherwise.  */
3493static bool
3494template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3495{
3496  tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3497  tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3498  if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3499    return false;
3500  if (!cp_tree_equal (req1, req2))
3501    return false;
3502  return true;
3503}
3504
3505/* Returns true if two template heads are equivalent. 17.6.6.1p6:
3506   Two template heads are equivalent if their template parameter
3507   lists are equivalent and their requires clauses are equivalent.
3508
3509   In pre-C++20, this is equivalent to calling comp_template_parms
3510   for the template parameters of TMPL1 and TMPL2.  */
3511
3512bool
3513template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3514{
3515  tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3516  tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3517
3518  /* Don't change the matching rules for pre-C++20.  */
3519  if (cxx_dialect < cxx20)
3520    return comp_template_parms (parms1, parms2);
3521
3522  /* ... have the same number of template parameters, and their
3523     corresponding parameters are equivalent.  */
3524  if (!template_parameter_lists_equivalent_p (parms1, parms2))
3525    return false;
3526
3527  /* ... if either has a requires-clause, they both do and their
3528     corresponding constraint-expressions are equivalent.  */
3529  return template_requirements_equivalent_p (parms1, parms2);
3530}
3531
3532/* Determine whether PARM is a parameter pack.  */
3533
3534bool
3535template_parameter_pack_p (const_tree parm)
3536{
3537  /* Determine if we have a non-type template parameter pack.  */
3538  if (TREE_CODE (parm) == PARM_DECL)
3539    return (DECL_TEMPLATE_PARM_P (parm)
3540            && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3541  if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3542    return TEMPLATE_PARM_PARAMETER_PACK (parm);
3543
3544  /* If this is a list of template parameters, we could get a
3545     TYPE_DECL or a TEMPLATE_DECL.  */
3546  if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3547    parm = TREE_TYPE (parm);
3548
3549  /* Otherwise it must be a type template parameter.  */
3550  return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3551	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3552	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3553}
3554
3555/* Determine if T is a function parameter pack.  */
3556
3557bool
3558function_parameter_pack_p (const_tree t)
3559{
3560  if (t && TREE_CODE (t) == PARM_DECL)
3561    return DECL_PACK_P (t);
3562  return false;
3563}
3564
3565/* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3566   PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3567
3568tree
3569get_function_template_decl (const_tree primary_func_tmpl_inst)
3570{
3571  if (! primary_func_tmpl_inst
3572      || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3573      || ! primary_template_specialization_p (primary_func_tmpl_inst))
3574    return NULL;
3575
3576  return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3577}
3578
3579/* Return true iff the function parameter PARAM_DECL was expanded
3580   from the function parameter pack PACK.  */
3581
3582bool
3583function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3584{
3585  if (DECL_ARTIFICIAL (param_decl)
3586      || !function_parameter_pack_p (pack))
3587    return false;
3588
3589  /* The parameter pack and its pack arguments have the same
3590     DECL_PARM_INDEX.  */
3591  return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3592}
3593
3594/* Determine whether ARGS describes a variadic template args list,
3595   i.e., one that is terminated by a template argument pack.  */
3596
3597static bool
3598template_args_variadic_p (tree args)
3599{
3600  int nargs;
3601  tree last_parm;
3602
3603  if (args == NULL_TREE)
3604    return false;
3605
3606  args = INNERMOST_TEMPLATE_ARGS (args);
3607  nargs = TREE_VEC_LENGTH (args);
3608
3609  if (nargs == 0)
3610    return false;
3611
3612  last_parm = TREE_VEC_ELT (args, nargs - 1);
3613
3614  return ARGUMENT_PACK_P (last_parm);
3615}
3616
3617/* Generate a new name for the parameter pack name NAME (an
3618   IDENTIFIER_NODE) that incorporates its */
3619
3620static tree
3621make_ith_pack_parameter_name (tree name, int i)
3622{
3623  /* Munge the name to include the parameter index.  */
3624#define NUMBUF_LEN 128
3625  char numbuf[NUMBUF_LEN];
3626  char* newname;
3627  int newname_len;
3628
3629  if (name == NULL_TREE)
3630    return name;
3631  snprintf (numbuf, NUMBUF_LEN, "%i", i);
3632  newname_len = IDENTIFIER_LENGTH (name)
3633	        + strlen (numbuf) + 2;
3634  newname = (char*)alloca (newname_len);
3635  snprintf (newname, newname_len,
3636	    "%s#%i", IDENTIFIER_POINTER (name), i);
3637  return get_identifier (newname);
3638}
3639
3640/* Return true if T is a primary function, class or alias template
3641   specialization, not including the template pattern.  */
3642
3643bool
3644primary_template_specialization_p (const_tree t)
3645{
3646  if (!t)
3647    return false;
3648
3649  if (VAR_OR_FUNCTION_DECL_P (t))
3650    return (DECL_LANG_SPECIFIC (t)
3651	    && DECL_USE_TEMPLATE (t)
3652	    && DECL_TEMPLATE_INFO (t)
3653	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3654  else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3655    return (CLASSTYPE_TEMPLATE_INFO (t)
3656	    && CLASSTYPE_USE_TEMPLATE (t)
3657	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3658  else if (alias_template_specialization_p (t, nt_transparent))
3659    return true;
3660  return false;
3661}
3662
3663/* Return true if PARM is a template template parameter.  */
3664
3665bool
3666template_template_parameter_p (const_tree parm)
3667{
3668  return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3669}
3670
3671/* Return true iff PARM is a DECL representing a type template
3672   parameter.  */
3673
3674bool
3675template_type_parameter_p (const_tree parm)
3676{
3677  return (parm
3678	  && (TREE_CODE (parm) == TYPE_DECL
3679	      || TREE_CODE (parm) == TEMPLATE_DECL)
3680	  && DECL_TEMPLATE_PARM_P (parm));
3681}
3682
3683/* Return the template parameters of T if T is a
3684   primary template instantiation, NULL otherwise.  */
3685
3686tree
3687get_primary_template_innermost_parameters (const_tree t)
3688{
3689  tree parms = NULL, template_info = NULL;
3690
3691  if ((template_info = get_template_info (t))
3692      && primary_template_specialization_p (t))
3693    parms = INNERMOST_TEMPLATE_PARMS
3694	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3695
3696  return parms;
3697}
3698
3699/* Returns the template arguments of T if T is a template instantiation,
3700   NULL otherwise.  */
3701
3702tree
3703get_template_innermost_arguments (const_tree t)
3704{
3705  tree args = NULL, template_info = NULL;
3706
3707  if ((template_info = get_template_info (t))
3708      && TI_ARGS (template_info))
3709    args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3710
3711  return args;
3712}
3713
3714/* Return the argument pack elements of T if T is a template argument pack,
3715   NULL otherwise.  */
3716
3717tree
3718get_template_argument_pack_elems (const_tree t)
3719{
3720  if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3721      && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3722    return NULL;
3723
3724  return ARGUMENT_PACK_ARGS (t);
3725}
3726
3727/* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3728   ARGUMENT_PACK_SELECT represents. */
3729
3730static tree
3731argument_pack_select_arg (tree t)
3732{
3733  tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3734  tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3735
3736  /* If the selected argument is an expansion E, that most likely means we were
3737     called from gen_elem_of_pack_expansion_instantiation during the
3738     substituting of an argument pack (of which the Ith element is a pack
3739     expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3740     In this case, the Ith element resulting from this substituting is going to
3741     be a pack expansion, which pattern is the pattern of E.  Let's return the
3742     pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3743     resulting pack expansion from it.  */
3744  if (PACK_EXPANSION_P (arg))
3745    {
3746      /* Make sure we aren't throwing away arg info.  */
3747      gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3748      arg = PACK_EXPANSION_PATTERN (arg);
3749    }
3750
3751  return arg;
3752}
3753
3754/* Return a modification of ARGS that's suitable for preserving inside a hash
3755   table.  In particular, this replaces each ARGUMENT_PACK_SELECT with its
3756   underlying argument.  ARGS is copied (upon modification) iff COW_P.  */
3757
3758static tree
3759preserve_args (tree args, bool cow_p = true)
3760{
3761  if (!args)
3762    return NULL_TREE;
3763
3764  for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3765    {
3766      tree t = TREE_VEC_ELT (args, i);
3767      tree r;
3768      if (!t)
3769	r = NULL_TREE;
3770      else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3771	r = argument_pack_select_arg (t);
3772      else if (TREE_CODE (t) == TREE_VEC)
3773	r = preserve_args (t, cow_p);
3774      else
3775	r = t;
3776      if (r != t)
3777	{
3778	  if (cow_p)
3779	    {
3780	      args = copy_template_args (args);
3781	      cow_p = false;
3782	    }
3783	  TREE_VEC_ELT (args, i) = r;
3784	}
3785    }
3786
3787  return args;
3788}
3789
3790/* True iff FN is a function representing a built-in variadic parameter
3791   pack.  */
3792
3793bool
3794builtin_pack_fn_p (tree fn)
3795{
3796  if (!fn
3797      || TREE_CODE (fn) != FUNCTION_DECL
3798      || !DECL_IS_UNDECLARED_BUILTIN (fn))
3799    return false;
3800
3801  if (id_equal (DECL_NAME (fn), "__integer_pack"))
3802    return true;
3803
3804  return false;
3805}
3806
3807/* True iff CALL is a call to a function representing a built-in variadic
3808   parameter pack.  */
3809
3810static bool
3811builtin_pack_call_p (tree call)
3812{
3813  if (TREE_CODE (call) != CALL_EXPR)
3814    return false;
3815  return builtin_pack_fn_p (CALL_EXPR_FN (call));
3816}
3817
3818/* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3819
3820static tree
3821expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3822		     tree in_decl)
3823{
3824  tree ohi = CALL_EXPR_ARG (call, 0);
3825  tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3826				   false/*fn*/, true/*int_cst*/);
3827
3828  if (instantiation_dependent_expression_p (hi))
3829    {
3830      if (hi != ohi)
3831	{
3832	  call = copy_node (call);
3833	  CALL_EXPR_ARG (call, 0) = hi;
3834	}
3835      tree ex = make_pack_expansion (call, complain);
3836      tree vec = make_tree_vec (1);
3837      TREE_VEC_ELT (vec, 0) = ex;
3838      return vec;
3839    }
3840  else
3841    {
3842      hi = instantiate_non_dependent_expr_sfinae (hi, complain);
3843      hi = cxx_constant_value (hi);
3844      int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3845
3846      /* Calculate the largest value of len that won't make the size of the vec
3847	 overflow an int.  The compiler will exceed resource limits long before
3848	 this, but it seems a decent place to diagnose.  */
3849      int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3850
3851      if (len < 0 || len > max)
3852	{
3853	  if ((complain & tf_error)
3854	      && hi != error_mark_node)
3855	    error ("argument to %<__integer_pack%> must be between 0 and %d",
3856		   max);
3857	  return error_mark_node;
3858	}
3859
3860      tree vec = make_tree_vec (len);
3861
3862      for (int i = 0; i < len; ++i)
3863	TREE_VEC_ELT (vec, i) = size_int (i);
3864
3865      return vec;
3866    }
3867}
3868
3869/* Return a TREE_VEC for the expansion of built-in template parameter pack
3870   CALL.  */
3871
3872static tree
3873expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3874			  tree in_decl)
3875{
3876  if (!builtin_pack_call_p (call))
3877    return NULL_TREE;
3878
3879  tree fn = CALL_EXPR_FN (call);
3880
3881  if (id_equal (DECL_NAME (fn), "__integer_pack"))
3882    return expand_integer_pack (call, args, complain, in_decl);
3883
3884  return NULL_TREE;
3885}
3886
3887/* Return true if the tree T has the extra args mechanism for
3888   avoiding partial instantiation.  */
3889
3890static bool
3891has_extra_args_mechanism_p (const_tree t)
3892{
3893  return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS  */
3894	  || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS  */
3895	  || (TREE_CODE (t) == IF_STMT
3896	      && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS  */
3897}
3898
3899/* Structure used to track the progress of find_parameter_packs_r.  */
3900struct find_parameter_pack_data
3901{
3902  /* TREE_LIST that will contain all of the parameter packs found by
3903     the traversal.  */
3904  tree* parameter_packs;
3905
3906  /* Set of AST nodes that have been visited by the traversal.  */
3907  hash_set<tree> *visited;
3908
3909  /* True iff we're making a type pack expansion.  */
3910  bool type_pack_expansion_p;
3911
3912  /* True iff we found a subtree that has the extra args mechanism.  */
3913  bool found_extra_args_tree_p = false;
3914};
3915
3916/* Identifies all of the argument packs that occur in a template
3917   argument and appends them to the TREE_LIST inside DATA, which is a
3918   find_parameter_pack_data structure. This is a subroutine of
3919   make_pack_expansion and uses_parameter_packs.  */
3920static tree
3921find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3922{
3923  tree t = *tp;
3924  struct find_parameter_pack_data* ppd =
3925    (struct find_parameter_pack_data*)data;
3926  bool parameter_pack_p = false;
3927
3928#define WALK_SUBTREE(NODE)				\
3929  cp_walk_tree (&(NODE), &find_parameter_packs_r,	\
3930		ppd, ppd->visited)			\
3931
3932  /* Don't look through typedefs; we are interested in whether a
3933     parameter pack is actually written in the expression/type we're
3934     looking at, not the target type.  */
3935  if (TYPE_P (t) && typedef_variant_p (t))
3936    {
3937      /* But do look at arguments for an alias template.  */
3938      if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3939	cp_walk_tree (&TI_ARGS (tinfo),
3940		      &find_parameter_packs_r,
3941		      ppd, ppd->visited);
3942      *walk_subtrees = 0;
3943      return NULL_TREE;
3944    }
3945
3946  /* Identify whether this is a parameter pack or not.  */
3947  switch (TREE_CODE (t))
3948    {
3949    case TEMPLATE_PARM_INDEX:
3950      if (TEMPLATE_PARM_PARAMETER_PACK (t))
3951        parameter_pack_p = true;
3952      break;
3953
3954    case TEMPLATE_TYPE_PARM:
3955      t = TYPE_MAIN_VARIANT (t);
3956      /* FALLTHRU */
3957    case TEMPLATE_TEMPLATE_PARM:
3958      /* If the placeholder appears in the decl-specifier-seq of a function
3959	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3960	 is a pack expansion, the invented template parameter is a template
3961	 parameter pack.  */
3962      if (ppd->type_pack_expansion_p && is_auto (t))
3963	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3964      if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3965        parameter_pack_p = true;
3966      break;
3967
3968    case FIELD_DECL:
3969    case PARM_DECL:
3970      if (DECL_PACK_P (t))
3971        {
3972          /* We don't want to walk into the type of a PARM_DECL,
3973             because we don't want to see the type parameter pack.  */
3974          *walk_subtrees = 0;
3975	  parameter_pack_p = true;
3976        }
3977      break;
3978
3979    case VAR_DECL:
3980      if (DECL_PACK_P (t))
3981        {
3982          /* We don't want to walk into the type of a variadic capture proxy,
3983             because we don't want to see the type parameter pack.  */
3984          *walk_subtrees = 0;
3985	  parameter_pack_p = true;
3986        }
3987      else if (variable_template_specialization_p (t))
3988	{
3989	  cp_walk_tree (&DECL_TI_ARGS (t),
3990			find_parameter_packs_r,
3991			ppd, ppd->visited);
3992	  *walk_subtrees = 0;
3993	}
3994      break;
3995
3996    case CALL_EXPR:
3997      if (builtin_pack_call_p (t))
3998	parameter_pack_p = true;
3999      break;
4000
4001    case BASES:
4002      parameter_pack_p = true;
4003      break;
4004    default:
4005      /* Not a parameter pack.  */
4006      break;
4007    }
4008
4009  if (parameter_pack_p)
4010    {
4011      /* Add this parameter pack to the list.  */
4012      *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
4013    }
4014
4015  if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
4016    ppd->found_extra_args_tree_p = true;
4017
4018  if (TYPE_P (t))
4019    cp_walk_tree (&TYPE_CONTEXT (t),
4020		  &find_parameter_packs_r, ppd, ppd->visited);
4021
4022  /* This switch statement will return immediately if we don't find a
4023     parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
4024  switch (TREE_CODE (t))
4025    {
4026    case BOUND_TEMPLATE_TEMPLATE_PARM:
4027      /* Check the template itself.  */
4028      cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
4029		    &find_parameter_packs_r, ppd, ppd->visited);
4030      return NULL_TREE;
4031
4032    case DECL_EXPR:
4033      {
4034	tree decl = DECL_EXPR_DECL (t);
4035	/* Ignore the declaration of a capture proxy for a parameter pack.  */
4036	if (is_capture_proxy (decl))
4037	  *walk_subtrees = 0;
4038	if (is_typedef_decl (decl))
4039	  /* Since we stop at typedefs above, we need to look through them at
4040	     the point of the DECL_EXPR.  */
4041	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4042			&find_parameter_packs_r, ppd, ppd->visited);
4043	return NULL_TREE;
4044      }
4045
4046    case TEMPLATE_DECL:
4047      if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4048	return NULL_TREE;
4049      cp_walk_tree (&TREE_TYPE (t),
4050		    &find_parameter_packs_r, ppd, ppd->visited);
4051      return NULL_TREE;
4052
4053    case TYPE_PACK_EXPANSION:
4054    case EXPR_PACK_EXPANSION:
4055      *walk_subtrees = 0;
4056      return NULL_TREE;
4057
4058    case INTEGER_TYPE:
4059      cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4060		    ppd, ppd->visited);
4061      *walk_subtrees = 0;
4062      return NULL_TREE;
4063
4064    case IDENTIFIER_NODE:
4065      cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4066		    ppd->visited);
4067      *walk_subtrees = 0;
4068      return NULL_TREE;
4069
4070    case LAMBDA_EXPR:
4071      {
4072	/* Since we defer implicit capture, look in the parms and body.  */
4073	tree fn = lambda_function (t);
4074	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4075		      ppd->visited);
4076	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4077		      ppd->visited);
4078	return NULL_TREE;
4079      }
4080
4081    case DECLTYPE_TYPE:
4082      {
4083	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4084	   type_pack_expansion_p to false so that any placeholders
4085	   within the expression don't get marked as parameter packs.  */
4086	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4087	ppd->type_pack_expansion_p = false;
4088	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4089		      ppd, ppd->visited);
4090	ppd->type_pack_expansion_p = type_pack_expansion_p;
4091	*walk_subtrees = 0;
4092	return NULL_TREE;
4093      }
4094
4095    case IF_STMT:
4096      cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4097		    ppd, ppd->visited);
4098      cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4099		    ppd, ppd->visited);
4100      cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4101		    ppd, ppd->visited);
4102      /* Don't walk into IF_STMT_EXTRA_ARGS.  */
4103      *walk_subtrees = 0;
4104      return NULL_TREE;
4105
4106    case TAG_DEFN:
4107      t = TREE_TYPE (t);
4108      if (CLASS_TYPE_P (t))
4109	/* Local class, need to look through the whole definition.  */
4110	for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4111	  cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4112			ppd, ppd->visited);
4113      else
4114	/* Enum, look at the values.  */
4115	for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4116	  cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4117			&find_parameter_packs_r,
4118			ppd, ppd->visited);
4119      return NULL_TREE;
4120
4121    case FUNCTION_TYPE:
4122    case METHOD_TYPE:
4123      WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4124      break;
4125
4126    default:
4127      return NULL_TREE;
4128    }
4129
4130#undef WALK_SUBTREE
4131
4132  return NULL_TREE;
4133}
4134
4135/* Determines if the expression or type T uses any parameter packs.  */
4136tree
4137uses_parameter_packs (tree t)
4138{
4139  tree parameter_packs = NULL_TREE;
4140  struct find_parameter_pack_data ppd;
4141  ppd.parameter_packs = &parameter_packs;
4142  ppd.visited = new hash_set<tree>;
4143  ppd.type_pack_expansion_p = false;
4144  cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4145  delete ppd.visited;
4146  return parameter_packs;
4147}
4148
4149/* Turn ARG, which may be an expression, type, or a TREE_LIST
4150   representation a base-class initializer into a parameter pack
4151   expansion. If all goes well, the resulting node will be an
4152   EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4153   respectively.  */
4154tree
4155make_pack_expansion (tree arg, tsubst_flags_t complain)
4156{
4157  tree result;
4158  tree parameter_packs = NULL_TREE;
4159  bool for_types = false;
4160  struct find_parameter_pack_data ppd;
4161
4162  if (!arg || arg == error_mark_node)
4163    return arg;
4164
4165  if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4166    {
4167      /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4168         class initializer.  In this case, the TREE_PURPOSE will be a
4169         _TYPE node (representing the base class expansion we're
4170         initializing) and the TREE_VALUE will be a TREE_LIST
4171         containing the initialization arguments.
4172
4173         The resulting expansion looks somewhat different from most
4174         expansions. Rather than returning just one _EXPANSION, we
4175         return a TREE_LIST whose TREE_PURPOSE is a
4176         TYPE_PACK_EXPANSION containing the bases that will be
4177         initialized.  The TREE_VALUE will be identical to the
4178         original TREE_VALUE, which is a list of arguments that will
4179         be passed to each base.  We do not introduce any new pack
4180         expansion nodes into the TREE_VALUE (although it is possible
4181         that some already exist), because the TREE_PURPOSE and
4182         TREE_VALUE all need to be expanded together with the same
4183         _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
4184         resulting TREE_PURPOSE will mention the parameter packs in
4185         both the bases and the arguments to the bases.  */
4186      tree purpose;
4187      tree value;
4188      tree parameter_packs = NULL_TREE;
4189
4190      /* Determine which parameter packs will be used by the base
4191         class expansion.  */
4192      ppd.visited = new hash_set<tree>;
4193      ppd.parameter_packs = &parameter_packs;
4194      ppd.type_pack_expansion_p = false;
4195      gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4196      cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4197                    &ppd, ppd.visited);
4198
4199      if (parameter_packs == NULL_TREE)
4200        {
4201	  if (complain & tf_error)
4202	    error ("base initializer expansion %qT contains no parameter packs",
4203		   arg);
4204          delete ppd.visited;
4205          return error_mark_node;
4206        }
4207
4208      if (TREE_VALUE (arg) != void_type_node)
4209        {
4210          /* Collect the sets of parameter packs used in each of the
4211             initialization arguments.  */
4212          for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4213            {
4214              /* Determine which parameter packs will be expanded in this
4215                 argument.  */
4216              cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4217                            &ppd, ppd.visited);
4218            }
4219        }
4220
4221      delete ppd.visited;
4222
4223      /* Create the pack expansion type for the base type.  */
4224      purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4225      SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4226      PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4227      PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4228
4229      /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4230	 they will rarely be compared to anything.  */
4231      SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4232
4233      return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4234    }
4235
4236  if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4237    for_types = true;
4238
4239  /* Build the PACK_EXPANSION_* node.  */
4240  result = for_types
4241     ? cxx_make_type (TYPE_PACK_EXPANSION)
4242     : make_node (EXPR_PACK_EXPANSION);
4243  SET_PACK_EXPANSION_PATTERN (result, arg);
4244  if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4245    {
4246      /* Propagate type and const-expression information.  */
4247      TREE_TYPE (result) = TREE_TYPE (arg);
4248      TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4249      /* Mark this read now, since the expansion might be length 0.  */
4250      mark_exp_read (arg);
4251    }
4252  else
4253    /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4254       they will rarely be compared to anything.  */
4255    SET_TYPE_STRUCTURAL_EQUALITY (result);
4256
4257  /* Determine which parameter packs will be expanded.  */
4258  ppd.parameter_packs = &parameter_packs;
4259  ppd.visited = new hash_set<tree>;
4260  ppd.type_pack_expansion_p = TYPE_P (arg);
4261  cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4262  delete ppd.visited;
4263
4264  /* Make sure we found some parameter packs.  */
4265  if (parameter_packs == NULL_TREE)
4266    {
4267      if (complain & tf_error)
4268	{
4269	  if (TYPE_P (arg))
4270	    error ("expansion pattern %qT contains no parameter packs", arg);
4271	  else
4272	    error ("expansion pattern %qE contains no parameter packs", arg);
4273	}
4274      return error_mark_node;
4275    }
4276  PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4277
4278  PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4279  if (ppd.found_extra_args_tree_p)
4280    /* If the pattern of this pack expansion contains a subtree that has
4281       the extra args mechanism for avoiding partial instantiation, then
4282       force this pack expansion to also use extra args.  Otherwise
4283       partial instantiation of this pack expansion may not lower the
4284       level of some parameter packs within the pattern, which would
4285       confuse tsubst_pack_expansion later (PR101764).  */
4286    PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4287
4288  return result;
4289}
4290
4291/* Checks T for any "bare" parameter packs, which have not yet been
4292   expanded, and issues an error if any are found. This operation can
4293   only be done on full expressions or types (e.g., an expression
4294   statement, "if" condition, etc.), because we could have expressions like:
4295
4296     foo(f(g(h(args)))...)
4297
4298   where "args" is a parameter pack. check_for_bare_parameter_packs
4299   should not be called for the subexpressions args, h(args),
4300   g(h(args)), or f(g(h(args))), because we would produce erroneous
4301   error messages.
4302
4303   Returns TRUE and emits an error if there were bare parameter packs,
4304   returns FALSE otherwise.  */
4305bool
4306check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4307{
4308  tree parameter_packs = NULL_TREE;
4309  struct find_parameter_pack_data ppd;
4310
4311  if (!processing_template_decl || !t || t == error_mark_node)
4312    return false;
4313
4314  if (TREE_CODE (t) == TYPE_DECL)
4315    t = TREE_TYPE (t);
4316
4317  ppd.parameter_packs = &parameter_packs;
4318  ppd.visited = new hash_set<tree>;
4319  ppd.type_pack_expansion_p = false;
4320  cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4321  delete ppd.visited;
4322
4323  if (!parameter_packs)
4324    return false;
4325
4326  if (loc == UNKNOWN_LOCATION)
4327    loc = cp_expr_loc_or_input_loc (t);
4328
4329  /* It's OK for a lambda to have an unexpanded parameter pack from the
4330     containing context, but do complain about unexpanded capture packs.  */
4331  tree lam = current_lambda_expr ();
4332  if (lam)
4333    lam = TREE_TYPE (lam);
4334
4335  if (lam && lam != current_class_type)
4336    {
4337      /* We're in a lambda, but it isn't the innermost class.
4338	 This should work, but currently doesn't.  */
4339      sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4340      return true;
4341    }
4342
4343  if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4344    for (; parameter_packs;
4345	 parameter_packs = TREE_CHAIN (parameter_packs))
4346      {
4347	tree pack = TREE_VALUE (parameter_packs);
4348	if (is_capture_proxy (pack)
4349	    || (TREE_CODE (pack) == PARM_DECL
4350		&& DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4351	  break;
4352      }
4353
4354  if (parameter_packs)
4355    {
4356      error_at (loc, "parameter packs not expanded with %<...%>:");
4357      while (parameter_packs)
4358        {
4359          tree pack = TREE_VALUE (parameter_packs);
4360          tree name = NULL_TREE;
4361
4362          if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4363              || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4364            name = TYPE_NAME (pack);
4365          else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4366            name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4367	  else if (TREE_CODE (pack) == CALL_EXPR)
4368	    name = DECL_NAME (CALL_EXPR_FN (pack));
4369          else
4370            name = DECL_NAME (pack);
4371
4372	  if (name)
4373	    inform (loc, "        %qD", name);
4374	  else
4375	    inform (loc, "        %s", "<anonymous>");
4376
4377          parameter_packs = TREE_CHAIN (parameter_packs);
4378        }
4379
4380      return true;
4381    }
4382
4383  return false;
4384}
4385
4386/* Expand any parameter packs that occur in the template arguments in
4387   ARGS.  */
4388tree
4389expand_template_argument_pack (tree args)
4390{
4391  if (args == error_mark_node)
4392    return error_mark_node;
4393
4394  tree result_args = NULL_TREE;
4395  int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4396  int num_result_args = -1;
4397  int non_default_args_count = -1;
4398
4399  /* First, determine if we need to expand anything, and the number of
4400     slots we'll need.  */
4401  for (in_arg = 0; in_arg < nargs; ++in_arg)
4402    {
4403      tree arg = TREE_VEC_ELT (args, in_arg);
4404      if (arg == NULL_TREE)
4405	return args;
4406      if (ARGUMENT_PACK_P (arg))
4407        {
4408          int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4409          if (num_result_args < 0)
4410            num_result_args = in_arg + num_packed;
4411          else
4412            num_result_args += num_packed;
4413        }
4414      else
4415        {
4416          if (num_result_args >= 0)
4417            num_result_args++;
4418        }
4419    }
4420
4421  /* If no expansion is necessary, we're done.  */
4422  if (num_result_args < 0)
4423    return args;
4424
4425  /* Expand arguments.  */
4426  result_args = make_tree_vec (num_result_args);
4427  if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4428    non_default_args_count =
4429      GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4430  for (in_arg = 0; in_arg < nargs; ++in_arg)
4431    {
4432      tree arg = TREE_VEC_ELT (args, in_arg);
4433      if (ARGUMENT_PACK_P (arg))
4434        {
4435          tree packed = ARGUMENT_PACK_ARGS (arg);
4436          int i, num_packed = TREE_VEC_LENGTH (packed);
4437          for (i = 0; i < num_packed; ++i, ++out_arg)
4438            TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4439	  if (non_default_args_count > 0)
4440	    non_default_args_count += num_packed - 1;
4441        }
4442      else
4443        {
4444          TREE_VEC_ELT (result_args, out_arg) = arg;
4445          ++out_arg;
4446        }
4447    }
4448  if (non_default_args_count >= 0)
4449    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4450  return result_args;
4451}
4452
4453/* Checks if DECL shadows a template parameter.
4454
4455   [temp.local]: A template-parameter shall not be redeclared within its
4456   scope (including nested scopes).
4457
4458   Emits an error and returns TRUE if the DECL shadows a parameter,
4459   returns FALSE otherwise.  */
4460
4461bool
4462check_template_shadow (tree decl)
4463{
4464  tree olddecl;
4465
4466  /* If we're not in a template, we can't possibly shadow a template
4467     parameter.  */
4468  if (!current_template_parms)
4469    return true;
4470
4471  /* Figure out what we're shadowing.  */
4472  decl = OVL_FIRST (decl);
4473  olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4474
4475  /* If there's no previous binding for this name, we're not shadowing
4476     anything, let alone a template parameter.  */
4477  if (!olddecl)
4478    return true;
4479
4480  /* If we're not shadowing a template parameter, we're done.  Note
4481     that OLDDECL might be an OVERLOAD (or perhaps even an
4482     ERROR_MARK), so we can't just blithely assume it to be a _DECL
4483     node.  */
4484  if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4485    return true;
4486
4487  /* We check for decl != olddecl to avoid bogus errors for using a
4488     name inside a class.  We check TPFI to avoid duplicate errors for
4489     inline member templates.  */
4490  if (decl == olddecl
4491      || (DECL_TEMPLATE_PARM_P (decl)
4492	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4493    return true;
4494
4495  /* Don't complain about the injected class name, as we've already
4496     complained about the class itself.  */
4497  if (DECL_SELF_REFERENCE_P (decl))
4498    return false;
4499
4500  if (DECL_TEMPLATE_PARM_P (decl))
4501    error ("declaration of template parameter %q+D shadows "
4502	   "template parameter", decl);
4503  else
4504    error ("declaration of %q+#D shadows template parameter", decl);
4505  inform (DECL_SOURCE_LOCATION (olddecl),
4506	  "template parameter %qD declared here", olddecl);
4507  return false;
4508}
4509
4510/* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4511   ORIG_LEVEL, DECL, and TYPE.  */
4512
4513static tree
4514build_template_parm_index (int index,
4515			   int level,
4516			   int orig_level,
4517			   tree decl,
4518			   tree type)
4519{
4520  tree t = make_node (TEMPLATE_PARM_INDEX);
4521  TEMPLATE_PARM_IDX (t) = index;
4522  TEMPLATE_PARM_LEVEL (t) = level;
4523  TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4524  TEMPLATE_PARM_DECL (t) = decl;
4525  TREE_TYPE (t) = type;
4526  TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4527  TREE_READONLY (t) = TREE_READONLY (decl);
4528
4529  return t;
4530}
4531
4532/* Find the canonical type parameter for the given template type
4533   parameter.  Returns the canonical type parameter, which may be TYPE
4534   if no such parameter existed.  */
4535
4536tree
4537canonical_type_parameter (tree type)
4538{
4539  int idx = TEMPLATE_TYPE_IDX (type);
4540
4541  gcc_assert (TREE_CODE (type) != TEMPLATE_TEMPLATE_PARM);
4542
4543  if (vec_safe_length (canonical_template_parms) <= (unsigned) idx)
4544    vec_safe_grow_cleared (canonical_template_parms, idx + 1, true);
4545
4546  for (tree list = (*canonical_template_parms)[idx];
4547       list; list = TREE_CHAIN (list))
4548    if (comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4549      return TREE_VALUE (list);
4550
4551  (*canonical_template_parms)[idx]
4552    = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4553  return type;
4554}
4555
4556/* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4557   TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4558   TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4559   new one is created.  */
4560
4561static tree
4562reduce_template_parm_level (tree index, tree type, int levels, tree args,
4563			    tsubst_flags_t complain)
4564{
4565  if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4566      || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4567	  != TEMPLATE_PARM_LEVEL (index) - levels)
4568      || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4569    {
4570      tree orig_decl = TEMPLATE_PARM_DECL (index);
4571
4572      tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4573			      TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4574			      type);
4575      TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4576      TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4577      DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4578      DECL_ARTIFICIAL (decl) = 1;
4579      SET_DECL_TEMPLATE_PARM_P (decl);
4580
4581      tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4582					    TEMPLATE_PARM_LEVEL (index) - levels,
4583					    TEMPLATE_PARM_ORIG_LEVEL (index),
4584					    decl, type);
4585      TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4586      TEMPLATE_PARM_PARAMETER_PACK (tpi)
4587	= TEMPLATE_PARM_PARAMETER_PACK (index);
4588
4589      /* Template template parameters need this.  */
4590      tree inner = decl;
4591      if (TREE_CODE (decl) == TEMPLATE_DECL)
4592	{
4593	  inner = build_decl (DECL_SOURCE_LOCATION (decl),
4594			      TYPE_DECL, DECL_NAME (decl), type);
4595	  DECL_TEMPLATE_RESULT (decl) = inner;
4596	  DECL_ARTIFICIAL (inner) = true;
4597	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4598	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4599	}
4600
4601      /* Attach the TPI to the decl.  */
4602      if (TREE_CODE (inner) == TYPE_DECL)
4603	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4604      else
4605	DECL_INITIAL (decl) = tpi;
4606    }
4607
4608  return TEMPLATE_PARM_DESCENDANTS (index);
4609}
4610
4611/* Process information from new template parameter PARM and append it
4612   to the LIST being built.  This new parameter is a non-type
4613   parameter iff IS_NON_TYPE is true. This new parameter is a
4614   parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4615   is in PARM_LOC.  */
4616
4617tree
4618process_template_parm (tree list, location_t parm_loc, tree parm,
4619		       bool is_non_type, bool is_parameter_pack)
4620{
4621  gcc_assert (TREE_CODE (parm) == TREE_LIST);
4622  tree prev = NULL_TREE;
4623  int idx = 0;
4624
4625  if (list)
4626    {
4627      prev = tree_last (list);
4628
4629      tree p = TREE_VALUE (prev);
4630      if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4631	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4632      else if (TREE_CODE (p) == PARM_DECL)
4633	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4634
4635      ++idx;
4636    }
4637
4638  tree decl = NULL_TREE;
4639  tree defval = TREE_PURPOSE (parm);
4640  tree constr = TREE_TYPE (parm);
4641
4642  if (is_non_type)
4643    {
4644      parm = TREE_VALUE (parm);
4645
4646      SET_DECL_TEMPLATE_PARM_P (parm);
4647
4648      if (TREE_TYPE (parm) != error_mark_node)
4649	{
4650	  /* [temp.param]
4651
4652	     The top-level cv-qualifiers on the template-parameter are
4653	     ignored when determining its type.  */
4654	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4655	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4656	    TREE_TYPE (parm) = error_mark_node;
4657	  else if (uses_parameter_packs (TREE_TYPE (parm))
4658		   && !is_parameter_pack
4659		   /* If we're in a nested template parameter list, the template
4660		      template parameter could be a parameter pack.  */
4661		   && processing_template_parmlist == 1)
4662	    {
4663	      /* This template parameter is not a parameter pack, but it
4664		 should be. Complain about "bare" parameter packs.  */
4665	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4666
4667	      /* Recover by calling this a parameter pack.  */
4668	      is_parameter_pack = true;
4669	    }
4670	}
4671
4672      /* A template parameter is not modifiable.  */
4673      TREE_CONSTANT (parm) = 1;
4674      TREE_READONLY (parm) = 1;
4675      decl = build_decl (parm_loc,
4676			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4677      TREE_CONSTANT (decl) = 1;
4678      TREE_READONLY (decl) = 1;
4679      DECL_INITIAL (parm) = DECL_INITIAL (decl)
4680	= build_template_parm_index (idx, current_template_depth,
4681				     current_template_depth,
4682				     decl, TREE_TYPE (parm));
4683
4684      TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4685	= is_parameter_pack;
4686    }
4687  else
4688    {
4689      tree t;
4690      parm = TREE_VALUE (TREE_VALUE (parm));
4691
4692      if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4693	{
4694	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4695	  /* This is for distinguishing between real templates and template
4696	     template parameters */
4697	  TREE_TYPE (parm) = t;
4698
4699	  /* any_template_parm_r expects to be able to get the targs of a
4700	     DECL_TEMPLATE_RESULT.  */
4701	  tree result = DECL_TEMPLATE_RESULT (parm);
4702	  TREE_TYPE (result) = t;
4703	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4704	  tree tinfo = build_template_info (parm, args);
4705	  retrofit_lang_decl (result);
4706	  DECL_TEMPLATE_INFO (result) = tinfo;
4707
4708	  decl = parm;
4709	}
4710      else
4711	{
4712	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4713	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4714	  decl = build_decl (parm_loc,
4715			     TYPE_DECL, parm, t);
4716	}
4717
4718      TYPE_NAME (t) = decl;
4719      TYPE_STUB_DECL (t) = decl;
4720      parm = decl;
4721      TEMPLATE_TYPE_PARM_INDEX (t)
4722	= build_template_parm_index (idx, current_template_depth,
4723				     current_template_depth,
4724				     decl, TREE_TYPE (parm));
4725      TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4726      if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4727	SET_TYPE_STRUCTURAL_EQUALITY (t);
4728      else
4729	TYPE_CANONICAL (t) = canonical_type_parameter (t);
4730    }
4731  DECL_ARTIFICIAL (decl) = 1;
4732  SET_DECL_TEMPLATE_PARM_P (decl);
4733
4734  /* Build requirements for the type/template parameter.
4735     This must be done after SET_DECL_TEMPLATE_PARM_P or
4736     process_template_parm could fail. */
4737  tree reqs = finish_shorthand_constraint (parm, constr);
4738
4739  decl = pushdecl (decl);
4740  if (!is_non_type)
4741    parm = decl;
4742
4743  /* Build the parameter node linking the parameter declaration,
4744     its default argument (if any), and its constraints (if any). */
4745  parm = build_tree_list (defval, parm);
4746  TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4747
4748  if (prev)
4749    TREE_CHAIN (prev) = parm;
4750  else
4751    list = parm;
4752
4753  return list;
4754}
4755
4756/* The end of a template parameter list has been reached.  Process the
4757   tree list into a parameter vector, converting each parameter into a more
4758   useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4759   as PARM_DECLs.  */
4760
4761tree
4762end_template_parm_list (tree parms)
4763{
4764  tree saved_parmlist = make_tree_vec (list_length (parms));
4765
4766  /* Pop the dummy parameter level and add the real one.  We do not
4767     morph the dummy parameter in place, as it might have been
4768     captured by a (nested) template-template-parm.  */
4769  current_template_parms = TREE_CHAIN (current_template_parms);
4770
4771  current_template_parms
4772    = tree_cons (size_int (current_template_depth + 1),
4773		 saved_parmlist, current_template_parms);
4774
4775  for (unsigned ix = 0; parms; ix++)
4776    {
4777      tree parm = parms;
4778      parms = TREE_CHAIN (parms);
4779      TREE_CHAIN (parm) = NULL_TREE;
4780
4781      TREE_VEC_ELT (saved_parmlist, ix) = parm;
4782    }
4783
4784  --processing_template_parmlist;
4785
4786  return saved_parmlist;
4787}
4788
4789// Explicitly indicate the end of the template parameter list. We assume
4790// that the current template parameters have been constructed and/or
4791// managed explicitly, as when creating new template template parameters
4792// from a shorthand constraint.
4793void
4794end_template_parm_list ()
4795{
4796  --processing_template_parmlist;
4797}
4798
4799/* end_template_decl is called after a template declaration is seen.  */
4800
4801void
4802end_template_decl (void)
4803{
4804  reset_specialization ();
4805
4806  if (! processing_template_decl)
4807    return;
4808
4809  /* This matches the pushlevel in begin_template_parm_list.  */
4810  finish_scope ();
4811
4812  --processing_template_decl;
4813  current_template_parms = TREE_CHAIN (current_template_parms);
4814}
4815
4816/* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4817   thereof, and converts it into an argument suitable to be passed to
4818   the type substitution functions.  Note that if the TREE_LIST contains
4819   an error_mark node, the returned argument is error_mark_node.  */
4820
4821tree
4822template_parm_to_arg (tree t)
4823{
4824  if (!t)
4825    return NULL_TREE;
4826
4827  if (TREE_CODE (t) == TREE_LIST)
4828    t = TREE_VALUE (t);
4829
4830  if (error_operand_p (t))
4831    return error_mark_node;
4832
4833  if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4834    {
4835      if (TREE_CODE (t) == TYPE_DECL
4836	  || TREE_CODE (t) == TEMPLATE_DECL)
4837	t = TREE_TYPE (t);
4838      else
4839	t = DECL_INITIAL (t);
4840    }
4841
4842  gcc_assert (TEMPLATE_PARM_P (t));
4843
4844  if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4845      || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4846    {
4847      if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4848	{
4849	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4850	     with a single element, which expands T.  */
4851	  tree vec = make_tree_vec (1);
4852	  if (CHECKING_P)
4853	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4854
4855	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4856
4857	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4858	  SET_ARGUMENT_PACK_ARGS (t, vec);
4859	}
4860    }
4861  else
4862    {
4863      if (TEMPLATE_PARM_PARAMETER_PACK (t))
4864	{
4865	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4866	     with a single element, which expands T.  */
4867	  tree vec = make_tree_vec (1);
4868	  if (CHECKING_P)
4869	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4870
4871	  t = convert_from_reference (t);
4872	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4873
4874	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4875	  SET_ARGUMENT_PACK_ARGS (t, vec);
4876	}
4877      else
4878	t = convert_from_reference (t);
4879    }
4880  return t;
4881}
4882
4883/* Given a single level of template parameters (a TREE_VEC), return it
4884   as a set of template arguments.  */
4885
4886tree
4887template_parms_level_to_args (tree parms)
4888{
4889  tree a = copy_node (parms);
4890  TREE_TYPE (a) = NULL_TREE;
4891  for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4892    TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4893
4894  if (CHECKING_P)
4895    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4896
4897  return a;
4898}
4899
4900/* Given a set of template parameters, return them as a set of template
4901   arguments.  The template parameters are represented as a TREE_VEC, in
4902   the form documented in cp-tree.h for template arguments.  */
4903
4904tree
4905template_parms_to_args (tree parms)
4906{
4907  tree header;
4908  tree args = NULL_TREE;
4909  int length = TMPL_PARMS_DEPTH (parms);
4910  int l = length;
4911
4912  /* If there is only one level of template parameters, we do not
4913     create a TREE_VEC of TREE_VECs.  Instead, we return a single
4914     TREE_VEC containing the arguments.  */
4915  if (length > 1)
4916    args = make_tree_vec (length);
4917
4918  for (header = parms; header; header = TREE_CHAIN (header))
4919    {
4920      tree a = template_parms_level_to_args (TREE_VALUE (header));
4921
4922      if (length > 1)
4923	TREE_VEC_ELT (args, --l) = a;
4924      else
4925	args = a;
4926    }
4927
4928  return args;
4929}
4930
4931/* Within the declaration of a template, return the currently active
4932   template parameters as an argument TREE_VEC.  */
4933
4934static tree
4935current_template_args (void)
4936{
4937  return template_parms_to_args (current_template_parms);
4938}
4939
4940/* Return the fully generic arguments for of TMPL, i.e. what
4941   current_template_args would be while parsing it.  */
4942
4943tree
4944generic_targs_for (tree tmpl)
4945{
4946  if (tmpl == NULL_TREE)
4947    return NULL_TREE;
4948  if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4949      || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4950    /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4951       template parameter, it has no TEMPLATE_INFO; for a partial
4952       specialization, it has the arguments for the primary template, and we
4953       want the arguments for the partial specialization.  */;
4954  else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4955    if (tree ti = get_template_info (result))
4956      return TI_ARGS (ti);
4957  return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4958}
4959
4960/* Return the template arguments corresponding to the template parameters of
4961   TMPL's enclosing scope.  When TMPL is a member of a partial specialization,
4962   this returns the arguments for the partial specialization as opposed to those
4963   for the primary template, which is the main difference between this function
4964   and simply using e.g. the TYPE_TI_ARGS of TMPL's DECL_CONTEXT.  */
4965
4966tree
4967outer_template_args (tree tmpl)
4968{
4969  tree ti = get_template_info (DECL_TEMPLATE_RESULT (tmpl));
4970  if (!ti)
4971    return NULL_TREE;
4972  tree args = TI_ARGS (ti);
4973  if (!PRIMARY_TEMPLATE_P (tmpl))
4974    return args;
4975  if (TMPL_ARGS_DEPTH (args) == 1)
4976    return NULL_TREE;
4977  args = copy_node (args);
4978  --TREE_VEC_LENGTH (args);
4979  return args;
4980}
4981
4982/* Update the declared TYPE by doing any lookups which were thought to be
4983   dependent, but are not now that we know the SCOPE of the declarator.  */
4984
4985tree
4986maybe_update_decl_type (tree orig_type, tree scope)
4987{
4988  tree type = orig_type;
4989
4990  if (type == NULL_TREE)
4991    return type;
4992
4993  if (TREE_CODE (orig_type) == TYPE_DECL)
4994    type = TREE_TYPE (type);
4995
4996  if (scope && TYPE_P (scope) && dependent_type_p (scope)
4997      && dependent_type_p (type)
4998      /* Don't bother building up the args in this case.  */
4999      && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5000    {
5001      /* tsubst in the args corresponding to the template parameters,
5002	 including auto if present.  Most things will be unchanged, but
5003	 make_typename_type and tsubst_qualified_id will resolve
5004	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
5005      tree args = current_template_args ();
5006      tree auto_node = type_uses_auto (type);
5007      tree pushed;
5008      if (auto_node)
5009	{
5010	  tree auto_vec = make_tree_vec (1);
5011	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
5012	  args = add_to_template_args (args, auto_vec);
5013	}
5014      pushed = push_scope (scope);
5015      type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5016      if (pushed)
5017	pop_scope (scope);
5018    }
5019
5020  if (type == error_mark_node)
5021    return orig_type;
5022
5023  if (TREE_CODE (orig_type) == TYPE_DECL)
5024    {
5025      if (same_type_p (type, TREE_TYPE (orig_type)))
5026	type = orig_type;
5027      else
5028	type = TYPE_NAME (type);
5029    }
5030  return type;
5031}
5032
5033/* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5034   template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
5035   the new  template is a member template. */
5036
5037static tree
5038build_template_decl (tree decl, tree parms, bool member_template_p)
5039{
5040  gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5041
5042  tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5043  SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5044  DECL_TEMPLATE_PARMS (tmpl) = parms;
5045  DECL_TEMPLATE_RESULT (tmpl) = decl;
5046  DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5047  TREE_TYPE (tmpl) = TREE_TYPE (decl);
5048  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5049  DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5050
5051  /* Propagate module information from the decl.  */
5052  DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5053
5054  return tmpl;
5055}
5056
5057struct template_parm_data
5058{
5059  /* The level of the template parameters we are currently
5060     processing.  */
5061  int level;
5062
5063  /* The index of the specialization argument we are currently
5064     processing.  */
5065  int current_arg;
5066
5067  /* An array whose size is the number of template parameters.  The
5068     elements are nonzero if the parameter has been used in any one
5069     of the arguments processed so far.  */
5070  int* parms;
5071
5072  /* An array whose size is the number of template arguments.  The
5073     elements are nonzero if the argument makes use of template
5074     parameters of this level.  */
5075  int* arg_uses_template_parms;
5076};
5077
5078/* Subroutine of push_template_decl used to see if each template
5079   parameter in a partial specialization is used in the explicit
5080   argument list.  If T is of the LEVEL given in DATA (which is
5081   treated as a template_parm_data*), then DATA->PARMS is marked
5082   appropriately.  */
5083
5084static int
5085mark_template_parm (tree t, void* data)
5086{
5087  int level;
5088  int idx;
5089  struct template_parm_data* tpd = (struct template_parm_data*) data;
5090
5091  template_parm_level_and_index (t, &level, &idx);
5092
5093  if (level == tpd->level)
5094    {
5095      tpd->parms[idx] = 1;
5096      tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5097    }
5098
5099  /* In C++17 the type of a non-type argument is a deduced context.  */
5100  if (cxx_dialect >= cxx17
5101      && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5102    for_each_template_parm (TREE_TYPE (t),
5103			    &mark_template_parm,
5104			    data,
5105			    NULL,
5106			    /*include_nondeduced_p=*/false);
5107
5108  /* Return zero so that for_each_template_parm will continue the
5109     traversal of the tree; we want to mark *every* template parm.  */
5110  return 0;
5111}
5112
5113/* Process the partial specialization DECL.  */
5114
5115static tree
5116process_partial_specialization (tree decl)
5117{
5118  tree type = TREE_TYPE (decl);
5119  tree tinfo = get_template_info (decl);
5120  tree maintmpl = TI_TEMPLATE (tinfo);
5121  tree specargs = TI_ARGS (tinfo);
5122  tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5123  tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5124  tree inner_parms;
5125  tree inst;
5126  int nargs = TREE_VEC_LENGTH (inner_args);
5127  int ntparms;
5128  int  i;
5129  bool did_error_intro = false;
5130  struct template_parm_data tpd;
5131  struct template_parm_data tpd2;
5132
5133  gcc_assert (current_template_parms);
5134
5135  /* A concept cannot be specialized.  */
5136  if (flag_concepts && variable_concept_p (maintmpl))
5137    {
5138      error ("specialization of variable concept %q#D", maintmpl);
5139      return error_mark_node;
5140    }
5141
5142  inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5143  ntparms = TREE_VEC_LENGTH (inner_parms);
5144
5145  /* We check that each of the template parameters given in the
5146     partial specialization is used in the argument list to the
5147     specialization.  For example:
5148
5149       template <class T> struct S;
5150       template <class T> struct S<T*>;
5151
5152     The second declaration is OK because `T*' uses the template
5153     parameter T, whereas
5154
5155       template <class T> struct S<int>;
5156
5157     is no good.  Even trickier is:
5158
5159       template <class T>
5160       struct S1
5161       {
5162	  template <class U>
5163	  struct S2;
5164	  template <class U>
5165	  struct S2<T>;
5166       };
5167
5168     The S2<T> declaration is actually invalid; it is a
5169     full-specialization.  Of course,
5170
5171	  template <class U>
5172	  struct S2<T (*)(U)>;
5173
5174     or some such would have been OK.  */
5175  tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5176  tpd.parms = XALLOCAVEC (int, ntparms);
5177  memset (tpd.parms, 0, sizeof (int) * ntparms);
5178
5179  tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5180  memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5181  for (i = 0; i < nargs; ++i)
5182    {
5183      tpd.current_arg = i;
5184      for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5185			      &mark_template_parm,
5186			      &tpd,
5187			      NULL,
5188			      /*include_nondeduced_p=*/false);
5189    }
5190  for (i = 0; i < ntparms; ++i)
5191    if (tpd.parms[i] == 0)
5192      {
5193	/* One of the template parms was not used in a deduced context in the
5194	   specialization.  */
5195	if (!did_error_intro)
5196	  {
5197	    error ("template parameters not deducible in "
5198		   "partial specialization:");
5199	    did_error_intro = true;
5200	  }
5201
5202	inform (input_location, "        %qD",
5203		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5204      }
5205
5206  if (did_error_intro)
5207    return error_mark_node;
5208
5209  /* [temp.class.spec]
5210
5211     The argument list of the specialization shall not be identical to
5212     the implicit argument list of the primary template.  */
5213  tree main_args
5214    = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5215  if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5216      && (!flag_concepts
5217	  || !strictly_subsumes (current_template_constraints (), maintmpl)))
5218    {
5219      if (!flag_concepts)
5220        error ("partial specialization %q+D does not specialize "
5221	       "any template arguments; to define the primary template, "
5222	       "remove the template argument list", decl);
5223      else
5224        error ("partial specialization %q+D does not specialize any "
5225	       "template arguments and is not more constrained than "
5226	       "the primary template; to define the primary template, "
5227	       "remove the template argument list", decl);
5228      inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5229    }
5230
5231  /* A partial specialization that replaces multiple parameters of the
5232     primary template with a pack expansion is less specialized for those
5233     parameters.  */
5234  if (nargs < DECL_NTPARMS (maintmpl))
5235    {
5236      error ("partial specialization is not more specialized than the "
5237	     "primary template because it replaces multiple parameters "
5238	     "with a pack expansion");
5239      inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5240      /* Avoid crash in process_partial_specialization.  */
5241      return decl;
5242    }
5243
5244  else if (nargs > DECL_NTPARMS (maintmpl))
5245    {
5246      error ("too many arguments for partial specialization %qT", type);
5247      inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5248      /* Avoid crash below.  */
5249      return decl;
5250    }
5251
5252  /* If we aren't in a dependent class, we can actually try deduction.  */
5253  else if (tpd.level == 1
5254	   /* FIXME we should be able to handle a partial specialization of a
5255	      partial instantiation, but currently we can't (c++/41727).  */
5256	   && TMPL_ARGS_DEPTH (specargs) == 1
5257	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5258    {
5259      auto_diagnostic_group d;
5260      if (pedwarn (input_location, 0,
5261		   "partial specialization %qD is not more specialized than",
5262		   decl))
5263	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5264		maintmpl);
5265    }
5266
5267  /* [temp.spec.partial]
5268
5269     The type of a template parameter corresponding to a specialized
5270     non-type argument shall not be dependent on a parameter of the
5271     specialization.
5272
5273     Also, we verify that pack expansions only occur at the
5274     end of the argument list.  */
5275  tpd2.parms = 0;
5276  for (i = 0; i < nargs; ++i)
5277    {
5278      tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5279      tree arg = TREE_VEC_ELT (inner_args, i);
5280      tree packed_args = NULL_TREE;
5281      int j, len = 1;
5282
5283      if (ARGUMENT_PACK_P (arg))
5284        {
5285          /* Extract the arguments from the argument pack. We'll be
5286             iterating over these in the following loop.  */
5287          packed_args = ARGUMENT_PACK_ARGS (arg);
5288          len = TREE_VEC_LENGTH (packed_args);
5289        }
5290
5291      for (j = 0; j < len; j++)
5292        {
5293          if (packed_args)
5294            /* Get the Jth argument in the parameter pack.  */
5295            arg = TREE_VEC_ELT (packed_args, j);
5296
5297          if (PACK_EXPANSION_P (arg))
5298            {
5299              /* Pack expansions must come at the end of the
5300                 argument list.  */
5301              if ((packed_args && j < len - 1)
5302                  || (!packed_args && i < nargs - 1))
5303                {
5304                  if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5305                    error ("parameter pack argument %qE must be at the "
5306			   "end of the template argument list", arg);
5307                  else
5308                    error ("parameter pack argument %qT must be at the "
5309			   "end of the template argument list", arg);
5310                }
5311            }
5312
5313          if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5314            /* We only care about the pattern.  */
5315            arg = PACK_EXPANSION_PATTERN (arg);
5316
5317          if (/* These first two lines are the `non-type' bit.  */
5318              !TYPE_P (arg)
5319              && TREE_CODE (arg) != TEMPLATE_DECL
5320              /* This next two lines are the `argument expression is not just a
5321                 simple identifier' condition and also the `specialized
5322                 non-type argument' bit.  */
5323              && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5324	      && !((REFERENCE_REF_P (arg)
5325		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5326		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5327            {
5328	      /* Look at the corresponding template parameter,
5329		 marking which template parameters its type depends
5330		 upon.  */
5331	      tree type = TREE_TYPE (parm);
5332
5333	      if (!tpd2.parms)
5334		{
5335		  /* We haven't yet initialized TPD2.  Do so now.  */
5336		  tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5337		  /* The number of parameters here is the number in the
5338		     main template, which, as checked in the assertion
5339		     above, is NARGS.  */
5340		  tpd2.parms = XALLOCAVEC (int, nargs);
5341		  tpd2.level =
5342		    TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5343		}
5344
5345	      /* Mark the template parameters.  But this time, we're
5346		 looking for the template parameters of the main
5347		 template, not in the specialization.  */
5348	      tpd2.current_arg = i;
5349	      tpd2.arg_uses_template_parms[i] = 0;
5350	      memset (tpd2.parms, 0, sizeof (int) * nargs);
5351	      for_each_template_parm (type,
5352				      &mark_template_parm,
5353				      &tpd2,
5354				      NULL,
5355				      /*include_nondeduced_p=*/false);
5356
5357	      if (tpd2.arg_uses_template_parms [i])
5358		{
5359		  /* The type depended on some template parameters.
5360		     If they are fully specialized in the
5361		     specialization, that's OK.  */
5362		  int j;
5363		  int count = 0;
5364		  for (j = 0; j < nargs; ++j)
5365		    if (tpd2.parms[j] != 0
5366			&& tpd.arg_uses_template_parms [j])
5367		      ++count;
5368		  if (count != 0)
5369		    error_n (input_location, count,
5370			     "type %qT of template argument %qE depends "
5371			     "on a template parameter",
5372			     "type %qT of template argument %qE depends "
5373			     "on template parameters",
5374			     type,
5375			     arg);
5376		}
5377            }
5378        }
5379    }
5380
5381  /* We should only get here once.  */
5382  if (TREE_CODE (decl) == TYPE_DECL)
5383    gcc_assert (!COMPLETE_TYPE_P (type));
5384
5385  // Build the template decl.
5386  tree tmpl = build_template_decl (decl, current_template_parms,
5387				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5388  SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5389  DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5390  DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5391
5392  /* Give template template parms a DECL_CONTEXT of the template
5393     for which they are a parameter.  */
5394  for (i = 0; i < ntparms; ++i)
5395    {
5396      tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5397      if (TREE_CODE (parm) == TEMPLATE_DECL)
5398	DECL_CONTEXT (parm) = tmpl;
5399    }
5400
5401  if (VAR_P (decl))
5402    /* We didn't register this in check_explicit_specialization so we could
5403       wait until the constraints were set.  */
5404    decl = register_specialization (decl, maintmpl, specargs, false, 0);
5405  else
5406    associate_classtype_constraints (type);
5407
5408  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5409    = tree_cons (specargs, tmpl,
5410                 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5411  TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5412
5413  for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5414       inst = TREE_CHAIN (inst))
5415    {
5416      tree instance = TREE_VALUE (inst);
5417      if (TYPE_P (instance)
5418	  ? (COMPLETE_TYPE_P (instance)
5419	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5420	  : DECL_TEMPLATE_INSTANTIATION (instance))
5421	{
5422	  tree spec = most_specialized_partial_spec (instance, tf_none);
5423	  tree inst_decl = (DECL_P (instance)
5424			    ? instance : TYPE_NAME (instance));
5425	  if (!spec)
5426	    /* OK */;
5427	  else if (spec == error_mark_node)
5428	    permerror (input_location,
5429		       "declaration of %qD ambiguates earlier template "
5430		       "instantiation for %qD", decl, inst_decl);
5431	  else if (TREE_VALUE (spec) == tmpl)
5432	    permerror (input_location,
5433		       "partial specialization of %qD after instantiation "
5434		       "of %qD", decl, inst_decl);
5435	}
5436    }
5437
5438  return decl;
5439}
5440
5441/* PARM is a template parameter of some form; return the corresponding
5442   TEMPLATE_PARM_INDEX.  */
5443
5444static tree
5445get_template_parm_index (tree parm)
5446{
5447  if (TREE_CODE (parm) == PARM_DECL
5448      || TREE_CODE (parm) == CONST_DECL)
5449    parm = DECL_INITIAL (parm);
5450  else if (TREE_CODE (parm) == TYPE_DECL
5451	   || TREE_CODE (parm) == TEMPLATE_DECL)
5452    parm = TREE_TYPE (parm);
5453  if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5454      || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5455      || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5456    parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5457  gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5458  return parm;
5459}
5460
5461/* Subroutine of fixed_parameter_pack_p below.  Look for any template
5462   parameter packs used by the template parameter PARM.  */
5463
5464static void
5465fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5466{
5467  /* A type parm can't refer to another parm.  */
5468  if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5469    return;
5470  else if (TREE_CODE (parm) == PARM_DECL)
5471    {
5472      cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5473		    ppd, ppd->visited);
5474      return;
5475    }
5476
5477  gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5478
5479  tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5480  for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5481    {
5482      tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5483      if (template_parameter_pack_p (p))
5484	/* Any packs in the type are expanded by this parameter.  */;
5485      else
5486	fixed_parameter_pack_p_1 (p, ppd);
5487    }
5488}
5489
5490/* PARM is a template parameter pack.  Return any parameter packs used in
5491   its type or the type of any of its template parameters.  If there are
5492   any such packs, it will be instantiated into a fixed template parameter
5493   list by partial instantiation rather than be fully deduced.  */
5494
5495tree
5496fixed_parameter_pack_p (tree parm)
5497{
5498  /* This can only be true in a member template.  */
5499  if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5500    return NULL_TREE;
5501  /* This can only be true for a parameter pack.  */
5502  if (!template_parameter_pack_p (parm))
5503    return NULL_TREE;
5504  /* A type parm can't refer to another parm.  */
5505  if (TREE_CODE (parm) == TYPE_DECL)
5506    return NULL_TREE;
5507
5508  tree parameter_packs = NULL_TREE;
5509  struct find_parameter_pack_data ppd;
5510  ppd.parameter_packs = &parameter_packs;
5511  ppd.visited = new hash_set<tree>;
5512  ppd.type_pack_expansion_p = false;
5513
5514  fixed_parameter_pack_p_1 (parm, &ppd);
5515
5516  delete ppd.visited;
5517  return parameter_packs;
5518}
5519
5520/* Check that a template declaration's use of default arguments and
5521   parameter packs is not invalid.  Here, PARMS are the template
5522   parameters.  IS_PRIMARY is true if DECL is the thing declared by
5523   a primary template.  IS_PARTIAL is true if DECL is a partial
5524   specialization.
5525
5526   IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5527   function template declaration or a friend class template
5528   declaration.  In the function case, 1 indicates a declaration, 2
5529   indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5530   emitted for extraneous default arguments.
5531
5532   Returns TRUE if there were no errors found, FALSE otherwise. */
5533
5534bool
5535check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5536                         bool is_partial, int is_friend_decl)
5537{
5538  const char *msg;
5539  int last_level_to_check;
5540  tree parm_level;
5541  bool no_errors = true;
5542
5543  /* [temp.param]
5544
5545     A default template-argument shall not be specified in a
5546     function template declaration or a function template definition, nor
5547     in the template-parameter-list of the definition of a member of a
5548     class template.  */
5549
5550  if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5551      || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5552    /* You can't have a function template declaration in a local
5553       scope, nor you can you define a member of a class template in a
5554       local scope.  */
5555    return true;
5556
5557  if ((TREE_CODE (decl) == TYPE_DECL
5558       && TREE_TYPE (decl)
5559       && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5560      || (TREE_CODE (decl) == FUNCTION_DECL
5561	  && LAMBDA_FUNCTION_P (decl)))
5562    /* A lambda doesn't have an explicit declaration; don't complain
5563       about the parms of the enclosing class.  */
5564    return true;
5565
5566  if (current_class_type
5567      && !TYPE_BEING_DEFINED (current_class_type)
5568      && DECL_LANG_SPECIFIC (decl)
5569      && DECL_DECLARES_FUNCTION_P (decl)
5570      /* If this is either a friend defined in the scope of the class
5571	 or a member function.  */
5572      && (DECL_FUNCTION_MEMBER_P (decl)
5573	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5574	  : DECL_FRIEND_CONTEXT (decl)
5575	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5576	  : false)
5577      /* And, if it was a member function, it really was defined in
5578	 the scope of the class.  */
5579      && (!DECL_FUNCTION_MEMBER_P (decl)
5580	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5581    /* We already checked these parameters when the template was
5582       declared, so there's no need to do it again now.  This function
5583       was defined in class scope, but we're processing its body now
5584       that the class is complete.  */
5585    return true;
5586
5587  /* Core issue 226 (C++0x only): the following only applies to class
5588     templates.  */
5589  if (is_primary
5590      && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5591    {
5592      /* [temp.param]
5593
5594         If a template-parameter has a default template-argument, all
5595         subsequent template-parameters shall have a default
5596         template-argument supplied.  */
5597      for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5598        {
5599          tree inner_parms = TREE_VALUE (parm_level);
5600          int ntparms = TREE_VEC_LENGTH (inner_parms);
5601          int seen_def_arg_p = 0;
5602          int i;
5603
5604          for (i = 0; i < ntparms; ++i)
5605            {
5606              tree parm = TREE_VEC_ELT (inner_parms, i);
5607
5608              if (parm == error_mark_node)
5609                continue;
5610
5611              if (TREE_PURPOSE (parm))
5612                seen_def_arg_p = 1;
5613              else if (seen_def_arg_p
5614		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5615                {
5616                  error ("no default argument for %qD", TREE_VALUE (parm));
5617                  /* For better subsequent error-recovery, we indicate that
5618                     there should have been a default argument.  */
5619                  TREE_PURPOSE (parm) = error_mark_node;
5620                  no_errors = false;
5621                }
5622	      else if (!is_partial
5623		       && !is_friend_decl
5624		       /* Don't complain about an enclosing partial
5625			  specialization.  */
5626		       && parm_level == parms
5627		       && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5628		       && i < ntparms - 1
5629		       && template_parameter_pack_p (TREE_VALUE (parm))
5630		       /* A fixed parameter pack will be partially
5631			  instantiated into a fixed length list.  */
5632		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5633		{
5634		  /* A primary class template, primary variable template
5635		     (DR 2032), or alias template can only have one
5636		     parameter pack, at the end of the template
5637		     parameter list.  */
5638
5639		  error ("parameter pack %q+D must be at the end of the"
5640			 " template parameter list", TREE_VALUE (parm));
5641
5642		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5643		    = error_mark_node;
5644		  no_errors = false;
5645		}
5646            }
5647        }
5648    }
5649
5650  if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5651      || is_partial
5652      || !is_primary
5653      || is_friend_decl)
5654    /* For an ordinary class template, default template arguments are
5655       allowed at the innermost level, e.g.:
5656	 template <class T = int>
5657	 struct S {};
5658       but, in a partial specialization, they're not allowed even
5659       there, as we have in [temp.class.spec]:
5660
5661	 The template parameter list of a specialization shall not
5662	 contain default template argument values.
5663
5664       So, for a partial specialization, or for a function template
5665       (in C++98/C++03), we look at all of them.  */
5666    ;
5667  else
5668    /* But, for a primary class template that is not a partial
5669       specialization we look at all template parameters except the
5670       innermost ones.  */
5671    parms = TREE_CHAIN (parms);
5672
5673  /* Figure out what error message to issue.  */
5674  if (is_friend_decl == 2)
5675    msg = G_("default template arguments may not be used in function template "
5676	     "friend re-declaration");
5677  else if (is_friend_decl)
5678    msg = G_("default template arguments may not be used in template "
5679	     "friend declarations");
5680  else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5681    msg = G_("default template arguments may not be used in function templates "
5682	     "without %<-std=c++11%> or %<-std=gnu++11%>");
5683  else if (is_partial)
5684    msg = G_("default template arguments may not be used in "
5685	     "partial specializations");
5686  else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5687    msg = G_("default argument for template parameter for class enclosing %qD");
5688  else
5689    /* Per [temp.param]/9, "A default template-argument shall not be
5690       specified in the template-parameter-lists of the definition of
5691       a member of a class template that appears outside of the member's
5692       class.", thus if we aren't handling a member of a class template
5693       there is no need to examine the parameters.  */
5694    return true;
5695
5696  if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5697    /* If we're inside a class definition, there's no need to
5698       examine the parameters to the class itself.  On the one
5699       hand, they will be checked when the class is defined, and,
5700       on the other, default arguments are valid in things like:
5701	 template <class T = double>
5702	 struct S { template <class U> void f(U); };
5703       Here the default argument for `S' has no bearing on the
5704       declaration of `f'.  */
5705    last_level_to_check = template_class_depth (current_class_type) + 1;
5706  else
5707    /* Check everything.  */
5708    last_level_to_check = 0;
5709
5710  for (parm_level = parms;
5711       parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5712       parm_level = TREE_CHAIN (parm_level))
5713    {
5714      tree inner_parms = TREE_VALUE (parm_level);
5715      int i;
5716      int ntparms;
5717
5718      ntparms = TREE_VEC_LENGTH (inner_parms);
5719      for (i = 0; i < ntparms; ++i)
5720        {
5721          if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5722            continue;
5723
5724	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5725	    {
5726	      if (msg)
5727	        {
5728                  no_errors = false;
5729                  if (is_friend_decl == 2)
5730                    return no_errors;
5731
5732		  error (msg, decl);
5733		  msg = 0;
5734	        }
5735
5736	      /* Clear out the default argument so that we are not
5737	         confused later.  */
5738	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5739	    }
5740        }
5741
5742      /* At this point, if we're still interested in issuing messages,
5743	 they must apply to classes surrounding the object declared.  */
5744      if (msg)
5745	msg = G_("default argument for template parameter for class "
5746		 "enclosing %qD");
5747    }
5748
5749  return no_errors;
5750}
5751
5752/* Worker for push_template_decl_real, called via
5753   for_each_template_parm.  DATA is really an int, indicating the
5754   level of the parameters we are interested in.  If T is a template
5755   parameter of that level, return nonzero.  */
5756
5757static int
5758template_parm_this_level_p (tree t, void* data)
5759{
5760  int this_level = *(int *)data;
5761  int level;
5762
5763  if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5764    level = TEMPLATE_PARM_LEVEL (t);
5765  else
5766    level = TEMPLATE_TYPE_LEVEL (t);
5767  return level == this_level;
5768}
5769
5770/* Worker for uses_outer_template_parms, called via for_each_template_parm.
5771   DATA is really an int, indicating the innermost outer level of parameters.
5772   If T is a template parameter of that level or further out, return
5773   nonzero.  */
5774
5775static int
5776template_parm_outer_level (tree t, void *data)
5777{
5778  int this_level = *(int *)data;
5779  int level;
5780
5781  if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5782    level = TEMPLATE_PARM_LEVEL (t);
5783  else
5784    level = TEMPLATE_TYPE_LEVEL (t);
5785  return level <= this_level;
5786}
5787
5788/* Creates a TEMPLATE_DECL for the indicated DECL using the template
5789   parameters given by current_template_args, or reuses a
5790   previously existing one, if appropriate.  Returns the DECL, or an
5791   equivalent one, if it is replaced via a call to duplicate_decls.
5792
5793   If IS_FRIEND is true, DECL is a friend declaration.  */
5794
5795tree
5796push_template_decl (tree decl, bool is_friend)
5797{
5798  if (decl == error_mark_node || !current_template_parms)
5799    return error_mark_node;
5800
5801  /* See if this is a partial specialization.  */
5802  bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5803		      && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5804		      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5805		     || (VAR_P (decl)
5806			 && DECL_LANG_SPECIFIC (decl)
5807			 && DECL_TEMPLATE_SPECIALIZATION (decl)
5808			 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5809
5810  /* No surprising friend functions.  */
5811  gcc_checking_assert (is_friend
5812		       || !(TREE_CODE (decl) == FUNCTION_DECL
5813			    && DECL_UNIQUE_FRIEND_P (decl)));
5814
5815  tree ctx;
5816  if (is_friend)
5817    /* For a friend, we want the context of the friend, not
5818       the type of which it is a friend.  */
5819    ctx = CP_DECL_CONTEXT (decl);
5820  else if (CP_DECL_CONTEXT (decl)
5821	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5822    /* In the case of a virtual function, we want the class in which
5823       it is defined.  */
5824    ctx = CP_DECL_CONTEXT (decl);
5825  else
5826    /* Otherwise, if we're currently defining some class, the DECL
5827       is assumed to be a member of the class.  */
5828    ctx = current_scope ();
5829
5830  if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5831    ctx = NULL_TREE;
5832
5833  if (!DECL_CONTEXT (decl))
5834    DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5835
5836  /* See if this is a primary template.  */
5837  bool is_primary = false;
5838  if (is_friend && ctx
5839      && uses_template_parms_level (ctx, current_template_depth))
5840    /* A friend template that specifies a class context, i.e.
5841         template <typename T> friend void A<T>::f();
5842       is not primary.  */
5843    ;
5844  else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5845    /* Lambdas are not primary.  */
5846    ;
5847  else
5848    is_primary = template_parm_scope_p ();
5849
5850  /* True if the template is a member template, in the sense of
5851     [temp.mem].  */
5852  bool member_template_p = false;
5853
5854  if (is_primary)
5855    {
5856      warning (OPT_Wtemplates, "template %qD declared", decl);
5857
5858      if (DECL_CLASS_SCOPE_P (decl))
5859	member_template_p = true;
5860
5861      if (TREE_CODE (decl) == TYPE_DECL
5862	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5863	{
5864	  error ("template class without a name");
5865	  return error_mark_node;
5866	}
5867      else if (TREE_CODE (decl) == FUNCTION_DECL)
5868	{
5869	  if (member_template_p)
5870	    {
5871	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5872		error ("member template %qD may not have virt-specifiers", decl);
5873	    }
5874	  if (DECL_DESTRUCTOR_P (decl))
5875	    {
5876	      /* [temp.mem]
5877
5878		 A destructor shall not be a member template.  */
5879	      error_at (DECL_SOURCE_LOCATION (decl),
5880			"destructor %qD declared as member template", decl);
5881	      return error_mark_node;
5882	    }
5883	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5884	      && (!prototype_p (TREE_TYPE (decl))
5885		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5886		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5887		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5888		      == void_list_node)))
5889	    {
5890	      /* [basic.stc.dynamic.allocation]
5891
5892		 An allocation function can be a function
5893		 template. ... Template allocation functions shall
5894		 have two or more parameters.  */
5895	      error ("invalid template declaration of %qD", decl);
5896	      return error_mark_node;
5897	    }
5898	}
5899      else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5900	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5901	/* Class template.  */;
5902      else if (TREE_CODE (decl) == TYPE_DECL
5903	       && TYPE_DECL_ALIAS_P (decl))
5904	/* alias-declaration */
5905	gcc_assert (!DECL_ARTIFICIAL (decl));
5906      else if (VAR_P (decl))
5907	/* C++14 variable template. */;
5908      else if (TREE_CODE (decl) == CONCEPT_DECL)
5909	/* C++20 concept definitions.  */;
5910      else
5911	{
5912	  error ("template declaration of %q#D", decl);
5913	  return error_mark_node;
5914	}
5915    }
5916
5917  bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5918		  && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5919		      || (VAR_OR_FUNCTION_DECL_P (decl)
5920			  && DECL_LOCAL_DECL_P (decl))));
5921
5922  /* Check to see that the rules regarding the use of default
5923     arguments are not being violated.  We check args for a friend
5924     functions when we know whether it's a definition, introducing
5925     declaration or re-declaration.  */
5926  if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5927    check_default_tmpl_args (decl, current_template_parms,
5928			     is_primary, is_partial, is_friend);
5929
5930  /* Ensure that there are no parameter packs in the type of this
5931     declaration that have not been expanded.  */
5932  if (TREE_CODE (decl) == FUNCTION_DECL)
5933    {
5934      /* Check each of the arguments individually to see if there are
5935         any bare parameter packs.  */
5936      tree type = TREE_TYPE (decl);
5937      tree arg = DECL_ARGUMENTS (decl);
5938      tree argtype = TYPE_ARG_TYPES (type);
5939
5940      while (arg && argtype)
5941        {
5942          if (!DECL_PACK_P (arg)
5943              && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5944            {
5945            /* This is a PARM_DECL that contains unexpanded parameter
5946               packs. We have already complained about this in the
5947               check_for_bare_parameter_packs call, so just replace
5948               these types with ERROR_MARK_NODE.  */
5949              TREE_TYPE (arg) = error_mark_node;
5950              TREE_VALUE (argtype) = error_mark_node;
5951            }
5952
5953          arg = DECL_CHAIN (arg);
5954          argtype = TREE_CHAIN (argtype);
5955        }
5956
5957      /* Check for bare parameter packs in the return type and the
5958         exception specifiers.  */
5959      if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5960	/* Errors were already issued, set return type to int
5961	   as the frontend doesn't expect error_mark_node as
5962	   the return type.  */
5963	TREE_TYPE (type) = integer_type_node;
5964      if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5965	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5966    }
5967  else
5968    {
5969      if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5970					  ? DECL_ORIGINAL_TYPE (decl)
5971					  : TREE_TYPE (decl)))
5972	{
5973	  TREE_TYPE (decl) = error_mark_node;
5974	  return error_mark_node;
5975	}
5976
5977      if (is_partial && VAR_P (decl)
5978	  && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5979	return error_mark_node;
5980    }
5981
5982  if (is_partial)
5983    return process_partial_specialization (decl);
5984
5985  tree args = current_template_args ();
5986  tree tmpl = NULL_TREE;
5987  bool new_template_p = false;
5988  if (local_p)
5989    {
5990      /* Does not get a template head.  */
5991      tmpl = NULL_TREE;
5992      gcc_checking_assert (!is_primary);
5993    }
5994  else if (!ctx
5995	   || TREE_CODE (ctx) == FUNCTION_DECL
5996	   || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5997	   || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5998	   || (is_friend && !(DECL_LANG_SPECIFIC (decl)
5999			      && DECL_TEMPLATE_INFO (decl))))
6000    {
6001      if (DECL_LANG_SPECIFIC (decl)
6002	  && DECL_TEMPLATE_INFO (decl)
6003	  && DECL_TI_TEMPLATE (decl))
6004	tmpl = DECL_TI_TEMPLATE (decl);
6005      /* If DECL is a TYPE_DECL for a class-template, then there won't
6006	 be DECL_LANG_SPECIFIC.  The information equivalent to
6007	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
6008      else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6009	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6010	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6011	{
6012	  /* Since a template declaration already existed for this
6013	     class-type, we must be redeclaring it here.  Make sure
6014	     that the redeclaration is valid.  */
6015	  redeclare_class_template (TREE_TYPE (decl),
6016				    current_template_parms,
6017				    current_template_constraints ());
6018	  /* We don't need to create a new TEMPLATE_DECL; just use the
6019	     one we already had.  */
6020	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6021	}
6022      else
6023	{
6024	  tmpl = build_template_decl (decl, current_template_parms,
6025				      member_template_p);
6026	  new_template_p = true;
6027
6028	  if (DECL_LANG_SPECIFIC (decl)
6029	      && DECL_TEMPLATE_SPECIALIZATION (decl))
6030	    {
6031	      /* A specialization of a member template of a template
6032		 class.  */
6033	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6034	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6035	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6036	    }
6037	}
6038    }
6039  else
6040    {
6041      tree a, t, current, parms;
6042      int i;
6043      tree tinfo = get_template_info (decl);
6044
6045      if (!tinfo)
6046	{
6047	  error ("template definition of non-template %q#D", decl);
6048	  return error_mark_node;
6049	}
6050
6051      tmpl = TI_TEMPLATE (tinfo);
6052
6053      if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6054	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6055	  && DECL_TEMPLATE_SPECIALIZATION (decl)
6056	  && DECL_MEMBER_TEMPLATE_P (tmpl))
6057	{
6058	  /* The declaration is a specialization of a member
6059	     template, declared outside the class.  Therefore, the
6060	     innermost template arguments will be NULL, so we
6061	     replace them with the arguments determined by the
6062	     earlier call to check_explicit_specialization.  */
6063	  args = DECL_TI_ARGS (decl);
6064
6065	  tree new_tmpl
6066	    = build_template_decl (decl, current_template_parms,
6067				   member_template_p);
6068	  DECL_TI_TEMPLATE (decl) = new_tmpl;
6069	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6070	  DECL_TEMPLATE_INFO (new_tmpl)
6071	    = build_template_info (tmpl, args);
6072
6073	  register_specialization (new_tmpl,
6074				   most_general_template (tmpl),
6075				   args,
6076				   is_friend, 0);
6077	  return decl;
6078	}
6079
6080      /* Make sure the template headers we got make sense.  */
6081
6082      parms = DECL_TEMPLATE_PARMS (tmpl);
6083      i = TMPL_PARMS_DEPTH (parms);
6084      if (TMPL_ARGS_DEPTH (args) != i)
6085	{
6086	  error ("expected %d levels of template parms for %q#D, got %d",
6087		 i, decl, TMPL_ARGS_DEPTH (args));
6088	  DECL_INTERFACE_KNOWN (decl) = 1;
6089	  return error_mark_node;
6090	}
6091      else
6092	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6093	  {
6094	    a = TMPL_ARGS_LEVEL (args, i);
6095	    t = INNERMOST_TEMPLATE_PARMS (parms);
6096
6097	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6098	      {
6099		if (current == decl)
6100		  error ("got %d template parameters for %q#D",
6101			 TREE_VEC_LENGTH (a), decl);
6102		else
6103		  error ("got %d template parameters for %q#T",
6104			 TREE_VEC_LENGTH (a), current);
6105		error ("  but %d required", TREE_VEC_LENGTH (t));
6106		/* Avoid crash in import_export_decl.  */
6107		DECL_INTERFACE_KNOWN (decl) = 1;
6108		return error_mark_node;
6109	      }
6110
6111	    if (current == decl)
6112	      current = ctx;
6113	    else if (current == NULL_TREE)
6114	      /* Can happen in erroneous input.  */
6115	      break;
6116	    else
6117	      current = get_containing_scope (current);
6118	  }
6119
6120      /* Check that the parms are used in the appropriate qualifying scopes
6121	 in the declarator.  */
6122      if (!comp_template_args
6123	  (TI_ARGS (tinfo),
6124	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6125	{
6126	  error ("template arguments to %qD do not match original "
6127		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6128	  if (!uses_template_parms (TI_ARGS (tinfo)))
6129	    inform (input_location, "use %<template<>%> for"
6130		    " an explicit specialization");
6131	  /* Avoid crash in import_export_decl.  */
6132	  DECL_INTERFACE_KNOWN (decl) = 1;
6133	  return error_mark_node;
6134	}
6135    }
6136
6137  gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6138
6139  if (new_template_p)
6140    {
6141      /* Push template declarations for global functions and types.
6142	 Note that we do not try to push a global template friend
6143	 declared in a template class; such a thing may well depend on
6144	 the template parameters of the class and we'll push it when
6145	 instantiating the befriending class.  */
6146      if (!ctx
6147	  && !(is_friend && template_class_depth (current_class_type) > 0))
6148	{
6149	  tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6150	  if (pushed == error_mark_node)
6151	    return error_mark_node;
6152
6153	  /* pushdecl may have found an existing template.  */
6154	  if (pushed != tmpl)
6155	    {
6156	      decl = DECL_TEMPLATE_RESULT (pushed);
6157	      tmpl = NULL_TREE;
6158	    }
6159	}
6160      else if (is_friend)
6161	{
6162	  /* Record this decl as belonging to the current class.  It's
6163	     not chained onto anything else.  */
6164	  DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6165	  gcc_checking_assert (!DECL_CHAIN (tmpl));
6166	  DECL_CHAIN (tmpl) = current_scope ();
6167	}
6168    }
6169  else if (tmpl)
6170    /* The type may have been completed, or (erroneously) changed.  */
6171    TREE_TYPE (tmpl) = TREE_TYPE (decl);
6172
6173  if (tmpl)
6174    {
6175      if (is_primary)
6176	{
6177	  tree parms = DECL_TEMPLATE_PARMS (tmpl);
6178
6179	  DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6180
6181	  /* Give template template parms a DECL_CONTEXT of the template
6182	     for which they are a parameter.  */
6183	  parms = INNERMOST_TEMPLATE_PARMS (parms);
6184	  for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6185	    {
6186	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6187	      if (TREE_CODE (parm) == TEMPLATE_DECL)
6188		DECL_CONTEXT (parm) = tmpl;
6189	    }
6190
6191	  if (TREE_CODE (decl) == TYPE_DECL
6192	      && TYPE_DECL_ALIAS_P (decl))
6193	    {
6194	      if (tree constr
6195		  = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6196		{
6197		  /* ??? Why don't we do this here for all templates?  */
6198		  constr = build_constraints (constr, NULL_TREE);
6199		  set_constraints (decl, constr);
6200		}
6201	      if (complex_alias_template_p (tmpl))
6202		TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6203	    }
6204	}
6205
6206      /* The DECL_TI_ARGS of DECL contains full set of arguments
6207	 referring wback to its most general template.  If TMPL is a
6208	 specialization, ARGS may only have the innermost set of
6209	 arguments.  Add the missing argument levels if necessary.  */
6210      if (DECL_TEMPLATE_INFO (tmpl))
6211	args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6212
6213      tree info = build_template_info (tmpl, args);
6214
6215      if (DECL_IMPLICIT_TYPEDEF_P (decl))
6216	SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6217      else
6218	{
6219	  retrofit_lang_decl (decl);
6220	  DECL_TEMPLATE_INFO (decl) = info;
6221	}
6222    }
6223
6224  if (flag_implicit_templates
6225      && !is_friend
6226      && TREE_PUBLIC (decl)
6227      && VAR_OR_FUNCTION_DECL_P (decl))
6228    /* Set DECL_COMDAT on template instantiations; if we force
6229       them to be emitted by explicit instantiation,
6230       mark_needed will tell cgraph to do the right thing.  */
6231    DECL_COMDAT (decl) = true;
6232
6233  gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6234
6235  return decl;
6236}
6237
6238/* FN is an inheriting constructor that inherits from the constructor
6239   template INHERITED; turn FN into a constructor template with a matching
6240   template header.  */
6241
6242tree
6243add_inherited_template_parms (tree fn, tree inherited)
6244{
6245  tree inner_parms
6246    = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6247  inner_parms = copy_node (inner_parms);
6248  tree parms
6249    = tree_cons (size_int (current_template_depth + 1),
6250		 inner_parms, current_template_parms);
6251  tree tmpl = build_template_decl (fn, parms, /*member*/true);
6252  tree args = template_parms_to_args (parms);
6253  DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6254  DECL_ARTIFICIAL (tmpl) = true;
6255  DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6256  return tmpl;
6257}
6258
6259/* Called when a class template TYPE is redeclared with the indicated
6260   template PARMS, e.g.:
6261
6262     template <class T> struct S;
6263     template <class T> struct S {};  */
6264
6265bool
6266redeclare_class_template (tree type, tree parms, tree cons)
6267{
6268  tree tmpl;
6269  tree tmpl_parms;
6270  int i;
6271
6272  if (!TYPE_TEMPLATE_INFO (type))
6273    {
6274      error ("%qT is not a template type", type);
6275      return false;
6276    }
6277
6278  tmpl = TYPE_TI_TEMPLATE (type);
6279  if (!PRIMARY_TEMPLATE_P (tmpl))
6280    /* The type is nested in some template class.  Nothing to worry
6281       about here; there are no new template parameters for the nested
6282       type.  */
6283    return true;
6284
6285  if (!parms)
6286    {
6287      error ("template specifiers not specified in declaration of %qD",
6288	     tmpl);
6289      return false;
6290    }
6291
6292  parms = INNERMOST_TEMPLATE_PARMS (parms);
6293  tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6294
6295  if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6296    {
6297      error_n (input_location, TREE_VEC_LENGTH (parms),
6298               "redeclared with %d template parameter",
6299               "redeclared with %d template parameters",
6300               TREE_VEC_LENGTH (parms));
6301      inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6302                "previous declaration %qD used %d template parameter",
6303                "previous declaration %qD used %d template parameters",
6304                tmpl, TREE_VEC_LENGTH (tmpl_parms));
6305      return false;
6306    }
6307
6308  for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6309    {
6310      tree tmpl_parm;
6311      tree parm;
6312
6313      if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6314          || TREE_VEC_ELT (parms, i) == error_mark_node)
6315        continue;
6316
6317      tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6318      if (error_operand_p (tmpl_parm))
6319	return false;
6320
6321      parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6322
6323      /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6324	 TEMPLATE_DECL.  */
6325      if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6326	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
6327	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6328	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6329	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6330		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6331	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6332	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6333		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6334	{
6335	  auto_diagnostic_group d;
6336	  error ("template parameter %q+#D", tmpl_parm);
6337	  if (DECL_P (parm))
6338	    inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6339	  else
6340	    inform (input_location, "redeclared here");
6341	  return false;
6342	}
6343
6344      /* The parameters can be declared to introduce different
6345	 constraints.  */
6346      tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6347      tree p2 = TREE_VEC_ELT (parms, i);
6348      if (!template_parameter_constraints_equivalent_p (p1, p2))
6349	{
6350	  auto_diagnostic_group d;
6351	  error ("declaration of template parameter %q+#D with different "
6352		 "constraints", parm);
6353	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6354		  "original declaration appeared here");
6355	  return false;
6356	}
6357
6358      /* Give each template template parm in this redeclaration a
6359	 DECL_CONTEXT of the template for which they are a parameter.  */
6360      if (TREE_CODE (parm) == TEMPLATE_DECL)
6361	{
6362	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6363	  DECL_CONTEXT (parm) = tmpl;
6364	}
6365    }
6366
6367  if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6368    return false;
6369
6370  tree ci = get_constraints (tmpl);
6371  tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6372  tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6373
6374  /* Two classes with different constraints declare different entities.  */
6375  if (!cp_tree_equal (req1, req2))
6376    {
6377      auto_diagnostic_group d;
6378      error_at (input_location, "redeclaration %q#D with different "
6379                                "constraints", tmpl);
6380      inform (DECL_SOURCE_LOCATION (tmpl),
6381              "original declaration appeared here");
6382      return false;
6383    }
6384
6385    return true;
6386}
6387
6388/* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6389   to be used when the caller has already checked
6390    !instantiation_dependent_uneval_expression_p (expr)
6391   and cleared processing_template_decl.  */
6392
6393tree
6394instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6395{
6396  return tsubst_copy_and_build (expr,
6397				/*args=*/NULL_TREE,
6398				complain,
6399				/*in_decl=*/NULL_TREE,
6400				/*function_p=*/false,
6401				/*integral_constant_expression_p=*/true);
6402}
6403
6404/* Instantiate the non-dependent expression EXPR.  */
6405
6406tree
6407instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6408{
6409  if (expr == NULL_TREE)
6410    return NULL_TREE;
6411
6412  if (processing_template_decl)
6413    {
6414      /* The caller should have checked this already.  */
6415      gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6416      processing_template_decl_sentinel s;
6417      expr = instantiate_non_dependent_expr_internal (expr, complain);
6418    }
6419  return expr;
6420}
6421
6422tree
6423instantiate_non_dependent_expr (tree expr)
6424{
6425  return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6426}
6427
6428/* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6429   expression is dependent or non-constant.  */
6430
6431tree
6432instantiate_non_dependent_or_null (tree expr)
6433{
6434  if (expr == NULL_TREE)
6435    return NULL_TREE;
6436  if (processing_template_decl)
6437    {
6438      if (!is_nondependent_constant_expression (expr))
6439	expr = NULL_TREE;
6440      else
6441	{
6442	  processing_template_decl_sentinel s;
6443	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6444	}
6445    }
6446  return expr;
6447}
6448
6449/* True iff T is a specialization of a variable template.  */
6450
6451bool
6452variable_template_specialization_p (tree t)
6453{
6454  if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6455    return false;
6456  tree tmpl = DECL_TI_TEMPLATE (t);
6457  return variable_template_p (tmpl);
6458}
6459
6460/* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6461   template declaration, or a TYPE_DECL for an alias declaration.  */
6462
6463bool
6464alias_type_or_template_p (tree t)
6465{
6466  if (t == NULL_TREE)
6467    return false;
6468  return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6469	  || (TYPE_P (t)
6470	      && TYPE_NAME (t)
6471	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6472	  || DECL_ALIAS_TEMPLATE_P (t));
6473}
6474
6475/* If T is a specialization of an alias template, return it; otherwise return
6476   NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6477
6478tree
6479alias_template_specialization_p (const_tree t,
6480				 bool transparent_typedefs)
6481{
6482  if (!TYPE_P (t))
6483    return NULL_TREE;
6484
6485  /* It's an alias template specialization if it's an alias and its
6486     TYPE_NAME is a specialization of a primary template.  */
6487  if (typedef_variant_p (t))
6488    {
6489      if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6490	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6491	  return CONST_CAST_TREE (t);
6492      if (transparent_typedefs)
6493	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6494						(TYPE_NAME (t)),
6495						transparent_typedefs);
6496    }
6497
6498  return NULL_TREE;
6499}
6500
6501/* Data structure for complex_alias_template_*.  */
6502
6503struct uses_all_template_parms_data
6504{
6505  int level;
6506  bool *seen;
6507};
6508
6509/* walk_tree callback for complex_alias_template_p.  */
6510
6511static tree
6512complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6513{
6514  tree t = *tp;
6515  auto &data = *(struct uses_all_template_parms_data*)data_;
6516
6517  switch (TREE_CODE (t))
6518    {
6519    case TEMPLATE_TYPE_PARM:
6520    case TEMPLATE_PARM_INDEX:
6521    case TEMPLATE_TEMPLATE_PARM:
6522    case BOUND_TEMPLATE_TEMPLATE_PARM:
6523      {
6524	tree idx = get_template_parm_index (t);
6525	if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6526	  data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6527      }
6528
6529    default:;
6530    }
6531
6532  if (!PACK_EXPANSION_P (t))
6533    return 0;
6534
6535  /* An alias template with a pack expansion that expands a pack from the
6536     enclosing class needs to be considered complex, to avoid confusion with
6537     the same pack being used as an argument to the alias's own template
6538     parameter (91966).  */
6539  for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6540       pack = TREE_CHAIN (pack))
6541    {
6542      tree parm_pack = TREE_VALUE (pack);
6543      if (!TEMPLATE_PARM_P (parm_pack))
6544	continue;
6545      int idx, level;
6546      template_parm_level_and_index (parm_pack, &level, &idx);
6547      if (level < data.level)
6548	return t;
6549
6550      /* Consider the expanded packs to be used outside the expansion...  */
6551      data.seen[idx] = true;
6552    }
6553
6554  /* ...but don't walk into the pattern.  Consider PR104008:
6555
6556     template <typename T, typename... Ts>
6557     using IsOneOf = disjunction<is_same<T, Ts>...>;
6558
6559     where IsOneOf seemingly uses all of its template parameters in its
6560     expansion (and does not expand a pack from the enclosing class), so the
6561     alias was not marked as complex.  However, if it is used like
6562     "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6563     expansion.  So only Ts is considered used by the pack expansion.  */
6564  *walk_subtrees = false;
6565
6566  return 0;
6567}
6568
6569/* An alias template is complex from a SFINAE perspective if a template-id
6570   using that alias can be ill-formed when the expansion is not, as with
6571   the void_t template.
6572
6573   Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6574   template arguments are empty packs.  */
6575
6576static bool
6577complex_alias_template_p (const_tree tmpl)
6578{
6579  /* A renaming alias isn't complex.  */
6580  if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6581    return false;
6582
6583  /* Any other constrained alias is complex.  */
6584  if (get_constraints (tmpl))
6585    return true;
6586
6587  struct uses_all_template_parms_data data;
6588  tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6589  tree parms = DECL_TEMPLATE_PARMS (tmpl);
6590  data.level = TMPL_PARMS_DEPTH (parms);
6591  int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6592  data.seen = XALLOCAVEC (bool, len);
6593  for (int i = 0; i < len; ++i)
6594    data.seen[i] = false;
6595
6596  if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6597    return true;
6598  for (int i = 0; i < len; ++i)
6599    if (!data.seen[i])
6600      return true;
6601  return false;
6602}
6603
6604/* If T is a specialization of a complex alias template with dependent
6605   template-arguments, return it; otherwise return NULL_TREE.  If T is a
6606   typedef to such a specialization, return the specialization.  */
6607
6608tree
6609dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6610{
6611  if (t == error_mark_node)
6612    return NULL_TREE;
6613  gcc_assert (TYPE_P (t));
6614
6615  if (!typedef_variant_p (t))
6616    return NULL_TREE;
6617
6618  tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6619  if (tinfo
6620      && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6621      && (any_dependent_template_arguments_p
6622	  (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6623    return CONST_CAST_TREE (t);
6624
6625  if (transparent_typedefs)
6626    {
6627      tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6628      return dependent_alias_template_spec_p (utype, transparent_typedefs);
6629    }
6630
6631  return NULL_TREE;
6632}
6633
6634/* Return the number of innermost template parameters in TMPL.  */
6635
6636static int
6637num_innermost_template_parms (const_tree tmpl)
6638{
6639  tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6640  return TREE_VEC_LENGTH (parms);
6641}
6642
6643/* Return either TMPL or another template that it is equivalent to under DR
6644   1286: An alias that just changes the name of a template is equivalent to
6645   the other template.  */
6646
6647static tree
6648get_underlying_template (tree tmpl)
6649{
6650  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6651  while (DECL_ALIAS_TEMPLATE_P (tmpl))
6652    {
6653      /* Determine if the alias is equivalent to an underlying template.  */
6654      tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6655      /* The underlying type may have been ill-formed. Don't proceed.  */
6656      if (!orig_type)
6657	break;
6658      tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6659      if (!tinfo)
6660	break;
6661
6662      tree underlying = TI_TEMPLATE (tinfo);
6663      if (!PRIMARY_TEMPLATE_P (underlying)
6664	  || (num_innermost_template_parms (tmpl)
6665	      != num_innermost_template_parms (underlying)))
6666	break;
6667
6668      /* Does the alias add cv-quals?  */
6669      if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6670	break;
6671
6672      tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6673      if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6674	break;
6675
6676      /* Are any default template arguments equivalent?  */
6677      tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6678      tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6679      const int nparms = TREE_VEC_LENGTH (aparms);
6680      for (int i = 0; i < nparms; ++i)
6681	{
6682	  tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6683	  tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6684	  if (!template_args_equal (adefarg, udefarg))
6685	    goto top_break;
6686	}
6687
6688      /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6689	 it's appropriate to treat a less-constrained alias as equivalent.  */
6690      if (!at_least_as_constrained (underlying, tmpl))
6691	break;
6692
6693      /* Alias is equivalent.  Strip it and repeat.  */
6694      tmpl = underlying;
6695    }
6696  top_break:;
6697
6698  return tmpl;
6699}
6700
6701/* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6702   must be a reference-to-function or a pointer-to-function type, as specified
6703   in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6704   and check that the resulting function has external linkage.  */
6705
6706static tree
6707convert_nontype_argument_function (tree type, tree expr,
6708				   tsubst_flags_t complain)
6709{
6710  tree fns = expr;
6711  tree fn, fn_no_ptr;
6712  linkage_kind linkage;
6713
6714  fn = instantiate_type (type, fns, tf_none);
6715  if (fn == error_mark_node)
6716    return error_mark_node;
6717
6718  if (value_dependent_expression_p (fn))
6719    goto accept;
6720
6721  fn_no_ptr = fn;
6722  if (REFERENCE_REF_P (fn_no_ptr))
6723    fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6724  fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6725  if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6726    fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6727  if (BASELINK_P (fn_no_ptr))
6728    fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6729
6730  /* [temp.arg.nontype]/1
6731
6732     A template-argument for a non-type, non-template template-parameter
6733     shall be one of:
6734     [...]
6735     -- the address of an object or function with external [C++11: or
6736        internal] linkage.  */
6737
6738  STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6739  if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6740    {
6741      if (complain & tf_error)
6742	{
6743	  location_t loc = cp_expr_loc_or_input_loc (expr);
6744	  error_at (loc, "%qE is not a valid template argument for type %qT",
6745		    expr, type);
6746	  if (TYPE_PTR_P (type))
6747	    inform (loc, "it must be the address of a function "
6748		    "with external linkage");
6749	  else
6750	    inform (loc, "it must be the name of a function with "
6751		    "external linkage");
6752	}
6753      return NULL_TREE;
6754    }
6755
6756  linkage = decl_linkage (fn_no_ptr);
6757  if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6758    {
6759      if (complain & tf_error)
6760	{
6761	  location_t loc = cp_expr_loc_or_input_loc (expr);
6762	  if (cxx_dialect >= cxx11)
6763	    error_at (loc, "%qE is not a valid template argument for type "
6764		      "%qT because %qD has no linkage",
6765		      expr, type, fn_no_ptr);
6766	  else
6767	    error_at (loc, "%qE is not a valid template argument for type "
6768		      "%qT because %qD does not have external linkage",
6769		      expr, type, fn_no_ptr);
6770	}
6771      return NULL_TREE;
6772    }
6773
6774 accept:
6775  if (TYPE_REF_P (type))
6776    {
6777      if (REFERENCE_REF_P (fn))
6778	fn = TREE_OPERAND (fn, 0);
6779      else
6780	fn = build_address (fn);
6781    }
6782  if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6783    fn = build_nop (type, fn);
6784
6785  return fn;
6786}
6787
6788/* Subroutine of convert_nontype_argument.
6789   Check if EXPR of type TYPE is a valid pointer-to-member constant.
6790   Emit an error otherwise.  */
6791
6792static bool
6793check_valid_ptrmem_cst_expr (tree type, tree expr,
6794			     tsubst_flags_t complain)
6795{
6796  tree orig_expr = expr;
6797  STRIP_NOPS (expr);
6798  if (null_ptr_cst_p (expr))
6799    return true;
6800  if (TREE_CODE (expr) == PTRMEM_CST
6801      && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6802		      PTRMEM_CST_CLASS (expr)))
6803    return true;
6804  if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6805    return true;
6806  if (processing_template_decl
6807      && TREE_CODE (expr) == ADDR_EXPR
6808      && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6809    return true;
6810  if (complain & tf_error)
6811    {
6812      location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6813      error_at (loc, "%qE is not a valid template argument for type %qT",
6814		orig_expr, type);
6815      if (TREE_CODE (expr) != PTRMEM_CST)
6816	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6817      else
6818	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6819    }
6820  return false;
6821}
6822
6823/* Returns TRUE iff the address of OP is value-dependent.
6824
6825   14.6.2.4 [temp.dep.temp]:
6826   A non-integral non-type template-argument is dependent if its type is
6827   dependent or it has either of the following forms
6828     qualified-id
6829     & qualified-id
6830   and contains a nested-name-specifier which specifies a class-name that
6831   names a dependent type.
6832
6833   We generalize this to just say that the address of a member of a
6834   dependent class is value-dependent; the above doesn't cover the
6835   address of a static data member named with an unqualified-id.  */
6836
6837static bool
6838has_value_dependent_address (tree op)
6839{
6840  STRIP_ANY_LOCATION_WRAPPER (op);
6841
6842  /* We could use get_inner_reference here, but there's no need;
6843     this is only relevant for template non-type arguments, which
6844     can only be expressed as &id-expression.  */
6845  if (DECL_P (op))
6846    {
6847      tree ctx = CP_DECL_CONTEXT (op);
6848
6849      if (TYPE_P (ctx) && dependent_type_p (ctx))
6850	return true;
6851
6852      if (VAR_P (op)
6853	  && TREE_STATIC (op)
6854	  && TREE_CODE (ctx) == FUNCTION_DECL
6855	  && type_dependent_expression_p (ctx))
6856	return true;
6857    }
6858
6859  return false;
6860}
6861
6862/* The next set of functions are used for providing helpful explanatory
6863   diagnostics for failed overload resolution.  Their messages should be
6864   indented by two spaces for consistency with the messages in
6865   call.cc  */
6866
6867static int
6868unify_success (bool /*explain_p*/)
6869{
6870  return 0;
6871}
6872
6873/* Other failure functions should call this one, to provide a single function
6874   for setting a breakpoint on.  */
6875
6876static int
6877unify_invalid (bool /*explain_p*/)
6878{
6879  return 1;
6880}
6881
6882static int
6883unify_parameter_deduction_failure (bool explain_p, tree parm)
6884{
6885  if (explain_p)
6886    inform (input_location,
6887	    "  couldn%'t deduce template parameter %qD", parm);
6888  return unify_invalid (explain_p);
6889}
6890
6891static int
6892unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6893{
6894  if (explain_p)
6895    inform (input_location,
6896	    "  types %qT and %qT have incompatible cv-qualifiers",
6897	    parm, arg);
6898  return unify_invalid (explain_p);
6899}
6900
6901static int
6902unify_type_mismatch (bool explain_p, tree parm, tree arg)
6903{
6904  if (explain_p)
6905    inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6906  return unify_invalid (explain_p);
6907}
6908
6909static int
6910unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6911{
6912  if (explain_p)
6913    inform (input_location,
6914	    "  template parameter %qD is not a parameter pack, but "
6915	    "argument %qD is",
6916	    parm, arg);
6917  return unify_invalid (explain_p);
6918}
6919
6920static int
6921unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6922{
6923  if (explain_p)
6924    inform (input_location,
6925	    "  template argument %qE does not match "
6926	    "pointer-to-member constant %qE",
6927	    arg, parm);
6928  return unify_invalid (explain_p);
6929}
6930
6931static int
6932unify_expression_unequal (bool explain_p, tree parm, tree arg)
6933{
6934  if (explain_p)
6935    inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6936  return unify_invalid (explain_p);
6937}
6938
6939static int
6940unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6941{
6942  if (explain_p)
6943    inform (input_location,
6944	    "  inconsistent parameter pack deduction with %qT and %qT",
6945	    old_arg, new_arg);
6946  return unify_invalid (explain_p);
6947}
6948
6949static int
6950unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6951{
6952  if (explain_p)
6953    {
6954      if (TYPE_P (parm))
6955	inform (input_location,
6956		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6957		parm, first, second);
6958      else
6959	inform (input_location,
6960		"  deduced conflicting values for non-type parameter "
6961		"%qE (%qE and %qE)", parm, first, second);
6962    }
6963  return unify_invalid (explain_p);
6964}
6965
6966static int
6967unify_vla_arg (bool explain_p, tree arg)
6968{
6969  if (explain_p)
6970    inform (input_location,
6971	    "  variable-sized array type %qT is not "
6972	    "a valid template argument",
6973	    arg);
6974  return unify_invalid (explain_p);
6975}
6976
6977static int
6978unify_method_type_error (bool explain_p, tree arg)
6979{
6980  if (explain_p)
6981    inform (input_location,
6982	    "  member function type %qT is not a valid template argument",
6983	    arg);
6984  return unify_invalid (explain_p);
6985}
6986
6987static int
6988unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6989{
6990  if (explain_p)
6991    {
6992      if (least_p)
6993	inform_n (input_location, wanted,
6994		  "  candidate expects at least %d argument, %d provided",
6995		  "  candidate expects at least %d arguments, %d provided",
6996		  wanted, have);
6997      else
6998	inform_n (input_location, wanted,
6999		  "  candidate expects %d argument, %d provided",
7000		  "  candidate expects %d arguments, %d provided",
7001		  wanted, have);
7002    }
7003  return unify_invalid (explain_p);
7004}
7005
7006static int
7007unify_too_many_arguments (bool explain_p, int have, int wanted)
7008{
7009  return unify_arity (explain_p, have, wanted);
7010}
7011
7012static int
7013unify_too_few_arguments (bool explain_p, int have, int wanted,
7014			 bool least_p = false)
7015{
7016  return unify_arity (explain_p, have, wanted, least_p);
7017}
7018
7019static int
7020unify_arg_conversion (bool explain_p, tree to_type,
7021		      tree from_type, tree arg)
7022{
7023  if (explain_p)
7024    inform (cp_expr_loc_or_input_loc (arg),
7025	    "  cannot convert %qE (type %qT) to type %qT",
7026	    arg, from_type, to_type);
7027  return unify_invalid (explain_p);
7028}
7029
7030static int
7031unify_no_common_base (bool explain_p, enum template_base_result r,
7032		      tree parm, tree arg)
7033{
7034  if (explain_p)
7035    switch (r)
7036      {
7037      case tbr_ambiguous_baseclass:
7038	inform (input_location, "  %qT is an ambiguous base class of %qT",
7039		parm, arg);
7040	break;
7041      default:
7042	inform (input_location, "  %qT is not derived from %qT", arg, parm);
7043	break;
7044      }
7045  return unify_invalid (explain_p);
7046}
7047
7048static int
7049unify_inconsistent_template_template_parameters (bool explain_p)
7050{
7051  if (explain_p)
7052    inform (input_location,
7053	    "  template parameters of a template template argument are "
7054	    "inconsistent with other deduced template arguments");
7055  return unify_invalid (explain_p);
7056}
7057
7058static int
7059unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7060{
7061  if (explain_p)
7062    inform (input_location,
7063	    "  cannot deduce a template for %qT from non-template type %qT",
7064	    parm, arg);
7065  return unify_invalid (explain_p);
7066}
7067
7068static int
7069unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7070{
7071  if (explain_p)
7072    inform (input_location,
7073	    "  template argument %qE does not match %qE", arg, parm);
7074  return unify_invalid (explain_p);
7075}
7076
7077/* True if T is a C++20 template parameter object to store the argument for a
7078   template parameter of class type.  */
7079
7080bool
7081template_parm_object_p (const_tree t)
7082{
7083  return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
7084	  && startswith (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA"));
7085}
7086
7087/* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7088   argument for TYPE, points to an unsuitable object.
7089
7090   Also adjust the type of the index in C++20 array subobject references.  */
7091
7092static bool
7093invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7094{
7095  switch (TREE_CODE (expr))
7096    {
7097    CASE_CONVERT:
7098      return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7099				       complain);
7100
7101    case TARGET_EXPR:
7102      return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7103				       complain);
7104
7105    case CONSTRUCTOR:
7106      {
7107	for (auto &e: CONSTRUCTOR_ELTS (expr))
7108	  if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7109	    return true;
7110      }
7111      break;
7112
7113    case ADDR_EXPR:
7114      {
7115	tree decl = TREE_OPERAND (expr, 0);
7116
7117	if (cxx_dialect >= cxx20)
7118	  while (TREE_CODE (decl) == COMPONENT_REF
7119		 || TREE_CODE (decl) == ARRAY_REF)
7120	    {
7121	      tree &op = TREE_OPERAND (decl, 1);
7122	      if (TREE_CODE (decl) == ARRAY_REF
7123		  && TREE_CODE (op) == INTEGER_CST)
7124		/* Canonicalize array offsets to ptrdiff_t; how they were
7125		   written doesn't matter for subobject identity.  */
7126		op = fold_convert (ptrdiff_type_node, op);
7127	      decl = TREE_OPERAND (decl, 0);
7128	    }
7129
7130	if (!VAR_P (decl))
7131	  {
7132	    if (complain & tf_error)
7133	      error_at (cp_expr_loc_or_input_loc (expr),
7134			"%qE is not a valid template argument of type %qT "
7135			"because %qE is not a variable", expr, type, decl);
7136	    return true;
7137	  }
7138	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7139	  {
7140	    if (complain & tf_error)
7141	      error_at (cp_expr_loc_or_input_loc (expr),
7142			"%qE is not a valid template argument of type %qT "
7143			"in C++98 because %qD does not have external linkage",
7144			expr, type, decl);
7145	    return true;
7146	  }
7147	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7148		 && decl_linkage (decl) == lk_none)
7149	  {
7150	    if (complain & tf_error)
7151	      error_at (cp_expr_loc_or_input_loc (expr),
7152			"%qE is not a valid template argument of type %qT "
7153			"because %qD has no linkage", expr, type, decl);
7154	    return true;
7155	  }
7156	/* C++17: For a non-type template-parameter of reference or pointer
7157	   type, the value of the constant expression shall not refer to (or
7158	   for a pointer type, shall not be the address of):
7159	   * a subobject (4.5),
7160	   * a temporary object (15.2),
7161	   * a string literal (5.13.5),
7162	   * the result of a typeid expression (8.2.8), or
7163	   * a predefined __func__ variable (11.4.1).  */
7164	else if (DECL_ARTIFICIAL (decl))
7165	  {
7166	    if (complain & tf_error)
7167	      error ("the address of %qD is not a valid template argument",
7168		     decl);
7169	    return true;
7170	  }
7171	else if (cxx_dialect < cxx20
7172		 && !(same_type_ignoring_top_level_qualifiers_p
7173		      (strip_array_types (TREE_TYPE (type)),
7174		       strip_array_types (TREE_TYPE (decl)))))
7175	  {
7176	    if (complain & tf_error)
7177	      error ("the address of the %qT subobject of %qD is not a "
7178		     "valid template argument", TREE_TYPE (type), decl);
7179	    return true;
7180	  }
7181	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7182	  {
7183	    if (complain & tf_error)
7184	      error ("the address of %qD is not a valid template argument "
7185		     "because it does not have static storage duration",
7186		     decl);
7187	    return true;
7188	  }
7189      }
7190      break;
7191
7192    default:
7193      if (!INDIRECT_TYPE_P (type))
7194	/* We're only concerned about pointers and references here.  */;
7195      else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7196	/* Null pointer values are OK in C++11.  */;
7197      else
7198	{
7199	  if (VAR_P (expr))
7200	    {
7201	      if (complain & tf_error)
7202		error ("%qD is not a valid template argument "
7203		       "because %qD is a variable, not the address of "
7204		       "a variable", expr, expr);
7205	      return true;
7206	    }
7207	  else
7208	    {
7209	      if (complain & tf_error)
7210		error ("%qE is not a valid template argument for %qT "
7211		       "because it is not the address of a variable",
7212		       expr, type);
7213	      return true;
7214	    }
7215	}
7216    }
7217  return false;
7218
7219}
7220
7221/* The template arguments corresponding to template parameter objects of types
7222   that contain pointers to members.  */
7223
7224static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7225
7226/* Return a VAR_DECL for the C++20 template parameter object corresponding to
7227   template argument EXPR.  */
7228
7229static tree
7230get_template_parm_object (tree expr, tsubst_flags_t complain)
7231{
7232  if (TREE_CODE (expr) == TARGET_EXPR)
7233    expr = TARGET_EXPR_INITIAL (expr);
7234
7235  if (!TREE_CONSTANT (expr))
7236    {
7237      if ((complain & tf_error)
7238	  && require_rvalue_constant_expression (expr))
7239	cxx_constant_value (expr);
7240      return error_mark_node;
7241    }
7242  if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7243    return error_mark_node;
7244
7245  /* This is no longer a compound literal.  */
7246  gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7247
7248  tree name = mangle_template_parm_object (expr);
7249  tree decl = get_global_binding (name);
7250  if (decl)
7251    return decl;
7252
7253  tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7254  decl = create_temporary_var (type);
7255  DECL_CONTEXT (decl) = NULL_TREE;
7256  TREE_STATIC (decl) = true;
7257  DECL_DECLARED_CONSTEXPR_P (decl) = true;
7258  TREE_READONLY (decl) = true;
7259  DECL_NAME (decl) = name;
7260  SET_DECL_ASSEMBLER_NAME (decl, name);
7261  comdat_linkage (decl);
7262
7263  if (!zero_init_p (type))
7264    {
7265      /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7266	 lower_var_init before we're done mangling.  So store the original
7267	 value elsewhere.  */
7268      tree copy = unshare_constructor (expr);
7269      hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7270    }
7271
7272  pushdecl_top_level_and_finish (decl, expr);
7273
7274  return decl;
7275}
7276
7277/* Return the actual template argument corresponding to template parameter
7278   object VAR.  */
7279
7280tree
7281tparm_object_argument (tree var)
7282{
7283  if (zero_init_p (TREE_TYPE (var)))
7284    return DECL_INITIAL (var);
7285  return *(tparm_obj_values->get (var));
7286}
7287
7288/* Attempt to convert the non-type template parameter EXPR to the
7289   indicated TYPE.  If the conversion is successful, return the
7290   converted value.  If the conversion is unsuccessful, return
7291   NULL_TREE if we issued an error message, or error_mark_node if we
7292   did not.  We issue error messages for out-and-out bad template
7293   parameters, but not simply because the conversion failed, since we
7294   might be just trying to do argument deduction.  Both TYPE and EXPR
7295   must be non-dependent.
7296
7297   The conversion follows the special rules described in
7298   [temp.arg.nontype], and it is much more strict than an implicit
7299   conversion.
7300
7301   This function is called twice for each template argument (see
7302   lookup_template_class for a more accurate description of this
7303   problem). This means that we need to handle expressions which
7304   are not valid in a C++ source, but can be created from the
7305   first call (for instance, casts to perform conversions). These
7306   hacks can go away after we fix the double coercion problem.  */
7307
7308static tree
7309convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7310{
7311  tree expr_type;
7312  location_t loc = cp_expr_loc_or_input_loc (expr);
7313
7314  /* Detect immediately string literals as invalid non-type argument.
7315     This special-case is not needed for correctness (we would easily
7316     catch this later), but only to provide better diagnostic for this
7317     common user mistake. As suggested by DR 100, we do not mention
7318     linkage issues in the diagnostic as this is not the point.  */
7319  if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7320    {
7321      if (complain & tf_error)
7322	error ("%qE is not a valid template argument for type %qT "
7323	       "because string literals can never be used in this context",
7324	       expr, type);
7325      return NULL_TREE;
7326    }
7327
7328  /* Add the ADDR_EXPR now for the benefit of
7329     value_dependent_expression_p.  */
7330  if (TYPE_PTROBV_P (type)
7331      && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7332    {
7333      expr = decay_conversion (expr, complain);
7334      if (expr == error_mark_node)
7335	return error_mark_node;
7336    }
7337
7338  /* If we are in a template, EXPR may be non-dependent, but still
7339     have a syntactic, rather than semantic, form.  For example, EXPR
7340     might be a SCOPE_REF, rather than the VAR_DECL to which the
7341     SCOPE_REF refers.  Preserving the qualifying scope is necessary
7342     so that access checking can be performed when the template is
7343     instantiated -- but here we need the resolved form so that we can
7344     convert the argument.  */
7345  bool non_dep = false;
7346  if (TYPE_REF_OBJ_P (type)
7347      && has_value_dependent_address (expr))
7348    /* If we want the address and it's value-dependent, don't fold.  */;
7349  else if (processing_template_decl
7350	   && is_nondependent_constant_expression (expr))
7351    non_dep = true;
7352  if (error_operand_p (expr))
7353    return error_mark_node;
7354  expr_type = TREE_TYPE (expr);
7355
7356  /* If the argument is non-dependent, perform any conversions in
7357     non-dependent context as well.  */
7358  processing_template_decl_sentinel s (non_dep);
7359  if (non_dep)
7360    expr = instantiate_non_dependent_expr_internal (expr, complain);
7361
7362  bool val_dep_p = value_dependent_expression_p (expr);
7363  if (val_dep_p)
7364    expr = canonicalize_expr_argument (expr, complain);
7365  else
7366    STRIP_ANY_LOCATION_WRAPPER (expr);
7367
7368  /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7369     to a non-type argument of "nullptr".  */
7370  if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7371    expr = fold_simple (convert (type, expr));
7372
7373  /* In C++11, integral or enumeration non-type template arguments can be
7374     arbitrary constant expressions.  Pointer and pointer to
7375     member arguments can be general constant expressions that evaluate
7376     to a null value, but otherwise still need to be of a specific form.  */
7377  if (cxx_dialect >= cxx11)
7378    {
7379      if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7380	/* A PTRMEM_CST is already constant, and a valid template
7381	   argument for a parameter of pointer to member type, we just want
7382	   to leave it in that form rather than lower it to a
7383	   CONSTRUCTOR.  */;
7384      else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7385	       || cxx_dialect >= cxx17)
7386	{
7387	  /* C++17: A template-argument for a non-type template-parameter shall
7388	     be a converted constant expression (8.20) of the type of the
7389	     template-parameter.  */
7390	  expr = build_converted_constant_expr (type, expr, complain);
7391	  if (expr == error_mark_node)
7392	    /* Make sure we return NULL_TREE only if we have really issued
7393	       an error, as described above.  */
7394	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
7395	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7396	    {
7397	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7398	      return expr;
7399	    }
7400	  expr = maybe_constant_value (expr, NULL_TREE,
7401				       /*manifestly_const_eval=*/true);
7402	  expr = convert_from_reference (expr);
7403	  /* EXPR may have become value-dependent.  */
7404	  val_dep_p = value_dependent_expression_p (expr);
7405	}
7406      else if (TYPE_PTR_OR_PTRMEM_P (type))
7407	{
7408	  tree folded = maybe_constant_value (expr, NULL_TREE,
7409					      /*manifestly_const_eval=*/true);
7410	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
7411	      : null_member_pointer_value_p (folded))
7412	    expr = folded;
7413	}
7414    }
7415
7416  if (TYPE_REF_P (type))
7417    expr = mark_lvalue_use (expr);
7418  else
7419    expr = mark_rvalue_use (expr);
7420
7421  /* HACK: Due to double coercion, we can get a
7422     NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7423     which is the tree that we built on the first call (see
7424     below when coercing to reference to object or to reference to
7425     function). We just strip everything and get to the arg.
7426     See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7427     for examples.  */
7428  if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7429    {
7430      /* Check this before we strip *& to avoid redundancy.  */
7431      if (!mark_single_function (expr, complain))
7432	return error_mark_node;
7433
7434      tree probe_type, probe = expr;
7435      if (REFERENCE_REF_P (probe))
7436	probe = TREE_OPERAND (probe, 0);
7437      probe_type = TREE_TYPE (probe);
7438      if (TREE_CODE (probe) == NOP_EXPR)
7439	{
7440	  /* ??? Maybe we could use convert_from_reference here, but we
7441	     would need to relax its constraints because the NOP_EXPR
7442	     could actually change the type to something more cv-qualified,
7443	     and this is not folded by convert_from_reference.  */
7444	  tree addr = TREE_OPERAND (probe, 0);
7445	  if (TYPE_REF_P (probe_type)
7446	      && TREE_CODE (addr) == ADDR_EXPR
7447	      && TYPE_PTR_P (TREE_TYPE (addr))
7448	      && (same_type_ignoring_top_level_qualifiers_p
7449		  (TREE_TYPE (probe_type),
7450		   TREE_TYPE (TREE_TYPE (addr)))))
7451	    {
7452	      expr = TREE_OPERAND (addr, 0);
7453	      expr_type = TREE_TYPE (probe_type);
7454	    }
7455	}
7456    }
7457
7458  /* [temp.arg.nontype]/5, bullet 1
7459
7460     For a non-type template-parameter of integral or enumeration type,
7461     integral promotions (_conv.prom_) and integral conversions
7462     (_conv.integral_) are applied.  */
7463  if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7464      || TREE_CODE (type) == REAL_TYPE)
7465    {
7466      if (cxx_dialect < cxx11)
7467	{
7468	  tree t = build_converted_constant_expr (type, expr, complain);
7469	  t = maybe_constant_value (t);
7470	  if (t != error_mark_node)
7471	    expr = t;
7472	}
7473
7474      if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7475	return error_mark_node;
7476
7477      /* Notice that there are constant expressions like '4 % 0' which
7478	 do not fold into integer constants.  */
7479      if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7480	{
7481	  if (complain & tf_error)
7482	    {
7483	      int errs = errorcount, warns = warningcount + werrorcount;
7484	      if (!require_potential_constant_expression (expr))
7485		expr = error_mark_node;
7486	      else
7487		expr = cxx_constant_value (expr);
7488	      if (errorcount > errs || warningcount + werrorcount > warns)
7489		inform (loc, "in template argument for type %qT", type);
7490	      if (expr == error_mark_node)
7491		return NULL_TREE;
7492	      /* else cxx_constant_value complained but gave us
7493		 a real constant, so go ahead.  */
7494	      if (!CONSTANT_CLASS_P (expr))
7495		{
7496		  /* Some assemble time constant expressions like
7497		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7498		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7499		     as we can emit them into .rodata initializers of
7500		     variables, yet they can't fold into an INTEGER_CST at
7501		     compile time.  Refuse them here.  */
7502		  gcc_checking_assert (reduced_constant_expression_p (expr));
7503		  error_at (loc, "template argument %qE for type %qT not "
7504				 "a compile-time constant", expr, type);
7505		  return NULL_TREE;
7506		}
7507	    }
7508	  else
7509	    return NULL_TREE;
7510	}
7511
7512      /* Avoid typedef problems.  */
7513      if (TREE_TYPE (expr) != type)
7514	expr = fold_convert (type, expr);
7515    }
7516  /* [temp.arg.nontype]/5, bullet 2
7517
7518     For a non-type template-parameter of type pointer to object,
7519     qualification conversions (_conv.qual_) and the array-to-pointer
7520     conversion (_conv.array_) are applied.  */
7521  else if (TYPE_PTROBV_P (type))
7522    {
7523      tree decayed = expr;
7524
7525      /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7526	 decay_conversion or an explicit cast.  If it's a problematic cast,
7527	 we'll complain about it below.  */
7528      if (TREE_CODE (expr) == NOP_EXPR)
7529	{
7530	  tree probe = expr;
7531	  STRIP_NOPS (probe);
7532	  if (TREE_CODE (probe) == ADDR_EXPR
7533	      && TYPE_PTR_P (TREE_TYPE (probe)))
7534	    {
7535	      expr = probe;
7536	      expr_type = TREE_TYPE (expr);
7537	    }
7538	}
7539
7540      /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7541
7542	 A template-argument for a non-type, non-template template-parameter
7543	 shall be one of: [...]
7544
7545	 -- the name of a non-type template-parameter;
7546	 -- the address of an object or function with external linkage, [...]
7547	    expressed as "& id-expression" where the & is optional if the name
7548	    refers to a function or array, or if the corresponding
7549	    template-parameter is a reference.
7550
7551	Here, we do not care about functions, as they are invalid anyway
7552	for a parameter of type pointer-to-object.  */
7553
7554      if (val_dep_p)
7555	/* Non-type template parameters are OK.  */
7556	;
7557      else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7558	/* Null pointer values are OK in C++11.  */;
7559      else if (TREE_CODE (expr) != ADDR_EXPR
7560	       && !INDIRECT_TYPE_P (expr_type))
7561	/* Other values, like integer constants, might be valid
7562	   non-type arguments of some other type.  */
7563	return error_mark_node;
7564      else if (invalid_tparm_referent_p (type, expr, complain))
7565	return NULL_TREE;
7566
7567      expr = decayed;
7568
7569      expr = perform_qualification_conversions (type, expr);
7570      if (expr == error_mark_node)
7571	return error_mark_node;
7572    }
7573  /* [temp.arg.nontype]/5, bullet 3
7574
7575     For a non-type template-parameter of type reference to object, no
7576     conversions apply. The type referred to by the reference may be more
7577     cv-qualified than the (otherwise identical) type of the
7578     template-argument. The template-parameter is bound directly to the
7579     template-argument, which must be an lvalue.  */
7580  else if (TYPE_REF_OBJ_P (type))
7581    {
7582      if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7583						      expr_type))
7584	return error_mark_node;
7585
7586      if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7587	{
7588	  if (complain & tf_error)
7589	    error ("%qE is not a valid template argument for type %qT "
7590		   "because of conflicts in cv-qualification", expr, type);
7591	  return NULL_TREE;
7592	}
7593
7594      if (!lvalue_p (expr))
7595	{
7596	  if (complain & tf_error)
7597	    error ("%qE is not a valid template argument for type %qT "
7598		   "because it is not an lvalue", expr, type);
7599	  return NULL_TREE;
7600	}
7601
7602      /* [temp.arg.nontype]/1
7603
7604	 A template-argument for a non-type, non-template template-parameter
7605	 shall be one of: [...]
7606
7607	 -- the address of an object or function with external linkage.  */
7608      if (INDIRECT_REF_P (expr)
7609	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7610	{
7611	  expr = TREE_OPERAND (expr, 0);
7612	  if (DECL_P (expr))
7613	    {
7614	      if (complain & tf_error)
7615		error ("%q#D is not a valid template argument for type %qT "
7616		       "because a reference variable does not have a constant "
7617		       "address", expr, type);
7618	      return NULL_TREE;
7619	    }
7620	}
7621
7622      if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7623	/* OK, dependent reference.  We don't want to ask whether a DECL is
7624	   itself value-dependent, since what we want here is its address.  */;
7625      else
7626	{
7627	  expr = build_address (expr);
7628
7629	  if (invalid_tparm_referent_p (type, expr, complain))
7630	    return NULL_TREE;
7631	}
7632
7633      if (!same_type_p (type, TREE_TYPE (expr)))
7634	expr = build_nop (type, expr);
7635    }
7636  /* [temp.arg.nontype]/5, bullet 4
7637
7638     For a non-type template-parameter of type pointer to function, only
7639     the function-to-pointer conversion (_conv.func_) is applied. If the
7640     template-argument represents a set of overloaded functions (or a
7641     pointer to such), the matching function is selected from the set
7642     (_over.over_).  */
7643  else if (TYPE_PTRFN_P (type))
7644    {
7645      /* If the argument is a template-id, we might not have enough
7646	 context information to decay the pointer.  */
7647      if (!type_unknown_p (expr_type))
7648	{
7649	  expr = decay_conversion (expr, complain);
7650	  if (expr == error_mark_node)
7651	    return error_mark_node;
7652	}
7653
7654      if (cxx_dialect >= cxx11 && integer_zerop (expr))
7655	/* Null pointer values are OK in C++11.  */
7656	return perform_qualification_conversions (type, expr);
7657
7658      expr = convert_nontype_argument_function (type, expr, complain);
7659      if (!expr || expr == error_mark_node)
7660	return expr;
7661    }
7662  /* [temp.arg.nontype]/5, bullet 5
7663
7664     For a non-type template-parameter of type reference to function, no
7665     conversions apply. If the template-argument represents a set of
7666     overloaded functions, the matching function is selected from the set
7667     (_over.over_).  */
7668  else if (TYPE_REFFN_P (type))
7669    {
7670      if (TREE_CODE (expr) == ADDR_EXPR)
7671	{
7672	  if (complain & tf_error)
7673	    {
7674	      error ("%qE is not a valid template argument for type %qT "
7675		     "because it is a pointer", expr, type);
7676	      inform (input_location, "try using %qE instead",
7677		      TREE_OPERAND (expr, 0));
7678	    }
7679	  return NULL_TREE;
7680	}
7681
7682      expr = convert_nontype_argument_function (type, expr, complain);
7683      if (!expr || expr == error_mark_node)
7684	return expr;
7685    }
7686  /* [temp.arg.nontype]/5, bullet 6
7687
7688     For a non-type template-parameter of type pointer to member function,
7689     no conversions apply. If the template-argument represents a set of
7690     overloaded member functions, the matching member function is selected
7691     from the set (_over.over_).  */
7692  else if (TYPE_PTRMEMFUNC_P (type))
7693    {
7694      expr = instantiate_type (type, expr, tf_none);
7695      if (expr == error_mark_node)
7696	return error_mark_node;
7697
7698      /* [temp.arg.nontype] bullet 1 says the pointer to member
7699         expression must be a pointer-to-member constant.  */
7700      if (!val_dep_p
7701	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7702	return NULL_TREE;
7703
7704      /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7705	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7706      if (fnptr_conv_p (type, TREE_TYPE (expr)))
7707	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7708    }
7709  /* [temp.arg.nontype]/5, bullet 7
7710
7711     For a non-type template-parameter of type pointer to data member,
7712     qualification conversions (_conv.qual_) are applied.  */
7713  else if (TYPE_PTRDATAMEM_P (type))
7714    {
7715      /* [temp.arg.nontype] bullet 1 says the pointer to member
7716         expression must be a pointer-to-member constant.  */
7717      if (!val_dep_p
7718	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7719	return NULL_TREE;
7720
7721      expr = perform_qualification_conversions (type, expr);
7722      if (expr == error_mark_node)
7723	return expr;
7724    }
7725  else if (NULLPTR_TYPE_P (type))
7726    {
7727      if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7728	{
7729	  if (complain & tf_error)
7730	    error ("%qE is not a valid template argument for type %qT "
7731		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7732	  return NULL_TREE;
7733	}
7734      return expr;
7735    }
7736  else if (CLASS_TYPE_P (type))
7737    {
7738      /* Replace the argument with a reference to the corresponding template
7739	 parameter object.  */
7740      if (!val_dep_p)
7741	expr = get_template_parm_object (expr, complain);
7742      if (expr == error_mark_node)
7743	return NULL_TREE;
7744    }
7745  /* A template non-type parameter must be one of the above.  */
7746  else
7747    gcc_unreachable ();
7748
7749  /* Sanity check: did we actually convert the argument to the
7750     right type?  */
7751  gcc_assert (same_type_ignoring_top_level_qualifiers_p
7752	      (type, TREE_TYPE (expr)));
7753  return convert_from_reference (expr);
7754}
7755
7756/* Subroutine of coerce_template_template_parms, which returns 1 if
7757   PARM_PARM and ARG_PARM match using the rule for the template
7758   parameters of template template parameters. Both PARM and ARG are
7759   template parameters; the rest of the arguments are the same as for
7760   coerce_template_template_parms.
7761 */
7762static int
7763coerce_template_template_parm (tree parm,
7764                              tree arg,
7765                              tsubst_flags_t complain,
7766                              tree in_decl,
7767                              tree outer_args)
7768{
7769  if (arg == NULL_TREE || error_operand_p (arg)
7770      || parm == NULL_TREE || error_operand_p (parm))
7771    return 0;
7772
7773  if (TREE_CODE (arg) != TREE_CODE (parm))
7774    return 0;
7775
7776  switch (TREE_CODE (parm))
7777    {
7778    case TEMPLATE_DECL:
7779      /* We encounter instantiations of templates like
7780	 template <template <template <class> class> class TT>
7781	 class C;  */
7782      {
7783	tree parmparm = DECL_TEMPLATE_PARMS (parm);
7784	tree argparm = DECL_TEMPLATE_PARMS (arg);
7785
7786	if (!coerce_template_template_parms
7787	    (parmparm, argparm, complain, in_decl, outer_args))
7788	  return 0;
7789      }
7790      /* Fall through.  */
7791
7792    case TYPE_DECL:
7793      if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7794	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7795	/* Argument is a parameter pack but parameter is not.  */
7796	return 0;
7797      break;
7798
7799    case PARM_DECL:
7800      /* The tsubst call is used to handle cases such as
7801
7802           template <int> class C {};
7803	   template <class T, template <T> class TT> class D {};
7804	   D<int, C> d;
7805
7806	 i.e. the parameter list of TT depends on earlier parameters.  */
7807      if (!uses_template_parms (TREE_TYPE (arg)))
7808	{
7809	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7810	  if (!uses_template_parms (t)
7811	      && !same_type_p (t, TREE_TYPE (arg)))
7812	    return 0;
7813	}
7814
7815      if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7816	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7817	/* Argument is a parameter pack but parameter is not.  */
7818	return 0;
7819
7820      break;
7821
7822    default:
7823      gcc_unreachable ();
7824    }
7825
7826  return 1;
7827}
7828
7829/* Coerce template argument list ARGLIST for use with template
7830   template-parameter TEMPL.  */
7831
7832static tree
7833coerce_template_args_for_ttp (tree templ, tree arglist,
7834			      tsubst_flags_t complain)
7835{
7836  /* Consider an example where a template template parameter declared as
7837
7838     template <class T, class U = std::allocator<T> > class TT
7839
7840     The template parameter level of T and U are one level larger than
7841     of TT.  To proper process the default argument of U, say when an
7842     instantiation `TT<int>' is seen, we need to build the full
7843     arguments containing {int} as the innermost level.  Outer levels,
7844     available when not appearing as default template argument, can be
7845     obtained from the arguments of the enclosing template.
7846
7847     Suppose that TT is later substituted with std::vector.  The above
7848     instantiation is `TT<int, std::allocator<T> >' with TT at
7849     level 1, and T at level 2, while the template arguments at level 1
7850     becomes {std::vector} and the inner level 2 is {int}.  */
7851
7852  tree outer = DECL_CONTEXT (templ);
7853  if (outer)
7854    outer = generic_targs_for (outer);
7855  else if (current_template_parms)
7856    {
7857      /* This is an argument of the current template, so we haven't set
7858	 DECL_CONTEXT yet.  */
7859      tree relevant_template_parms;
7860
7861      /* Parameter levels that are greater than the level of the given
7862	 template template parm are irrelevant.  */
7863      relevant_template_parms = current_template_parms;
7864      while (TMPL_PARMS_DEPTH (relevant_template_parms)
7865	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7866	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7867
7868      outer = template_parms_to_args (relevant_template_parms);
7869    }
7870
7871  if (outer)
7872    arglist = add_to_template_args (outer, arglist);
7873
7874  tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7875  return coerce_template_parms (parmlist, arglist, templ,
7876				complain,
7877				/*require_all_args=*/true,
7878				/*use_default_args=*/true);
7879}
7880
7881/* A cache of template template parameters with match-all default
7882   arguments.  */
7883static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7884
7885/* T is a bound template template-parameter.  Copy its arguments into default
7886   arguments of the template template-parameter's template parameters.  */
7887
7888static tree
7889add_defaults_to_ttp (tree otmpl)
7890{
7891  if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7892    return *c;
7893
7894  tree ntmpl = copy_node (otmpl);
7895
7896  tree ntype = copy_node (TREE_TYPE (otmpl));
7897  TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7898  TYPE_MAIN_VARIANT (ntype) = ntype;
7899  TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7900  TYPE_NAME (ntype) = ntmpl;
7901  SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7902
7903  tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7904    = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7905  TEMPLATE_PARM_DECL (idx) = ntmpl;
7906  TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7907
7908  tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7909  tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7910  TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7911  tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7912  for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7913    {
7914      tree o = TREE_VEC_ELT (vec, i);
7915      if (!template_parameter_pack_p (TREE_VALUE (o)))
7916	{
7917	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7918	  TREE_PURPOSE (n) = any_targ_node;
7919	}
7920    }
7921
7922  hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7923  return ntmpl;
7924}
7925
7926/* ARG is a bound potential template template-argument, and PARGS is a list
7927   of arguments for the corresponding template template-parameter.  Adjust
7928   PARGS as appropriate for application to ARG's template, and if ARG is a
7929   BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7930   arguments to the template template parameter.  */
7931
7932static tree
7933coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7934{
7935  ++processing_template_decl;
7936  tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7937  if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7938    {
7939      /* When comparing two template template-parameters in partial ordering,
7940	 rewrite the one currently being used as an argument to have default
7941	 arguments for all parameters.  */
7942      arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7943      pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7944      if (pargs != error_mark_node)
7945	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7946					   TYPE_TI_ARGS (arg));
7947    }
7948  else
7949    {
7950      tree aparms
7951	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7952      pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7953				       /*require_all*/true,
7954				       /*use_default*/true);
7955    }
7956  --processing_template_decl;
7957  return pargs;
7958}
7959
7960/* Subroutine of unify for the case when PARM is a
7961   BOUND_TEMPLATE_TEMPLATE_PARM.  */
7962
7963static int
7964unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7965		      bool explain_p)
7966{
7967  tree parmvec = TYPE_TI_ARGS (parm);
7968  tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7969
7970  /* The template template parm might be variadic and the argument
7971     not, so flatten both argument lists.  */
7972  parmvec = expand_template_argument_pack (parmvec);
7973  argvec = expand_template_argument_pack (argvec);
7974
7975  if (flag_new_ttp)
7976    {
7977      /* In keeping with P0522R0, adjust P's template arguments
7978	 to apply to A's template; then flatten it again.  */
7979      tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7980      nparmvec = expand_template_argument_pack (nparmvec);
7981
7982      if (unify (tparms, targs, nparmvec, argvec,
7983		 UNIFY_ALLOW_NONE, explain_p))
7984	return 1;
7985
7986      /* If the P0522 adjustment eliminated a pack expansion, deduce
7987	 empty packs.  */
7988      if (flag_new_ttp
7989	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7990	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7991				   DEDUCE_EXACT, /*sub*/true, explain_p))
7992	return 1;
7993    }
7994  else
7995    {
7996      /* Deduce arguments T, i from TT<T> or TT<i>.
7997	 We check each element of PARMVEC and ARGVEC individually
7998	 rather than the whole TREE_VEC since they can have
7999	 different number of elements, which is allowed under N2555.  */
8000
8001      int len = TREE_VEC_LENGTH (parmvec);
8002
8003      /* Check if the parameters end in a pack, making them
8004	 variadic.  */
8005      int parm_variadic_p = 0;
8006      if (len > 0
8007	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8008	parm_variadic_p = 1;
8009
8010      for (int i = 0; i < len - parm_variadic_p; ++i)
8011	/* If the template argument list of P contains a pack
8012	   expansion that is not the last template argument, the
8013	   entire template argument list is a non-deduced
8014	   context.  */
8015	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8016	  return unify_success (explain_p);
8017
8018      if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8019	return unify_too_few_arguments (explain_p,
8020					TREE_VEC_LENGTH (argvec), len);
8021
8022      for (int i = 0; i < len - parm_variadic_p; ++i)
8023	if (unify (tparms, targs,
8024		   TREE_VEC_ELT (parmvec, i),
8025		   TREE_VEC_ELT (argvec, i),
8026		   UNIFY_ALLOW_NONE, explain_p))
8027	  return 1;
8028
8029      if (parm_variadic_p
8030	  && unify_pack_expansion (tparms, targs,
8031				   parmvec, argvec,
8032				   DEDUCE_EXACT,
8033				   /*subr=*/true, explain_p))
8034	return 1;
8035    }
8036
8037  return 0;
8038}
8039
8040/* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
8041   template template parameters.  Both PARM_PARMS and ARG_PARMS are
8042   vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
8043   or PARM_DECL.
8044
8045   Consider the example:
8046     template <class T> class A;
8047     template<template <class U> class TT> class B;
8048
8049   For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
8050   the parameters to A, and OUTER_ARGS contains A.  */
8051
8052static int
8053coerce_template_template_parms (tree parm_parms_full,
8054				tree arg_parms_full,
8055				tsubst_flags_t complain,
8056				tree in_decl,
8057				tree outer_args)
8058{
8059  int nparms, nargs, i;
8060  tree parm, arg;
8061  int variadic_p = 0;
8062
8063  tree parm_parms = INNERMOST_TEMPLATE_PARMS (parm_parms_full);
8064  tree arg_parms = INNERMOST_TEMPLATE_PARMS (arg_parms_full);
8065
8066  gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
8067  gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
8068
8069  nparms = TREE_VEC_LENGTH (parm_parms);
8070  nargs = TREE_VEC_LENGTH (arg_parms);
8071
8072  if (flag_new_ttp)
8073    {
8074      /* P0522R0: A template template-parameter P is at least as specialized as
8075	 a template template-argument A if, given the following rewrite to two
8076	 function templates, the function template corresponding to P is at
8077	 least as specialized as the function template corresponding to A
8078	 according to the partial ordering rules for function templates
8079	 ([temp.func.order]). Given an invented class template X with the
8080	 template parameter list of A (including default arguments):
8081
8082	 * Each of the two function templates has the same template parameters,
8083	 respectively, as P or A.
8084
8085	 * Each function template has a single function parameter whose type is
8086	 a specialization of X with template arguments corresponding to the
8087	 template parameters from the respective function template where, for
8088	 each template parameter PP in the template parameter list of the
8089	 function template, a corresponding template argument AA is formed. If
8090	 PP declares a parameter pack, then AA is the pack expansion
8091	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8092
8093	 If the rewrite produces an invalid type, then P is not at least as
8094	 specialized as A.  */
8095
8096      /* So coerce P's args to apply to A's parms, and then deduce between A's
8097	 args and the converted args.  If that succeeds, A is at least as
8098	 specialized as P, so they match.*/
8099      processing_template_decl_sentinel ptds (/*reset*/false);
8100      ++processing_template_decl;
8101
8102      tree pargs = template_parms_level_to_args (parm_parms);
8103
8104      /* PARM, and thus the context in which we are passing ARG to it, may be
8105	 at a deeper level than ARG; when trying to coerce to ARG_PARMS, we
8106	 want to provide the right number of levels, so we reduce the number of
8107	 levels in OUTER_ARGS before prepending them.  This is most important
8108	 when ARG is a namespace-scope template, as in alias-decl-ttp2.C.
8109
8110	 ARG might also be deeper than PARM (ttp23).  In that case, we include
8111	 all of OUTER_ARGS.  The missing levels seem potentially problematic,
8112	 but I can't come up with a testcase that breaks.  */
8113      if (int arg_outer_levs = TMPL_PARMS_DEPTH (arg_parms_full) - 1)
8114	{
8115	  auto x = make_temp_override (TREE_VEC_LENGTH (outer_args));
8116	  if (TMPL_ARGS_DEPTH (outer_args) > arg_outer_levs)
8117	    TREE_VEC_LENGTH (outer_args) = arg_outer_levs;
8118	  pargs = add_to_template_args (outer_args, pargs);
8119	}
8120
8121      pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
8122				     /*require_all*/true, /*use_default*/true);
8123      if (pargs != error_mark_node)
8124	{
8125	  tree targs = make_tree_vec (nargs);
8126	  tree aargs = template_parms_level_to_args (arg_parms);
8127	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8128		      /*explain*/false))
8129	    return 1;
8130	}
8131    }
8132
8133  /* Determine whether we have a parameter pack at the end of the
8134     template template parameter's template parameter list.  */
8135  if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8136    {
8137      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8138
8139      if (error_operand_p (parm))
8140	return 0;
8141
8142      switch (TREE_CODE (parm))
8143        {
8144        case TEMPLATE_DECL:
8145        case TYPE_DECL:
8146          if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8147            variadic_p = 1;
8148          break;
8149
8150        case PARM_DECL:
8151          if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8152            variadic_p = 1;
8153          break;
8154
8155        default:
8156          gcc_unreachable ();
8157        }
8158    }
8159
8160  if (nargs != nparms
8161      && !(variadic_p && nargs >= nparms - 1))
8162    return 0;
8163
8164  /* Check all of the template parameters except the parameter pack at
8165     the end (if any).  */
8166  for (i = 0; i < nparms - variadic_p; ++i)
8167    {
8168      if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8169          || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8170        continue;
8171
8172      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8173      arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8174
8175      if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8176                                          outer_args))
8177	return 0;
8178
8179    }
8180
8181  if (variadic_p)
8182    {
8183      /* Check each of the template parameters in the template
8184	 argument against the template parameter pack at the end of
8185	 the template template parameter.  */
8186      if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8187	return 0;
8188
8189      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8190
8191      for (; i < nargs; ++i)
8192        {
8193          if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8194            continue;
8195
8196          arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8197
8198          if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8199                                              outer_args))
8200            return 0;
8201        }
8202    }
8203
8204  return 1;
8205}
8206
8207/* Verifies that the deduced template arguments (in TARGS) for the
8208   template template parameters (in TPARMS) represent valid bindings,
8209   by comparing the template parameter list of each template argument
8210   to the template parameter list of its corresponding template
8211   template parameter, in accordance with DR150. This
8212   routine can only be called after all template arguments have been
8213   deduced. It will return TRUE if all of the template template
8214   parameter bindings are okay, FALSE otherwise.  */
8215bool
8216template_template_parm_bindings_ok_p (tree tparms, tree targs)
8217{
8218  int i, ntparms = TREE_VEC_LENGTH (tparms);
8219  bool ret = true;
8220
8221  /* We're dealing with template parms in this process.  */
8222  ++processing_template_decl;
8223
8224  targs = INNERMOST_TEMPLATE_ARGS (targs);
8225
8226  for (i = 0; i < ntparms; ++i)
8227    {
8228      tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8229      tree targ = TREE_VEC_ELT (targs, i);
8230
8231      if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8232	{
8233	  tree packed_args = NULL_TREE;
8234	  int idx, len = 1;
8235
8236	  if (ARGUMENT_PACK_P (targ))
8237	    {
8238	      /* Look inside the argument pack.  */
8239	      packed_args = ARGUMENT_PACK_ARGS (targ);
8240	      len = TREE_VEC_LENGTH (packed_args);
8241	    }
8242
8243	  for (idx = 0; idx < len; ++idx)
8244	    {
8245	      tree targ_parms = NULL_TREE;
8246
8247	      if (packed_args)
8248		/* Extract the next argument from the argument
8249		   pack.  */
8250		targ = TREE_VEC_ELT (packed_args, idx);
8251
8252	      if (PACK_EXPANSION_P (targ))
8253		/* Look at the pattern of the pack expansion.  */
8254		targ = PACK_EXPANSION_PATTERN (targ);
8255
8256	      /* Extract the template parameters from the template
8257		 argument.  */
8258	      if (TREE_CODE (targ) == TEMPLATE_DECL)
8259		targ_parms = DECL_TEMPLATE_PARMS (targ);
8260	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8261		targ_parms = DECL_TEMPLATE_PARMS (TYPE_NAME (targ));
8262
8263	      /* Verify that we can coerce the template template
8264		 parameters from the template argument to the template
8265		 parameter.  This requires an exact match.  */
8266	      if (targ_parms
8267		  && !coerce_template_template_parms
8268		       (DECL_TEMPLATE_PARMS (tparm),
8269			targ_parms,
8270			tf_none,
8271			tparm,
8272			targs))
8273		{
8274		  ret = false;
8275		  goto out;
8276		}
8277	    }
8278	}
8279    }
8280
8281 out:
8282
8283  --processing_template_decl;
8284  return ret;
8285}
8286
8287/* Since type attributes aren't mangled, we need to strip them from
8288   template type arguments.  */
8289
8290tree
8291canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8292{
8293  if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8294    return arg;
8295  bool removed_attributes = false;
8296  tree canon = strip_typedefs (arg, &removed_attributes);
8297  if (removed_attributes
8298      && (complain & tf_warning))
8299    warning (OPT_Wignored_attributes,
8300	     "ignoring attributes on template argument %qT", arg);
8301  return canon;
8302}
8303
8304/* And from inside dependent non-type arguments like sizeof(Type).  */
8305
8306static tree
8307canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8308{
8309  if (!arg || arg == error_mark_node)
8310    return arg;
8311  bool removed_attributes = false;
8312  tree canon = strip_typedefs_expr (arg, &removed_attributes);
8313  if (removed_attributes
8314      && (complain & tf_warning))
8315    warning (OPT_Wignored_attributes,
8316	     "ignoring attributes in template argument %qE", arg);
8317  return canon;
8318}
8319
8320/* A template declaration can be substituted for a constrained
8321   template template parameter only when the argument is no more
8322   constrained than the parameter.  */
8323
8324static bool
8325is_compatible_template_arg (tree parm, tree arg)
8326{
8327  tree parm_cons = get_constraints (parm);
8328
8329  /* For now, allow constrained template template arguments
8330     and unconstrained template template parameters.  */
8331  if (parm_cons == NULL_TREE)
8332    return true;
8333
8334  /* If the template parameter is constrained, we need to rewrite its
8335     constraints in terms of the ARG's template parameters. This ensures
8336     that all of the template parameter types will have the same depth.
8337
8338     Note that this is only valid when coerce_template_template_parm is
8339     true for the innermost template parameters of PARM and ARG. In other
8340     words, because coercion is successful, this conversion will be valid.  */
8341  tree new_args = NULL_TREE;
8342  if (parm_cons)
8343    {
8344      tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8345      new_args = template_parms_level_to_args (aparms);
8346      ++processing_template_decl;
8347      parm_cons = tsubst_constraint_info (parm_cons, new_args,
8348					  tf_none, NULL_TREE);
8349      --processing_template_decl;
8350      if (parm_cons == error_mark_node)
8351        return false;
8352    }
8353
8354  return weakly_subsumes (parm_cons, arg);
8355}
8356
8357// Convert a placeholder argument into a binding to the original
8358// parameter. The original parameter is saved as the TREE_TYPE of
8359// ARG.
8360static inline tree
8361convert_wildcard_argument (tree parm, tree arg)
8362{
8363  TREE_TYPE (arg) = parm;
8364  return arg;
8365}
8366
8367/* We can't fully resolve ARG given as a non-type template argument to TYPE,
8368   because one of them is dependent.  But we need to represent the
8369   conversion for the benefit of cp_tree_equal.  */
8370
8371static tree
8372maybe_convert_nontype_argument (tree type, tree arg)
8373{
8374  /* Auto parms get no conversion.  */
8375  if (type_uses_auto (type))
8376    return arg;
8377  /* We don't need or want to add this conversion now if we're going to use the
8378     argument for deduction.  */
8379  if (value_dependent_expression_p (arg))
8380    return arg;
8381
8382  type = cv_unqualified (type);
8383  tree argtype = TREE_TYPE (arg);
8384  if (same_type_p (type, argtype))
8385    return arg;
8386
8387  arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8388  IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8389  return arg;
8390}
8391
8392/* Convert the indicated template ARG as necessary to match the
8393   indicated template PARM.  Returns the converted ARG, or
8394   error_mark_node if the conversion was unsuccessful.  Error and
8395   warning messages are issued under control of COMPLAIN.  This
8396   conversion is for the Ith parameter in the parameter list.  ARGS is
8397   the full set of template arguments deduced so far.  */
8398
8399static tree
8400convert_template_argument (tree parm,
8401			   tree arg,
8402			   tree args,
8403			   tsubst_flags_t complain,
8404			   int i,
8405			   tree in_decl)
8406{
8407  tree orig_arg;
8408  tree val;
8409  int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8410
8411  if (parm == error_mark_node || error_operand_p (arg))
8412    return error_mark_node;
8413
8414  /* Trivially convert placeholders. */
8415  if (TREE_CODE (arg) == WILDCARD_DECL)
8416    return convert_wildcard_argument (parm, arg);
8417
8418  if (arg == any_targ_node)
8419    return arg;
8420
8421  if (TREE_CODE (arg) == TREE_LIST
8422      && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8423    {
8424      /* The template argument was the name of some
8425	 member function.  That's usually
8426	 invalid, but static members are OK.  In any
8427	 case, grab the underlying fields/functions
8428	 and issue an error later if required.  */
8429      TREE_TYPE (arg) = unknown_type_node;
8430    }
8431
8432  orig_arg = arg;
8433
8434  requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8435  requires_type = (TREE_CODE (parm) == TYPE_DECL
8436		   || requires_tmpl_type);
8437
8438  /* When determining whether an argument pack expansion is a template,
8439     look at the pattern.  */
8440  if (PACK_EXPANSION_P (arg))
8441    arg = PACK_EXPANSION_PATTERN (arg);
8442
8443  /* Deal with an injected-class-name used as a template template arg.  */
8444  if (requires_tmpl_type && CLASS_TYPE_P (arg))
8445    {
8446      tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8447      if (TREE_CODE (t) == TEMPLATE_DECL)
8448	{
8449	  if (cxx_dialect >= cxx11)
8450	    /* OK under DR 1004.  */;
8451	  else if (complain & tf_warning_or_error)
8452	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8453		     " used as template template argument", TYPE_NAME (arg));
8454	  else if (flag_pedantic_errors)
8455	    t = arg;
8456
8457	  arg = t;
8458	}
8459    }
8460
8461  is_tmpl_type =
8462    ((TREE_CODE (arg) == TEMPLATE_DECL
8463      && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8464     || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8465     || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8466     || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8467
8468  if (is_tmpl_type
8469      && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8470	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8471    arg = TYPE_STUB_DECL (arg);
8472
8473  is_type = TYPE_P (arg) || is_tmpl_type;
8474
8475  if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8476      && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8477    {
8478      if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8479	{
8480	  if (complain & tf_error)
8481	    error ("invalid use of destructor %qE as a type", orig_arg);
8482	  return error_mark_node;
8483	}
8484
8485      permerror (input_location,
8486		 "to refer to a type member of a template parameter, "
8487		 "use %<typename %E%>", orig_arg);
8488
8489      orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8490				     TREE_OPERAND (arg, 1),
8491				     typename_type,
8492				     complain);
8493      arg = orig_arg;
8494      is_type = 1;
8495    }
8496  if (is_type != requires_type)
8497    {
8498      if (in_decl)
8499	{
8500	  if (complain & tf_error)
8501	    {
8502	      error ("type/value mismatch at argument %d in template "
8503		     "parameter list for %qD",
8504		     i + 1, in_decl);
8505	      if (is_type)
8506		{
8507		  /* The template argument is a type, but we're expecting
8508		     an expression.  */
8509		  inform (input_location,
8510			  "  expected a constant of type %qT, got %qT",
8511			  TREE_TYPE (parm),
8512			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8513		  /* [temp.arg]/2: "In a template-argument, an ambiguity
8514		     between a type-id and an expression is resolved to a
8515		     type-id, regardless of the form of the corresponding
8516		     template-parameter."  So give the user a clue.  */
8517		  if (TREE_CODE (arg) == FUNCTION_TYPE)
8518		    inform (input_location, "  ambiguous template argument "
8519			    "for non-type template parameter is treated as "
8520			    "function type");
8521		}
8522	      else if (requires_tmpl_type)
8523		inform (input_location,
8524			"  expected a class template, got %qE", orig_arg);
8525	      else
8526		inform (input_location,
8527			"  expected a type, got %qE", orig_arg);
8528	    }
8529	}
8530      return error_mark_node;
8531    }
8532  if (is_tmpl_type ^ requires_tmpl_type)
8533    {
8534      if (in_decl && (complain & tf_error))
8535	{
8536	  error ("type/value mismatch at argument %d in template "
8537		 "parameter list for %qD",
8538		 i + 1, in_decl);
8539	  if (is_tmpl_type)
8540	    inform (input_location,
8541		    "  expected a type, got %qT", DECL_NAME (arg));
8542	  else
8543	    inform (input_location,
8544		    "  expected a class template, got %qT", orig_arg);
8545	}
8546      return error_mark_node;
8547    }
8548
8549  if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8550    /* We already did the appropriate conversion when packing args.  */
8551    val = orig_arg;
8552  else if (is_type)
8553    {
8554      if (requires_tmpl_type)
8555	{
8556	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8557	    /* The number of argument required is not known yet.
8558	       Just accept it for now.  */
8559	    val = orig_arg;
8560	  else
8561	    {
8562	      tree parmparm = DECL_TEMPLATE_PARMS (parm);
8563	      tree argparm;
8564
8565	      /* Strip alias templates that are equivalent to another
8566		 template.  */
8567	      arg = get_underlying_template (arg);
8568	      argparm = DECL_TEMPLATE_PARMS (arg);
8569
8570	      if (coerce_template_template_parms (parmparm, argparm,
8571						  complain, in_decl,
8572						  args))
8573		{
8574		  val = arg;
8575
8576		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8577		     TEMPLATE_DECL.  */
8578		  if (val != error_mark_node)
8579                    {
8580                      if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8581                        val = TREE_TYPE (val);
8582		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8583			val = make_pack_expansion (val, complain);
8584                    }
8585		}
8586	      else
8587		{
8588		  if (in_decl && (complain & tf_error))
8589		    {
8590		      error ("type/value mismatch at argument %d in "
8591			     "template parameter list for %qD",
8592			     i + 1, in_decl);
8593		      inform (input_location,
8594			      "  expected a template of type %qD, got %qT",
8595			      parm, orig_arg);
8596		    }
8597
8598		  val = error_mark_node;
8599		}
8600
8601              // Check that the constraints are compatible before allowing the
8602              // substitution.
8603              if (val != error_mark_node)
8604                if (!is_compatible_template_arg (parm, arg))
8605                  {
8606		    if (in_decl && (complain & tf_error))
8607                      {
8608                        error ("constraint mismatch at argument %d in "
8609                               "template parameter list for %qD",
8610                               i + 1, in_decl);
8611                        inform (input_location, "  expected %qD but got %qD",
8612                                parm, arg);
8613                      }
8614		    val = error_mark_node;
8615                  }
8616	    }
8617	}
8618      else
8619	val = orig_arg;
8620      /* We only form one instance of each template specialization.
8621	 Therefore, if we use a non-canonical variant (i.e., a
8622	 typedef), any future messages referring to the type will use
8623	 the typedef, which is confusing if those future uses do not
8624	 themselves also use the typedef.  */
8625      if (TYPE_P (val))
8626	val = canonicalize_type_argument (val, complain);
8627    }
8628  else
8629    {
8630      tree t = TREE_TYPE (parm);
8631
8632      if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8633	  > TMPL_ARGS_DEPTH (args))
8634	/* We don't have enough levels of args to do any substitution.  This
8635	   can happen in the context of -fnew-ttp-matching.  */;
8636      else if (tree a = type_uses_auto (t))
8637	{
8638	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8639				 LOOKUP_IMPLICIT);
8640	  if (t == error_mark_node)
8641	    return error_mark_node;
8642	}
8643      else
8644	t = tsubst (t, args, complain, in_decl);
8645
8646      /* Perform array-to-pointer and function-to-pointer conversion
8647	 as per [temp.param]/10.  */
8648      t = type_decays_to (t);
8649
8650      if (invalid_nontype_parm_type_p (t, complain))
8651	return error_mark_node;
8652
8653      /* Drop top-level cv-qualifiers on the substituted/deduced type of
8654	 this non-type template parameter, as per [temp.param]/6.  */
8655      t = cv_unqualified (t);
8656
8657      if (t != TREE_TYPE (parm))
8658	t = canonicalize_type_argument (t, complain);
8659
8660      if (!type_dependent_expression_p (orig_arg)
8661	  && !uses_template_parms (t))
8662	/* We used to call digest_init here.  However, digest_init
8663	   will report errors, which we don't want when complain
8664	   is zero.  More importantly, digest_init will try too
8665	   hard to convert things: for example, `0' should not be
8666	   converted to pointer type at this point according to
8667	   the standard.  Accepting this is not merely an
8668	   extension, since deciding whether or not these
8669	   conversions can occur is part of determining which
8670	   function template to call, or whether a given explicit
8671	   argument specification is valid.  */
8672	val = convert_nontype_argument (t, orig_arg, complain);
8673      else
8674	{
8675	  val = canonicalize_expr_argument (orig_arg, complain);
8676	  val = maybe_convert_nontype_argument (t, val);
8677	}
8678
8679
8680      if (val == NULL_TREE)
8681	val = error_mark_node;
8682      else if (val == error_mark_node && (complain & tf_error))
8683	error_at (cp_expr_loc_or_input_loc (orig_arg),
8684		  "could not convert template argument %qE from %qT to %qT",
8685		  orig_arg, TREE_TYPE (orig_arg), t);
8686
8687      if (INDIRECT_REF_P (val))
8688        {
8689          /* Reject template arguments that are references to built-in
8690             functions with no library fallbacks.  */
8691          const_tree inner = TREE_OPERAND (val, 0);
8692	  const_tree innertype = TREE_TYPE (inner);
8693	  if (innertype
8694	      && TYPE_REF_P (innertype)
8695	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8696	      && TREE_OPERAND_LENGTH (inner) > 0
8697              && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8698              return error_mark_node;
8699        }
8700
8701      if (TREE_CODE (val) == SCOPE_REF)
8702	{
8703	  /* Strip typedefs from the SCOPE_REF.  */
8704	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8705	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8706						   complain);
8707	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8708				      QUALIFIED_NAME_IS_TEMPLATE (val));
8709	}
8710    }
8711
8712  return val;
8713}
8714
8715/* Coerces the remaining template arguments in INNER_ARGS (from
8716   ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8717   Returns the coerced argument pack. PARM_IDX is the position of this
8718   parameter in the template parameter list. ARGS is the original
8719   template argument list.  */
8720static tree
8721coerce_template_parameter_pack (tree parms,
8722                                int parm_idx,
8723                                tree args,
8724                                tree inner_args,
8725                                int arg_idx,
8726                                tree new_args,
8727                                int* lost,
8728                                tree in_decl,
8729                                tsubst_flags_t complain)
8730{
8731  tree parm = TREE_VEC_ELT (parms, parm_idx);
8732  int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8733  tree packed_args;
8734  tree argument_pack;
8735  tree packed_parms = NULL_TREE;
8736
8737  if (arg_idx > nargs)
8738    arg_idx = nargs;
8739
8740  if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8741    {
8742      /* When the template parameter is a non-type template parameter pack
8743         or template template parameter pack whose type or template
8744         parameters use parameter packs, we know exactly how many arguments
8745         we are looking for.  Build a vector of the instantiated decls for
8746         these template parameters in PACKED_PARMS.  */
8747      /* We can't use make_pack_expansion here because it would interpret a
8748	 _DECL as a use rather than a declaration.  */
8749      tree decl = TREE_VALUE (parm);
8750      tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8751      SET_PACK_EXPANSION_PATTERN (exp, decl);
8752      PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8753      SET_TYPE_STRUCTURAL_EQUALITY (exp);
8754
8755      TREE_VEC_LENGTH (args)--;
8756      packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8757      TREE_VEC_LENGTH (args)++;
8758
8759      if (packed_parms == error_mark_node)
8760        return error_mark_node;
8761
8762      /* If we're doing a partial instantiation of a member template,
8763         verify that all of the types used for the non-type
8764         template parameter pack are, in fact, valid for non-type
8765         template parameters.  */
8766      if (arg_idx < nargs
8767          && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8768        {
8769          int j, len = TREE_VEC_LENGTH (packed_parms);
8770          for (j = 0; j < len; ++j)
8771            {
8772              tree t = TREE_VEC_ELT (packed_parms, j);
8773              if (TREE_CODE (t) == PARM_DECL
8774		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8775                return error_mark_node;
8776            }
8777	  /* We don't know how many args we have yet, just
8778	     use the unconverted ones for now.  */
8779	  return NULL_TREE;
8780        }
8781
8782      packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8783    }
8784  /* Check if we have a placeholder pack, which indicates we're
8785     in the context of a introduction list.  In that case we want
8786     to match this pack to the single placeholder.  */
8787  else if (arg_idx < nargs
8788           && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8789           && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8790    {
8791      nargs = arg_idx + 1;
8792      packed_args = make_tree_vec (1);
8793    }
8794  else
8795    packed_args = make_tree_vec (nargs - arg_idx);
8796
8797  /* Convert the remaining arguments, which will be a part of the
8798     parameter pack "parm".  */
8799  int first_pack_arg = arg_idx;
8800  for (; arg_idx < nargs; ++arg_idx)
8801    {
8802      tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8803      tree actual_parm = TREE_VALUE (parm);
8804      int pack_idx = arg_idx - first_pack_arg;
8805
8806      if (packed_parms)
8807        {
8808	  /* Once we've packed as many args as we have types, stop.  */
8809	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8810	    break;
8811	  else if (PACK_EXPANSION_P (arg))
8812	    /* We don't know how many args we have yet, just
8813	       use the unconverted ones for now.  */
8814	    return NULL_TREE;
8815	  else
8816	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8817        }
8818
8819      if (arg == error_mark_node)
8820	{
8821	  if (complain & tf_error)
8822	    error ("template argument %d is invalid", arg_idx + 1);
8823	}
8824      else
8825	arg = convert_template_argument (actual_parm,
8826					 arg, new_args, complain, parm_idx,
8827					 in_decl);
8828      if (arg == error_mark_node)
8829        (*lost)++;
8830      TREE_VEC_ELT (packed_args, pack_idx) = arg;
8831    }
8832
8833  if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8834      && TREE_VEC_LENGTH (packed_args) > 0)
8835    {
8836      if (complain & tf_error)
8837	error ("wrong number of template arguments (%d, should be %d)",
8838	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8839      return error_mark_node;
8840    }
8841
8842  if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8843      || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8844    argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8845  else
8846    {
8847      argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8848      TREE_CONSTANT (argument_pack) = 1;
8849    }
8850
8851  SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8852  if (CHECKING_P)
8853    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8854					 TREE_VEC_LENGTH (packed_args));
8855  return argument_pack;
8856}
8857
8858/* Returns the number of pack expansions in the template argument vector
8859   ARGS.  */
8860
8861static int
8862pack_expansion_args_count (tree args)
8863{
8864  int i;
8865  int count = 0;
8866  if (args)
8867    for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8868      {
8869	tree elt = TREE_VEC_ELT (args, i);
8870	if (elt && PACK_EXPANSION_P (elt))
8871	  ++count;
8872      }
8873  return count;
8874}
8875
8876/* Convert all template arguments to their appropriate types, and
8877   return a vector containing the innermost resulting template
8878   arguments.  If any error occurs, return error_mark_node. Error and
8879   warning messages are issued under control of COMPLAIN.
8880
8881   If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8882   for arguments not specified in ARGS.  Otherwise, if
8883   USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8884   unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8885   USE_DEFAULT_ARGS is false, then all arguments must be specified in
8886   ARGS.  */
8887
8888static tree
8889coerce_template_parms (tree parms,
8890		       tree args,
8891		       tree in_decl,
8892		       tsubst_flags_t complain,
8893		       bool require_all_args,
8894		       bool use_default_args)
8895{
8896  int nparms, nargs, parm_idx, arg_idx, lost = 0;
8897  tree orig_inner_args;
8898  tree inner_args;
8899  tree new_args;
8900  tree new_inner_args;
8901
8902  /* When used as a boolean value, indicates whether this is a
8903     variadic template parameter list. Since it's an int, we can also
8904     subtract it from nparms to get the number of non-variadic
8905     parameters.  */
8906  int variadic_p = 0;
8907  int variadic_args_p = 0;
8908  int post_variadic_parms = 0;
8909
8910  /* Adjustment to nparms for fixed parameter packs.  */
8911  int fixed_pack_adjust = 0;
8912  int fixed_packs = 0;
8913  int missing = 0;
8914
8915  /* Likewise for parameters with default arguments.  */
8916  int default_p = 0;
8917
8918  if (args == error_mark_node)
8919    return error_mark_node;
8920
8921  nparms = TREE_VEC_LENGTH (parms);
8922
8923  /* Determine if there are any parameter packs or default arguments.  */
8924  for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8925    {
8926      tree parm = TREE_VEC_ELT (parms, parm_idx);
8927      if (variadic_p)
8928	++post_variadic_parms;
8929      if (template_parameter_pack_p (TREE_VALUE (parm)))
8930	++variadic_p;
8931      if (TREE_PURPOSE (parm))
8932	++default_p;
8933    }
8934
8935  inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8936  /* If there are no parameters that follow a parameter pack, we need to
8937     expand any argument packs so that we can deduce a parameter pack from
8938     some non-packed args followed by an argument pack, as in variadic85.C.
8939     If there are such parameters, we need to leave argument packs intact
8940     so the arguments are assigned properly.  This can happen when dealing
8941     with a nested class inside a partial specialization of a class
8942     template, as in variadic92.C, or when deducing a template parameter pack
8943     from a sub-declarator, as in variadic114.C.  */
8944  if (!post_variadic_parms)
8945    inner_args = expand_template_argument_pack (inner_args);
8946
8947  /* Count any pack expansion args.  */
8948  variadic_args_p = pack_expansion_args_count (inner_args);
8949
8950  nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8951  if ((nargs - variadic_args_p > nparms && !variadic_p)
8952      || (nargs < nparms - variadic_p
8953	  && require_all_args
8954	  && !variadic_args_p
8955	  && (!use_default_args
8956	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8957                  && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8958    {
8959    bad_nargs:
8960      if (complain & tf_error)
8961	{
8962          if (variadic_p || default_p)
8963            {
8964              nparms -= variadic_p + default_p;
8965	      error ("wrong number of template arguments "
8966		     "(%d, should be at least %d)", nargs, nparms);
8967            }
8968	  else
8969	     error ("wrong number of template arguments "
8970		    "(%d, should be %d)", nargs, nparms);
8971
8972	  if (in_decl)
8973	    inform (DECL_SOURCE_LOCATION (in_decl),
8974		    "provided for %qD", in_decl);
8975	}
8976
8977      return error_mark_node;
8978    }
8979  /* We can't pass a pack expansion to a non-pack parameter of an alias
8980     template (DR 1430).  */
8981  else if (in_decl
8982	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8983	       || concept_definition_p (in_decl))
8984	   && variadic_args_p
8985	   && nargs - variadic_args_p < nparms - variadic_p)
8986    {
8987      if (complain & tf_error)
8988	{
8989	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8990	    {
8991	      tree arg = TREE_VEC_ELT (inner_args, i);
8992	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8993
8994	      if (PACK_EXPANSION_P (arg)
8995		  && !template_parameter_pack_p (parm))
8996		{
8997		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8998		    error_at (location_of (arg),
8999			      "pack expansion argument for non-pack parameter "
9000			      "%qD of alias template %qD", parm, in_decl);
9001		  else
9002		    error_at (location_of (arg),
9003			      "pack expansion argument for non-pack parameter "
9004			      "%qD of concept %qD", parm, in_decl);
9005		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
9006		  goto found;
9007		}
9008	    }
9009	  gcc_unreachable ();
9010	found:;
9011	}
9012      return error_mark_node;
9013    }
9014
9015  /* We need to evaluate the template arguments, even though this
9016     template-id may be nested within a "sizeof".  */
9017  cp_evaluated ev;
9018
9019  new_inner_args = make_tree_vec (nparms);
9020  new_args = add_outermost_template_args (args, new_inner_args);
9021  int pack_adjust = 0;
9022  for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9023    {
9024      tree arg;
9025      tree parm;
9026
9027      /* Get the Ith template parameter.  */
9028      parm = TREE_VEC_ELT (parms, parm_idx);
9029
9030      if (parm == error_mark_node)
9031	{
9032	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9033	  continue;
9034	}
9035
9036      /* Calculate the next argument.  */
9037      if (arg_idx < nargs)
9038	arg = TREE_VEC_ELT (inner_args, arg_idx);
9039      else
9040	arg = NULL_TREE;
9041
9042      if (template_parameter_pack_p (TREE_VALUE (parm))
9043	  && (arg || require_all_args || !(complain & tf_partial))
9044	  && !(arg && ARGUMENT_PACK_P (arg)))
9045        {
9046	  /* Some arguments will be placed in the
9047	     template parameter pack PARM.  */
9048	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
9049						inner_args, arg_idx,
9050						new_args, &lost,
9051						in_decl, complain);
9052
9053	  if (arg == NULL_TREE)
9054	    {
9055	      /* We don't know how many args we have yet, just use the
9056		 unconverted (and still packed) ones for now.  */
9057	      new_inner_args = orig_inner_args;
9058	      arg_idx = nargs;
9059	      break;
9060	    }
9061
9062          TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9063
9064          /* Store this argument.  */
9065          if (arg == error_mark_node)
9066	    {
9067	      lost++;
9068	      /* We are done with all of the arguments.  */
9069	      arg_idx = nargs;
9070	      break;
9071	    }
9072	  else
9073	    {
9074	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9075	      arg_idx += pack_adjust;
9076	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9077		{
9078		  ++fixed_packs;
9079		  fixed_pack_adjust += pack_adjust;
9080		}
9081	    }
9082
9083          continue;
9084        }
9085      else if (arg)
9086	{
9087          if (PACK_EXPANSION_P (arg))
9088            {
9089	      /* "If every valid specialization of a variadic template
9090		 requires an empty template parameter pack, the template is
9091		 ill-formed, no diagnostic required."  So check that the
9092		 pattern works with this parameter.  */
9093	      tree pattern = PACK_EXPANSION_PATTERN (arg);
9094	      tree conv = convert_template_argument (TREE_VALUE (parm),
9095						     pattern, new_args,
9096						     complain, parm_idx,
9097						     in_decl);
9098	      if (conv == error_mark_node)
9099		{
9100		  if (complain & tf_error)
9101		    inform (input_location, "so any instantiation with a "
9102			    "non-empty parameter pack would be ill-formed");
9103		  ++lost;
9104		}
9105	      else if (TYPE_P (conv) && !TYPE_P (pattern))
9106		/* Recover from missing typename.  */
9107		TREE_VEC_ELT (inner_args, arg_idx)
9108		  = make_pack_expansion (conv, complain);
9109
9110              /* We don't know how many args we have yet, just
9111                 use the unconverted ones for now.  */
9112              new_inner_args = inner_args;
9113	      arg_idx = nargs;
9114              break;
9115            }
9116        }
9117      else if (require_all_args)
9118	{
9119	  /* There must be a default arg in this case.  */
9120	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9121				     complain, in_decl);
9122	  /* The position of the first default template argument,
9123	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9124	     Record that.  */
9125	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9126	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9127						 arg_idx - pack_adjust);
9128	}
9129      else
9130	break;
9131
9132      if (arg == error_mark_node)
9133	{
9134	  if (complain & tf_error)
9135	    error ("template argument %d is invalid", arg_idx + 1);
9136	}
9137      else if (!arg)
9138	{
9139	  /* This can occur if there was an error in the template
9140	     parameter list itself (which we would already have
9141	     reported) that we are trying to recover from, e.g., a class
9142	     template with a parameter list such as
9143	     template<typename..., typename> (cpp0x/variadic150.C).  */
9144	  ++lost;
9145
9146	  /* This can also happen with a fixed parameter pack (71834).  */
9147	  if (arg_idx >= nargs)
9148	    ++missing;
9149	}
9150      else
9151	arg = convert_template_argument (TREE_VALUE (parm),
9152					 arg, new_args, complain,
9153                                         parm_idx, in_decl);
9154
9155      if (arg == error_mark_node)
9156	lost++;
9157
9158      TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9159    }
9160
9161  if (missing || arg_idx < nargs - variadic_args_p)
9162    {
9163      /* If we had fixed parameter packs, we didn't know how many arguments we
9164	 actually needed earlier; now we do.  */
9165      nparms += fixed_pack_adjust;
9166      variadic_p -= fixed_packs;
9167      goto bad_nargs;
9168    }
9169
9170  if (arg_idx < nargs)
9171    {
9172      /* We had some pack expansion arguments that will only work if the packs
9173	 are empty, but wait until instantiation time to complain.
9174	 See variadic-ttp3.C.  */
9175
9176      /* Except that we can't provide empty packs to alias templates or
9177         concepts when there are no corresponding parameters. Basically,
9178         we can get here with this:
9179
9180             template<typename T> concept C = true;
9181
9182             template<typename... Args>
9183	       requires C<Args...>
9184             void f();
9185
9186         When parsing C<Args...>, we try to form a concept check of
9187         C<?, Args...>. Without the extra check for substituting an empty
9188         pack past the last parameter, we can accept the check as valid.
9189
9190         FIXME: This may be valid for alias templates (but I doubt it).
9191
9192         FIXME: The error could be better also.   */
9193      if (in_decl && concept_definition_p (in_decl))
9194	{
9195	  if (complain & tf_error)
9196	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9197		      "too many arguments");
9198	  return error_mark_node;
9199	}
9200
9201      int len = nparms + (nargs - arg_idx);
9202      tree args = make_tree_vec (len);
9203      int i = 0;
9204      for (; i < nparms; ++i)
9205	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9206      for (; i < len; ++i, ++arg_idx)
9207	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9208					       arg_idx - pack_adjust);
9209      new_inner_args = args;
9210    }
9211
9212  if (lost)
9213    {
9214      gcc_assert (!(complain & tf_error) || seen_error ());
9215      return error_mark_node;
9216    }
9217
9218  if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9219    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9220					 TREE_VEC_LENGTH (new_inner_args));
9221
9222  return new_inner_args;
9223}
9224
9225/* Convert all template arguments to their appropriate types, and
9226   return a vector containing the innermost resulting template
9227   arguments.  If any error occurs, return error_mark_node. Error and
9228   warning messages are not issued.
9229
9230   Note that no function argument deduction is performed, and default
9231   arguments are used to fill in unspecified arguments. */
9232tree
9233coerce_template_parms (tree parms, tree args, tree in_decl)
9234{
9235  return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9236}
9237
9238/* Convert all template arguments to their appropriate type, and
9239   instantiate default arguments as needed. This returns a vector
9240   containing the innermost resulting template arguments, or
9241   error_mark_node if unsuccessful.  */
9242tree
9243coerce_template_parms (tree parms, tree args, tree in_decl,
9244                       tsubst_flags_t complain)
9245{
9246  return coerce_template_parms (parms, args, in_decl, complain, true, true);
9247}
9248
9249/* Like coerce_template_parms.  If PARMS represents all template
9250   parameters levels, this function returns a vector of vectors
9251   representing all the resulting argument levels.  Note that in this
9252   case, only the innermost arguments are coerced because the
9253   outermost ones are supposed to have been coerced already.
9254
9255   Otherwise, if PARMS represents only (the innermost) vector of
9256   parameters, this function returns a vector containing just the
9257   innermost resulting arguments.  */
9258
9259static tree
9260coerce_innermost_template_parms (tree parms,
9261				  tree args,
9262				  tree in_decl,
9263				  tsubst_flags_t complain,
9264				  bool require_all_args,
9265				  bool use_default_args)
9266{
9267  int parms_depth = TMPL_PARMS_DEPTH (parms);
9268  int args_depth = TMPL_ARGS_DEPTH (args);
9269  tree coerced_args;
9270
9271  if (parms_depth > 1)
9272    {
9273      coerced_args = make_tree_vec (parms_depth);
9274      tree level;
9275      int cur_depth;
9276
9277      for (level = parms, cur_depth = parms_depth;
9278	   parms_depth > 0 && level != NULL_TREE;
9279	   level = TREE_CHAIN (level), --cur_depth)
9280	{
9281	  tree l;
9282	  if (cur_depth == args_depth)
9283	    l = coerce_template_parms (TREE_VALUE (level),
9284				       args, in_decl, complain,
9285				       require_all_args,
9286				       use_default_args);
9287	  else
9288	    l = TMPL_ARGS_LEVEL (args, cur_depth);
9289
9290	  if (l == error_mark_node)
9291	    return error_mark_node;
9292
9293	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9294	}
9295    }
9296  else
9297    coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9298					  args, in_decl, complain,
9299					  require_all_args,
9300					  use_default_args);
9301  return coerced_args;
9302}
9303
9304/* Returns true if T is a wrapper to make a C++20 template parameter
9305   object const.  */
9306
9307static bool
9308class_nttp_const_wrapper_p (tree t)
9309{
9310  if (cxx_dialect < cxx20)
9311    return false;
9312  return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9313	  && CP_TYPE_CONST_P (TREE_TYPE (t))
9314	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9315}
9316
9317/* Returns 1 if template args OT and NT are equivalent.  */
9318
9319int
9320template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9321{
9322  if (nt == ot)
9323    return 1;
9324  if (nt == NULL_TREE || ot == NULL_TREE)
9325    return false;
9326  if (nt == any_targ_node || ot == any_targ_node)
9327    return true;
9328
9329  if (class_nttp_const_wrapper_p (nt))
9330    nt = TREE_OPERAND (nt, 0);
9331  if (class_nttp_const_wrapper_p (ot))
9332    ot = TREE_OPERAND (ot, 0);
9333
9334  /* DR 1558: Don't treat an alias template specialization with dependent
9335     arguments as equivalent to its underlying type when used as a template
9336     argument; we need them to be distinct so that we substitute into the
9337     specialization arguments at instantiation time.  And aliases can't be
9338     equivalent without being ==, so we don't need to look any deeper.
9339
9340     During partial ordering, however, we need to treat them normally so we can
9341     order uses of the same alias with different cv-qualification (79960).  */
9342  auto cso = make_temp_override (comparing_dependent_aliases);
9343  if (!partial_order)
9344    ++comparing_dependent_aliases;
9345
9346  if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9347    /* For member templates */
9348    return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9349  else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9350    return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9351	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9352				    PACK_EXPANSION_PATTERN (nt))
9353	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9354				    PACK_EXPANSION_EXTRA_ARGS (nt)));
9355  else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9356    return cp_tree_equal (ot, nt);
9357  else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9358    gcc_unreachable ();
9359  else if (TYPE_P (nt) || TYPE_P (ot))
9360    {
9361      if (!(TYPE_P (nt) && TYPE_P (ot)))
9362	return false;
9363      return same_type_p (ot, nt);
9364    }
9365  else
9366    {
9367      /* Try to treat a template non-type argument that has been converted
9368	 to the parameter type as equivalent to one that hasn't yet.  */
9369      for (enum tree_code code1 = TREE_CODE (ot);
9370	   CONVERT_EXPR_CODE_P (code1)
9371	     || code1 == NON_LVALUE_EXPR;
9372	   code1 = TREE_CODE (ot))
9373	ot = TREE_OPERAND (ot, 0);
9374
9375      for (enum tree_code code2 = TREE_CODE (nt);
9376	   CONVERT_EXPR_CODE_P (code2)
9377	     || code2 == NON_LVALUE_EXPR;
9378	   code2 = TREE_CODE (nt))
9379	nt = TREE_OPERAND (nt, 0);
9380
9381      return cp_tree_equal (ot, nt);
9382    }
9383}
9384
9385/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9386   template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9387   NEWARG_PTR with the offending arguments if they are non-NULL.  */
9388
9389int
9390comp_template_args (tree oldargs, tree newargs,
9391		    tree *oldarg_ptr, tree *newarg_ptr,
9392		    bool partial_order)
9393{
9394  int i;
9395
9396  if (oldargs == newargs)
9397    return 1;
9398
9399  if (!oldargs || !newargs)
9400    return 0;
9401
9402  if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9403    return 0;
9404
9405  for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9406    {
9407      tree nt = TREE_VEC_ELT (newargs, i);
9408      tree ot = TREE_VEC_ELT (oldargs, i);
9409
9410      if (! template_args_equal (ot, nt, partial_order))
9411	{
9412	  if (oldarg_ptr != NULL)
9413	    *oldarg_ptr = ot;
9414	  if (newarg_ptr != NULL)
9415	    *newarg_ptr = nt;
9416	  return 0;
9417	}
9418    }
9419  return 1;
9420}
9421
9422inline bool
9423comp_template_args_porder (tree oargs, tree nargs)
9424{
9425  return comp_template_args (oargs, nargs, NULL, NULL, true);
9426}
9427
9428/* Implement a freelist interface for objects of type T.
9429
9430   Head is a separate object, rather than a regular member, so that we
9431   can define it as a GTY deletable pointer, which is highly
9432   desirable.  A data member could be declared that way, but then the
9433   containing object would implicitly get GTY((user)), which would
9434   prevent us from instantiating freelists as global objects.
9435   Although this way we can create freelist global objects, they're
9436   such thin wrappers that instantiating temporaries at every use
9437   loses nothing and saves permanent storage for the freelist object.
9438
9439   Member functions next, anew, poison and reinit have default
9440   implementations that work for most of the types we're interested
9441   in, but if they don't work for some type, they should be explicitly
9442   specialized.  See the comments before them for requirements, and
9443   the example specializations for the tree_list_freelist.  */
9444template <typename T>
9445class freelist
9446{
9447  /* Return the next object in a chain.  We could just do type
9448     punning, but if we access the object with its underlying type, we
9449     avoid strict-aliasing trouble.  This needs only work between
9450     poison and reinit.  */
9451  static T *&next (T *obj) { return obj->next; }
9452
9453  /* Return a newly allocated, uninitialized or minimally-initialized
9454     object of type T.  Any initialization performed by anew should
9455     either remain across the life of the object and the execution of
9456     poison, or be redone by reinit.  */
9457  static T *anew () { return ggc_alloc<T> (); }
9458
9459  /* Optionally scribble all over the bits holding the object, so that
9460     they become (mostly?) uninitialized memory.  This is called while
9461     preparing to make the object part of the free list.  */
9462  static void poison (T *obj) {
9463    T *p ATTRIBUTE_UNUSED = obj;
9464    T **q ATTRIBUTE_UNUSED = &next (obj);
9465
9466#ifdef ENABLE_GC_CHECKING
9467    /* Poison the data, to indicate the data is garbage.  */
9468    VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9469    memset (p, 0xa5, sizeof (*p));
9470#endif
9471    /* Let valgrind know the object is free.  */
9472    VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9473
9474    /* Let valgrind know the next portion of the object is available,
9475       but uninitialized.  */
9476    VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9477  }
9478
9479  /* Bring an object that underwent at least one lifecycle after anew
9480     and before the most recent free and poison, back to a usable
9481     state, reinitializing whatever is needed for it to be
9482     functionally equivalent to an object just allocated and returned
9483     by anew.  This may poison or clear the next field, used by
9484     freelist housekeeping after poison was called.  */
9485  static void reinit (T *obj) {
9486    T **q ATTRIBUTE_UNUSED = &next (obj);
9487
9488#ifdef ENABLE_GC_CHECKING
9489    memset (q, 0xa5, sizeof (*q));
9490#endif
9491    /* Let valgrind know the entire object is available, but
9492       uninitialized.  */
9493    VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9494  }
9495
9496  /* Reference a GTY-deletable pointer that points to the first object
9497     in the free list proper.  */
9498  T *&head;
9499public:
9500  /* Construct a freelist object chaining objects off of HEAD.  */
9501  freelist (T *&head) : head(head) {}
9502
9503  /* Add OBJ to the free object list.  The former head becomes OBJ's
9504     successor.  */
9505  void free (T *obj)
9506  {
9507    poison (obj);
9508    next (obj) = head;
9509    head = obj;
9510  }
9511
9512  /* Take an object from the free list, if one is available, or
9513     allocate a new one.  Objects taken from the free list should be
9514     regarded as filled with garbage, except for bits that are
9515     configured to be preserved across free and alloc.  */
9516  T *alloc ()
9517  {
9518    if (head)
9519      {
9520	T *obj = head;
9521	head = next (head);
9522	reinit (obj);
9523	return obj;
9524      }
9525    else
9526      return anew ();
9527  }
9528};
9529
9530/* Explicitly specialize the interfaces for freelist<tree_node>: we
9531   want to allocate a TREE_LIST using the usual interface, and ensure
9532   TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9533   build_tree_list logic in reinit, so this could go out of sync.  */
9534template <>
9535inline tree &
9536freelist<tree_node>::next (tree obj)
9537{
9538  return TREE_CHAIN (obj);
9539}
9540template <>
9541inline tree
9542freelist<tree_node>::anew ()
9543{
9544  return build_tree_list (NULL, NULL);
9545}
9546template <>
9547inline void
9548freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9549{
9550  int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9551  tree p ATTRIBUTE_UNUSED = obj;
9552  tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9553  tree *q ATTRIBUTE_UNUSED = &next (obj);
9554
9555#ifdef ENABLE_GC_CHECKING
9556  gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9557
9558  /* Poison the data, to indicate the data is garbage.  */
9559  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9560  memset (p, 0xa5, size);
9561#endif
9562  /* Let valgrind know the object is free.  */
9563  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9564  /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9565  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9566  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9567
9568#ifdef ENABLE_GC_CHECKING
9569  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9570  /* Keep TREE_CHAIN functional.  */
9571  TREE_SET_CODE (obj, TREE_LIST);
9572#else
9573  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9574#endif
9575}
9576template <>
9577inline void
9578freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9579{
9580  tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9581
9582#ifdef ENABLE_GC_CHECKING
9583  gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9584  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9585  memset (obj, 0, sizeof (tree_list));
9586#endif
9587
9588  /* Let valgrind know the entire object is available, but
9589     uninitialized.  */
9590  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9591
9592#ifdef ENABLE_GC_CHECKING
9593  TREE_SET_CODE (obj, TREE_LIST);
9594#else
9595  VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9596#endif
9597}
9598
9599/* Point to the first object in the TREE_LIST freelist.  */
9600static GTY((deletable)) tree tree_list_freelist_head;
9601/* Return the/an actual TREE_LIST freelist.  */
9602static inline freelist<tree_node>
9603tree_list_freelist ()
9604{
9605  return tree_list_freelist_head;
9606}
9607
9608/* Point to the first object in the tinst_level freelist.  */
9609static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9610/* Return the/an actual tinst_level freelist.  */
9611static inline freelist<tinst_level>
9612tinst_level_freelist ()
9613{
9614  return tinst_level_freelist_head;
9615}
9616
9617/* Point to the first object in the pending_template freelist.  */
9618static GTY((deletable)) pending_template *pending_template_freelist_head;
9619/* Return the/an actual pending_template freelist.  */
9620static inline freelist<pending_template>
9621pending_template_freelist ()
9622{
9623  return pending_template_freelist_head;
9624}
9625
9626/* Build the TREE_LIST object out of a split list, store it
9627   permanently, and return it.  */
9628tree
9629tinst_level::to_list ()
9630{
9631  gcc_assert (split_list_p ());
9632  tree ret = tree_list_freelist ().alloc ();
9633  TREE_PURPOSE (ret) = tldcl;
9634  TREE_VALUE (ret) = targs;
9635  tldcl = ret;
9636  targs = NULL;
9637  gcc_assert (tree_list_p ());
9638  return ret;
9639}
9640
9641const unsigned short tinst_level::refcount_infinity;
9642
9643/* Increment OBJ's refcount unless it is already infinite.  */
9644static tinst_level *
9645inc_refcount_use (tinst_level *obj)
9646{
9647  if (obj && obj->refcount != tinst_level::refcount_infinity)
9648    ++obj->refcount;
9649  return obj;
9650}
9651
9652/* Release storage for OBJ and node, if it's a TREE_LIST.  */
9653void
9654tinst_level::free (tinst_level *obj)
9655{
9656  if (obj->tree_list_p ())
9657    tree_list_freelist ().free (obj->get_node ());
9658  tinst_level_freelist ().free (obj);
9659}
9660
9661/* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9662   OBJ's DECL and OBJ, and start over with the tinst_level object that
9663   used to be referenced by OBJ's NEXT.  */
9664static void
9665dec_refcount_use (tinst_level *obj)
9666{
9667  while (obj
9668	 && obj->refcount != tinst_level::refcount_infinity
9669	 && !--obj->refcount)
9670    {
9671      tinst_level *next = obj->next;
9672      tinst_level::free (obj);
9673      obj = next;
9674    }
9675}
9676
9677/* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9678   and of the former PTR.  Omitting the second argument is equivalent
9679   to passing (T*)NULL; this is allowed because passing the
9680   zero-valued integral constant NULL confuses type deduction and/or
9681   overload resolution.  */
9682template <typename T>
9683static void
9684set_refcount_ptr (T *& ptr, T *obj = NULL)
9685{
9686  T *save = ptr;
9687  ptr = inc_refcount_use (obj);
9688  dec_refcount_use (save);
9689}
9690
9691static void
9692add_pending_template (tree d)
9693{
9694  tree ti = (TYPE_P (d)
9695	     ? CLASSTYPE_TEMPLATE_INFO (d)
9696	     : DECL_TEMPLATE_INFO (d));
9697  struct pending_template *pt;
9698  int level;
9699
9700  if (TI_PENDING_TEMPLATE_FLAG (ti))
9701    return;
9702
9703  /* We are called both from instantiate_decl, where we've already had a
9704     tinst_level pushed, and instantiate_template, where we haven't.
9705     Compensate.  */
9706  gcc_assert (TREE_CODE (d) != TREE_LIST);
9707  level = !current_tinst_level
9708    || current_tinst_level->maybe_get_node () != d;
9709
9710  if (level)
9711    push_tinst_level (d);
9712
9713  pt = pending_template_freelist ().alloc ();
9714  pt->next = NULL;
9715  pt->tinst = NULL;
9716  set_refcount_ptr (pt->tinst, current_tinst_level);
9717  if (last_pending_template)
9718    last_pending_template->next = pt;
9719  else
9720    pending_templates = pt;
9721
9722  last_pending_template = pt;
9723
9724  TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9725
9726  if (level)
9727    pop_tinst_level ();
9728}
9729
9730
9731/* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9732   ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9733   documentation for TEMPLATE_ID_EXPR.  */
9734
9735tree
9736lookup_template_function (tree fns, tree arglist)
9737{
9738  if (fns == error_mark_node || arglist == error_mark_node)
9739    return error_mark_node;
9740
9741  gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9742
9743  if (!is_overloaded_fn (fns) && !identifier_p (fns))
9744    {
9745      error ("%q#D is not a function template", fns);
9746      return error_mark_node;
9747    }
9748
9749  if (BASELINK_P (fns))
9750    {
9751      fns = copy_node (fns);
9752      BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9753					 unknown_type_node,
9754					 BASELINK_FUNCTIONS (fns),
9755					 arglist);
9756      return fns;
9757    }
9758
9759  return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9760}
9761
9762/* Within the scope of a template class S<T>, the name S gets bound
9763   (in build_self_reference) to a TYPE_DECL for the class, not a
9764   TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9765   or one of its enclosing classes, and that type is a template,
9766   return the associated TEMPLATE_DECL.  Otherwise, the original
9767   DECL is returned.
9768
9769   Also handle the case when DECL is a TREE_LIST of ambiguous
9770   injected-class-names from different bases.  */
9771
9772tree
9773maybe_get_template_decl_from_type_decl (tree decl)
9774{
9775  if (decl == NULL_TREE)
9776    return decl;
9777
9778  /* DR 176: A lookup that finds an injected-class-name (10.2
9779     [class.member.lookup]) can result in an ambiguity in certain cases
9780     (for example, if it is found in more than one base class). If all of
9781     the injected-class-names that are found refer to specializations of
9782     the same class template, and if the name is followed by a
9783     template-argument-list, the reference refers to the class template
9784     itself and not a specialization thereof, and is not ambiguous.  */
9785  if (TREE_CODE (decl) == TREE_LIST)
9786    {
9787      tree t, tmpl = NULL_TREE;
9788      for (t = decl; t; t = TREE_CHAIN (t))
9789	{
9790	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9791	  if (!tmpl)
9792	    tmpl = elt;
9793	  else if (tmpl != elt)
9794	    break;
9795	}
9796      if (tmpl && t == NULL_TREE)
9797	return tmpl;
9798      else
9799	return decl;
9800    }
9801
9802  return (decl != NULL_TREE
9803	  && DECL_SELF_REFERENCE_P (decl)
9804	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9805    ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9806}
9807
9808/* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9809   parameters, find the desired type.
9810
9811   D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9812
9813   IN_DECL, if non-NULL, is the template declaration we are trying to
9814   instantiate.
9815
9816   If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9817   the class we are looking up.
9818
9819   Issue error and warning messages under control of COMPLAIN.
9820
9821   If the template class is really a local class in a template
9822   function, then the FUNCTION_CONTEXT is the function in which it is
9823   being instantiated.
9824
9825   ??? Note that this function is currently called *twice* for each
9826   template-id: the first time from the parser, while creating the
9827   incomplete type (finish_template_type), and the second type during the
9828   real instantiation (instantiate_template_class). This is surely something
9829   that we want to avoid. It also causes some problems with argument
9830   coercion (see convert_nontype_argument for more information on this).  */
9831
9832static tree
9833lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9834			 int entering_scope, tsubst_flags_t complain)
9835{
9836  tree templ = NULL_TREE, parmlist;
9837  tree t;
9838  spec_entry **slot;
9839  spec_entry *entry;
9840  spec_entry elt;
9841  hashval_t hash;
9842
9843  if (identifier_p (d1))
9844    {
9845      tree value = innermost_non_namespace_value (d1);
9846      if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9847	templ = value;
9848      else
9849	{
9850	  if (context)
9851	    push_decl_namespace (context);
9852	  templ = lookup_name (d1);
9853	  templ = maybe_get_template_decl_from_type_decl (templ);
9854	  if (context)
9855	    pop_decl_namespace ();
9856	}
9857      if (templ)
9858	context = DECL_CONTEXT (templ);
9859    }
9860  else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9861    {
9862      tree type = TREE_TYPE (d1);
9863
9864      /* If we are declaring a constructor, say A<T>::A<T>, we will get
9865	 an implicit typename for the second A.  Deal with it.  */
9866      if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9867	type = TREE_TYPE (type);
9868
9869      if (CLASSTYPE_TEMPLATE_INFO (type))
9870	{
9871	  templ = CLASSTYPE_TI_TEMPLATE (type);
9872	  d1 = DECL_NAME (templ);
9873	}
9874    }
9875  else if (TREE_CODE (d1) == ENUMERAL_TYPE
9876	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9877    {
9878      templ = TYPE_TI_TEMPLATE (d1);
9879      d1 = DECL_NAME (templ);
9880    }
9881  else if (DECL_TYPE_TEMPLATE_P (d1))
9882    {
9883      templ = d1;
9884      d1 = DECL_NAME (templ);
9885      context = DECL_CONTEXT (templ);
9886    }
9887  else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9888    {
9889      templ = d1;
9890      d1 = DECL_NAME (templ);
9891    }
9892
9893  /* Issue an error message if we didn't find a template.  */
9894  if (! templ)
9895    {
9896      if (complain & tf_error)
9897	error ("%qT is not a template", d1);
9898      return error_mark_node;
9899    }
9900
9901  if (TREE_CODE (templ) != TEMPLATE_DECL
9902	 /* Make sure it's a user visible template, if it was named by
9903	    the user.  */
9904      || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9905	  && !PRIMARY_TEMPLATE_P (templ)))
9906    {
9907      if (complain & tf_error)
9908	{
9909	  error ("non-template type %qT used as a template", d1);
9910	  if (in_decl)
9911	    error ("for template declaration %q+D", in_decl);
9912	}
9913      return error_mark_node;
9914    }
9915
9916  complain &= ~tf_user;
9917
9918  /* An alias that just changes the name of a template is equivalent to the
9919     other template, so if any of the arguments are pack expansions, strip
9920     the alias to avoid problems with a pack expansion passed to a non-pack
9921     alias template parameter (DR 1430).  */
9922  if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9923    templ = get_underlying_template (templ);
9924
9925  if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9926    {
9927      tree parm;
9928      tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9929      if (arglist2 == error_mark_node
9930	  || (!uses_template_parms (arglist2)
9931	      && check_instantiated_args (templ, arglist2, complain)))
9932	return error_mark_node;
9933
9934      parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9935      return parm;
9936    }
9937  else
9938    {
9939      tree template_type = TREE_TYPE (templ);
9940      tree gen_tmpl;
9941      tree type_decl;
9942      tree found = NULL_TREE;
9943      int arg_depth;
9944      int parm_depth;
9945      int is_dependent_type;
9946      int use_partial_inst_tmpl = false;
9947
9948      if (template_type == error_mark_node)
9949	/* An error occurred while building the template TEMPL, and a
9950	   diagnostic has most certainly been emitted for that
9951	   already.  Let's propagate that error.  */
9952	return error_mark_node;
9953
9954      gen_tmpl = most_general_template (templ);
9955      if (modules_p ())
9956	lazy_load_pendings (gen_tmpl);
9957
9958      parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9959      parm_depth = TMPL_PARMS_DEPTH (parmlist);
9960      arg_depth = TMPL_ARGS_DEPTH (arglist);
9961
9962      if (arg_depth == 1 && parm_depth > 1)
9963	{
9964	  /* We've been given an incomplete set of template arguments.
9965	     For example, given:
9966
9967	       template <class T> struct S1 {
9968		 template <class U> struct S2 {};
9969		 template <class U> struct S2<U*> {};
9970		};
9971
9972	     we will be called with an ARGLIST of `U*', but the
9973	     TEMPLATE will be `template <class T> template
9974	     <class U> struct S1<T>::S2'.  We must fill in the missing
9975	     arguments.  */
9976	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9977	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9978	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9979	}
9980
9981      /* Now we should have enough arguments.  */
9982      gcc_assert (parm_depth == arg_depth);
9983
9984      /* From here on, we're only interested in the most general
9985	 template.  */
9986
9987      /* Shortcut looking up the current class scope again.  */
9988      if (current_class_type)
9989	if (tree ti = CLASSTYPE_TEMPLATE_INFO (current_class_type))
9990	  if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9991	      && comp_template_args (arglist, TI_ARGS (ti)))
9992	    return current_class_type;
9993
9994      /* Calculate the BOUND_ARGS.  These will be the args that are
9995	 actually tsubst'd into the definition to create the
9996	 instantiation.  */
9997      arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9998						 complain,
9999						 /*require_all_args=*/true,
10000						 /*use_default_args=*/true);
10001
10002      if (arglist == error_mark_node)
10003	/* We were unable to bind the arguments.  */
10004	return error_mark_node;
10005
10006      /* In the scope of a template class, explicit references to the
10007	 template class refer to the type of the template, not any
10008	 instantiation of it.  For example, in:
10009
10010	   template <class T> class C { void f(C<T>); }
10011
10012	 the `C<T>' is just the same as `C'.  Outside of the
10013	 class, however, such a reference is an instantiation.  */
10014      if (entering_scope
10015	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
10016	  || currently_open_class (template_type))
10017	{
10018	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10019
10020	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10021	    return template_type;
10022	}
10023
10024      /* If we already have this specialization, return it.  */
10025      elt.tmpl = gen_tmpl;
10026      elt.args = arglist;
10027      elt.spec = NULL_TREE;
10028      hash = spec_hasher::hash (&elt);
10029      entry = type_specializations->find_with_hash (&elt, hash);
10030
10031      if (entry)
10032	return entry->spec;
10033
10034      /* If the template's constraints are not satisfied,
10035         then we cannot form a valid type.
10036
10037         Note that the check is deferred until after the hash
10038         lookup. This prevents redundant checks on previously
10039         instantiated specializations. */
10040      if (flag_concepts
10041	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
10042	  && !constraints_satisfied_p (gen_tmpl, arglist))
10043        {
10044          if (complain & tf_error)
10045            {
10046	      auto_diagnostic_group d;
10047              error ("template constraint failure for %qD", gen_tmpl);
10048              diagnose_constraints (input_location, gen_tmpl, arglist);
10049            }
10050          return error_mark_node;
10051        }
10052
10053      is_dependent_type = uses_template_parms (arglist);
10054
10055      /* If the deduced arguments are invalid, then the binding
10056	 failed.  */
10057      if (!is_dependent_type
10058	  && check_instantiated_args (gen_tmpl,
10059				      INNERMOST_TEMPLATE_ARGS (arglist),
10060				      complain))
10061	return error_mark_node;
10062
10063      if (!is_dependent_type
10064	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
10065	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10066	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10067	/* This occurs when the user has tried to define a tagged type
10068	   in a scope that forbids it.  We emitted an error during the
10069	   parse.  We didn't complete the bail out then, so here we
10070	   are.  */
10071	return error_mark_node;
10072
10073      context = DECL_CONTEXT (gen_tmpl);
10074      if (context && TYPE_P (context))
10075	{
10076	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
10077	  context = complete_type (context);
10078	}
10079      else
10080	context = tsubst (context, arglist, complain, in_decl);
10081
10082      if (context == error_mark_node)
10083	return error_mark_node;
10084
10085      if (!context)
10086	context = global_namespace;
10087
10088      /* Create the type.  */
10089      if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10090	{
10091	  /* The user referred to a specialization of an alias
10092	    template represented by GEN_TMPL.
10093
10094	    [temp.alias]/2 says:
10095
10096	        When a template-id refers to the specialization of an
10097		alias template, it is equivalent to the associated
10098		type obtained by substitution of its
10099		template-arguments for the template-parameters in the
10100		type-id of the alias template.  */
10101
10102	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10103	  /* Note that the call above (by indirectly calling
10104	     register_specialization in tsubst_decl) registers the
10105	     TYPE_DECL representing the specialization of the alias
10106	     template.  So next time someone substitutes ARGLIST for
10107	     the template parms into the alias template (GEN_TMPL),
10108	     she'll get that TYPE_DECL back.  */
10109
10110	  if (t == error_mark_node)
10111	    return t;
10112	}
10113      else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10114	{
10115	  if (!is_dependent_type)
10116	    {
10117	      set_current_access_from_decl (TYPE_NAME (template_type));
10118	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10119			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
10120				      arglist, complain, in_decl),
10121			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10122						 arglist, complain, in_decl),
10123			      SCOPED_ENUM_P (template_type), NULL);
10124
10125	      if (t == error_mark_node)
10126		return t;
10127	    }
10128	  else
10129            {
10130              /* We don't want to call start_enum for this type, since
10131                 the values for the enumeration constants may involve
10132                 template parameters.  And, no one should be interested
10133                 in the enumeration constants for such a type.  */
10134              t = cxx_make_type (ENUMERAL_TYPE);
10135              SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10136            }
10137          SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10138	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
10139	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10140	}
10141      else if (CLASS_TYPE_P (template_type))
10142	{
10143	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
10144	     instantiated here.  */
10145	  gcc_assert (!LAMBDA_TYPE_P (template_type));
10146
10147	  t = make_class_type (TREE_CODE (template_type));
10148	  CLASSTYPE_DECLARED_CLASS (t)
10149	    = CLASSTYPE_DECLARED_CLASS (template_type);
10150	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10151
10152	  /* A local class.  Make sure the decl gets registered properly.  */
10153	  if (context == current_function_decl)
10154	    if (pushtag (DECL_NAME (gen_tmpl), t)
10155		== error_mark_node)
10156	      return error_mark_node;
10157
10158	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10159	    /* This instantiation is another name for the primary
10160	       template type. Set the TYPE_CANONICAL field
10161	       appropriately. */
10162	    TYPE_CANONICAL (t) = template_type;
10163	  else if (any_template_arguments_need_structural_equality_p (arglist))
10164	    /* Some of the template arguments require structural
10165	       equality testing, so this template class requires
10166	       structural equality testing. */
10167	    SET_TYPE_STRUCTURAL_EQUALITY (t);
10168	}
10169      else
10170	gcc_unreachable ();
10171
10172      /* If we called start_enum or pushtag above, this information
10173	 will already be set up.  */
10174      type_decl = TYPE_NAME (t);
10175      if (!type_decl)
10176	{
10177	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10178
10179	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10180	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10181	  DECL_SOURCE_LOCATION (type_decl)
10182	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10183	}
10184
10185      set_instantiating_module (type_decl);
10186      /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10187	 of export flag.  We want to propagate this because it might
10188	 be a friend declaration that pushes a new hidden binding.  */
10189      DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10190
10191      if (CLASS_TYPE_P (template_type))
10192	{
10193	  TREE_PRIVATE (type_decl)
10194	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10195	  TREE_PROTECTED (type_decl)
10196	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10197	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10198	    {
10199	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10200	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10201	    }
10202	}
10203
10204      if (OVERLOAD_TYPE_P (t)
10205	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10206	{
10207	  static const char *tags[] = {"abi_tag", "may_alias"};
10208
10209	  for (unsigned ix = 0; ix != 2; ix++)
10210	    {
10211	      tree attributes
10212		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10213
10214	      if (attributes)
10215		TYPE_ATTRIBUTES (t)
10216		  = tree_cons (TREE_PURPOSE (attributes),
10217			       TREE_VALUE (attributes),
10218			       TYPE_ATTRIBUTES (t));
10219	    }
10220	}
10221
10222      /* Let's consider the explicit specialization of a member
10223         of a class template specialization that is implicitly instantiated,
10224	 e.g.:
10225	     template<class T>
10226	     struct S
10227	     {
10228	       template<class U> struct M {}; //#0
10229	     };
10230
10231	     template<>
10232	     template<>
10233	     struct S<int>::M<char> //#1
10234	     {
10235	       int i;
10236	     };
10237	[temp.expl.spec]/4 says this is valid.
10238
10239	In this case, when we write:
10240	S<int>::M<char> m;
10241
10242	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10243	the one of #0.
10244
10245	When we encounter #1, we want to store the partial instantiation
10246	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10247
10248	For all cases other than this "explicit specialization of member of a
10249	class template", we just want to store the most general template into
10250	the CLASSTYPE_TI_TEMPLATE of M.
10251
10252	This case of "explicit specialization of member of a class template"
10253	only happens when:
10254	1/ the enclosing class is an instantiation of, and therefore not
10255	the same as, the context of the most general template, and
10256	2/ we aren't looking at the partial instantiation itself, i.e.
10257	the innermost arguments are not the same as the innermost parms of
10258	the most general template.
10259
10260	So it's only when 1/ and 2/ happens that we want to use the partial
10261	instantiation of the member template in lieu of its most general
10262	template.  */
10263
10264      if (PRIMARY_TEMPLATE_P (gen_tmpl)
10265	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10266	  /* the enclosing class must be an instantiation...  */
10267	  && CLASS_TYPE_P (context)
10268	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10269	{
10270	  TREE_VEC_LENGTH (arglist)--;
10271	  ++processing_template_decl;
10272	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10273	  tree partial_inst_args =
10274	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10275		    arglist, complain, NULL_TREE);
10276	  --processing_template_decl;
10277	  TREE_VEC_LENGTH (arglist)++;
10278	  if (partial_inst_args == error_mark_node)
10279	    return error_mark_node;
10280	  use_partial_inst_tmpl =
10281	    /*...and we must not be looking at the partial instantiation
10282	     itself. */
10283	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10284				 partial_inst_args);
10285	}
10286
10287      if (!use_partial_inst_tmpl)
10288	/* This case is easy; there are no member templates involved.  */
10289	found = gen_tmpl;
10290      else
10291	{
10292	  /* This is a full instantiation of a member template.  Find
10293	     the partial instantiation of which this is an instance.  */
10294
10295	  /* Temporarily reduce by one the number of levels in the ARGLIST
10296	     so as to avoid comparing the last set of arguments.  */
10297	  TREE_VEC_LENGTH (arglist)--;
10298	  /* We don't use COMPLAIN in the following call because this isn't
10299	     the immediate context of deduction.  For instance, tf_partial
10300	     could be set here as we might be at the beginning of template
10301	     argument deduction when any explicitly specified template
10302	     arguments are substituted into the function type.  tf_partial
10303	     could lead into trouble because we wouldn't find the partial
10304	     instantiation that might have been created outside tf_partial
10305	     context, because the levels of template parameters wouldn't
10306	     match, because in a tf_partial context, tsubst doesn't reduce
10307	     TEMPLATE_PARM_LEVEL.  */
10308	  found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10309	  TREE_VEC_LENGTH (arglist)++;
10310	  /* FOUND is either a proper class type, or an alias
10311	     template specialization.  In the later case, it's a
10312	     TYPE_DECL, resulting from the substituting of arguments
10313	     for parameters in the TYPE_DECL of the alias template
10314	     done earlier.  So be careful while getting the template
10315	     of FOUND.  */
10316	  found = (TREE_CODE (found) == TEMPLATE_DECL
10317		   ? found
10318		   : (TREE_CODE (found) == TYPE_DECL
10319		      ? DECL_TI_TEMPLATE (found)
10320		      : CLASSTYPE_TI_TEMPLATE (found)));
10321
10322	  if (DECL_CLASS_TEMPLATE_P (found)
10323	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10324	    {
10325	      /* If this partial instantiation is specialized, we want to
10326		 use it for hash table lookup.  */
10327	      elt.tmpl = found;
10328	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10329	      hash = spec_hasher::hash (&elt);
10330	    }
10331	}
10332
10333      /* Build template info for the new specialization.  */
10334      SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10335
10336      elt.spec = t;
10337      slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10338      gcc_checking_assert (*slot == NULL);
10339      entry = ggc_alloc<spec_entry> ();
10340      *entry = elt;
10341      *slot = entry;
10342
10343      /* Note this use of the partial instantiation so we can check it
10344	 later in maybe_process_partial_specialization.  */
10345      DECL_TEMPLATE_INSTANTIATIONS (found)
10346	= tree_cons (arglist, t,
10347		     DECL_TEMPLATE_INSTANTIATIONS (found));
10348
10349      if (TREE_CODE (template_type) == ENUMERAL_TYPE
10350	  && !uses_template_parms (current_nonlambda_scope ())
10351	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10352	/* Now that the type has been registered on the instantiations
10353	   list, we set up the enumerators.  Because the enumeration
10354	   constants may involve the enumeration type itself, we make
10355	   sure to register the type first, and then create the
10356	   constants.  That way, doing tsubst_expr for the enumeration
10357	   constants won't result in recursive calls here; we'll find
10358	   the instantiation and exit above.  */
10359	tsubst_enum (template_type, t, arglist);
10360
10361      if (CLASS_TYPE_P (template_type) && is_dependent_type)
10362	/* If the type makes use of template parameters, the
10363	   code that generates debugging information will crash.  */
10364	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10365
10366      /* Possibly limit visibility based on template args.  */
10367      TREE_PUBLIC (type_decl) = 1;
10368      determine_visibility (type_decl);
10369
10370      inherit_targ_abi_tags (t);
10371
10372      return t;
10373    }
10374}
10375
10376/* Wrapper for lookup_template_class_1.  */
10377
10378tree
10379lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10380                       int entering_scope, tsubst_flags_t complain)
10381{
10382  tree ret;
10383  timevar_push (TV_TEMPLATE_INST);
10384  ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10385                                 entering_scope, complain);
10386  timevar_pop (TV_TEMPLATE_INST);
10387  return ret;
10388}
10389
10390/* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10391
10392tree
10393lookup_template_variable (tree templ, tree arglist)
10394{
10395  if (flag_concepts && variable_concept_p (templ))
10396    return build_concept_check (templ, arglist, tf_none);
10397
10398  /* The type of the expression is NULL_TREE since the template-id could refer
10399     to an explicit or partial specialization. */
10400  return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10401}
10402
10403/* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10404
10405tree
10406finish_template_variable (tree var, tsubst_flags_t complain)
10407{
10408  tree templ = TREE_OPERAND (var, 0);
10409  tree arglist = TREE_OPERAND (var, 1);
10410
10411  tree parms = DECL_TEMPLATE_PARMS (templ);
10412  arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10413					     /*req_all*/true,
10414					     /*use_default*/true);
10415  if (arglist == error_mark_node)
10416    return error_mark_node;
10417
10418  if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10419    {
10420      if (complain & tf_error)
10421	{
10422	  auto_diagnostic_group d;
10423	  error ("use of invalid variable template %qE", var);
10424	  diagnose_constraints (location_of (var), templ, arglist);
10425	}
10426      return error_mark_node;
10427    }
10428
10429  return instantiate_template (templ, arglist, complain);
10430}
10431
10432/* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10433   TARGS template args, and instantiate it if it's not dependent.  */
10434
10435tree
10436lookup_and_finish_template_variable (tree templ, tree targs,
10437				     tsubst_flags_t complain)
10438{
10439  templ = lookup_template_variable (templ, targs);
10440  if (!any_dependent_template_arguments_p (targs))
10441    {
10442      /* We may be called while doing a partial substitution, but the
10443	 type of the variable template may be auto, in which case we
10444	 will call do_auto_deduction in mark_used (which clears tf_partial)
10445	 and the auto must be properly reduced at that time for the
10446	 deduction to work.  */
10447      complain &= ~tf_partial;
10448      templ = finish_template_variable (templ, complain);
10449      mark_used (templ);
10450    }
10451
10452  return convert_from_reference (templ);
10453}
10454
10455/* If the set of template parameters PARMS contains a template parameter
10456   at the given LEVEL and INDEX, then return this parameter.  Otherwise
10457   return NULL_TREE.  */
10458
10459static tree
10460corresponding_template_parameter (tree parms, int level, int index)
10461{
10462  while (TMPL_PARMS_DEPTH (parms) > level)
10463    parms = TREE_CHAIN (parms);
10464
10465  if (TMPL_PARMS_DEPTH (parms) != level
10466      || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10467    return NULL_TREE;
10468
10469  tree t = TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), index));
10470  /* As in template_parm_to_arg.  */
10471  if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10472    t = TREE_TYPE (t);
10473  else
10474    t = DECL_INITIAL (t);
10475
10476  gcc_assert (TEMPLATE_PARM_P (t));
10477  return t;
10478}
10479
10480/* Return the template parameter from PARMS that positionally corresponds
10481   to the template parameter PARM, or else return NULL_TREE.  */
10482
10483static tree
10484corresponding_template_parameter (tree parms, tree parm)
10485{
10486  int level, index;
10487  template_parm_level_and_index (parm, &level, &index);
10488  return corresponding_template_parameter (parms, level, index);
10489}
10490
10491
10492struct pair_fn_data
10493{
10494  tree_fn_t fn;
10495  tree_fn_t any_fn;
10496  void *data;
10497  /* True when we should also visit template parameters that occur in
10498     non-deduced contexts.  */
10499  bool include_nondeduced_p;
10500  hash_set<tree> *visited;
10501};
10502
10503/* Called from for_each_template_parm via walk_tree.  */
10504
10505static tree
10506for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10507{
10508  tree t = *tp;
10509  struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10510  tree_fn_t fn = pfd->fn;
10511  void *data = pfd->data;
10512  tree result = NULL_TREE;
10513
10514#define WALK_SUBTREE(NODE)						\
10515  do									\
10516    {									\
10517      result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
10518				       pfd->include_nondeduced_p,	\
10519				       pfd->any_fn);			\
10520      if (result) goto out;						\
10521    }									\
10522  while (0)
10523
10524  if (pfd->any_fn && (*pfd->any_fn)(t, data))
10525    return t;
10526
10527  if (TYPE_P (t)
10528      && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10529    WALK_SUBTREE (TYPE_CONTEXT (t));
10530
10531  switch (TREE_CODE (t))
10532    {
10533    case RECORD_TYPE:
10534      if (TYPE_PTRMEMFUNC_P (t))
10535	break;
10536      /* Fall through.  */
10537
10538    case UNION_TYPE:
10539    case ENUMERAL_TYPE:
10540      if (!TYPE_TEMPLATE_INFO (t))
10541	*walk_subtrees = 0;
10542      else
10543	WALK_SUBTREE (TYPE_TI_ARGS (t));
10544      break;
10545
10546    case INTEGER_TYPE:
10547      WALK_SUBTREE (TYPE_MIN_VALUE (t));
10548      WALK_SUBTREE (TYPE_MAX_VALUE (t));
10549      break;
10550
10551    case METHOD_TYPE:
10552      /* Since we're not going to walk subtrees, we have to do this
10553	 explicitly here.  */
10554      WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10555      /* Fall through.  */
10556
10557    case FUNCTION_TYPE:
10558      /* Check the return type.  */
10559      WALK_SUBTREE (TREE_TYPE (t));
10560
10561      /* Check the parameter types.  Since default arguments are not
10562	 instantiated until they are needed, the TYPE_ARG_TYPES may
10563	 contain expressions that involve template parameters.  But,
10564	 no-one should be looking at them yet.  And, once they're
10565	 instantiated, they don't contain template parameters, so
10566	 there's no point in looking at them then, either.  */
10567      {
10568	tree parm;
10569
10570	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10571	  WALK_SUBTREE (TREE_VALUE (parm));
10572
10573	/* Since we've already handled the TYPE_ARG_TYPES, we don't
10574	   want walk_tree walking into them itself.  */
10575	*walk_subtrees = 0;
10576      }
10577
10578      if (flag_noexcept_type)
10579	{
10580	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
10581	  if (spec)
10582	    WALK_SUBTREE (TREE_PURPOSE (spec));
10583	}
10584      break;
10585
10586    case TYPEOF_TYPE:
10587    case DECLTYPE_TYPE:
10588    case UNDERLYING_TYPE:
10589      if (pfd->include_nondeduced_p
10590	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10591				     pfd->visited,
10592				     pfd->include_nondeduced_p,
10593				     pfd->any_fn))
10594	return error_mark_node;
10595      *walk_subtrees = false;
10596      break;
10597
10598    case FUNCTION_DECL:
10599    case VAR_DECL:
10600      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10601	WALK_SUBTREE (DECL_TI_ARGS (t));
10602      /* Fall through.  */
10603
10604    case PARM_DECL:
10605    case CONST_DECL:
10606      if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10607	WALK_SUBTREE (DECL_INITIAL (t));
10608      if (DECL_CONTEXT (t)
10609	  && pfd->include_nondeduced_p)
10610	WALK_SUBTREE (DECL_CONTEXT (t));
10611      break;
10612
10613    case BOUND_TEMPLATE_TEMPLATE_PARM:
10614      /* Record template parameters such as `T' inside `TT<T>'.  */
10615      WALK_SUBTREE (TYPE_TI_ARGS (t));
10616      /* Fall through.  */
10617
10618    case TEMPLATE_TEMPLATE_PARM:
10619    case TEMPLATE_TYPE_PARM:
10620    case TEMPLATE_PARM_INDEX:
10621      if (fn && (*fn)(t, data))
10622	return t;
10623      else if (!fn)
10624	return t;
10625      break;
10626
10627    case TEMPLATE_DECL:
10628      /* A template template parameter is encountered.  */
10629      if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10630	WALK_SUBTREE (TREE_TYPE (t));
10631
10632      /* Already substituted template template parameter */
10633      *walk_subtrees = 0;
10634      break;
10635
10636    case TYPENAME_TYPE:
10637      /* A template-id in a TYPENAME_TYPE might be a deduced context after
10638	 partial instantiation.  */
10639      WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10640      *walk_subtrees = 0;
10641      break;
10642
10643    case INDIRECT_REF:
10644    case COMPONENT_REF:
10645      /* If there's no type, then this thing must be some expression
10646	 involving template parameters.  */
10647      if (!fn && !TREE_TYPE (t))
10648	return error_mark_node;
10649      break;
10650
10651    case CONSTRUCTOR:
10652    case TRAIT_EXPR:
10653    case PLUS_EXPR:
10654    case MULT_EXPR:
10655    case SCOPE_REF:
10656      /* These are non-deduced contexts.  */
10657      if (!pfd->include_nondeduced_p)
10658	*walk_subtrees = 0;
10659      break;
10660
10661    case MODOP_EXPR:
10662    case CAST_EXPR:
10663    case IMPLICIT_CONV_EXPR:
10664    case REINTERPRET_CAST_EXPR:
10665    case CONST_CAST_EXPR:
10666    case STATIC_CAST_EXPR:
10667    case DYNAMIC_CAST_EXPR:
10668    case ARROW_EXPR:
10669    case DOTSTAR_EXPR:
10670    case TYPEID_EXPR:
10671    case PSEUDO_DTOR_EXPR:
10672      if (!fn)
10673	return error_mark_node;
10674      break;
10675
10676    default:
10677      break;
10678    }
10679
10680  #undef WALK_SUBTREE
10681
10682  /* We didn't find any template parameters we liked.  */
10683 out:
10684  return result;
10685}
10686
10687/* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10688   BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10689   call FN with the parameter and the DATA.
10690   If FN returns nonzero, the iteration is terminated, and
10691   for_each_template_parm returns 1.  Otherwise, the iteration
10692   continues.  If FN never returns a nonzero value, the value
10693   returned by for_each_template_parm is 0.  If FN is NULL, it is
10694   considered to be the function which always returns 1.
10695
10696   If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10697   parameters that occur in non-deduced contexts.  When false, only
10698   visits those template parameters that can be deduced.  */
10699
10700static tree
10701for_each_template_parm (tree t, tree_fn_t fn, void* data,
10702			hash_set<tree> *visited,
10703			bool include_nondeduced_p,
10704			tree_fn_t any_fn)
10705{
10706  struct pair_fn_data pfd;
10707  tree result;
10708
10709  /* Set up.  */
10710  pfd.fn = fn;
10711  pfd.any_fn = any_fn;
10712  pfd.data = data;
10713  pfd.include_nondeduced_p = include_nondeduced_p;
10714
10715  /* Walk the tree.  (Conceptually, we would like to walk without
10716     duplicates, but for_each_template_parm_r recursively calls
10717     for_each_template_parm, so we would need to reorganize a fair
10718     bit to use walk_tree_without_duplicates, so we keep our own
10719     visited list.)  */
10720  if (visited)
10721    pfd.visited = visited;
10722  else
10723    pfd.visited = new hash_set<tree>;
10724  result = cp_walk_tree (&t,
10725		         for_each_template_parm_r,
10726		         &pfd,
10727		         pfd.visited);
10728
10729  /* Clean up.  */
10730  if (!visited)
10731    {
10732      delete pfd.visited;
10733      pfd.visited = 0;
10734    }
10735
10736  return result;
10737}
10738
10739struct find_template_parameter_info
10740{
10741  explicit find_template_parameter_info (tree ctx_parms)
10742    : parm_list (NULL_TREE),
10743      ctx_parms (ctx_parms),
10744      max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10745  {}
10746
10747  hash_set<tree> visited;
10748  hash_set<tree> parms;
10749  tree parm_list;
10750  tree ctx_parms;
10751  int max_depth;
10752};
10753
10754/* Appends the declaration of T to the list in DATA.  */
10755
10756static int
10757keep_template_parm (tree t, void* data)
10758{
10759  find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10760
10761  /* Template parameters declared within the expression are not part of
10762     the parameter mapping. For example, in this concept:
10763
10764       template<typename T>
10765       concept C = requires { <expr> } -> same_as<int>;
10766
10767     the return specifier same_as<int> declares a new decltype parameter
10768     that must not be part of the parameter mapping. The same is true
10769     for generic lambda parameters, lambda template parameters, etc.  */
10770  int level;
10771  int index;
10772  template_parm_level_and_index (t, &level, &index);
10773  if (level == 0 || level > ftpi->max_depth)
10774    return 0;
10775
10776  if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10777    /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10778       BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
10779    t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10780
10781  /* This template parameter might be an argument to a cached dependent
10782     specalization that was formed earlier inside some other template, in
10783     which case the parameter is not among the ones that are in-scope.
10784     Look in CTX_PARMS to find the corresponding in-scope template
10785     parameter, and use it instead.  */
10786  if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10787    t = in_scope;
10788
10789  /* Arguments like const T yield parameters like const T. This means that
10790     a template-id like X<T, const T> would yield two distinct parameters:
10791     T and const T. Adjust types to their unqualified versions.  */
10792  if (TYPE_P (t))
10793    t = TYPE_MAIN_VARIANT (t);
10794  if (!ftpi->parms.add (t))
10795    ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10796
10797  /* Verify the parameter we found has a valid index.  */
10798  if (flag_checking)
10799    {
10800      tree parms = ftpi->ctx_parms;
10801      while (TMPL_PARMS_DEPTH (parms) > level)
10802	parms = TREE_CHAIN (parms);
10803      if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10804	gcc_assert (index < len);
10805    }
10806
10807  return 0;
10808}
10809
10810/* Ensure that we recursively examine certain terms that are not normally
10811   visited in for_each_template_parm_r.  */
10812
10813static int
10814any_template_parm_r (tree t, void *data)
10815{
10816  find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10817
10818#define WALK_SUBTREE(NODE)						\
10819  do									\
10820    {									\
10821      for_each_template_parm (NODE, keep_template_parm, data,		\
10822			      &ftpi->visited, true,			\
10823			      any_template_parm_r);			\
10824    }									\
10825  while (0)
10826
10827  /* A mention of a member alias/typedef is a use of all of its template
10828     arguments, including those from the enclosing class, so we don't use
10829     alias_template_specialization_p here.  */
10830  if (TYPE_P (t) && typedef_variant_p (t))
10831    if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10832      WALK_SUBTREE (TI_ARGS (tinfo));
10833
10834  switch (TREE_CODE (t))
10835    {
10836    case TEMPLATE_TYPE_PARM:
10837      /* Type constraints of a placeholder type may contain parameters.  */
10838      if (is_auto (t))
10839	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10840	  WALK_SUBTREE (constr);
10841      break;
10842
10843    case TEMPLATE_ID_EXPR:
10844      /* Search through references to variable templates.  */
10845      WALK_SUBTREE (TREE_OPERAND (t, 0));
10846      WALK_SUBTREE (TREE_OPERAND (t, 1));
10847      break;
10848
10849    case TEMPLATE_PARM_INDEX:
10850    case PARM_DECL:
10851      /* A parameter or constraint variable may also depend on a template
10852	 parameter without explicitly naming it.  */
10853      WALK_SUBTREE (TREE_TYPE (t));
10854      break;
10855
10856    case TEMPLATE_DECL:
10857      /* If T is a member template that shares template parameters with
10858	 ctx_parms, we need to mark all those parameters for mapping.
10859	 To that end, it should suffice to just walk the DECL_CONTEXT of
10860	 the template (assuming the template is not overly general).  */
10861      WALK_SUBTREE (DECL_CONTEXT (t));
10862      break;
10863
10864    case LAMBDA_EXPR:
10865      {
10866	/* Look in the parms and body.  */
10867	tree fn = lambda_function (t);
10868	WALK_SUBTREE (TREE_TYPE (fn));
10869	WALK_SUBTREE (DECL_SAVED_TREE (fn));
10870      }
10871      break;
10872
10873    case IDENTIFIER_NODE:
10874      if (IDENTIFIER_CONV_OP_P (t))
10875	/* The conversion-type-id of a conversion operator may be dependent.  */
10876	WALK_SUBTREE (TREE_TYPE (t));
10877      break;
10878
10879    case CONVERT_EXPR:
10880      if (is_dummy_object (t))
10881	WALK_SUBTREE (TREE_TYPE (t));
10882      break;
10883
10884    default:
10885      break;
10886    }
10887
10888  /* Keep walking.  */
10889  return 0;
10890}
10891
10892/* Returns a list of unique template parameters found within T, where CTX_PARMS
10893   are the template parameters in scope.  */
10894
10895tree
10896find_template_parameters (tree t, tree ctx_parms)
10897{
10898  if (!ctx_parms)
10899    return NULL_TREE;
10900
10901  find_template_parameter_info ftpi (ctx_parms);
10902  for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10903			  /*include_nondeduced*/true, any_template_parm_r);
10904  return ftpi.parm_list;
10905}
10906
10907/* Returns true if T depends on any template parameter.  */
10908
10909int
10910uses_template_parms (tree t)
10911{
10912  if (t == NULL_TREE)
10913    return false;
10914
10915  bool dependent_p;
10916  int saved_processing_template_decl;
10917
10918  saved_processing_template_decl = processing_template_decl;
10919  if (!saved_processing_template_decl)
10920    processing_template_decl = 1;
10921  if (TYPE_P (t))
10922    dependent_p = dependent_type_p (t);
10923  else if (TREE_CODE (t) == TREE_VEC)
10924    dependent_p = any_dependent_template_arguments_p (t);
10925  else if (TREE_CODE (t) == TREE_LIST)
10926    dependent_p = (uses_template_parms (TREE_VALUE (t))
10927		   || uses_template_parms (TREE_CHAIN (t)));
10928  else if (TREE_CODE (t) == TYPE_DECL)
10929    dependent_p = dependent_type_p (TREE_TYPE (t));
10930  else if (t == error_mark_node || TREE_CODE (t) == NAMESPACE_DECL)
10931    dependent_p = false;
10932  else
10933    dependent_p = instantiation_dependent_expression_p (t);
10934
10935  processing_template_decl = saved_processing_template_decl;
10936
10937  return dependent_p;
10938}
10939
10940/* Returns true iff we're processing an incompletely instantiated function
10941   template.  Useful instead of processing_template_decl because the latter
10942   is set to 0 during instantiate_non_dependent_expr.  */
10943
10944bool
10945in_template_function (void)
10946{
10947  /* Inspect the less volatile cfun->decl instead of current_function_decl;
10948     the latter might get set for e.g. access checking during satisfaction.  */
10949  tree fn = cfun ? cfun->decl : NULL_TREE;
10950  bool ret;
10951  ++processing_template_decl;
10952  ret = (fn && DECL_LANG_SPECIFIC (fn)
10953	 && DECL_TEMPLATE_INFO (fn)
10954	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10955  --processing_template_decl;
10956  return ret;
10957}
10958
10959/* Returns true if T depends on any template parameter with level LEVEL.  */
10960
10961bool
10962uses_template_parms_level (tree t, int level)
10963{
10964  return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10965				 /*include_nondeduced_p=*/true);
10966}
10967
10968/* Returns true if the signature of DECL depends on any template parameter from
10969   its enclosing class.  */
10970
10971static bool
10972uses_outer_template_parms (tree decl)
10973{
10974  int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10975  if (depth == 0)
10976    return false;
10977  if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10978			      &depth, NULL, /*include_nondeduced_p=*/true))
10979    return true;
10980  if (PRIMARY_TEMPLATE_P (decl)
10981      || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10982    {
10983      tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10984      for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10985	{
10986	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10987	  tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10988	  if (TREE_CODE (parm) == PARM_DECL
10989	      && for_each_template_parm (TREE_TYPE (parm),
10990					 template_parm_outer_level,
10991					 &depth, NULL, /*nondeduced*/true))
10992	    return true;
10993	  if (TREE_CODE (parm) == TEMPLATE_DECL
10994	      && uses_outer_template_parms (parm))
10995	    return true;
10996	  if (defarg
10997	      && for_each_template_parm (defarg, template_parm_outer_level,
10998					 &depth, NULL, /*nondeduced*/true))
10999	    return true;
11000	}
11001    }
11002  if (uses_outer_template_parms_in_constraints (decl))
11003    return true;
11004  return false;
11005}
11006
11007/* Returns true if the constraints of DECL depend on any template parameters
11008   from its enclosing scope.  */
11009
11010bool
11011uses_outer_template_parms_in_constraints (tree decl)
11012{
11013  tree ci = get_constraints (decl);
11014  if (ci)
11015    ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11016  if (!ci)
11017    return false;
11018  int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11019  if (depth == 0)
11020    return false;
11021  return for_each_template_parm (ci, template_parm_outer_level,
11022				 &depth, NULL, /*nondeduced*/true);
11023}
11024
11025/* Returns TRUE iff INST is an instantiation we don't need to do in an
11026   ill-formed translation unit, i.e. a variable or function that isn't
11027   usable in a constant expression.  */
11028
11029static inline bool
11030neglectable_inst_p (tree d)
11031{
11032  return (d && DECL_P (d)
11033	  && !undeduced_auto_decl (d)
11034	  && !(TREE_CODE (d) == FUNCTION_DECL
11035	       ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11036	       : decl_maybe_constant_var_p (d)));
11037}
11038
11039/* Returns TRUE iff we should refuse to instantiate DECL because it's
11040   neglectable and instantiated from within an erroneous instantiation.  */
11041
11042static bool
11043limit_bad_template_recursion (tree decl)
11044{
11045  struct tinst_level *lev = current_tinst_level;
11046  int errs = errorcount + sorrycount;
11047  if (errs == 0 || !neglectable_inst_p (decl))
11048    return false;
11049
11050  /* Avoid instantiating members of an ill-formed class.  */
11051  bool refuse
11052    = (DECL_CLASS_SCOPE_P (decl)
11053       && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11054
11055  if (!refuse)
11056    {
11057      for (; lev; lev = lev->next)
11058	if (neglectable_inst_p (lev->maybe_get_node ()))
11059	  break;
11060      refuse = (lev && errs > lev->errors);
11061    }
11062
11063  if (refuse)
11064    {
11065      /* Don't warn about it not being defined.  */
11066      suppress_warning (decl, OPT_Wunused);
11067      tree clone;
11068      FOR_EACH_CLONE (clone, decl)
11069	suppress_warning (clone, OPT_Wunused);
11070    }
11071  return refuse;
11072}
11073
11074static int tinst_depth;
11075extern int max_tinst_depth;
11076int depth_reached;
11077
11078static GTY(()) struct tinst_level *last_error_tinst_level;
11079
11080/* We're starting to instantiate D; record the template instantiation context
11081   at LOC for diagnostics and to restore it later.  */
11082
11083bool
11084push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11085{
11086  struct tinst_level *new_level;
11087
11088  if (tinst_depth >= max_tinst_depth)
11089    {
11090      /* Tell error.cc not to try to instantiate any templates.  */
11091      at_eof = 2;
11092      fatal_error (input_location,
11093		   "template instantiation depth exceeds maximum of %d"
11094		   " (use %<-ftemplate-depth=%> to increase the maximum)",
11095                   max_tinst_depth);
11096      return false;
11097    }
11098
11099  /* If the current instantiation caused problems, don't let it instantiate
11100     anything else.  Do allow deduction substitution and decls usable in
11101     constant expressions.  */
11102  if (!targs && limit_bad_template_recursion (tldcl))
11103    {
11104      /* Avoid no_linkage_errors and unused function (and all other)
11105	 warnings for this decl.  */
11106      suppress_warning (tldcl);
11107      return false;
11108    }
11109
11110  /* When not -quiet, dump template instantiations other than functions, since
11111     announce_function will take care of those.  */
11112  if (!quiet_flag && !targs
11113      && TREE_CODE (tldcl) != TREE_LIST
11114      && TREE_CODE (tldcl) != FUNCTION_DECL)
11115    fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11116
11117  new_level = tinst_level_freelist ().alloc ();
11118  new_level->tldcl = tldcl;
11119  new_level->targs = targs;
11120  new_level->locus = loc;
11121  new_level->errors = errorcount + sorrycount;
11122  new_level->next = NULL;
11123  new_level->refcount = 0;
11124  new_level->path = new_level->visible = nullptr;
11125  set_refcount_ptr (new_level->next, current_tinst_level);
11126  set_refcount_ptr (current_tinst_level, new_level);
11127
11128  ++tinst_depth;
11129  if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11130    depth_reached = tinst_depth;
11131
11132  return true;
11133}
11134
11135/* We're starting substitution of TMPL<ARGS>; record the template
11136   substitution context for diagnostics and to restore it later.  */
11137
11138bool
11139push_tinst_level (tree tmpl, tree args)
11140{
11141  return push_tinst_level_loc (tmpl, args, input_location);
11142}
11143
11144/* We're starting to instantiate D; record INPUT_LOCATION and the
11145   template instantiation context for diagnostics and to restore it
11146   later.  */
11147
11148bool
11149push_tinst_level (tree d)
11150{
11151  return push_tinst_level_loc (d, input_location);
11152}
11153
11154/* Likewise, but record LOC as the program location.  */
11155
11156bool
11157push_tinst_level_loc (tree d, location_t loc)
11158{
11159  gcc_assert (TREE_CODE (d) != TREE_LIST);
11160  return push_tinst_level_loc (d, NULL, loc);
11161}
11162
11163/* We're done instantiating this template; return to the instantiation
11164   context.  */
11165
11166void
11167pop_tinst_level (void)
11168{
11169  /* Restore the filename and line number stashed away when we started
11170     this instantiation.  */
11171  input_location = current_tinst_level->locus;
11172  set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11173  --tinst_depth;
11174}
11175
11176/* We're instantiating a deferred template; restore the template
11177   instantiation context in which the instantiation was requested, which
11178   is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
11179
11180static tree
11181reopen_tinst_level (struct tinst_level *level)
11182{
11183  struct tinst_level *t;
11184
11185  tinst_depth = 0;
11186  for (t = level; t; t = t->next)
11187    ++tinst_depth;
11188
11189  set_refcount_ptr (current_tinst_level, level);
11190  pop_tinst_level ();
11191  if (current_tinst_level)
11192    current_tinst_level->errors = errorcount+sorrycount;
11193  return level->maybe_get_node ();
11194}
11195
11196/* Returns the TINST_LEVEL which gives the original instantiation
11197   context.  */
11198
11199struct tinst_level *
11200outermost_tinst_level (void)
11201{
11202  struct tinst_level *level = current_tinst_level;
11203  if (level)
11204    while (level->next)
11205      level = level->next;
11206  return level;
11207}
11208
11209/* True iff T is a friend function declaration that is not itself a template
11210   and is not defined in a class template.  */
11211
11212bool
11213non_templated_friend_p (tree t)
11214{
11215  if (t && TREE_CODE (t) == FUNCTION_DECL
11216      && DECL_UNIQUE_FRIEND_P (t))
11217    {
11218      tree ti = DECL_TEMPLATE_INFO (t);
11219      if (!ti)
11220	return true;
11221      /* DECL_FRIEND_CONTEXT is set for a friend defined in class.  */
11222      if (DECL_FRIEND_CONTEXT (t))
11223	return false;
11224      /* Non-templated friends in a class template are still represented with a
11225	 TEMPLATE_DECL; check that its primary template is the befriending
11226	 class.  Note that DECL_PRIMARY_TEMPLATE is null for
11227	 template <class T> friend A<T>::f(); */
11228      tree tmpl = TI_TEMPLATE (ti);
11229      tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11230      return (primary && primary != tmpl);
11231    }
11232  else
11233    return false;
11234}
11235
11236/* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
11237   vector of template arguments, as for tsubst.
11238
11239   Returns an appropriate tsubst'd friend declaration.  */
11240
11241static tree
11242tsubst_friend_function (tree decl, tree args)
11243{
11244  tree new_friend;
11245
11246  if (TREE_CODE (decl) == FUNCTION_DECL
11247      && DECL_TEMPLATE_INSTANTIATION (decl)
11248      && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11249    /* This was a friend declared with an explicit template
11250       argument list, e.g.:
11251
11252       friend void f<>(T);
11253
11254       to indicate that f was a template instantiation, not a new
11255       function declaration.  Now, we have to figure out what
11256       instantiation of what template.  */
11257    {
11258      tree template_id, arglist, fns;
11259      tree new_args;
11260      tree tmpl;
11261      tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11262
11263      /* Friend functions are looked up in the containing namespace scope.
11264	 We must enter that scope, to avoid finding member functions of the
11265	 current class with same name.  */
11266      push_nested_namespace (ns);
11267      fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11268			 tf_warning_or_error, NULL_TREE,
11269			 /*integral_constant_expression_p=*/false);
11270      pop_nested_namespace (ns);
11271      arglist = tsubst (DECL_TI_ARGS (decl), args,
11272			tf_warning_or_error, NULL_TREE);
11273      template_id = lookup_template_function (fns, arglist);
11274
11275      new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11276      tmpl = determine_specialization (template_id, new_friend,
11277				       &new_args,
11278				       /*need_member_template=*/0,
11279				       TREE_VEC_LENGTH (args),
11280				       tsk_none);
11281      return instantiate_template (tmpl, new_args, tf_error);
11282    }
11283
11284  new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11285  if (new_friend == error_mark_node)
11286    return error_mark_node;
11287
11288  /* The NEW_FRIEND will look like an instantiation, to the
11289     compiler, but is not an instantiation from the point of view of
11290     the language.  For example, we might have had:
11291
11292     template <class T> struct S {
11293       template <class U> friend void f(T, U);
11294     };
11295
11296     Then, in S<int>, template <class U> void f(int, U) is not an
11297     instantiation of anything.  */
11298
11299  DECL_USE_TEMPLATE (new_friend) = 0;
11300  if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11301    {
11302      DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11303      DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11304      DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11305	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11306
11307      /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11308	 match in decls_match.  */
11309      tree parms = DECL_TEMPLATE_PARMS (new_friend);
11310      tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11311      treqs = maybe_substitute_reqs_for (treqs, new_friend);
11312      if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11313	{
11314	  TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11315	  /* As well as each TEMPLATE_PARM_CONSTRAINTS.  */
11316	  tsubst_each_template_parm_constraints (parms, args,
11317						 tf_warning_or_error);
11318	}
11319    }
11320
11321  /* The mangled name for the NEW_FRIEND is incorrect.  The function
11322     is not a template instantiation and should not be mangled like
11323     one.  Therefore, we forget the mangling here; we'll recompute it
11324     later if we need it.  */
11325  if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11326    {
11327      SET_DECL_RTL (new_friend, NULL);
11328      SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11329    }
11330
11331  if (DECL_NAMESPACE_SCOPE_P (new_friend))
11332    {
11333      tree old_decl;
11334      tree ns;
11335
11336      /* We must save some information from NEW_FRIEND before calling
11337	 duplicate decls since that function will free NEW_FRIEND if
11338	 possible.  */
11339      tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11340      tree new_friend_result_template_info = NULL_TREE;
11341      bool new_friend_is_defn =
11342	(DECL_INITIAL (DECL_TEMPLATE_RESULT
11343		       (template_for_substitution (new_friend)))
11344	 != NULL_TREE);
11345      tree not_tmpl = new_friend;
11346
11347      if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11348	{
11349	  /* This declaration is a `primary' template.  */
11350	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11351
11352	  not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11353	  new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11354	}
11355
11356      /* Inside pushdecl_namespace_level, we will push into the
11357	 current namespace. However, the friend function should go
11358	 into the namespace of the template.  */
11359      ns = decl_namespace_context (new_friend);
11360      push_nested_namespace (ns);
11361      old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11362      pop_nested_namespace (ns);
11363
11364      if (old_decl == error_mark_node)
11365	return error_mark_node;
11366
11367      if (old_decl != new_friend)
11368	{
11369	  /* This new friend declaration matched an existing
11370	     declaration.  For example, given:
11371
11372	       template <class T> void f(T);
11373	       template <class U> class C {
11374		 template <class T> friend void f(T) {}
11375	       };
11376
11377	     the friend declaration actually provides the definition
11378	     of `f', once C has been instantiated for some type.  So,
11379	     old_decl will be the out-of-class template declaration,
11380	     while new_friend is the in-class definition.
11381
11382	     But, if `f' was called before this point, the
11383	     instantiation of `f' will have DECL_TI_ARGS corresponding
11384	     to `T' but not to `U', references to which might appear
11385	     in the definition of `f'.  Previously, the most general
11386	     template for an instantiation of `f' was the out-of-class
11387	     version; now it is the in-class version.  Therefore, we
11388	     run through all specialization of `f', adding to their
11389	     DECL_TI_ARGS appropriately.  In particular, they need a
11390	     new set of outer arguments, corresponding to the
11391	     arguments for this class instantiation.
11392
11393	     The same situation can arise with something like this:
11394
11395	       friend void f(int);
11396	       template <class T> class C {
11397		 friend void f(T) {}
11398	       };
11399
11400	     when `C<int>' is instantiated.  Now, `f(int)' is defined
11401	     in the class.  */
11402
11403	  if (!new_friend_is_defn)
11404	    /* On the other hand, if the in-class declaration does
11405	       *not* provide a definition, then we don't want to alter
11406	       existing definitions.  We can just leave everything
11407	       alone.  */
11408	    ;
11409	  else
11410	    {
11411	      tree new_template = TI_TEMPLATE (new_friend_template_info);
11412	      tree new_args = TI_ARGS (new_friend_template_info);
11413
11414	      /* Overwrite whatever template info was there before, if
11415		 any, with the new template information pertaining to
11416		 the declaration.  */
11417	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11418
11419	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11420		{
11421		  /* We should have called reregister_specialization in
11422		     duplicate_decls.  */
11423		  gcc_assert (retrieve_specialization (new_template,
11424						       new_args, 0)
11425			      == old_decl);
11426
11427		  /* Instantiate it if the global has already been used.  */
11428		  if (DECL_ODR_USED (old_decl))
11429		    instantiate_decl (old_decl, /*defer_ok=*/true,
11430				      /*expl_inst_class_mem_p=*/false);
11431		}
11432	      else
11433		{
11434		  tree t;
11435
11436		  /* Indicate that the old function template is a partial
11437		     instantiation.  */
11438		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11439		    = new_friend_result_template_info;
11440
11441		  gcc_assert (new_template
11442			      == most_general_template (new_template));
11443		  gcc_assert (new_template != old_decl);
11444
11445		  /* Reassign any specializations already in the hash table
11446		     to the new more general template, and add the
11447		     additional template args.  */
11448		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11449		       t != NULL_TREE;
11450		       t = TREE_CHAIN (t))
11451		    {
11452		      tree spec = TREE_VALUE (t);
11453		      spec_entry elt;
11454
11455		      elt.tmpl = old_decl;
11456		      elt.args = DECL_TI_ARGS (spec);
11457		      elt.spec = NULL_TREE;
11458
11459		      decl_specializations->remove_elt (&elt);
11460
11461		      DECL_TI_ARGS (spec)
11462			= add_outermost_template_args (new_args,
11463						       DECL_TI_ARGS (spec));
11464
11465		      register_specialization
11466			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
11467
11468		    }
11469		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11470		}
11471	    }
11472
11473	  /* The information from NEW_FRIEND has been merged into OLD_DECL
11474	     by duplicate_decls.  */
11475	  new_friend = old_decl;
11476	}
11477    }
11478  else
11479    {
11480      tree context = DECL_CONTEXT (new_friend);
11481      bool dependent_p;
11482
11483      /* In the code
11484	   template <class T> class C {
11485	     template <class U> friend void C1<U>::f (); // case 1
11486	     friend void C2<T>::f ();			 // case 2
11487	   };
11488	 we only need to make sure CONTEXT is a complete type for
11489	 case 2.  To distinguish between the two cases, we note that
11490	 CONTEXT of case 1 remains dependent type after tsubst while
11491	 this isn't true for case 2.  */
11492      ++processing_template_decl;
11493      dependent_p = dependent_type_p (context);
11494      --processing_template_decl;
11495
11496      if (!dependent_p
11497	  && !complete_type_or_else (context, NULL_TREE))
11498	return error_mark_node;
11499
11500      if (COMPLETE_TYPE_P (context))
11501	{
11502	  tree fn = new_friend;
11503	  /* do_friend adds the TEMPLATE_DECL for any member friend
11504	     template even if it isn't a member template, i.e.
11505	       template <class T> friend A<T>::f();
11506	     Look through it in that case.  */
11507	  if (TREE_CODE (fn) == TEMPLATE_DECL
11508	      && !PRIMARY_TEMPLATE_P (fn))
11509	    fn = DECL_TEMPLATE_RESULT (fn);
11510	  /* Check to see that the declaration is really present, and,
11511	     possibly obtain an improved declaration.  */
11512	  fn = check_classfn (context, fn, NULL_TREE);
11513
11514	  if (fn)
11515	    new_friend = fn;
11516	}
11517    }
11518
11519  return new_friend;
11520}
11521
11522/* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11523   template arguments, as for tsubst.
11524
11525   Returns an appropriate tsubst'd friend type or error_mark_node on
11526   failure.  */
11527
11528static tree
11529tsubst_friend_class (tree friend_tmpl, tree args)
11530{
11531  tree tmpl;
11532
11533  if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11534    {
11535      tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11536      return TREE_TYPE (tmpl);
11537    }
11538
11539  tree context = CP_DECL_CONTEXT (friend_tmpl);
11540  if (TREE_CODE (context) == NAMESPACE_DECL)
11541    push_nested_namespace (context);
11542  else
11543    {
11544      context = tsubst (context, args, tf_error, NULL_TREE);
11545      push_nested_class (context);
11546    }
11547
11548  tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11549		      LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11550
11551  if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11552    {
11553      /* The friend template has already been declared.  Just
11554	 check to see that the declarations match, and install any new
11555	 default parameters.  We must tsubst the default parameters,
11556	 of course.  We only need the innermost template parameters
11557	 because that is all that redeclare_class_template will look
11558	 at.  */
11559      if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11560	  > TMPL_ARGS_DEPTH (args))
11561	{
11562	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11563					      args, tf_warning_or_error);
11564	  tsubst_each_template_parm_constraints (parms, args,
11565						 tf_warning_or_error);
11566          location_t saved_input_location = input_location;
11567          input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11568          tree cons = get_constraints (tmpl);
11569          redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11570          input_location = saved_input_location;
11571	}
11572    }
11573  else
11574    {
11575      /* The friend template has not already been declared.  In this
11576	 case, the instantiation of the template class will cause the
11577	 injection of this template into the namespace scope.  */
11578      tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11579
11580      if (tmpl != error_mark_node)
11581	{
11582	  /* The new TMPL is not an instantiation of anything, so we
11583	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11584	     for the new type because that is supposed to be the
11585	     corresponding template decl, i.e., TMPL.  */
11586	  DECL_USE_TEMPLATE (tmpl) = 0;
11587	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11588	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11589	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11590	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11591
11592	  /* Substitute into and set the constraints on the new declaration.  */
11593	  if (tree ci = get_constraints (friend_tmpl))
11594	    {
11595	      ++processing_template_decl;
11596	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11597					   DECL_FRIEND_CONTEXT (friend_tmpl));
11598	      --processing_template_decl;
11599	      set_constraints (tmpl, ci);
11600	      tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11601						     args, tf_warning_or_error);
11602	    }
11603
11604	  /* Inject this template into the enclosing namspace scope.  */
11605	  tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11606	}
11607    }
11608
11609  if (TREE_CODE (context) == NAMESPACE_DECL)
11610    pop_nested_namespace (context);
11611  else
11612    pop_nested_class ();
11613
11614  return TREE_TYPE (tmpl);
11615}
11616
11617/* Returns zero if TYPE cannot be completed later due to circularity.
11618   Otherwise returns one.  */
11619
11620static int
11621can_complete_type_without_circularity (tree type)
11622{
11623  if (type == NULL_TREE || type == error_mark_node)
11624    return 0;
11625  else if (COMPLETE_TYPE_P (type))
11626    return 1;
11627  else if (TREE_CODE (type) == ARRAY_TYPE)
11628    return can_complete_type_without_circularity (TREE_TYPE (type));
11629  else if (CLASS_TYPE_P (type)
11630	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11631    return 0;
11632  else
11633    return 1;
11634}
11635
11636static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11637				tsubst_flags_t, tree);
11638
11639/* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11640   T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11641
11642static tree
11643tsubst_attribute (tree t, tree *decl_p, tree args,
11644		  tsubst_flags_t complain, tree in_decl)
11645{
11646  gcc_assert (ATTR_IS_DEPENDENT (t));
11647
11648  tree val = TREE_VALUE (t);
11649  if (val == NULL_TREE)
11650    /* Nothing to do.  */;
11651  else if ((flag_openmp || flag_openmp_simd)
11652	   && is_attribute_p ("omp declare simd",
11653			      get_attribute_name (t)))
11654    {
11655      tree clauses = TREE_VALUE (val);
11656      clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11657				    complain, in_decl);
11658      c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11659      clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11660      tree parms = DECL_ARGUMENTS (*decl_p);
11661      clauses
11662	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11663      if (clauses)
11664	val = build_tree_list (NULL_TREE, clauses);
11665      else
11666	val = NULL_TREE;
11667    }
11668  else if (flag_openmp
11669	   && is_attribute_p ("omp declare variant base",
11670			      get_attribute_name (t)))
11671    {
11672      ++cp_unevaluated_operand;
11673      tree varid
11674	= tsubst_expr (TREE_PURPOSE (val), args, complain,
11675		       in_decl, /*integral_constant_expression_p=*/false);
11676      --cp_unevaluated_operand;
11677      tree chain = TREE_CHAIN (val);
11678      location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11679      tree ctx = copy_list (TREE_VALUE (val));
11680      tree simd = get_identifier ("simd");
11681      tree score = get_identifier (" score");
11682      tree condition = get_identifier ("condition");
11683      for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11684	{
11685	  const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11686	  TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11687	  for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11688	    {
11689	      if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11690		{
11691		  tree clauses = TREE_VALUE (t2);
11692		  clauses = tsubst_omp_clauses (clauses,
11693						C_ORT_OMP_DECLARE_SIMD, args,
11694						complain, in_decl);
11695		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11696		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11697		  TREE_VALUE (t2) = clauses;
11698		}
11699	      else
11700		{
11701		  TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11702		  for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11703		    if (TREE_VALUE (t3))
11704		      {
11705			bool allow_string
11706			  = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11707			     && TREE_PURPOSE (t3) != score);
11708			tree v = TREE_VALUE (t3);
11709			if (TREE_CODE (v) == STRING_CST && allow_string)
11710			  continue;
11711			v = tsubst_expr (v, args, complain, in_decl, true);
11712			v = fold_non_dependent_expr (v);
11713			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11714			    || (TREE_PURPOSE (t3) == score
11715				? TREE_CODE (v) != INTEGER_CST
11716				: !tree_fits_shwi_p (v)))
11717			  {
11718			    location_t loc
11719			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11720						    match_loc);
11721			    if (TREE_PURPOSE (t3) == score)
11722			      error_at (loc, "score argument must be "
11723					     "constant integer expression");
11724			    else if (allow_string)
11725			      error_at (loc, "property must be constant "
11726					     "integer expression or string "
11727					     "literal");
11728			    else
11729			      error_at (loc, "property must be constant "
11730					     "integer expression");
11731			    return NULL_TREE;
11732			  }
11733			else if (TREE_PURPOSE (t3) == score
11734				 && tree_int_cst_sgn (v) < 0)
11735			  {
11736			    location_t loc
11737			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11738						    match_loc);
11739			    error_at (loc, "score argument must be "
11740					   "non-negative");
11741			    return NULL_TREE;
11742			  }
11743			TREE_VALUE (t3) = v;
11744		      }
11745		}
11746	    }
11747	}
11748      val = tree_cons (varid, ctx, chain);
11749    }
11750  /* If the first attribute argument is an identifier, don't
11751     pass it through tsubst.  Attributes like mode, format,
11752     cleanup and several target specific attributes expect it
11753     unmodified.  */
11754  else if (attribute_takes_identifier_p (get_attribute_name (t)))
11755    {
11756      tree chain
11757	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11758		       /*integral_constant_expression_p=*/false);
11759      if (chain != TREE_CHAIN (val))
11760	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11761    }
11762  else if (PACK_EXPANSION_P (val))
11763    {
11764      /* An attribute pack expansion.  */
11765      tree purp = TREE_PURPOSE (t);
11766      tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11767      if (pack == error_mark_node)
11768	return error_mark_node;
11769      int len = TREE_VEC_LENGTH (pack);
11770      tree list = NULL_TREE;
11771      tree *q = &list;
11772      for (int i = 0; i < len; ++i)
11773	{
11774	  tree elt = TREE_VEC_ELT (pack, i);
11775	  *q = build_tree_list (purp, elt);
11776	  q = &TREE_CHAIN (*q);
11777	}
11778      return list;
11779    }
11780  else
11781    val = tsubst_expr (val, args, complain, in_decl,
11782		       /*integral_constant_expression_p=*/false);
11783
11784  if (val == error_mark_node)
11785    return error_mark_node;
11786  if (val != TREE_VALUE (t))
11787    return build_tree_list (TREE_PURPOSE (t), val);
11788  return t;
11789}
11790
11791/* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11792   unchanged or a new TREE_LIST chain.  */
11793
11794static tree
11795tsubst_attributes (tree attributes, tree args,
11796		   tsubst_flags_t complain, tree in_decl)
11797{
11798  tree last_dep = NULL_TREE;
11799
11800  for (tree t = attributes; t; t = TREE_CHAIN (t))
11801    if (ATTR_IS_DEPENDENT (t))
11802      {
11803	last_dep = t;
11804	attributes = copy_list (attributes);
11805	break;
11806      }
11807
11808  if (last_dep)
11809    for (tree *p = &attributes; *p; )
11810      {
11811	tree t = *p;
11812	if (ATTR_IS_DEPENDENT (t))
11813	  {
11814	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11815	    if (subst != t)
11816	      {
11817		*p = subst;
11818		while (*p)
11819		  p = &TREE_CHAIN (*p);
11820		*p = TREE_CHAIN (t);
11821		continue;
11822	      }
11823	  }
11824	p = &TREE_CHAIN (*p);
11825      }
11826
11827  return attributes;
11828}
11829
11830/* Apply any attributes which had to be deferred until instantiation
11831   time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11832   ARGS, COMPLAIN, IN_DECL are as tsubst.  Returns true normally,
11833   false on error.  */
11834
11835static bool
11836apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11837				tree args, tsubst_flags_t complain, tree in_decl)
11838{
11839  tree t;
11840  tree *p;
11841
11842  if (attributes == NULL_TREE)
11843    return true;
11844
11845  if (DECL_P (*decl_p))
11846    {
11847      if (TREE_TYPE (*decl_p) == error_mark_node)
11848	return false;
11849      p = &DECL_ATTRIBUTES (*decl_p);
11850      /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11851         to our attributes parameter.  */
11852      gcc_assert (*p == attributes);
11853    }
11854  else
11855    {
11856      p = &TYPE_ATTRIBUTES (*decl_p);
11857      /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11858	 lookup_template_class_1, and should be preserved.  */
11859      gcc_assert (*p != attributes);
11860      while (*p)
11861	p = &TREE_CHAIN (*p);
11862    }
11863
11864  /* save_template_attributes puts the dependent attributes at the beginning of
11865     the list; find the non-dependent ones.  */
11866  for (t = attributes; t; t = TREE_CHAIN (t))
11867    if (!ATTR_IS_DEPENDENT (t))
11868      break;
11869  tree nondep = t;
11870
11871  /* Apply any non-dependent attributes.  */
11872  *p = nondep;
11873
11874  if (nondep == attributes)
11875    return true;
11876
11877  /* And then any dependent ones.  */
11878  tree late_attrs = NULL_TREE;
11879  tree *q = &late_attrs;
11880  for (t = attributes; t != nondep; t = TREE_CHAIN (t))
11881    {
11882      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11883      if (*q == error_mark_node)
11884	return false;
11885      if (*q == t)
11886	{
11887	  *q = copy_node (t);
11888	  TREE_CHAIN (*q) = NULL_TREE;
11889	}
11890      while (*q)
11891	q = &TREE_CHAIN (*q);
11892    }
11893
11894  /* cplus_decl_attributes can add some attributes implicitly.  For templates,
11895     those attributes should have been added already when those templates were
11896     parsed, and shouldn't be added based on from which context they are
11897     first time instantiated.  */
11898  auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
11899  auto o2 = make_temp_override (optimization_current_node,
11900				optimization_default_node);
11901  auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
11902  auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
11903				NULL);
11904
11905  cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11906
11907  return true;
11908}
11909
11910/* The template TMPL is being instantiated with the template arguments TARGS.
11911   Perform the access checks that we deferred when parsing the template.  */
11912
11913static void
11914perform_instantiation_time_access_checks (tree tmpl, tree targs)
11915{
11916  unsigned i;
11917  deferred_access_check *chk;
11918
11919  if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
11920    return;
11921
11922  if (vec<deferred_access_check, va_gc> *access_checks
11923      = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
11924    FOR_EACH_VEC_ELT (*access_checks, i, chk)
11925      {
11926	tree decl = chk->decl;
11927	tree diag_decl = chk->diag_decl;
11928	tree type_scope = TREE_TYPE (chk->binfo);
11929
11930	if (uses_template_parms (type_scope))
11931	  type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11932
11933	/* Make access check error messages point to the location
11934	   of the use of the typedef.  */
11935	iloc_sentinel ils (chk->loc);
11936	perform_or_defer_access_check (TYPE_BINFO (type_scope),
11937				       decl, diag_decl, tf_warning_or_error);
11938      }
11939}
11940
11941static tree
11942instantiate_class_template_1 (tree type)
11943{
11944  tree templ, args, pattern, t, member;
11945  tree typedecl;
11946  tree pbinfo;
11947  tree base_list;
11948  unsigned int saved_maximum_field_alignment;
11949  tree fn_context;
11950
11951  if (type == error_mark_node)
11952    return error_mark_node;
11953
11954  if (COMPLETE_OR_OPEN_TYPE_P (type)
11955      || uses_template_parms (type))
11956    return type;
11957
11958  /* Figure out which template is being instantiated.  */
11959  templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11960  gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11961
11962  /* Mark the type as in the process of being defined.  */
11963  TYPE_BEING_DEFINED (type) = 1;
11964
11965  /* We may be in the middle of deferred access check.  Disable
11966     it now.  */
11967  deferring_access_check_sentinel acs (dk_no_deferred);
11968
11969  /* Determine what specialization of the original template to
11970     instantiate.  */
11971  t = most_specialized_partial_spec (type, tf_warning_or_error);
11972  if (t == error_mark_node)
11973    return error_mark_node;
11974  else if (t)
11975    {
11976      /* This TYPE is actually an instantiation of a partial
11977	 specialization.  We replace the innermost set of ARGS with
11978	 the arguments appropriate for substitution.  For example,
11979	 given:
11980
11981	   template <class T> struct S {};
11982	   template <class T> struct S<T*> {};
11983
11984	 and supposing that we are instantiating S<int*>, ARGS will
11985	 presently be {int*} -- but we need {int}.  */
11986      pattern = TREE_TYPE (t);
11987      args = TREE_PURPOSE (t);
11988    }
11989  else
11990    {
11991      pattern = TREE_TYPE (templ);
11992      args = CLASSTYPE_TI_ARGS (type);
11993    }
11994
11995  /* If the template we're instantiating is incomplete, then clearly
11996     there's nothing we can do.  */
11997  if (!COMPLETE_TYPE_P (pattern))
11998    {
11999      /* We can try again later.  */
12000      TYPE_BEING_DEFINED (type) = 0;
12001      return type;
12002    }
12003
12004  /* If we've recursively instantiated too many templates, stop.  */
12005  if (! push_tinst_level (type))
12006    return type;
12007
12008  int saved_unevaluated_operand = cp_unevaluated_operand;
12009  int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12010
12011  fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12012  /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
12013  if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12014    fn_context = error_mark_node;
12015  if (!fn_context)
12016    push_to_top_level ();
12017  else
12018    {
12019      cp_unevaluated_operand = 0;
12020      c_inhibit_evaluation_warnings = 0;
12021    }
12022  /* Use #pragma pack from the template context.  */
12023  saved_maximum_field_alignment = maximum_field_alignment;
12024  maximum_field_alignment = TYPE_PRECISION (pattern);
12025
12026  SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12027
12028  /* Set the input location to the most specialized template definition.
12029     This is needed if tsubsting causes an error.  */
12030  typedecl = TYPE_MAIN_DECL (pattern);
12031  input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12032    DECL_SOURCE_LOCATION (typedecl);
12033
12034  set_instantiating_module (TYPE_NAME (type));
12035
12036  TYPE_PACKED (type) = TYPE_PACKED (pattern);
12037  SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12038  TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12039  CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12040  if (ANON_AGGR_TYPE_P (pattern))
12041    SET_ANON_AGGR_TYPE_P (type);
12042  if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12043    {
12044      CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12045      CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12046      /* Adjust visibility for template arguments.  */
12047      determine_visibility (TYPE_MAIN_DECL (type));
12048    }
12049  if (CLASS_TYPE_P (type))
12050    CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12051
12052  pbinfo = TYPE_BINFO (pattern);
12053
12054  /* We should never instantiate a nested class before its enclosing
12055     class; we need to look up the nested class by name before we can
12056     instantiate it, and that lookup should instantiate the enclosing
12057     class.  */
12058  gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12059	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12060
12061  base_list = NULL_TREE;
12062  /* Defer access checking while we substitute into the types named in
12063     the base-clause.  */
12064  push_deferring_access_checks (dk_deferred);
12065  if (BINFO_N_BASE_BINFOS (pbinfo))
12066    {
12067      tree pbase_binfo;
12068      int i;
12069
12070      /* Substitute into each of the bases to determine the actual
12071	 basetypes.  */
12072      for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12073	{
12074	  tree base;
12075	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
12076          tree expanded_bases = NULL_TREE;
12077          int idx, len = 1;
12078
12079          if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12080            {
12081              expanded_bases =
12082		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12083				       args, tf_error, NULL_TREE);
12084              if (expanded_bases == error_mark_node)
12085                continue;
12086
12087              len = TREE_VEC_LENGTH (expanded_bases);
12088            }
12089
12090          for (idx = 0; idx < len; idx++)
12091            {
12092              if (expanded_bases)
12093                /* Extract the already-expanded base class.  */
12094                base = TREE_VEC_ELT (expanded_bases, idx);
12095              else
12096                /* Substitute to figure out the base class.  */
12097                base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12098                               NULL_TREE);
12099
12100              if (base == error_mark_node)
12101                continue;
12102
12103              base_list = tree_cons (access, base, base_list);
12104              if (BINFO_VIRTUAL_P (pbase_binfo))
12105                TREE_TYPE (base_list) = integer_type_node;
12106            }
12107	}
12108
12109      /* The list is now in reverse order; correct that.  */
12110      base_list = nreverse (base_list);
12111    }
12112  /* Now call xref_basetypes to set up all the base-class
12113     information.  */
12114  xref_basetypes (type, base_list);
12115
12116  apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12117				  (int) ATTR_FLAG_TYPE_IN_PLACE,
12118				  args, tf_error, NULL_TREE);
12119  fixup_attribute_variants (type);
12120
12121  /* Now that our base classes are set up, enter the scope of the
12122     class, so that name lookups into base classes, etc. will work
12123     correctly.  This is precisely analogous to what we do in
12124     begin_class_definition when defining an ordinary non-template
12125     class, except we also need to push the enclosing classes.  */
12126  push_nested_class (type);
12127
12128  /* Now check accessibility of the types named in its base-clause,
12129     relative to the scope of the class.  */
12130  pop_to_parent_deferring_access_checks ();
12131
12132  /* A vector to hold members marked with attribute used. */
12133  auto_vec<tree> used;
12134
12135  /* Now members are processed in the order of declaration.  */
12136  for (member = CLASSTYPE_DECL_LIST (pattern);
12137       member; member = TREE_CHAIN (member))
12138    {
12139      tree t = TREE_VALUE (member);
12140
12141      if (TREE_PURPOSE (member))
12142	{
12143	  if (TYPE_P (t))
12144	    {
12145	      if (LAMBDA_TYPE_P (t))
12146		/* A closure type for a lambda in an NSDMI or default argument.
12147		   Ignore it; it will be regenerated when needed.  */
12148		continue;
12149
12150	      bool class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
12151				       && TYPE_LANG_SPECIFIC (t)
12152				       && CLASSTYPE_IS_TEMPLATE (t));
12153
12154	      /* If the member is a class template, then -- even after
12155		 substitution -- there may be dependent types in the
12156		 template argument list for the class.  We increment
12157		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
12158		 that function will assume that no types are dependent
12159		 when outside of a template.  */
12160	      if (class_template_p)
12161		++processing_template_decl;
12162	      tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12163	      if (class_template_p)
12164		--processing_template_decl;
12165	      if (newtag == error_mark_node)
12166		continue;
12167
12168	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12169		{
12170		  tree name = TYPE_IDENTIFIER (t);
12171
12172		  if (class_template_p)
12173		    /* Unfortunately, lookup_template_class sets
12174		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
12175		       instantiation (i.e., for the type of a member
12176		       template class nested within a template class.)
12177		       This behavior is required for
12178		       maybe_process_partial_specialization to work
12179		       correctly, but is not accurate in this case;
12180		       the TAG is not an instantiation of anything.
12181		       (The corresponding TEMPLATE_DECL is an
12182		       instantiation, but the TYPE is not.) */
12183		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
12184
12185		  /* Now, install the tag.  We don't use pushtag
12186		     because that does too much work -- creating an
12187		     implicit typedef, which we've already done.  */
12188		  set_identifier_type_value (name, TYPE_NAME (newtag));
12189		  maybe_add_class_template_decl_list (type, newtag, false);
12190		  TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12191		  determine_visibility (TYPE_NAME (newtag));
12192		}
12193	    }
12194	  else if (DECL_DECLARES_FUNCTION_P (t))
12195	    {
12196	      tree r;
12197
12198	      if (TREE_CODE (t) == TEMPLATE_DECL)
12199		++processing_template_decl;
12200	      r = tsubst (t, args, tf_error, NULL_TREE);
12201	      if (TREE_CODE (t) == TEMPLATE_DECL)
12202		--processing_template_decl;
12203	      set_current_access_from_decl (r);
12204	      finish_member_declaration (r);
12205	      /* Instantiate members marked with attribute used.  */
12206	      if (r != error_mark_node && DECL_PRESERVE_P (r))
12207		used.safe_push (r);
12208	      if (TREE_CODE (r) == FUNCTION_DECL
12209		  && DECL_OMP_DECLARE_REDUCTION_P (r))
12210		cp_check_omp_declare_reduction (r);
12211	    }
12212	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12213		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
12214	    /* A closure type for a lambda in an NSDMI or default argument.
12215	       Ignore it; it will be regenerated when needed.  */;
12216	  else
12217	    {
12218	      /* Build new TYPE_FIELDS.  */
12219              if (TREE_CODE (t) == STATIC_ASSERT)
12220		tsubst_expr (t, args, tf_warning_or_error, NULL_TREE,
12221			     /*integral_constant_expression_p=*/true);
12222	      else if (TREE_CODE (t) != CONST_DECL)
12223		{
12224		  tree r;
12225		  tree vec = NULL_TREE;
12226		  int len = 1;
12227
12228		  gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12229		  /* The file and line for this declaration, to
12230		     assist in error message reporting.  Since we
12231		     called push_tinst_level above, we don't need to
12232		     restore these.  */
12233		  input_location = DECL_SOURCE_LOCATION (t);
12234
12235		  if (TREE_CODE (t) == TEMPLATE_DECL)
12236		    ++processing_template_decl;
12237		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12238		  if (TREE_CODE (t) == TEMPLATE_DECL)
12239		    --processing_template_decl;
12240
12241		  if (TREE_CODE (r) == TREE_VEC)
12242		    {
12243		      /* A capture pack became multiple fields.  */
12244		      vec = r;
12245		      len = TREE_VEC_LENGTH (vec);
12246		    }
12247
12248		  for (int i = 0; i < len; ++i)
12249		    {
12250		      if (vec)
12251			r = TREE_VEC_ELT (vec, i);
12252		      if (VAR_P (r))
12253			{
12254			  /* In [temp.inst]:
12255
12256			     [t]he initialization (and any associated
12257			     side-effects) of a static data member does
12258			     not occur unless the static data member is
12259			     itself used in a way that requires the
12260			     definition of the static data member to
12261			     exist.
12262
12263			     Therefore, we do not substitute into the
12264			     initialized for the static data member here.  */
12265			  finish_static_data_member_decl
12266			    (r,
12267			     /*init=*/NULL_TREE,
12268			     /*init_const_expr_p=*/false,
12269			     /*asmspec_tree=*/NULL_TREE,
12270			     /*flags=*/0);
12271			  /* Instantiate members marked with attribute used. */
12272			  if (r != error_mark_node && DECL_PRESERVE_P (r))
12273			    used.safe_push (r);
12274			}
12275		      else if (TREE_CODE (r) == FIELD_DECL)
12276			{
12277			  /* Determine whether R has a valid type and can be
12278			     completed later.  If R is invalid, then its type
12279			     is replaced by error_mark_node.  */
12280			  tree rtype = TREE_TYPE (r);
12281			  if (can_complete_type_without_circularity (rtype))
12282			    complete_type (rtype);
12283
12284			  if (!complete_or_array_type_p (rtype))
12285			    {
12286			      /* If R's type couldn't be completed and
12287				 it isn't a flexible array member (whose
12288				 type is incomplete by definition) give
12289				 an error.  */
12290			      cxx_incomplete_type_error (r, rtype);
12291			      TREE_TYPE (r) = error_mark_node;
12292			    }
12293			  else if (TREE_CODE (rtype) == ARRAY_TYPE
12294				   && TYPE_DOMAIN (rtype) == NULL_TREE
12295				   && (TREE_CODE (type) == UNION_TYPE
12296				       || TREE_CODE (type) == QUAL_UNION_TYPE))
12297			    {
12298			      error ("flexible array member %qD in union", r);
12299			      TREE_TYPE (r) = error_mark_node;
12300			    }
12301			  else if (!verify_type_context (input_location,
12302							 TCTX_FIELD, rtype))
12303			    TREE_TYPE (r) = error_mark_node;
12304			}
12305
12306		      /* If it is a TYPE_DECL for a class-scoped
12307			 ENUMERAL_TYPE, such a thing will already have
12308			 been added to the field list by tsubst_enum
12309			 in finish_member_declaration case above.  */
12310		      if (!(TREE_CODE (r) == TYPE_DECL
12311			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12312			    && DECL_ARTIFICIAL (r)))
12313			{
12314			  set_current_access_from_decl (r);
12315			  finish_member_declaration (r);
12316			}
12317		    }
12318		}
12319	    }
12320	}
12321      else
12322	{
12323	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12324	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12325	    {
12326	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
12327
12328	      tree friend_type = t;
12329	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12330		{
12331		  /* template <class T> friend class C;  */
12332		  friend_type = tsubst_friend_class (friend_type, args);
12333		}
12334	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12335		{
12336		  /* template <class T> friend class C::D;  */
12337		  friend_type = tsubst (friend_type, args,
12338					tf_warning_or_error, NULL_TREE);
12339		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12340		    friend_type = TREE_TYPE (friend_type);
12341		}
12342	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12343		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12344		{
12345		  /* This could be either
12346
12347		       friend class T::C;
12348
12349		     when dependent_type_p is false or
12350
12351		       template <class U> friend class T::C;
12352
12353		     otherwise.  */
12354		  /* Bump processing_template_decl in case this is something like
12355		     template <class T> friend struct A<T>::B.  */
12356		  ++processing_template_decl;
12357		  friend_type = tsubst (friend_type, args,
12358					tf_warning_or_error, NULL_TREE);
12359		  --processing_template_decl;
12360		}
12361	      else if (uses_template_parms (friend_type))
12362		/* friend class C<T>;  */
12363		friend_type = tsubst (friend_type, args,
12364				      tf_warning_or_error, NULL_TREE);
12365
12366	      /* Otherwise it's
12367
12368		   friend class C;
12369
12370		 where C is already declared or
12371
12372		   friend class C<int>;
12373
12374		 We don't have to do anything in these cases.  */
12375
12376	      if (friend_type != error_mark_node)
12377		make_friend_class (type, friend_type, /*complain=*/false);
12378	    }
12379	  else
12380	    {
12381	      /* Build new DECL_FRIENDLIST.  */
12382	      tree r;
12383
12384	      /* The file and line for this declaration, to
12385		 assist in error message reporting.  Since we
12386		 called push_tinst_level above, we don't need to
12387		 restore these.  */
12388	      input_location = DECL_SOURCE_LOCATION (t);
12389
12390	      if (TREE_CODE (t) == TEMPLATE_DECL)
12391		{
12392		  ++processing_template_decl;
12393		  push_deferring_access_checks (dk_no_check);
12394		}
12395
12396	      r = tsubst_friend_function (t, args);
12397	      add_friend (type, r, /*complain=*/false);
12398	      if (TREE_CODE (t) == TEMPLATE_DECL)
12399		{
12400		  pop_deferring_access_checks ();
12401		  --processing_template_decl;
12402		}
12403	    }
12404	}
12405    }
12406
12407  if (fn_context)
12408    {
12409      /* Restore these before substituting into the lambda capture
12410	 initializers.  */
12411      cp_unevaluated_operand = saved_unevaluated_operand;
12412      c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12413    }
12414
12415  /* Set the file and line number information to whatever is given for
12416     the class itself.  This puts error messages involving generated
12417     implicit functions at a predictable point, and the same point
12418     that would be used for non-template classes.  */
12419  input_location = DECL_SOURCE_LOCATION (typedecl);
12420
12421  unreverse_member_declarations (type);
12422  finish_struct_1 (type);
12423  TYPE_BEING_DEFINED (type) = 0;
12424
12425  /* Remember if instantiating this class ran into errors, so we can avoid
12426     instantiating member functions in limit_bad_template_recursion.  We set
12427     this flag even if the problem was in another instantiation triggered by
12428     this one, as that will likely also cause trouble for member functions.  */
12429  if (errorcount + sorrycount > current_tinst_level->errors)
12430    CLASSTYPE_ERRONEOUS (type) = true;
12431
12432  /* We don't instantiate default arguments for member functions.  14.7.1:
12433
12434     The implicit instantiation of a class template specialization causes
12435     the implicit instantiation of the declarations, but not of the
12436     definitions or default arguments, of the class member functions,
12437     member classes, static data members and member templates....  */
12438
12439  perform_instantiation_time_access_checks (pattern, args);
12440  perform_deferred_access_checks (tf_warning_or_error);
12441
12442  /* Now that we've gone through all the members, instantiate those
12443     marked with attribute used.  We must do this in the context of
12444     the class -- not the context we pushed from, as that might be
12445     inside a template and change the behaviour of mark_used.  */
12446  for (tree x : used)
12447    mark_used (x);
12448
12449  pop_nested_class ();
12450  maximum_field_alignment = saved_maximum_field_alignment;
12451  if (!fn_context)
12452    pop_from_top_level ();
12453  pop_tinst_level ();
12454
12455  /* The vtable for a template class can be emitted in any translation
12456     unit in which the class is instantiated.  When there is no key
12457     method, however, finish_struct_1 will already have added TYPE to
12458     the keyed_classes.  */
12459  if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12460    vec_safe_push (keyed_classes, type);
12461
12462  return type;
12463}
12464
12465/* Wrapper for instantiate_class_template_1.  */
12466
12467tree
12468instantiate_class_template (tree type)
12469{
12470  tree ret;
12471  timevar_push (TV_TEMPLATE_INST);
12472  ret = instantiate_class_template_1 (type);
12473  timevar_pop (TV_TEMPLATE_INST);
12474  return ret;
12475}
12476
12477tree
12478tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12479{
12480  tree r;
12481
12482  if (!t)
12483    r = t;
12484  else if (TYPE_P (t))
12485    r = tsubst (t, args, complain, in_decl);
12486  else
12487    {
12488      if (!(complain & tf_warning))
12489	++c_inhibit_evaluation_warnings;
12490      r = tsubst_expr (t, args, complain, in_decl,
12491		       /*integral_constant_expression_p=*/true);
12492      if (!(complain & tf_warning))
12493	--c_inhibit_evaluation_warnings;
12494    }
12495
12496  return r;
12497}
12498
12499/* Given a function parameter pack TMPL_PARM and some function parameters
12500   instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12501   and set *SPEC_P to point at the next point in the list.  */
12502
12503tree
12504extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12505{
12506  /* Collect all of the extra "packed" parameters into an
12507     argument pack.  */
12508  tree argpack;
12509  tree spec_parm = *spec_p;
12510  int len;
12511
12512  for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12513    if (tmpl_parm
12514	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12515      break;
12516
12517  spec_parm = *spec_p;
12518  if (len == 1 && DECL_PACK_P (spec_parm))
12519    {
12520      /* The instantiation is still a parameter pack; don't wrap it in a
12521	 NONTYPE_ARGUMENT_PACK.  */
12522      argpack = spec_parm;
12523      spec_parm = DECL_CHAIN (spec_parm);
12524    }
12525  else
12526    {
12527      /* Fill in PARMVEC with all of the parameters.  */
12528      tree parmvec = make_tree_vec (len);
12529      argpack = make_node (NONTYPE_ARGUMENT_PACK);
12530      for (int i = 0; i < len; i++)
12531	{
12532	  tree elt = spec_parm;
12533	  if (DECL_PACK_P (elt))
12534	    elt = make_pack_expansion (elt);
12535	  TREE_VEC_ELT (parmvec, i) = elt;
12536	  spec_parm = DECL_CHAIN (spec_parm);
12537	}
12538
12539      /* Build the argument packs.  */
12540      SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12541    }
12542  *spec_p = spec_parm;
12543
12544  return argpack;
12545}
12546
12547/* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12548   NONTYPE_ARGUMENT_PACK.  */
12549
12550static tree
12551make_fnparm_pack (tree spec_parm)
12552{
12553  return extract_fnparm_pack (NULL_TREE, &spec_parm);
12554}
12555
12556/* Return 1 if the Ith element of the argument pack ARG_PACK is a
12557   pack expansion with no extra args, 2 if it has extra args, or 0
12558   if it is not a pack expansion.  */
12559
12560static int
12561argument_pack_element_is_expansion_p (tree arg_pack, int i)
12562{
12563  if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12564    /* We're being called before this happens in tsubst_pack_expansion.  */
12565    arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12566  tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12567  if (i >= TREE_VEC_LENGTH (vec))
12568    return 0;
12569  tree elt = TREE_VEC_ELT (vec, i);
12570  if (DECL_P (elt))
12571    /* A decl pack is itself an expansion.  */
12572    elt = TREE_TYPE (elt);
12573  if (!PACK_EXPANSION_P (elt))
12574    return 0;
12575  if (PACK_EXPANSION_EXTRA_ARGS (elt))
12576    return 2;
12577  return 1;
12578}
12579
12580
12581/* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12582
12583static tree
12584make_argument_pack_select (tree arg_pack, unsigned index)
12585{
12586  tree aps = make_node (ARGUMENT_PACK_SELECT);
12587
12588  ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12589  ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12590
12591  return aps;
12592}
12593
12594/*  This is a subroutine of tsubst_pack_expansion.
12595
12596    It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12597    mechanism to store the (non complete list of) arguments of the
12598    substitution and return a non substituted pack expansion, in order
12599    to wait for when we have enough arguments to really perform the
12600    substitution.  */
12601
12602static bool
12603use_pack_expansion_extra_args_p (tree t,
12604				 tree parm_packs,
12605				 int arg_pack_len,
12606				 bool has_empty_arg)
12607{
12608  if (has_empty_arg
12609      && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12610    return true;
12611
12612  /* If one pack has an expansion and another pack has a normal
12613     argument or if one pack has an empty argument and an another
12614     one hasn't then tsubst_pack_expansion cannot perform the
12615     substitution and need to fall back on the
12616     PACK_EXPANSION_EXTRA mechanism.  */
12617  if (parm_packs == NULL_TREE)
12618    return false;
12619  else if (has_empty_arg)
12620    {
12621      /* If all the actual packs are pack expansions, we can still
12622	 subsitute directly.  */
12623      for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12624	{
12625	  tree a = TREE_VALUE (p);
12626	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12627	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12628	  a = ARGUMENT_PACK_ARGS (a);
12629	  if (TREE_VEC_LENGTH (a) == 1)
12630	    a = TREE_VEC_ELT (a, 0);
12631	  if (PACK_EXPANSION_P (a))
12632	    continue;
12633	  return true;
12634	}
12635      return false;
12636    }
12637
12638  for (int i = 0 ; i < arg_pack_len; ++i)
12639    {
12640      bool has_expansion_arg = false;
12641      bool has_non_expansion_arg = false;
12642      for (tree parm_pack = parm_packs;
12643	   parm_pack;
12644	   parm_pack = TREE_CHAIN (parm_pack))
12645	{
12646	  tree arg = TREE_VALUE (parm_pack);
12647
12648	  int exp = argument_pack_element_is_expansion_p (arg, i);
12649	  if (exp == 2)
12650	    /* We can't substitute a pack expansion with extra args into
12651	       our pattern.  */
12652	    return true;
12653	  else if (exp)
12654	    has_expansion_arg = true;
12655	  else
12656	    has_non_expansion_arg = true;
12657	}
12658
12659      if (has_expansion_arg && has_non_expansion_arg)
12660	{
12661	  gcc_checking_assert (false);
12662	  return true;
12663	}
12664    }
12665  return false;
12666}
12667
12668/* [temp.variadic]/6 says that:
12669
12670       The instantiation of a pack expansion [...]
12671       produces a list E1,E2, ..., En, where N is the number of elements
12672       in the pack expansion parameters.
12673
12674   This subroutine of tsubst_pack_expansion produces one of these Ei.
12675
12676   PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12677   TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12678   PATTERN, and each TREE_VALUE is its corresponding argument pack.
12679   INDEX is the index 'i' of the element Ei to produce.  ARGS,
12680   COMPLAIN, and IN_DECL are the same parameters as for the
12681   tsubst_pack_expansion function.
12682
12683   The function returns the resulting Ei upon successful completion,
12684   or error_mark_node.
12685
12686   Note that this function possibly modifies the ARGS parameter, so
12687   it's the responsibility of the caller to restore it.  */
12688
12689static tree
12690gen_elem_of_pack_expansion_instantiation (tree pattern,
12691					  tree parm_packs,
12692					  unsigned index,
12693					  tree args /* This parm gets
12694						       modified.  */,
12695					  tsubst_flags_t complain,
12696					  tree in_decl)
12697{
12698  tree t;
12699  bool ith_elem_is_expansion = false;
12700
12701  /* For each parameter pack, change the substitution of the parameter
12702     pack to the ith argument in its argument pack, then expand the
12703     pattern.  */
12704  for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12705    {
12706      tree parm = TREE_PURPOSE (pack);
12707      tree arg_pack = TREE_VALUE (pack);
12708      tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
12709
12710      ith_elem_is_expansion |=
12711	argument_pack_element_is_expansion_p (arg_pack, index);
12712
12713      /* Select the Ith argument from the pack.  */
12714      if (TREE_CODE (parm) == PARM_DECL
12715	  || VAR_P (parm)
12716	  || TREE_CODE (parm) == FIELD_DECL)
12717	{
12718	  if (index == 0)
12719	    {
12720	      aps = make_argument_pack_select (arg_pack, index);
12721	      if (!mark_used (parm, complain) && !(complain & tf_error))
12722		return error_mark_node;
12723	      register_local_specialization (aps, parm);
12724	    }
12725	  else
12726	    aps = retrieve_local_specialization (parm);
12727	}
12728      else
12729	{
12730	  int idx, level;
12731	  template_parm_level_and_index (parm, &level, &idx);
12732
12733	  if (index == 0)
12734	    {
12735	      aps = make_argument_pack_select (arg_pack, index);
12736	      /* Update the corresponding argument.  */
12737	      TMPL_ARG (args, level, idx) = aps;
12738	    }
12739	  else
12740	    /* Re-use the ARGUMENT_PACK_SELECT.  */
12741	    aps = TMPL_ARG (args, level, idx);
12742	}
12743      ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12744    }
12745
12746  /* Substitute into the PATTERN with the (possibly altered)
12747     arguments.  */
12748  if (pattern == in_decl)
12749    /* Expanding a fixed parameter pack from
12750       coerce_template_parameter_pack.  */
12751    t = tsubst_decl (pattern, args, complain);
12752  else if (pattern == error_mark_node)
12753    t = error_mark_node;
12754  else if (!TYPE_P (pattern))
12755    t = tsubst_expr (pattern, args, complain, in_decl,
12756		     /*integral_constant_expression_p=*/false);
12757  else
12758    {
12759      t = tsubst (pattern, args, complain, in_decl);
12760      if (is_auto (t) && !ith_elem_is_expansion)
12761	/* When expanding the fake auto... pack expansion from add_capture, we
12762	   need to mark that the expansion is no longer a pack.  */
12763	TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12764    }
12765
12766  /*  If the Ith argument pack element is a pack expansion, then
12767      the Ith element resulting from the substituting is going to
12768      be a pack expansion as well.  */
12769  if (ith_elem_is_expansion)
12770    t = make_pack_expansion (t, complain);
12771
12772  return t;
12773}
12774
12775/* When the unexpanded parameter pack in a fold expression expands to an empty
12776   sequence, the value of the expression is as follows; the program is
12777   ill-formed if the operator is not listed in this table.
12778
12779   &&	true
12780   ||	false
12781   ,	void()  */
12782
12783tree
12784expand_empty_fold (tree t, tsubst_flags_t complain)
12785{
12786  tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12787  if (!FOLD_EXPR_MODIFY_P (t))
12788    switch (code)
12789      {
12790      case TRUTH_ANDIF_EXPR:
12791	return boolean_true_node;
12792      case TRUTH_ORIF_EXPR:
12793	return boolean_false_node;
12794      case COMPOUND_EXPR:
12795	return void_node;
12796      default:
12797	break;
12798      }
12799
12800  if (complain & tf_error)
12801    error_at (location_of (t),
12802	      "fold of empty expansion over %O", code);
12803  return error_mark_node;
12804}
12805
12806/* Given a fold-expression T and a current LEFT and RIGHT operand,
12807   form an expression that combines the two terms using the
12808   operator of T. */
12809
12810static tree
12811fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12812{
12813  tree_code code = FOLD_EXPR_OP (t);
12814
12815  tree lookups = templated_operator_saved_lookups (t);
12816
12817  // Handle compound assignment operators.
12818  if (FOLD_EXPR_MODIFY_P (t))
12819    return build_x_modify_expr (input_location, left, code, right,
12820				lookups, complain);
12821
12822  warning_sentinel s(warn_parentheses);
12823  switch (code)
12824    {
12825    case COMPOUND_EXPR:
12826      return build_x_compound_expr (input_location, left, right,
12827				    lookups, complain);
12828    default:
12829      return build_x_binary_op (input_location, code,
12830                                left, TREE_CODE (left),
12831                                right, TREE_CODE (right),
12832				lookups, /*overload=*/NULL,
12833                                complain);
12834    }
12835}
12836
12837/* Substitute ARGS into the pack of a fold expression T. */
12838
12839static inline tree
12840tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12841{
12842  return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12843}
12844
12845/* Substitute ARGS into the pack of a fold expression T. */
12846
12847static inline tree
12848tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12849{
12850  return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12851}
12852
12853/* Expand a PACK of arguments into a grouped as left fold.
12854   Given a pack containing elements A0, A1, ..., An and an
12855   operator @, this builds the expression:
12856
12857      ((A0 @ A1) @ A2) ... @ An
12858
12859   Note that PACK must not be empty.
12860
12861   The operator is defined by the original fold expression T. */
12862
12863static tree
12864expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12865{
12866  tree left = TREE_VEC_ELT (pack, 0);
12867  for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12868    {
12869      tree right = TREE_VEC_ELT (pack, i);
12870      left = fold_expression (t, left, right, complain);
12871    }
12872  return left;
12873}
12874
12875/* Substitute into a unary left fold expression. */
12876
12877static tree
12878tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12879                        tree in_decl)
12880{
12881  tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12882  if (pack == error_mark_node)
12883    return error_mark_node;
12884  if (PACK_EXPANSION_P (pack))
12885    {
12886      tree r = copy_node (t);
12887      FOLD_EXPR_PACK (r) = pack;
12888      return r;
12889    }
12890  if (TREE_VEC_LENGTH (pack) == 0)
12891    return expand_empty_fold (t, complain);
12892  else
12893    return expand_left_fold (t, pack, complain);
12894}
12895
12896/* Substitute into a binary left fold expression.
12897
12898   Do ths by building a single (non-empty) vector of argumnts and
12899   building the expression from those elements. */
12900
12901static tree
12902tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12903                         tree in_decl)
12904{
12905  tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12906  if (pack == error_mark_node)
12907    return error_mark_node;
12908  tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12909  if (init == error_mark_node)
12910    return error_mark_node;
12911
12912  if (PACK_EXPANSION_P (pack))
12913    {
12914      tree r = copy_node (t);
12915      FOLD_EXPR_PACK (r) = pack;
12916      FOLD_EXPR_INIT (r) = init;
12917      return r;
12918    }
12919
12920  tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12921  TREE_VEC_ELT (vec, 0) = init;
12922  for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12923    TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12924
12925  return expand_left_fold (t, vec, complain);
12926}
12927
12928/* Expand a PACK of arguments into a grouped as right fold.
12929   Given a pack containing elementns A0, A1, ..., and an
12930   operator @, this builds the expression:
12931
12932      A0@ ... (An-2 @ (An-1 @ An))
12933
12934   Note that PACK must not be empty.
12935
12936   The operator is defined by the original fold expression T. */
12937
12938tree
12939expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12940{
12941  // Build the expression.
12942  int n = TREE_VEC_LENGTH (pack);
12943  tree right = TREE_VEC_ELT (pack, n - 1);
12944  for (--n; n != 0; --n)
12945    {
12946      tree left = TREE_VEC_ELT (pack, n - 1);
12947      right = fold_expression (t, left, right, complain);
12948    }
12949  return right;
12950}
12951
12952/* Substitute into a unary right fold expression. */
12953
12954static tree
12955tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12956                         tree in_decl)
12957{
12958  tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12959  if (pack == error_mark_node)
12960    return error_mark_node;
12961  if (PACK_EXPANSION_P (pack))
12962    {
12963      tree r = copy_node (t);
12964      FOLD_EXPR_PACK (r) = pack;
12965      return r;
12966    }
12967  if (TREE_VEC_LENGTH (pack) == 0)
12968    return expand_empty_fold (t, complain);
12969  else
12970    return expand_right_fold (t, pack, complain);
12971}
12972
12973/* Substitute into a binary right fold expression.
12974
12975   Do ths by building a single (non-empty) vector of arguments and
12976   building the expression from those elements. */
12977
12978static tree
12979tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12980                         tree in_decl)
12981{
12982  tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12983  if (pack == error_mark_node)
12984    return error_mark_node;
12985  tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12986  if (init == error_mark_node)
12987    return error_mark_node;
12988
12989  if (PACK_EXPANSION_P (pack))
12990    {
12991      tree r = copy_node (t);
12992      FOLD_EXPR_PACK (r) = pack;
12993      FOLD_EXPR_INIT (r) = init;
12994      return r;
12995    }
12996
12997  int n = TREE_VEC_LENGTH (pack);
12998  tree vec = make_tree_vec (n + 1);
12999  for (int i = 0; i < n; ++i)
13000    TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13001  TREE_VEC_ELT (vec, n) = init;
13002
13003  return expand_right_fold (t, vec, complain);
13004}
13005
13006/* Walk through the pattern of a pack expansion, adding everything in
13007   local_specializations to a list.  */
13008
13009class el_data
13010{
13011public:
13012  /* Set of variables declared within the pattern.  */
13013  hash_set<tree> internal;
13014  /* Set of AST nodes that have been visited by the traversal.  */
13015  hash_set<tree> visited;
13016  /* List of local_specializations used within the pattern.  */
13017  tree extra;
13018  tsubst_flags_t complain;
13019  /* True iff we don't want to walk into unevaluated contexts.  */
13020  bool skip_unevaluated_operands = false;
13021  /* The unevaluated contexts that we avoided walking.  */
13022  auto_vec<tree> skipped_trees;
13023
13024  el_data (tsubst_flags_t c)
13025    : extra (NULL_TREE), complain (c) {}
13026};
13027static tree
13028extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13029{
13030  el_data &data = *reinterpret_cast<el_data*>(data_);
13031  tree *extra = &data.extra;
13032  tsubst_flags_t complain = data.complain;
13033
13034  if (data.skip_unevaluated_operands
13035      && unevaluated_p (TREE_CODE (*tp)))
13036    {
13037      data.skipped_trees.safe_push (*tp);
13038      *walk_subtrees = 0;
13039      return NULL_TREE;
13040    }
13041
13042  if (TYPE_P (*tp) && typedef_variant_p (*tp))
13043    /* Remember local typedefs (85214).  */
13044    tp = &TYPE_NAME (*tp);
13045
13046  if (TREE_CODE (*tp) == DECL_EXPR)
13047    {
13048      tree decl = DECL_EXPR_DECL (*tp);
13049      data.internal.add (decl);
13050      if (VAR_P (decl)
13051	  && DECL_DECOMPOSITION_P (decl)
13052	  && TREE_TYPE (decl) != error_mark_node)
13053	{
13054	  gcc_assert (DECL_NAME (decl) == NULL_TREE);
13055	  for (tree decl2 = DECL_CHAIN (decl);
13056	       decl2
13057	       && VAR_P (decl2)
13058	       && DECL_DECOMPOSITION_P (decl2)
13059	       && DECL_NAME (decl2)
13060	       && TREE_TYPE (decl2) != error_mark_node;
13061	       decl2 = DECL_CHAIN (decl2))
13062	    {
13063	      gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13064	      data.internal.add (decl2);
13065	    }
13066	}
13067    }
13068  else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13069    {
13070      /* Since we defer implicit capture, look in the parms and body.  */
13071      tree fn = lambda_function (*tp);
13072      cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13073		    &data.visited);
13074      cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13075		    &data.visited);
13076    }
13077  else if (tree spec = retrieve_local_specialization (*tp))
13078    {
13079      if (data.internal.contains (*tp))
13080	/* Don't mess with variables declared within the pattern.  */
13081	return NULL_TREE;
13082      if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13083	{
13084	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
13085	  tree args = ARGUMENT_PACK_ARGS (spec);
13086	  if (TREE_VEC_LENGTH (args) == 1)
13087	    {
13088	      tree elt = TREE_VEC_ELT (args, 0);
13089	      if (PACK_EXPANSION_P (elt))
13090		elt = PACK_EXPANSION_PATTERN (elt);
13091	      if (DECL_PACK_P (elt))
13092		spec = elt;
13093	    }
13094	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13095	    {
13096	      /* Handle lambda capture here, since we aren't doing any
13097		 substitution now, and so tsubst_copy won't call
13098		 process_outer_var_ref.  */
13099	      tree args = ARGUMENT_PACK_ARGS (spec);
13100	      int len = TREE_VEC_LENGTH (args);
13101	      for (int i = 0; i < len; ++i)
13102		{
13103		  tree arg = TREE_VEC_ELT (args, i);
13104		  tree carg = arg;
13105		  if (outer_automatic_var_p (arg))
13106		    carg = process_outer_var_ref (arg, complain);
13107		  if (carg != arg)
13108		    {
13109		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13110			 proxies.  */
13111		      if (i == 0)
13112			{
13113			  spec = copy_node (spec);
13114			  args = copy_node (args);
13115			  SET_ARGUMENT_PACK_ARGS (spec, args);
13116			  register_local_specialization (spec, *tp);
13117			}
13118		      TREE_VEC_ELT (args, i) = carg;
13119		    }
13120		}
13121	    }
13122	}
13123      if (outer_automatic_var_p (spec))
13124	spec = process_outer_var_ref (spec, complain);
13125      *extra = tree_cons (*tp, spec, *extra);
13126    }
13127  return NULL_TREE;
13128}
13129static tree
13130extract_local_specs (tree pattern, tsubst_flags_t complain)
13131{
13132  el_data data (complain);
13133  /* Walk the pattern twice, ignoring unevaluated operands the first time
13134     around, so that if a local specialization appears in both an evaluated
13135     and unevaluated context we prefer to process it in the evaluated context
13136     (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13137     context).  */
13138  data.skip_unevaluated_operands = true;
13139  cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13140  /* Now walk the unevaluated contexts we skipped the first time around.  */
13141  data.skip_unevaluated_operands = false;
13142  for (tree t : data.skipped_trees)
13143    {
13144      data.visited.remove (t);
13145      cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13146    }
13147  return data.extra;
13148}
13149
13150/* Extract any uses of local_specializations from PATTERN and add them to ARGS
13151   for use in PACK_EXPANSION_EXTRA_ARGS.  */
13152
13153tree
13154build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13155{
13156  /* Make a copy of the extra arguments so that they won't get changed
13157     out from under us.  */
13158  tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13159  if (local_specializations)
13160    if (tree locals = extract_local_specs (pattern, complain))
13161      extra = tree_cons (NULL_TREE, extra, locals);
13162  return extra;
13163}
13164
13165/* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13166   normal template args to ARGS.  */
13167
13168tree
13169add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13170{
13171  if (extra && TREE_CODE (extra) == TREE_LIST)
13172    {
13173      for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13174	{
13175	  /* The partial instantiation involved local declarations collected in
13176	     extract_local_specs; map from the general template to our local
13177	     context.  */
13178	  tree gen = TREE_PURPOSE (elt);
13179	  tree inst = TREE_VALUE (elt);
13180	  if (DECL_P (inst))
13181	    if (tree local = retrieve_local_specialization (inst))
13182	      inst = local;
13183	  /* else inst is already a full instantiation of the pack.  */
13184	  register_local_specialization (inst, gen);
13185	}
13186      gcc_assert (!TREE_PURPOSE (extra));
13187      extra = TREE_VALUE (extra);
13188    }
13189  if (uses_template_parms (extra))
13190    {
13191      /* This can happen after dependent substitution into a
13192	 requires-expr or a lambda that uses constexpr if.  */
13193      extra = tsubst_template_args (extra, args, complain, in_decl);
13194      args = add_outermost_template_args (args, extra);
13195    }
13196  else
13197    args = add_to_template_args (extra, args);
13198  return args;
13199}
13200
13201/* Substitute ARGS into T, which is an pack expansion
13202   (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13203   TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13204   (if only a partial substitution could be performed) or
13205   ERROR_MARK_NODE if there was an error.  */
13206tree
13207tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13208		       tree in_decl)
13209{
13210  tree pattern;
13211  tree pack, packs = NULL_TREE;
13212  bool unsubstituted_packs = false;
13213  int i, len = -1;
13214  tree result;
13215  bool need_local_specializations = false;
13216  int levels;
13217
13218  gcc_assert (PACK_EXPANSION_P (t));
13219  pattern = PACK_EXPANSION_PATTERN (t);
13220
13221  /* Add in any args remembered from an earlier partial instantiation.  */
13222  args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13223
13224  levels = TMPL_ARGS_DEPTH (args);
13225
13226  /* Determine the argument packs that will instantiate the parameter
13227     packs used in the expansion expression. While we're at it,
13228     compute the number of arguments to be expanded and make sure it
13229     is consistent.  */
13230  for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13231       pack = TREE_CHAIN (pack))
13232    {
13233      tree parm_pack = TREE_VALUE (pack);
13234      tree arg_pack = NULL_TREE;
13235      tree orig_arg = NULL_TREE;
13236      int level = 0;
13237
13238      if (TREE_CODE (parm_pack) == BASES)
13239	{
13240	  gcc_assert (parm_pack == pattern);
13241	  if (BASES_DIRECT (parm_pack))
13242	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13243							args, complain,
13244							in_decl, false),
13245					   complain);
13246	  else
13247	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13248						 args, complain, in_decl,
13249						 false), complain);
13250	}
13251      else if (builtin_pack_call_p (parm_pack))
13252	{
13253	  if (parm_pack != pattern)
13254	    {
13255	      if (complain & tf_error)
13256		sorry ("%qE is not the entire pattern of the pack expansion",
13257		       parm_pack);
13258	      return error_mark_node;
13259	    }
13260	  return expand_builtin_pack_call (parm_pack, args,
13261					   complain, in_decl);
13262	}
13263      else if (TREE_CODE (parm_pack) == PARM_DECL)
13264	{
13265	  /* We know we have correct local_specializations if this
13266	     expansion is at function scope, or if we're dealing with a
13267	     local parameter in a requires expression; for the latter,
13268	     tsubst_requires_expr set it up appropriately.  */
13269	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13270	    arg_pack = retrieve_local_specialization (parm_pack);
13271	  else
13272	    /* We can't rely on local_specializations for a parameter
13273	       name used later in a function declaration (such as in a
13274	       late-specified return type).  Even if it exists, it might
13275	       have the wrong value for a recursive call.  */
13276	    need_local_specializations = true;
13277
13278	  if (!arg_pack)
13279	    {
13280	      /* This parameter pack was used in an unevaluated context.  Just
13281		 make a dummy decl, since it's only used for its type.  */
13282	      ++cp_unevaluated_operand;
13283	      arg_pack = tsubst_decl (parm_pack, args, complain);
13284	      --cp_unevaluated_operand;
13285	      if (arg_pack && DECL_PACK_P (arg_pack))
13286		/* Partial instantiation of the parm_pack, we can't build
13287		   up an argument pack yet.  */
13288		arg_pack = NULL_TREE;
13289	      else
13290		arg_pack = make_fnparm_pack (arg_pack);
13291	    }
13292	  else if (DECL_PACK_P (arg_pack))
13293	    /* This argument pack isn't fully instantiated yet.  */
13294	    arg_pack = NULL_TREE;
13295	}
13296      else if (is_capture_proxy (parm_pack))
13297	{
13298	  arg_pack = retrieve_local_specialization (parm_pack);
13299	  if (DECL_PACK_P (arg_pack))
13300	    arg_pack = NULL_TREE;
13301	}
13302      else
13303        {
13304	  int idx;
13305          template_parm_level_and_index (parm_pack, &level, &idx);
13306          if (level <= levels)
13307            arg_pack = TMPL_ARG (args, level, idx);
13308
13309	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13310	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13311	    arg_pack = NULL_TREE;
13312        }
13313
13314      orig_arg = arg_pack;
13315      if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13316	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13317
13318      if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13319	/* This can only happen if we forget to expand an argument
13320	   pack somewhere else. Just return an error, silently.  */
13321	{
13322	  result = make_tree_vec (1);
13323	  TREE_VEC_ELT (result, 0) = error_mark_node;
13324	  return result;
13325	}
13326
13327      if (arg_pack)
13328        {
13329          int my_len =
13330            TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13331
13332	  /* Don't bother trying to do a partial substitution with
13333	     incomplete packs; we'll try again after deduction.  */
13334          if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13335            return t;
13336
13337          if (len < 0)
13338	    len = my_len;
13339	  else if (len != my_len)
13340            {
13341	      if (!(complain & tf_error))
13342		/* Fail quietly.  */;
13343              else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13344                error ("mismatched argument pack lengths while expanding %qT",
13345                       pattern);
13346              else
13347                error ("mismatched argument pack lengths while expanding %qE",
13348                       pattern);
13349              return error_mark_node;
13350            }
13351
13352          /* Keep track of the parameter packs and their corresponding
13353             argument packs.  */
13354          packs = tree_cons (parm_pack, arg_pack, packs);
13355          TREE_TYPE (packs) = orig_arg;
13356        }
13357      else
13358	{
13359	  /* We can't substitute for this parameter pack.  We use a flag as
13360	     well as the missing_level counter because function parameter
13361	     packs don't have a level.  */
13362	  gcc_assert (processing_template_decl || is_auto (parm_pack));
13363	  unsubstituted_packs = true;
13364	}
13365    }
13366
13367  /* If the expansion is just T..., return the matching argument pack, unless
13368     we need to call convert_from_reference on all the elements.  This is an
13369     important optimization; see c++/68422.  */
13370  if (!unsubstituted_packs
13371      && TREE_PURPOSE (packs) == pattern)
13372    {
13373      tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13374
13375      /* If the argument pack is a single pack expansion, pull it out.  */
13376      if (TREE_VEC_LENGTH (args) == 1
13377	  && pack_expansion_args_count (args))
13378	return TREE_VEC_ELT (args, 0);
13379
13380      /* Types need no adjustment, nor does sizeof..., and if we still have
13381	 some pack expansion args we won't do anything yet.  */
13382      if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13383	  || PACK_EXPANSION_SIZEOF_P (t)
13384	  || pack_expansion_args_count (args))
13385	return args;
13386      /* Also optimize expression pack expansions if we can tell that the
13387	 elements won't have reference type.  */
13388      tree type = TREE_TYPE (pattern);
13389      if (type && !TYPE_REF_P (type)
13390	  && !PACK_EXPANSION_P (type)
13391	  && !WILDCARD_TYPE_P (type))
13392	return args;
13393      /* Otherwise use the normal path so we get convert_from_reference.  */
13394    }
13395
13396  /* We cannot expand this expansion expression, because we don't have
13397     all of the argument packs we need.  */
13398  if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13399    {
13400      /* We got some full packs, but we can't substitute them in until we
13401	 have values for all the packs.  So remember these until then.  */
13402
13403      t = make_pack_expansion (pattern, complain);
13404      PACK_EXPANSION_EXTRA_ARGS (t)
13405	= build_extra_args (pattern, args, complain);
13406      return t;
13407    }
13408
13409  /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13410     type, so create our own local specializations map; the current map is
13411     either NULL or (in the case of recursive unification) might have
13412     bindings that we don't want to use or alter.  */
13413  local_specialization_stack lss (need_local_specializations
13414				  ? lss_blank : lss_nop);
13415
13416  if (unsubstituted_packs)
13417    {
13418      /* There were no real arguments, we're just replacing a parameter
13419	 pack with another version of itself. Substitute into the
13420	 pattern and return a PACK_EXPANSION_*. The caller will need to
13421	 deal with that.  */
13422      if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13423	result = tsubst_expr (pattern, args, complain, in_decl,
13424			 /*integral_constant_expression_p=*/false);
13425      else
13426	result = tsubst (pattern, args, complain, in_decl);
13427      result = make_pack_expansion (result, complain);
13428      PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13429      PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13430      if (PACK_EXPANSION_AUTO_P (t))
13431	{
13432	  /* This is a fake auto... pack expansion created in add_capture with
13433	     _PACKS that don't appear in the pattern.  Copy one over.  */
13434	  packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13435	  pack = retrieve_local_specialization (TREE_VALUE (packs));
13436	  gcc_checking_assert (DECL_PACK_P (pack));
13437	  PACK_EXPANSION_PARAMETER_PACKS (result)
13438	    = build_tree_list (NULL_TREE, pack);
13439	  PACK_EXPANSION_AUTO_P (result) = true;
13440	}
13441      return result;
13442    }
13443
13444  gcc_assert (len >= 0);
13445
13446  /* For each argument in each argument pack, substitute into the
13447     pattern.  */
13448  result = make_tree_vec (len);
13449  tree elem_args = copy_template_args (args);
13450  for (i = 0; i < len; ++i)
13451    {
13452      t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13453						    i,
13454						    elem_args, complain,
13455						    in_decl);
13456      TREE_VEC_ELT (result, i) = t;
13457      if (t == error_mark_node)
13458	{
13459	  result = error_mark_node;
13460	  break;
13461	}
13462    }
13463
13464  /* Update ARGS to restore the substitution from parameter packs to
13465     their argument packs.  */
13466  for (pack = packs; pack; pack = TREE_CHAIN (pack))
13467    {
13468      tree parm = TREE_PURPOSE (pack);
13469
13470      if (TREE_CODE (parm) == PARM_DECL
13471	  || VAR_P (parm)
13472	  || TREE_CODE (parm) == FIELD_DECL)
13473        register_local_specialization (TREE_TYPE (pack), parm);
13474      else
13475        {
13476          int idx, level;
13477
13478	  if (TREE_VALUE (pack) == NULL_TREE)
13479	    continue;
13480
13481          template_parm_level_and_index (parm, &level, &idx);
13482
13483          /* Update the corresponding argument.  */
13484          if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13485            TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13486              TREE_TYPE (pack);
13487          else
13488            TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13489        }
13490    }
13491
13492  /* If the dependent pack arguments were such that we end up with only a
13493     single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13494  if (len == 1 && TREE_CODE (result) == TREE_VEC
13495      && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13496    return TREE_VEC_ELT (result, 0);
13497
13498  return result;
13499}
13500
13501/* Make an argument pack out of the TREE_VEC VEC.  */
13502
13503static tree
13504make_argument_pack (tree vec)
13505{
13506  tree pack;
13507
13508  if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13509    pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13510  else
13511    {
13512      pack = make_node (NONTYPE_ARGUMENT_PACK);
13513      TREE_CONSTANT (pack) = 1;
13514    }
13515  SET_ARGUMENT_PACK_ARGS (pack, vec);
13516  return pack;
13517}
13518
13519/* Return an exact copy of template args T that can be modified
13520   independently.  */
13521
13522static tree
13523copy_template_args (tree t)
13524{
13525  if (t == error_mark_node)
13526    return t;
13527
13528  int len = TREE_VEC_LENGTH (t);
13529  tree new_vec = make_tree_vec (len);
13530
13531  for (int i = 0; i < len; ++i)
13532    {
13533      tree elt = TREE_VEC_ELT (t, i);
13534      if (elt && TREE_CODE (elt) == TREE_VEC)
13535	elt = copy_template_args (elt);
13536      TREE_VEC_ELT (new_vec, i) = elt;
13537    }
13538
13539  NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13540    = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13541
13542  return new_vec;
13543}
13544
13545/* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13546
13547tree
13548tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13549		      tree in_decl)
13550{
13551  /* Substitute into each of the arguments.  */
13552  tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13553					 args, complain, in_decl);
13554  tree new_arg = error_mark_node;
13555  if (pack_args != error_mark_node)
13556    {
13557      if (TYPE_P (orig_arg))
13558	{
13559	  new_arg = cxx_make_type (TREE_CODE (orig_arg));
13560	  SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13561	}
13562      else
13563	{
13564	  new_arg = make_node (TREE_CODE (orig_arg));
13565	  TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13566	}
13567
13568      SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13569    }
13570
13571  return new_arg;
13572}
13573
13574/* Substitute ARGS into the vector or list of template arguments T.  */
13575
13576tree
13577tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13578{
13579  tree orig_t = t;
13580  int len, need_new = 0, i, expanded_len_adjust = 0, out;
13581  tree *elts;
13582
13583  if (t == error_mark_node)
13584    return error_mark_node;
13585
13586  len = TREE_VEC_LENGTH (t);
13587  elts = XALLOCAVEC (tree, len);
13588
13589  for (i = 0; i < len; i++)
13590    {
13591      tree orig_arg = TREE_VEC_ELT (t, i);
13592      tree new_arg;
13593
13594      if (!orig_arg)
13595	new_arg = NULL_TREE;
13596      else if (TREE_CODE (orig_arg) == TREE_VEC)
13597	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13598      else if (PACK_EXPANSION_P (orig_arg))
13599        {
13600          /* Substitute into an expansion expression.  */
13601          new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13602
13603          if (TREE_CODE (new_arg) == TREE_VEC)
13604            /* Add to the expanded length adjustment the number of
13605               expanded arguments. We subtract one from this
13606               measurement, because the argument pack expression
13607               itself is already counted as 1 in
13608               LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13609               the argument pack is empty.  */
13610            expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13611        }
13612      else if (ARGUMENT_PACK_P (orig_arg))
13613	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13614      else
13615	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13616
13617      if (new_arg == error_mark_node)
13618	return error_mark_node;
13619
13620      elts[i] = new_arg;
13621      if (new_arg != orig_arg)
13622	need_new = 1;
13623    }
13624
13625  if (!need_new)
13626    return t;
13627
13628  /* Make space for the expanded arguments coming from template
13629     argument packs.  */
13630  t = make_tree_vec (len + expanded_len_adjust);
13631  /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13632     arguments for a member template.
13633     In that case each TREE_VEC in ORIG_T represents a level of template
13634     arguments, and ORIG_T won't carry any non defaulted argument count.
13635     It will rather be the nested TREE_VECs that will carry one.
13636     In other words, ORIG_T carries a non defaulted argument count only
13637     if it doesn't contain any nested TREE_VEC.  */
13638  if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13639    {
13640      int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13641      count += expanded_len_adjust;
13642      SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13643    }
13644  for (i = 0, out = 0; i < len; i++)
13645    {
13646      tree orig_arg = TREE_VEC_ELT (orig_t, i);
13647      if (orig_arg
13648	  && (PACK_EXPANSION_P (orig_arg) || ARGUMENT_PACK_P (orig_arg))
13649          && TREE_CODE (elts[i]) == TREE_VEC)
13650        {
13651          int idx;
13652
13653          /* Now expand the template argument pack "in place".  */
13654          for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13655            TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13656        }
13657      else
13658        {
13659          TREE_VEC_ELT (t, out) = elts[i];
13660          out++;
13661        }
13662    }
13663
13664  return t;
13665}
13666
13667/* Substitute ARGS into one level PARMS of template parameters.  */
13668
13669static tree
13670tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13671{
13672  if (parms == error_mark_node)
13673    return error_mark_node;
13674
13675  tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13676
13677  for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13678    {
13679      tree tuple = TREE_VEC_ELT (parms, i);
13680
13681      if (tuple == error_mark_node)
13682	continue;
13683
13684      TREE_VEC_ELT (new_vec, i) =
13685	tsubst_template_parm (tuple, args, complain);
13686    }
13687
13688  return new_vec;
13689}
13690
13691/* Return the result of substituting ARGS into the template parameters
13692   given by PARMS.  If there are m levels of ARGS and m + n levels of
13693   PARMS, then the result will contain n levels of PARMS.  For
13694   example, if PARMS is `template <class T> template <class U>
13695   template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13696   result will be `template <int*, double, class V>'.  */
13697
13698static tree
13699tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13700{
13701  tree r = NULL_TREE;
13702  tree* new_parms;
13703
13704  /* When substituting into a template, we must set
13705     PROCESSING_TEMPLATE_DECL as the template parameters may be
13706     dependent if they are based on one-another, and the dependency
13707     predicates are short-circuit outside of templates.  */
13708  ++processing_template_decl;
13709
13710  for (new_parms = &r;
13711       parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13712       new_parms = &(TREE_CHAIN (*new_parms)),
13713	 parms = TREE_CHAIN (parms))
13714    {
13715      tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13716						  args, complain);
13717      *new_parms =
13718	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13719			     - TMPL_ARGS_DEPTH (args)),
13720		   new_vec, NULL_TREE);
13721      TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13722	= TEMPLATE_PARMS_CONSTRAINTS (parms);
13723    }
13724
13725  --processing_template_decl;
13726
13727  return r;
13728}
13729
13730/* Return the result of substituting ARGS into one template parameter
13731   given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13732   parameter and which TREE_PURPOSE is the default argument of the
13733   template parameter.  */
13734
13735static tree
13736tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13737{
13738  tree default_value, parm_decl;
13739
13740  if (args == NULL_TREE
13741      || t == NULL_TREE
13742      || t == error_mark_node)
13743    return t;
13744
13745  gcc_assert (TREE_CODE (t) == TREE_LIST);
13746
13747  default_value = TREE_PURPOSE (t);
13748  parm_decl = TREE_VALUE (t);
13749
13750  parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13751  if (TREE_CODE (parm_decl) == PARM_DECL
13752      && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13753    parm_decl = error_mark_node;
13754  default_value = tsubst_template_arg (default_value, args,
13755				       complain, NULL_TREE);
13756
13757  tree r = build_tree_list (default_value, parm_decl);
13758  TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13759  return r;
13760}
13761
13762/* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13763   parameter in PARMS for sake of declaration matching.  */
13764
13765static void
13766tsubst_each_template_parm_constraints (tree parms, tree args,
13767				       tsubst_flags_t complain)
13768{
13769  ++processing_template_decl;
13770  for (; parms; parms = TREE_CHAIN (parms))
13771    {
13772      tree level = TREE_VALUE (parms);
13773      for (int i = 0; i < TREE_VEC_LENGTH (level); ++i)
13774	{
13775	  tree parm = TREE_VEC_ELT (level, i);
13776	  TEMPLATE_PARM_CONSTRAINTS (parm)
13777	    = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13778				 complain, NULL_TREE);
13779	}
13780    }
13781  --processing_template_decl;
13782}
13783
13784/* Substitute the ARGS into the indicated aggregate (or enumeration)
13785   type T.  If T is not an aggregate or enumeration type, it is
13786   handled as if by tsubst.  IN_DECL is as for tsubst.  If
13787   ENTERING_SCOPE is nonzero, T is the context for a template which
13788   we are presently tsubst'ing.  Return the substituted value.  */
13789
13790static tree
13791tsubst_aggr_type (tree t,
13792		  tree args,
13793		  tsubst_flags_t complain,
13794		  tree in_decl,
13795		  int entering_scope)
13796{
13797  if (t == NULL_TREE)
13798    return NULL_TREE;
13799
13800  /* If T is an alias template specialization, we want to substitute that
13801     rather than strip it, especially if it's dependent_alias_template_spec_p.
13802     It should be OK not to handle entering_scope in this case, since
13803     DECL_CONTEXT will never be an alias template specialization.  We only get
13804     here with an alias when tsubst calls us for TYPENAME_TYPE.  */
13805  if (alias_template_specialization_p (t, nt_transparent))
13806    return tsubst (t, args, complain, in_decl);
13807
13808  switch (TREE_CODE (t))
13809    {
13810    case RECORD_TYPE:
13811      if (TYPE_PTRMEMFUNC_P (t))
13812	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13813
13814      /* Fall through.  */
13815    case ENUMERAL_TYPE:
13816    case UNION_TYPE:
13817      if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13818	{
13819	  tree argvec;
13820	  tree context;
13821	  tree r;
13822
13823	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
13824	  cp_evaluated ev;
13825
13826	  /* First, determine the context for the type we are looking
13827	     up.  */
13828	  context = TYPE_CONTEXT (t);
13829	  if (context && TYPE_P (context))
13830	    {
13831	      context = tsubst_aggr_type (context, args, complain,
13832					  in_decl, /*entering_scope=*/1);
13833	      /* If context is a nested class inside a class template,
13834	         it may still need to be instantiated (c++/33959).  */
13835	      context = complete_type (context);
13836	    }
13837
13838	  /* Then, figure out what arguments are appropriate for the
13839	     type we are trying to find.  For example, given:
13840
13841	       template <class T> struct S;
13842	       template <class T, class U> void f(T, U) { S<U> su; }
13843
13844	     and supposing that we are instantiating f<int, double>,
13845	     then our ARGS will be {int, double}, but, when looking up
13846	     S we only want {double}.  */
13847	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13848					 complain, in_decl);
13849	  if (argvec == error_mark_node)
13850	    r = error_mark_node;
13851	  else if (!entering_scope && (complain & tf_dguide)
13852		   && dependent_scope_p (context))
13853	    {
13854	      /* See maybe_dependent_member_ref.  */
13855	      tree name = TYPE_IDENTIFIER (t);
13856	      tree fullname = name;
13857	      if (instantiates_primary_template_p (t))
13858		fullname = build_nt (TEMPLATE_ID_EXPR, name,
13859				     INNERMOST_TEMPLATE_ARGS (argvec));
13860	      return build_typename_type (context, name, fullname,
13861					  typename_type);
13862	    }
13863	  else
13864	    {
13865	      r = lookup_template_class (t, argvec, in_decl, context,
13866					 entering_scope, complain);
13867	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13868	    }
13869
13870	  return r;
13871	}
13872      else
13873	/* This is not a template type, so there's nothing to do.  */
13874	return t;
13875
13876    default:
13877      return tsubst (t, args, complain, in_decl);
13878    }
13879}
13880
13881/* Map from a FUNCTION_DECL to a vec of default argument instantiations,
13882   indexed in reverse order of the parameters.  */
13883
13884static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
13885
13886/* Return a reference to the vec* of defarg insts for FN.  */
13887
13888static vec<tree,va_gc> *&
13889defarg_insts_for (tree fn)
13890{
13891  if (!defarg_inst)
13892    defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
13893  tree_vec_map in = { { fn }, nullptr };
13894  tree_vec_map **slot
13895    = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
13896  if (!*slot)
13897    {
13898      *slot = ggc_alloc<tree_vec_map> ();
13899      **slot = in;
13900    }
13901  return (*slot)->to;
13902}
13903
13904/* Substitute into the default argument ARG (a default argument for
13905   FN), which has the indicated TYPE.  */
13906
13907tree
13908tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13909			 tsubst_flags_t complain)
13910{
13911  int errs = errorcount + sorrycount;
13912
13913  /* This can happen in invalid code.  */
13914  if (TREE_CODE (arg) == DEFERRED_PARSE)
13915    return arg;
13916
13917  /* Shortcut {}.  */
13918  if (BRACE_ENCLOSED_INITIALIZER_P (arg)
13919      && CONSTRUCTOR_NELTS (arg) == 0)
13920    return arg;
13921
13922  tree parm = FUNCTION_FIRST_USER_PARM (fn);
13923  parm = chain_index (parmnum, parm);
13924  tree parmtype = TREE_TYPE (parm);
13925  if (DECL_BY_REFERENCE (parm))
13926    parmtype = TREE_TYPE (parmtype);
13927  if (parmtype == error_mark_node)
13928    return error_mark_node;
13929
13930  gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13931
13932  /* Remember the location of the pointer to the vec rather than the location
13933     of the particular element, in case the vec grows in tsubst_expr.  */
13934  vec<tree,va_gc> *&defs = defarg_insts_for (fn);
13935  /* Index in reverse order to avoid allocating space for initial parameters
13936     that don't have default arguments.  */
13937  unsigned ridx = list_length (parm);
13938  if (vec_safe_length (defs) < ridx)
13939    vec_safe_grow_cleared (defs, ridx);
13940  else if (tree inst = (*defs)[ridx - 1])
13941    return inst;
13942
13943  /* This default argument came from a template.  Instantiate the
13944     default argument here, not in tsubst.  In the case of
13945     something like:
13946
13947       template <class T>
13948       struct S {
13949	 static T t();
13950	 void f(T = t());
13951       };
13952
13953     we must be careful to do name lookup in the scope of S<T>,
13954     rather than in the current class.  */
13955  push_to_top_level ();
13956  push_access_scope (fn);
13957  push_deferring_access_checks (dk_no_deferred);
13958  start_lambda_scope (parm);
13959
13960  /* The default argument expression may cause implicitly defined
13961     member functions to be synthesized, which will result in garbage
13962     collection.  We must treat this situation as if we were within
13963     the body of function so as to avoid collecting live data on the
13964     stack.  */
13965  ++function_depth;
13966  arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13967		     complain, NULL_TREE,
13968		     /*integral_constant_expression_p=*/false);
13969  --function_depth;
13970
13971  finish_lambda_scope ();
13972
13973  /* Make sure the default argument is reasonable.  */
13974  arg = check_default_argument (type, arg, complain);
13975
13976  if (errorcount+sorrycount > errs
13977      && (complain & tf_warning_or_error))
13978    inform (input_location,
13979	    "  when instantiating default argument for call to %qD", fn);
13980
13981  pop_deferring_access_checks ();
13982  pop_access_scope (fn);
13983  pop_from_top_level ();
13984
13985  if (arg != error_mark_node && !cp_unevaluated_operand)
13986    (*defs)[ridx - 1] = arg;
13987
13988  return arg;
13989}
13990
13991/* Substitute into all the default arguments for FN.  */
13992
13993static void
13994tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13995{
13996  tree arg;
13997  tree tmpl_args;
13998
13999  tmpl_args = DECL_TI_ARGS (fn);
14000
14001  /* If this function is not yet instantiated, we certainly don't need
14002     its default arguments.  */
14003  if (uses_template_parms (tmpl_args))
14004    return;
14005  /* Don't do this again for clones.  */
14006  if (DECL_CLONED_FUNCTION_P (fn))
14007    return;
14008
14009  int i = 0;
14010  for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14011       arg;
14012       arg = TREE_CHAIN (arg), ++i)
14013    if (TREE_PURPOSE (arg))
14014      TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14015						    TREE_VALUE (arg),
14016						    TREE_PURPOSE (arg),
14017						    complain);
14018}
14019
14020/* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
14021static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14022
14023/* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
14024
14025void
14026store_explicit_specifier (tree v, tree t)
14027{
14028  if (!explicit_specifier_map)
14029    explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14030  DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14031  explicit_specifier_map->put (v, t);
14032}
14033
14034/* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
14035
14036tree
14037lookup_explicit_specifier (tree v)
14038{
14039  return *explicit_specifier_map->get (v);
14040}
14041
14042/* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14043   FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14044   are ARG_TYPES, and exception specification is RAISES, and otherwise is
14045   identical to T.  */
14046
14047static tree
14048rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14049				 tree raises, tsubst_flags_t complain)
14050{
14051  gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14052
14053  tree new_type;
14054  if (TREE_CODE (t) == FUNCTION_TYPE)
14055    {
14056      new_type = build_function_type (return_type, arg_types);
14057      new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14058    }
14059  else
14060    {
14061      tree r = TREE_TYPE (TREE_VALUE (arg_types));
14062      /* Don't pick up extra function qualifiers from the basetype.  */
14063      r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14064      if (! MAYBE_CLASS_TYPE_P (r))
14065	{
14066	  /* [temp.deduct]
14067
14068	     Type deduction may fail for any of the following
14069	     reasons:
14070
14071	     -- Attempting to create "pointer to member of T" when T
14072	     is not a class type.  */
14073	  if (complain & tf_error)
14074	    error ("creating pointer to member function of non-class type %qT",
14075		   r);
14076	  return error_mark_node;
14077	}
14078
14079      new_type = build_method_type_directly (r, return_type,
14080					     TREE_CHAIN (arg_types));
14081    }
14082  new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14083
14084  cp_ref_qualifier rqual = type_memfn_rqual (t);
14085  bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14086  return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14087}
14088
14089/* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14090   each of its formal parameters.  If there is a disagreement then rebuild
14091   DECL's function type according to its formal parameter types, as part of a
14092   resolution for Core issues 1001/1322.  */
14093
14094static void
14095maybe_rebuild_function_decl_type (tree decl)
14096{
14097  bool function_type_needs_rebuilding = false;
14098  if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14099    {
14100      tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14101      while (parm_type_list && parm_type_list != void_list_node)
14102	{
14103	  tree parm_type = TREE_VALUE (parm_type_list);
14104	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14105	  if (!same_type_p (parm_type, formal_parm_type_unqual))
14106	    {
14107	      function_type_needs_rebuilding = true;
14108	      break;
14109	    }
14110
14111	  parm_list = DECL_CHAIN (parm_list);
14112	  parm_type_list = TREE_CHAIN (parm_type_list);
14113	}
14114    }
14115
14116  if (!function_type_needs_rebuilding)
14117    return;
14118
14119  const tree fntype = TREE_TYPE (decl);
14120  tree parm_list = DECL_ARGUMENTS (decl);
14121  tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14122  tree new_parm_type_list = NULL_TREE;
14123  tree *q = &new_parm_type_list;
14124  for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14125    {
14126      *q = copy_node (old_parm_type_list);
14127      parm_list = DECL_CHAIN (parm_list);
14128      old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14129      q = &TREE_CHAIN (*q);
14130    }
14131  while (old_parm_type_list && old_parm_type_list != void_list_node)
14132    {
14133      *q = copy_node (old_parm_type_list);
14134      tree *new_parm_type = &TREE_VALUE (*q);
14135      tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14136      if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14137	*new_parm_type = formal_parm_type_unqual;
14138
14139      parm_list = DECL_CHAIN (parm_list);
14140      old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14141      q = &TREE_CHAIN (*q);
14142    }
14143  if (old_parm_type_list == void_list_node)
14144    *q = void_list_node;
14145
14146  TREE_TYPE (decl)
14147    = rebuild_function_or_method_type (fntype,
14148				       TREE_TYPE (fntype), new_parm_type_list,
14149				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14150}
14151
14152/* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
14153
14154static tree
14155tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14156		      tree lambda_fntype)
14157{
14158  tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14159  hashval_t hash = 0;
14160  tree in_decl = t;
14161
14162  /* Nobody should be tsubst'ing into non-template functions.  */
14163  gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14164	      || DECL_LOCAL_DECL_P (t));
14165
14166  if (DECL_LOCAL_DECL_P (t))
14167    {
14168      if (tree spec = retrieve_local_specialization (t))
14169	return spec;
14170    }
14171  else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14172    {
14173      /* If T is not dependent, just return it.  */
14174      if (!uses_template_parms (DECL_TI_ARGS (t))
14175	  && !LAMBDA_FUNCTION_P (t))
14176	return t;
14177
14178      /* Calculate the most general template of which R is a
14179	 specialization.  */
14180      gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14181
14182      /* We're substituting a lambda function under tsubst_lambda_expr but not
14183	 directly from it; find the matching function we're already inside.
14184	 But don't do this if T is a generic lambda with a single level of
14185	 template parms, as in that case we're doing a normal instantiation. */
14186      if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14187	  && (!generic_lambda_fn_p (t)
14188	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14189	return enclosing_instantiation_of (t);
14190
14191      /* Calculate the complete set of arguments used to
14192	 specialize R.  */
14193      argvec = tsubst_template_args (DECL_TI_ARGS
14194				     (DECL_TEMPLATE_RESULT
14195				      (DECL_TI_TEMPLATE (t))),
14196				     args, complain, in_decl);
14197      if (argvec == error_mark_node)
14198	return error_mark_node;
14199
14200      /* Check to see if we already have this specialization.  */
14201      if (!lambda_fntype)
14202	{
14203	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
14204	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14205	    /* The spec for these args might be a partial instantiation of the
14206	       template, but here what we want is the FUNCTION_DECL.  */
14207	    return STRIP_TEMPLATE (spec);
14208	}
14209    }
14210  else
14211    {
14212      /* This special case arises when we have something like this:
14213
14214	 template <class T> struct S {
14215	   friend void f<int>(int, double);
14216	 };
14217
14218	 Here, the DECL_TI_TEMPLATE for the friend declaration
14219	 will be an IDENTIFIER_NODE.  We are being called from
14220	 tsubst_friend_function, and we want only to create a
14221	 new decl (R) with appropriate types so that we can call
14222	 determine_specialization.  */
14223      gen_tmpl = NULL_TREE;
14224      argvec = NULL_TREE;
14225    }
14226
14227  tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14228		  : NULL_TREE);
14229  tree ctx = closure ? closure : DECL_CONTEXT (t);
14230  bool member = ctx && TYPE_P (ctx);
14231
14232  if (member && !closure)
14233    ctx = tsubst_aggr_type (ctx, args,
14234			    complain, t, /*entering_scope=*/1);
14235
14236  tree type = (lambda_fntype ? lambda_fntype
14237	       : tsubst (TREE_TYPE (t), args,
14238			 complain | tf_fndecl_type, in_decl));
14239  if (type == error_mark_node)
14240    return error_mark_node;
14241
14242  /* If we hit excessive deduction depth, the type is bogus even if
14243     it isn't error_mark_node, so don't build a decl.  */
14244  if (excessive_deduction_depth)
14245    return error_mark_node;
14246
14247  /* We do NOT check for matching decls pushed separately at this
14248     point, as they may not represent instantiations of this
14249     template, and in any case are considered separate under the
14250     discrete model.  */
14251  tree r = copy_decl (t);
14252  DECL_USE_TEMPLATE (r) = 0;
14253  TREE_TYPE (r) = type;
14254  /* Clear out the mangled name and RTL for the instantiation.  */
14255  SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14256  SET_DECL_RTL (r, NULL);
14257  /* Leave DECL_INITIAL set on deleted instantiations.  */
14258  if (!DECL_DELETED_FN (r))
14259    DECL_INITIAL (r) = NULL_TREE;
14260  DECL_CONTEXT (r) = ctx;
14261  set_instantiating_module (r);
14262
14263  /* Handle explicit(dependent-expr).  */
14264  if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14265    {
14266      tree spec = lookup_explicit_specifier (t);
14267      spec = tsubst_copy_and_build (spec, args, complain, in_decl,
14268				    /*function_p=*/false,
14269				    /*i_c_e_p=*/true);
14270      spec = build_explicit_specifier (spec, complain);
14271      if (instantiation_dependent_expression_p (spec))
14272	store_explicit_specifier (r, spec);
14273      else
14274	{
14275	  DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14276	  DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14277	}
14278    }
14279
14280  /* OpenMP UDRs have the only argument a reference to the declared
14281     type.  We want to diagnose if the declared type is a reference,
14282     which is invalid, but as references to references are usually
14283     quietly merged, diagnose it here.  */
14284  if (DECL_OMP_DECLARE_REDUCTION_P (t))
14285    {
14286      tree argtype
14287	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14288      argtype = tsubst (argtype, args, complain, in_decl);
14289      if (TYPE_REF_P (argtype))
14290	error_at (DECL_SOURCE_LOCATION (t),
14291		  "reference type %qT in "
14292		  "%<#pragma omp declare reduction%>", argtype);
14293      if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14294	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14295					  argtype);
14296    }
14297
14298  if (member && DECL_CONV_FN_P (r))
14299    /* Type-conversion operator.  Reconstruct the name, in
14300       case it's the name of one of the template's parameters.  */
14301    DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14302
14303  tree parms = DECL_ARGUMENTS (t);
14304  if (closure)
14305    parms = DECL_CHAIN (parms);
14306  parms = tsubst (parms, args, complain, t);
14307  for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14308    DECL_CONTEXT (parm) = r;
14309  if (closure)
14310    {
14311      tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14312      DECL_NAME (tparm) = closure_identifier;
14313      DECL_CHAIN (tparm) = parms;
14314      parms = tparm;
14315    }
14316  DECL_ARGUMENTS (r) = parms;
14317  DECL_RESULT (r) = NULL_TREE;
14318
14319  maybe_rebuild_function_decl_type (r);
14320
14321  TREE_STATIC (r) = 0;
14322  TREE_PUBLIC (r) = TREE_PUBLIC (t);
14323  DECL_EXTERNAL (r) = 1;
14324  /* If this is an instantiation of a function with internal
14325     linkage, we already know what object file linkage will be
14326     assigned to the instantiation.  */
14327  DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14328  DECL_DEFER_OUTPUT (r) = 0;
14329  DECL_CHAIN (r) = NULL_TREE;
14330  DECL_PENDING_INLINE_INFO (r) = 0;
14331  DECL_PENDING_INLINE_P (r) = 0;
14332  DECL_SAVED_TREE (r) = NULL_TREE;
14333  DECL_STRUCT_FUNCTION (r) = NULL;
14334  TREE_USED (r) = 0;
14335  /* We'll re-clone as appropriate in instantiate_template.  */
14336  DECL_CLONED_FUNCTION (r) = NULL_TREE;
14337
14338  /* If we aren't complaining now, return on error before we register
14339     the specialization so that we'll complain eventually.  */
14340  if ((complain & tf_error) == 0
14341      && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14342      && !grok_op_properties (r, /*complain=*/false))
14343    return error_mark_node;
14344
14345  /* Associate the constraints directly with the instantiation. We
14346     don't substitute through the constraints; that's only done when
14347     they are checked.  */
14348  if (tree ci = get_constraints (t))
14349    set_constraints (r, ci);
14350
14351  if (DECL_FRIEND_CONTEXT (t))
14352    SET_DECL_FRIEND_CONTEXT (r,
14353			     tsubst (DECL_FRIEND_CONTEXT (t),
14354				     args, complain, in_decl));
14355
14356  if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14357				       args, complain, in_decl))
14358    return error_mark_node;
14359
14360  /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
14361     this in the special friend case mentioned above where
14362     GEN_TMPL is NULL.  */
14363  if (gen_tmpl && !closure)
14364    {
14365      DECL_TEMPLATE_INFO (r)
14366	= build_template_info (gen_tmpl, argvec);
14367      SET_DECL_IMPLICIT_INSTANTIATION (r);
14368
14369      tree new_r
14370	= register_specialization (r, gen_tmpl, argvec, false, hash);
14371      if (new_r != r)
14372	/* We instantiated this while substituting into
14373	   the type earlier (template/friend54.C).  */
14374	return new_r;
14375
14376      /* We're not supposed to instantiate default arguments
14377	 until they are called, for a template.  But, for a
14378	 declaration like:
14379
14380	 template <class T> void f ()
14381	 { extern void g(int i = T()); }
14382
14383	 we should do the substitution when the template is
14384	 instantiated.  We handle the member function case in
14385	 instantiate_class_template since the default arguments
14386	 might refer to other members of the class.  */
14387      if (!member
14388	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
14389	  && !uses_template_parms (argvec))
14390	tsubst_default_arguments (r, complain);
14391    }
14392  else if (DECL_LOCAL_DECL_P (r))
14393    {
14394      if (!cp_unevaluated_operand)
14395	register_local_specialization (r, t);
14396    }
14397  else
14398    DECL_TEMPLATE_INFO (r) = NULL_TREE;
14399
14400  /* Copy the list of befriending classes.  */
14401  for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14402       *friends;
14403       friends = &TREE_CHAIN (*friends))
14404    {
14405      *friends = copy_node (*friends);
14406      TREE_VALUE (*friends)
14407	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14408    }
14409
14410  if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14411    {
14412      maybe_retrofit_in_chrg (r);
14413      if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14414	return error_mark_node;
14415      /* If this is an instantiation of a member template, clone it.
14416	 If it isn't, that'll be handled by
14417	 clone_constructors_and_destructors.  */
14418      if (PRIMARY_TEMPLATE_P (gen_tmpl))
14419	clone_cdtor (r, /*update_methods=*/false);
14420    }
14421  else if ((complain & tf_error) != 0
14422	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14423	   && !grok_op_properties (r, /*complain=*/true))
14424    return error_mark_node;
14425
14426  /* Possibly limit visibility based on template args.  */
14427  DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14428  if (DECL_VISIBILITY_SPECIFIED (t))
14429    {
14430      DECL_VISIBILITY_SPECIFIED (r) = 0;
14431      DECL_ATTRIBUTES (r)
14432	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14433    }
14434  determine_visibility (r);
14435  if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14436      && !processing_template_decl)
14437    defaulted_late_check (r);
14438
14439  if (flag_openmp)
14440    if (tree attr = lookup_attribute ("omp declare variant base",
14441				      DECL_ATTRIBUTES (r)))
14442      omp_declare_variant_finalize (r, attr);
14443
14444  return r;
14445}
14446
14447/* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
14448
14449static tree
14450tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14451		      tree lambda_fntype)
14452{
14453  /* We can get here when processing a member function template,
14454     member class template, or template template parameter.  */
14455  tree decl = DECL_TEMPLATE_RESULT (t);
14456  tree in_decl = t;
14457  tree spec;
14458  tree tmpl_args;
14459  tree full_args;
14460  tree r;
14461  hashval_t hash = 0;
14462
14463  if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14464    {
14465      /* Template template parameter is treated here.  */
14466      tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14467      if (new_type == error_mark_node)
14468	r = error_mark_node;
14469      /* If we get a real template back, return it.  This can happen in
14470	 the context of most_specialized_partial_spec.  */
14471      else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14472	r = new_type;
14473      else
14474	/* The new TEMPLATE_DECL was built in
14475	   reduce_template_parm_level.  */
14476	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14477      return r;
14478    }
14479
14480  if (!lambda_fntype)
14481    {
14482      /* We might already have an instance of this template.
14483	 The ARGS are for the surrounding class type, so the
14484	 full args contain the tsubst'd args for the context,
14485	 plus the innermost args from the template decl.  */
14486      tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14487	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14488	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14489      /* Because this is a template, the arguments will still be
14490	 dependent, even after substitution.  If
14491	 PROCESSING_TEMPLATE_DECL is not set, the dependency
14492	 predicates will short-circuit.  */
14493      ++processing_template_decl;
14494      full_args = tsubst_template_args (tmpl_args, args,
14495					complain, in_decl);
14496      --processing_template_decl;
14497      if (full_args == error_mark_node)
14498	return error_mark_node;
14499
14500      /* If this is a default template template argument,
14501	 tsubst might not have changed anything.  */
14502      if (full_args == tmpl_args)
14503	return t;
14504
14505      hash = hash_tmpl_and_args (t, full_args);
14506      spec = retrieve_specialization (t, full_args, hash);
14507      if (spec != NULL_TREE)
14508	{
14509	  if (TYPE_P (spec))
14510	    /* Type partial instantiations are stored as the type by
14511	       lookup_template_class_1, not here as the template.  */
14512	    spec = CLASSTYPE_TI_TEMPLATE (spec);
14513	  return spec;
14514	}
14515    }
14516
14517  /* Make a new template decl.  It will be similar to the
14518     original, but will record the current template arguments.
14519     We also create a new function declaration, which is just
14520     like the old one, but points to this new template, rather
14521     than the old one.  */
14522  r = copy_decl (t);
14523  gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14524  DECL_CHAIN (r) = NULL_TREE;
14525
14526  // Build new template info linking to the original template decl.
14527  if (!lambda_fntype)
14528    {
14529      DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14530      SET_DECL_IMPLICIT_INSTANTIATION (r);
14531    }
14532  else
14533    DECL_TEMPLATE_INFO (r) = NULL_TREE;
14534
14535  /* The template parameters for this new template are all the
14536     template parameters for the old template, except the
14537     outermost level of parameters.  */
14538  auto tparm_guard = make_temp_override (current_template_parms);
14539  DECL_TEMPLATE_PARMS (r)
14540    = current_template_parms
14541    = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14542			     complain);
14543
14544  bool class_p = false;
14545  tree inner = decl;
14546  ++processing_template_decl;
14547  if (TREE_CODE (inner) == FUNCTION_DECL)
14548    inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14549  else
14550    {
14551      if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14552	{
14553	  class_p = true;
14554	  inner = TREE_TYPE (inner);
14555	}
14556      if (class_p)
14557	inner = tsubst_aggr_type (inner, args, complain,
14558				  in_decl, /*entering*/1);
14559      else
14560	inner = tsubst (inner, args, complain, in_decl);
14561    }
14562  --processing_template_decl;
14563  if (inner == error_mark_node)
14564    return error_mark_node;
14565
14566  if (class_p)
14567    {
14568      /* For a partial specialization, we need to keep pointing to
14569	 the primary template.  */
14570      if (!DECL_TEMPLATE_SPECIALIZATION (t))
14571	CLASSTYPE_TI_TEMPLATE (inner) = r;
14572
14573      DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14574      inner = TYPE_MAIN_DECL (inner);
14575    }
14576  else if (lambda_fntype)
14577    {
14578      tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14579      DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14580    }
14581  else
14582    {
14583      DECL_TI_TEMPLATE (inner) = r;
14584      DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14585    }
14586
14587  DECL_TEMPLATE_RESULT (r) = inner;
14588  TREE_TYPE (r) = TREE_TYPE (inner);
14589  DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14590
14591  if (modules_p ())
14592    {
14593      /* Propagate module information from the decl.  */
14594      DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14595      if (DECL_LANG_SPECIFIC (inner))
14596	/* If this is a constrained template, the above tsubst of
14597	   inner can find the unconstrained template, which may have
14598	   come from an import.  This is ok, because we don't
14599	   register this instantiation (see below).  */
14600	gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14601			     || (TEMPLATE_PARMS_CONSTRAINTS
14602				 (DECL_TEMPLATE_PARMS (t))));
14603    }
14604
14605  DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14606  DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14607
14608  if (PRIMARY_TEMPLATE_P (t))
14609    DECL_PRIMARY_TEMPLATE (r) = r;
14610
14611  if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14612    /* Record this non-type partial instantiation.  */
14613    register_specialization (r, t,
14614			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14615			     false, hash);
14616
14617  return r;
14618}
14619
14620/* True if FN is the op() for a lambda in an uninstantiated template.  */
14621
14622bool
14623lambda_fn_in_template_p (tree fn)
14624{
14625  if (!fn || !LAMBDA_FUNCTION_P (fn))
14626    return false;
14627  tree closure = DECL_CONTEXT (fn);
14628  return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14629}
14630
14631/* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14632   which the above is true.  */
14633
14634bool
14635regenerated_lambda_fn_p (tree fn)
14636{
14637  if (!fn || !LAMBDA_FUNCTION_P (fn))
14638    return false;
14639  tree closure = DECL_CONTEXT (fn);
14640  tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14641  return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14642}
14643
14644/* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14645   If T is not a regenerated LAMBDA_EXPR, return T.  */
14646
14647tree
14648most_general_lambda (tree t)
14649{
14650  while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14651    t = TI_TEMPLATE (ti);
14652  return t;
14653}
14654
14655/* Return the set of template arguments used to regenerate the lambda T
14656   from its most general lambda.  */
14657
14658tree
14659lambda_regenerating_args (tree t)
14660{
14661  if (LAMBDA_FUNCTION_P (t))
14662    t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14663  gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14664  if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14665    return TI_ARGS (ti);
14666  else
14667    return NULL_TREE;
14668}
14669
14670/* We're instantiating a variable from template function TCTX.  Return the
14671   corresponding current enclosing scope.  We can match them up using
14672   DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14673   the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14674   the template definition in regenerate_decl_from_template.  */
14675
14676static tree
14677enclosing_instantiation_of (tree tctx)
14678{
14679  tree fn = current_function_decl;
14680
14681  /* We shouldn't ever need to do this for other artificial functions.  */
14682  gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14683
14684  for (; fn; fn = decl_function_context (fn))
14685    if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14686      return fn;
14687  gcc_unreachable ();
14688}
14689
14690/* Substitute the ARGS into the T, which is a _DECL.  Return the
14691   result of the substitution.  Issue error and warning messages under
14692   control of COMPLAIN.  */
14693
14694static tree
14695tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14696{
14697#define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14698  location_t saved_loc;
14699  tree r = NULL_TREE;
14700  tree in_decl = t;
14701  hashval_t hash = 0;
14702
14703  /* Set the filename and linenumber to improve error-reporting.  */
14704  saved_loc = input_location;
14705  input_location = DECL_SOURCE_LOCATION (t);
14706
14707  switch (TREE_CODE (t))
14708    {
14709    case TEMPLATE_DECL:
14710      r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14711      break;
14712
14713    case FUNCTION_DECL:
14714      r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14715      break;
14716
14717    case PARM_DECL:
14718      {
14719	tree type = NULL_TREE;
14720        int i, len = 1;
14721        tree expanded_types = NULL_TREE;
14722        tree prev_r = NULL_TREE;
14723        tree first_r = NULL_TREE;
14724
14725        if (DECL_PACK_P (t))
14726          {
14727            /* If there is a local specialization that isn't a
14728               parameter pack, it means that we're doing a "simple"
14729               substitution from inside tsubst_pack_expansion. Just
14730               return the local specialization (which will be a single
14731               parm).  */
14732            tree spec = retrieve_local_specialization (t);
14733            if (spec
14734                && TREE_CODE (spec) == PARM_DECL
14735                && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14736              RETURN (spec);
14737
14738            /* Expand the TYPE_PACK_EXPANSION that provides the types for
14739               the parameters in this function parameter pack.  */
14740            expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14741						    complain, in_decl);
14742            if (TREE_CODE (expanded_types) == TREE_VEC)
14743              {
14744                len = TREE_VEC_LENGTH (expanded_types);
14745
14746                /* Zero-length parameter packs are boring. Just substitute
14747                   into the chain.  */
14748		if (len == 0 && !cp_unevaluated_operand)
14749                  RETURN (tsubst (TREE_CHAIN (t), args, complain,
14750				  TREE_CHAIN (t)));
14751              }
14752            else
14753              {
14754                /* All we did was update the type. Make a note of that.  */
14755                type = expanded_types;
14756                expanded_types = NULL_TREE;
14757              }
14758          }
14759
14760        /* Loop through all of the parameters we'll build. When T is
14761           a function parameter pack, LEN is the number of expanded
14762           types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14763        r = NULL_TREE;
14764        for (i = 0; i < len; ++i)
14765          {
14766            prev_r = r;
14767            r = copy_node (t);
14768            if (DECL_TEMPLATE_PARM_P (t))
14769              SET_DECL_TEMPLATE_PARM_P (r);
14770
14771            if (expanded_types)
14772              /* We're on the Ith parameter of the function parameter
14773                 pack.  */
14774              {
14775                /* Get the Ith type.  */
14776                type = TREE_VEC_ELT (expanded_types, i);
14777
14778		/* Rename the parameter to include the index.  */
14779		DECL_NAME (r)
14780		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14781              }
14782            else if (!type)
14783              /* We're dealing with a normal parameter.  */
14784              type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14785
14786            type = type_decays_to (type);
14787            TREE_TYPE (r) = type;
14788            cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14789
14790            if (DECL_INITIAL (r))
14791              {
14792                if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14793                  DECL_INITIAL (r) = TREE_TYPE (r);
14794                else
14795                  DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14796                                             complain, in_decl);
14797              }
14798
14799            DECL_CONTEXT (r) = NULL_TREE;
14800
14801            if (!DECL_TEMPLATE_PARM_P (r))
14802              DECL_ARG_TYPE (r) = type_passed_as (type);
14803
14804	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14805						 args, complain, in_decl))
14806	      return error_mark_node;
14807
14808            /* Keep track of the first new parameter we
14809               generate. That's what will be returned to the
14810               caller.  */
14811            if (!first_r)
14812              first_r = r;
14813
14814            /* Build a proper chain of parameters when substituting
14815               into a function parameter pack.  */
14816            if (prev_r)
14817              DECL_CHAIN (prev_r) = r;
14818          }
14819
14820	/* If cp_unevaluated_operand is set, we're just looking for a
14821	   single dummy parameter, so don't keep going.  */
14822	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14823	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14824				   complain, DECL_CHAIN (t));
14825
14826        /* FIRST_R contains the start of the chain we've built.  */
14827        r = first_r;
14828      }
14829      break;
14830
14831    case FIELD_DECL:
14832      {
14833	tree type = NULL_TREE;
14834	tree vec = NULL_TREE;
14835	tree expanded_types = NULL_TREE;
14836	int len = 1;
14837
14838	if (PACK_EXPANSION_P (TREE_TYPE (t)))
14839	  {
14840	    /* This field is a lambda capture pack.  Return a TREE_VEC of
14841	       the expanded fields to instantiate_class_template_1.  */
14842            expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14843						    complain, in_decl);
14844            if (TREE_CODE (expanded_types) == TREE_VEC)
14845              {
14846                len = TREE_VEC_LENGTH (expanded_types);
14847		vec = make_tree_vec (len);
14848              }
14849            else
14850              {
14851                /* All we did was update the type. Make a note of that.  */
14852                type = expanded_types;
14853                expanded_types = NULL_TREE;
14854              }
14855	  }
14856
14857	for (int i = 0; i < len; ++i)
14858	  {
14859	    r = copy_decl (t);
14860	    if (expanded_types)
14861	      {
14862		type = TREE_VEC_ELT (expanded_types, i);
14863		DECL_NAME (r)
14864		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14865	      }
14866            else if (!type)
14867              type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14868
14869	    if (type == error_mark_node)
14870	      RETURN (error_mark_node);
14871	    TREE_TYPE (r) = type;
14872	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14873
14874	    if (DECL_C_BIT_FIELD (r))
14875	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14876		 number of bits.  */
14877	      DECL_BIT_FIELD_REPRESENTATIVE (r)
14878		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14879			       complain, in_decl,
14880			       /*integral_constant_expression_p=*/true);
14881	    if (DECL_INITIAL (t))
14882	      {
14883		/* Set up DECL_TEMPLATE_INFO so that we can get at the
14884		   NSDMI in perform_member_init.  Still set DECL_INITIAL
14885		   so that we know there is one.  */
14886		DECL_INITIAL (r) = void_node;
14887		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14888		retrofit_lang_decl (r);
14889		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14890	      }
14891	    /* We don't have to set DECL_CONTEXT here; it is set by
14892	       finish_member_declaration.  */
14893	    DECL_CHAIN (r) = NULL_TREE;
14894
14895	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14896						 args, complain, in_decl))
14897	      return error_mark_node;
14898
14899	    if (vec)
14900	      TREE_VEC_ELT (vec, i) = r;
14901	  }
14902
14903	if (vec)
14904	  r = vec;
14905      }
14906      break;
14907
14908    case USING_DECL:
14909      /* We reach here only for member using decls.  We also need to check
14910	 uses_template_parms because DECL_DEPENDENT_P is not set for a
14911	 using-declaration that designates a member of the current
14912	 instantiation (c++/53549).  */
14913      if (DECL_DEPENDENT_P (t)
14914	  || uses_template_parms (USING_DECL_SCOPE (t)))
14915	{
14916	  tree scope = USING_DECL_SCOPE (t);
14917	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14918	  if (PACK_EXPANSION_P (scope))
14919	    {
14920	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14921	      int len = TREE_VEC_LENGTH (vec);
14922	      r = make_tree_vec (len);
14923	      for (int i = 0; i < len; ++i)
14924		{
14925		  tree escope = TREE_VEC_ELT (vec, i);
14926		  tree elt = do_class_using_decl (escope, name);
14927		  if (!elt)
14928		    {
14929		      r = error_mark_node;
14930		      break;
14931		    }
14932		  else
14933		    {
14934		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14935		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14936		    }
14937		  TREE_VEC_ELT (r, i) = elt;
14938		}
14939	    }
14940	  else
14941	    {
14942	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14943					     complain, in_decl);
14944	      r = do_class_using_decl (inst_scope, name);
14945	      if (!r)
14946		r = error_mark_node;
14947	      else
14948		{
14949		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
14950		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
14951		}
14952	    }
14953	}
14954      else
14955	{
14956	  r = copy_node (t);
14957	  DECL_CHAIN (r) = NULL_TREE;
14958	}
14959      break;
14960
14961    case TYPE_DECL:
14962    case VAR_DECL:
14963      {
14964	tree argvec = NULL_TREE;
14965	tree gen_tmpl = NULL_TREE;
14966	tree tmpl = NULL_TREE;
14967	tree type = NULL_TREE;
14968
14969	if (TREE_TYPE (t) == error_mark_node)
14970	  RETURN (error_mark_node);
14971
14972	if (TREE_CODE (t) == TYPE_DECL
14973	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14974	  {
14975	    /* If this is the canonical decl, we don't have to
14976	       mess with instantiations, and often we can't (for
14977	       typename, template type parms and such).  Note that
14978	       TYPE_NAME is not correct for the above test if
14979	       we've copied the type for a typedef.  */
14980	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14981	    if (type == error_mark_node)
14982	      RETURN (error_mark_node);
14983	    r = TYPE_NAME (type);
14984	    break;
14985	  }
14986
14987	/* Check to see if we already have the specialization we
14988	   need.  */
14989	tree spec = NULL_TREE;
14990	bool local_p = false;
14991	tree ctx = DECL_CONTEXT (t);
14992	if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
14993	    && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
14994	  {
14995	    local_p = false;
14996	    if (DECL_CLASS_SCOPE_P (t))
14997	      {
14998		ctx = tsubst_aggr_type (ctx, args,
14999					complain,
15000					in_decl, /*entering_scope=*/1);
15001		/* If CTX is unchanged, then T is in fact the
15002		   specialization we want.  That situation occurs when
15003		   referencing a static data member within in its own
15004		   class.  We can use pointer equality, rather than
15005		   same_type_p, because DECL_CONTEXT is always
15006		   canonical...  */
15007		if (ctx == DECL_CONTEXT (t)
15008		    /* ... unless T is a member template; in which
15009		       case our caller can be willing to create a
15010		       specialization of that template represented
15011		       by T.  */
15012		    && !(DECL_TI_TEMPLATE (t)
15013			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15014		  spec = t;
15015	      }
15016
15017	    if (!spec)
15018	      {
15019		tmpl = DECL_TI_TEMPLATE (t);
15020		gen_tmpl = most_general_template (tmpl);
15021		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15022		if (argvec != error_mark_node)
15023		  argvec = (coerce_innermost_template_parms
15024			    (DECL_TEMPLATE_PARMS (gen_tmpl),
15025			     argvec, t, complain,
15026			     /*all*/true, /*defarg*/true));
15027		if (argvec == error_mark_node)
15028		  RETURN (error_mark_node);
15029		hash = hash_tmpl_and_args (gen_tmpl, argvec);
15030		spec = retrieve_specialization (gen_tmpl, argvec, hash);
15031	      }
15032	  }
15033	else
15034	  {
15035	    if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15036	      /* Subsequent calls to pushdecl will fill this in.  */
15037	      ctx = NULL_TREE;
15038	    /* A local variable.  */
15039	    local_p = true;
15040	    /* Unless this is a reference to a static variable from an
15041	       enclosing function, in which case we need to fill it in now.  */
15042	    if (TREE_STATIC (t))
15043	      {
15044		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15045		if (fn != current_function_decl)
15046		  ctx = fn;
15047	      }
15048	    spec = retrieve_local_specialization (t);
15049	  }
15050	/* If we already have the specialization we need, there is
15051	   nothing more to do.  */
15052	if (spec)
15053	  {
15054	    r = spec;
15055	    break;
15056	  }
15057
15058	/* Create a new node for the specialization we need.  */
15059	if (type == NULL_TREE)
15060	  {
15061	    if (is_typedef_decl (t))
15062	      type = DECL_ORIGINAL_TYPE (t);
15063	    else
15064	      type = TREE_TYPE (t);
15065	    if (VAR_P (t)
15066		&& VAR_HAD_UNKNOWN_BOUND (t)
15067		&& type != error_mark_node)
15068	      type = strip_array_domain (type);
15069	    tsubst_flags_t tcomplain = complain;
15070	    if (VAR_P (t))
15071	      tcomplain |= tf_tst_ok;
15072	    type = tsubst (type, args, tcomplain, in_decl);
15073	    /* Substituting the type might have recursively instantiated this
15074	       same alias (c++/86171).  */
15075	    if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15076		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15077	      {
15078		r = spec;
15079		break;
15080	      }
15081	  }
15082	r = copy_decl (t);
15083	if (VAR_P (r))
15084	  {
15085	    DECL_INITIALIZED_P (r) = 0;
15086	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
15087	    if (type == error_mark_node)
15088	      RETURN (error_mark_node);
15089	    if (TREE_CODE (type) == FUNCTION_TYPE)
15090	      {
15091		/* It may seem that this case cannot occur, since:
15092
15093		   typedef void f();
15094		   void g() { f x; }
15095
15096		   declares a function, not a variable.  However:
15097
15098		   typedef void f();
15099		   template <typename T> void g() { T t; }
15100		   template void g<f>();
15101
15102		   is an attempt to declare a variable with function
15103		   type.  */
15104		error ("variable %qD has function type",
15105		       /* R is not yet sufficiently initialized, so we
15106			  just use its name.  */
15107		       DECL_NAME (r));
15108		RETURN (error_mark_node);
15109	      }
15110	    type = complete_type (type);
15111	    /* Wait until cp_finish_decl to set this again, to handle
15112	       circular dependency (template/instantiate6.C). */
15113	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15114	    type = check_var_type (DECL_NAME (r), type,
15115				   DECL_SOURCE_LOCATION (r));
15116	    if (DECL_HAS_VALUE_EXPR_P (t))
15117	      {
15118		tree ve = DECL_VALUE_EXPR (t);
15119		/* If the DECL_VALUE_EXPR is converted to the declared type,
15120		   preserve the identity so that gimplify_type_sizes works.  */
15121		bool nop = (TREE_CODE (ve) == NOP_EXPR);
15122		if (nop)
15123		  ve = TREE_OPERAND (ve, 0);
15124		ve = tsubst_expr (ve, args, complain, in_decl,
15125				  /*constant_expression_p=*/false);
15126		if (REFERENCE_REF_P (ve))
15127		  {
15128		    gcc_assert (TYPE_REF_P (type));
15129		    ve = TREE_OPERAND (ve, 0);
15130		  }
15131		if (nop)
15132		  ve = build_nop (type, ve);
15133		else if (DECL_LANG_SPECIFIC (t)
15134			 && DECL_OMP_PRIVATIZED_MEMBER (t)
15135			 && TREE_CODE (ve) == COMPONENT_REF
15136			 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15137			 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15138		  type = TREE_TYPE (ve);
15139		else
15140		  gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15141				       == TYPE_MAIN_VARIANT (type));
15142		SET_DECL_VALUE_EXPR (r, ve);
15143	      }
15144	    if (CP_DECL_THREAD_LOCAL_P (r)
15145		&& !processing_template_decl)
15146	      set_decl_tls_model (r, decl_default_tls_model (r));
15147	  }
15148	else if (DECL_SELF_REFERENCE_P (t))
15149	  SET_DECL_SELF_REFERENCE_P (r);
15150	TREE_TYPE (r) = type;
15151	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15152	DECL_CONTEXT (r) = ctx;
15153	/* Clear out the mangled name and RTL for the instantiation.  */
15154	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15155	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15156	  SET_DECL_RTL (r, NULL);
15157	set_instantiating_module (r);
15158
15159	/* The initializer must not be expanded until it is required;
15160	   see [temp.inst].  */
15161	DECL_INITIAL (r) = NULL_TREE;
15162	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15163	if (VAR_P (r))
15164	  {
15165	    if (DECL_LANG_SPECIFIC (r))
15166	      SET_DECL_DEPENDENT_INIT_P (r, false);
15167
15168	    SET_DECL_MODE (r, VOIDmode);
15169
15170	    /* Possibly limit visibility based on template args.  */
15171	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15172	    if (DECL_VISIBILITY_SPECIFIED (t))
15173	      {
15174		DECL_VISIBILITY_SPECIFIED (r) = 0;
15175		DECL_ATTRIBUTES (r)
15176		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15177	      }
15178	    determine_visibility (r);
15179	  }
15180
15181	if (!local_p)
15182	  {
15183	    /* A static data member declaration is always marked
15184	       external when it is declared in-class, even if an
15185	       initializer is present.  We mimic the non-template
15186	       processing here.  */
15187	    DECL_EXTERNAL (r) = 1;
15188	    if (DECL_NAMESPACE_SCOPE_P (t))
15189	      DECL_NOT_REALLY_EXTERN (r) = 1;
15190
15191	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15192	    SET_DECL_IMPLICIT_INSTANTIATION (r);
15193	    if (!error_operand_p (r) || (complain & tf_error))
15194	      register_specialization (r, gen_tmpl, argvec, false, hash);
15195	  }
15196	else
15197	  {
15198	    if (DECL_LANG_SPECIFIC (r))
15199	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
15200	    if (!cp_unevaluated_operand)
15201	      register_local_specialization (r, t);
15202	  }
15203
15204	DECL_CHAIN (r) = NULL_TREE;
15205
15206	if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15207					     /*flags=*/0,
15208					     args, complain, in_decl))
15209	  return error_mark_node;
15210
15211	/* Preserve a typedef that names a type.  */
15212	if (is_typedef_decl (r) && type != error_mark_node)
15213	  {
15214	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15215	    set_underlying_type (r);
15216
15217	    /* common_handle_aligned_attribute doesn't apply the alignment
15218	       to DECL_ORIGINAL_TYPE.  */
15219	    if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15220	      TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15221						  TYPE_ALIGN (TREE_TYPE (t)));
15222	  }
15223
15224	layout_decl (r, 0);
15225      }
15226      break;
15227
15228    default:
15229      gcc_unreachable ();
15230    }
15231#undef RETURN
15232
15233 out:
15234  /* Restore the file and line information.  */
15235  input_location = saved_loc;
15236
15237  return r;
15238}
15239
15240/* Substitute into the complete parameter type list PARMS.  */
15241
15242tree
15243tsubst_function_parms (tree parms,
15244		       tree args,
15245		       tsubst_flags_t complain,
15246		       tree in_decl)
15247{
15248  return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15249}
15250
15251/* Substitute into the ARG_TYPES of a function type.
15252   If END is a TREE_CHAIN, leave it and any following types
15253   un-substituted.  */
15254
15255static tree
15256tsubst_arg_types (tree arg_types,
15257		  tree args,
15258		  tree end,
15259		  tsubst_flags_t complain,
15260		  tree in_decl)
15261{
15262  tree type = NULL_TREE;
15263  int len = 1;
15264  tree expanded_args = NULL_TREE;
15265
15266  if (!arg_types || arg_types == void_list_node || arg_types == end)
15267    return arg_types;
15268
15269  if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15270    {
15271      /* For a pack expansion, perform substitution on the
15272         entire expression. Later on, we'll handle the arguments
15273         one-by-one.  */
15274      expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15275                                            args, complain, in_decl);
15276
15277      if (TREE_CODE (expanded_args) == TREE_VEC)
15278        /* So that we'll spin through the parameters, one by one.  */
15279	len = TREE_VEC_LENGTH (expanded_args);
15280      else
15281        {
15282          /* We only partially substituted into the parameter
15283             pack. Our type is TYPE_PACK_EXPANSION.  */
15284          type = expanded_args;
15285          expanded_args = NULL_TREE;
15286        }
15287    }
15288  else
15289    type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15290
15291  /* Check if a substituted type is erroneous before substituting into
15292     the rest of the chain.  */
15293  for (int i = 0; i < len; i++)
15294    {
15295      if (expanded_args)
15296	type = TREE_VEC_ELT (expanded_args, i);
15297
15298      if (type == error_mark_node)
15299	return error_mark_node;
15300      if (VOID_TYPE_P (type))
15301	{
15302	  if (complain & tf_error)
15303	    {
15304	      error ("invalid parameter type %qT", type);
15305	      if (in_decl)
15306		error ("in declaration %q+D", in_decl);
15307	    }
15308	  return error_mark_node;
15309	}
15310    }
15311
15312  /* We do not substitute into default arguments here.  The standard
15313     mandates that they be instantiated only when needed, which is
15314     done in build_over_call.  */
15315  tree default_arg = TREE_PURPOSE (arg_types);
15316
15317  /* Except that we do substitute default arguments under tsubst_lambda_expr,
15318     since the new op() won't have any associated template arguments for us
15319     to refer to later.  */
15320  if (lambda_fn_in_template_p (in_decl)
15321      || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15322	  && DECL_LOCAL_DECL_P (in_decl)))
15323    default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
15324					 false/*fn*/, false/*constexpr*/);
15325
15326  tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15327					       args, end, complain, in_decl);
15328  if (remaining_arg_types == error_mark_node)
15329    return error_mark_node;
15330
15331  for (int i = len-1; i >= 0; i--)
15332    {
15333      if (expanded_args)
15334	type = TREE_VEC_ELT (expanded_args, i);
15335
15336      /* Do array-to-pointer, function-to-pointer conversion, and ignore
15337	 top-level qualifiers as required.  */
15338      type = cv_unqualified (type_decays_to (type));
15339
15340      if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15341	{
15342	  /* We've instantiated a template before its default arguments
15343	     have been parsed.  This can happen for a nested template
15344	     class, and is not an error unless we require the default
15345	     argument in a call of this function.  */
15346	  remaining_arg_types
15347	    = tree_cons (default_arg, type, remaining_arg_types);
15348	  vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15349			 remaining_arg_types);
15350	}
15351      else
15352	remaining_arg_types
15353	  = hash_tree_cons (default_arg, type, remaining_arg_types);
15354    }
15355
15356  return remaining_arg_types;
15357}
15358
15359/* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
15360   *not* handle the exception-specification for FNTYPE, because the
15361   initial substitution of explicitly provided template parameters
15362   during argument deduction forbids substitution into the
15363   exception-specification:
15364
15365     [temp.deduct]
15366
15367     All references in the function type of the function template to  the
15368     corresponding template parameters are replaced by the specified tem-
15369     plate argument values.  If a substitution in a template parameter or
15370     in  the function type of the function template results in an invalid
15371     type, type deduction fails.  [Note: The equivalent  substitution  in
15372     exception specifications is done only when the function is instanti-
15373     ated, at which point a program is  ill-formed  if  the  substitution
15374     results in an invalid type.]  */
15375
15376static tree
15377tsubst_function_type (tree t,
15378		      tree args,
15379		      tsubst_flags_t complain,
15380		      tree in_decl)
15381{
15382  tree return_type;
15383  tree arg_types = NULL_TREE;
15384
15385  /* The TYPE_CONTEXT is not used for function/method types.  */
15386  gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15387
15388  /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15389     failure.  */
15390  bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15391
15392  if (late_return_type_p)
15393    {
15394      /* Substitute the argument types.  */
15395      arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15396				    complain, in_decl);
15397      if (arg_types == error_mark_node)
15398	return error_mark_node;
15399
15400      tree save_ccp = current_class_ptr;
15401      tree save_ccr = current_class_ref;
15402      tree this_type = (TREE_CODE (t) == METHOD_TYPE
15403			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15404      bool do_inject = this_type && CLASS_TYPE_P (this_type);
15405      if (do_inject)
15406	{
15407	  /* DR 1207: 'this' is in scope in the trailing return type.  */
15408	  inject_this_parameter (this_type, cp_type_quals (this_type));
15409	}
15410
15411      /* Substitute the return type.  */
15412      return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15413
15414      if (do_inject)
15415	{
15416	  current_class_ptr = save_ccp;
15417	  current_class_ref = save_ccr;
15418	}
15419    }
15420  else
15421    /* Substitute the return type.  */
15422    return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15423
15424  if (return_type == error_mark_node)
15425    return error_mark_node;
15426  /* DR 486 clarifies that creation of a function type with an
15427     invalid return type is a deduction failure.  */
15428  if (TREE_CODE (return_type) == ARRAY_TYPE
15429      || TREE_CODE (return_type) == FUNCTION_TYPE)
15430    {
15431      if (complain & tf_error)
15432	{
15433	  if (TREE_CODE (return_type) == ARRAY_TYPE)
15434	    error ("function returning an array");
15435	  else
15436	    error ("function returning a function");
15437	}
15438      return error_mark_node;
15439    }
15440
15441  if (!late_return_type_p)
15442    {
15443      /* Substitute the argument types.  */
15444      arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15445				    complain, in_decl);
15446      if (arg_types == error_mark_node)
15447	return error_mark_node;
15448    }
15449
15450  /* Construct a new type node and return it.  */
15451  return rebuild_function_or_method_type (t, return_type, arg_types,
15452					  /*raises=*/NULL_TREE, complain);
15453}
15454
15455/* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
15456   ARGS into that specification, and return the substituted
15457   specification.  If there is no specification, return NULL_TREE.  */
15458
15459static tree
15460tsubst_exception_specification (tree fntype,
15461				tree args,
15462				tsubst_flags_t complain,
15463				tree in_decl,
15464				bool defer_ok)
15465{
15466  tree specs;
15467  tree new_specs;
15468
15469  specs = TYPE_RAISES_EXCEPTIONS (fntype);
15470  new_specs = NULL_TREE;
15471  if (specs && TREE_PURPOSE (specs))
15472    {
15473      /* A noexcept-specifier.  */
15474      tree expr = TREE_PURPOSE (specs);
15475      if (TREE_CODE (expr) == INTEGER_CST)
15476	new_specs = expr;
15477      else if (defer_ok)
15478	{
15479	  /* Defer instantiation of noexcept-specifiers to avoid
15480	     excessive instantiations (c++/49107).  */
15481	  new_specs = make_node (DEFERRED_NOEXCEPT);
15482	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15483	    {
15484	      /* We already partially instantiated this member template,
15485		 so combine the new args with the old.  */
15486	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
15487		= DEFERRED_NOEXCEPT_PATTERN (expr);
15488	      DEFERRED_NOEXCEPT_ARGS (new_specs)
15489		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15490	    }
15491	  else
15492	    {
15493	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15494	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15495	    }
15496	}
15497      else
15498	{
15499	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15500	    {
15501	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15502					   args);
15503	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15504	    }
15505	  new_specs = tsubst_copy_and_build
15506	    (expr, args, complain, in_decl, /*function_p=*/false,
15507	     /*integral_constant_expression_p=*/true);
15508	}
15509      new_specs = build_noexcept_spec (new_specs, complain);
15510      /* We've instantiated a template before a noexcept-specifier
15511	 contained therein has been parsed.  This can happen for
15512	 a nested template class:
15513
15514	  struct S {
15515	    template<typename> struct B { B() noexcept(...); };
15516	    struct A : B<int> { ... use B() ... };
15517	  };
15518
15519	 where completing B<int> will trigger instantiating the
15520	 noexcept, even though we only parse it at the end of S.  */
15521      if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15522	{
15523	  gcc_checking_assert (defer_ok);
15524	  vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15525	}
15526    }
15527  else if (specs)
15528    {
15529      if (! TREE_VALUE (specs))
15530	new_specs = specs;
15531      else
15532	while (specs)
15533	  {
15534	    tree spec;
15535            int i, len = 1;
15536            tree expanded_specs = NULL_TREE;
15537
15538            if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15539              {
15540                /* Expand the pack expansion type.  */
15541                expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15542                                                       args, complain,
15543                                                       in_decl);
15544
15545		if (expanded_specs == error_mark_node)
15546		  return error_mark_node;
15547		else if (TREE_CODE (expanded_specs) == TREE_VEC)
15548		  len = TREE_VEC_LENGTH (expanded_specs);
15549		else
15550		  {
15551		    /* We're substituting into a member template, so
15552		       we got a TYPE_PACK_EXPANSION back.  Add that
15553		       expansion and move on.  */
15554		    gcc_assert (TREE_CODE (expanded_specs)
15555				== TYPE_PACK_EXPANSION);
15556		    new_specs = add_exception_specifier (new_specs,
15557							 expanded_specs,
15558							 complain);
15559		    specs = TREE_CHAIN (specs);
15560		    continue;
15561		  }
15562              }
15563
15564            for (i = 0; i < len; ++i)
15565              {
15566                if (expanded_specs)
15567                  spec = TREE_VEC_ELT (expanded_specs, i);
15568                else
15569                  spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15570                if (spec == error_mark_node)
15571                  return spec;
15572                new_specs = add_exception_specifier (new_specs, spec,
15573                                                     complain);
15574              }
15575
15576            specs = TREE_CHAIN (specs);
15577	  }
15578    }
15579  return new_specs;
15580}
15581
15582/* Substitute through a TREE_LIST of types or expressions, handling pack
15583   expansions.  */
15584
15585tree
15586tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15587{
15588  if (t == void_list_node)
15589    return t;
15590
15591  tree purpose = TREE_PURPOSE (t);
15592  tree purposevec = NULL_TREE;
15593  if (!purpose)
15594    ;
15595  else if (PACK_EXPANSION_P (purpose))
15596    {
15597      purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15598      if (TREE_CODE (purpose) == TREE_VEC)
15599	purposevec = purpose;
15600    }
15601  else if (TYPE_P (purpose))
15602    purpose = tsubst (purpose, args, complain, in_decl);
15603  else
15604    purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15605  if (purpose == error_mark_node || purposevec == error_mark_node)
15606    return error_mark_node;
15607
15608  tree value = TREE_VALUE (t);
15609  tree valuevec = NULL_TREE;
15610  if (!value)
15611    ;
15612  else if (PACK_EXPANSION_P (value))
15613    {
15614      value = tsubst_pack_expansion (value, args, complain, in_decl);
15615      if (TREE_CODE (value) == TREE_VEC)
15616	valuevec = value;
15617    }
15618  else if (TYPE_P (value))
15619    value = tsubst (value, args, complain, in_decl);
15620  else
15621    value = tsubst_copy_and_build (value, args, complain, in_decl);
15622  if (value == error_mark_node || valuevec == error_mark_node)
15623    return error_mark_node;
15624
15625  tree chain = TREE_CHAIN (t);
15626  if (!chain)
15627    ;
15628  else if (TREE_CODE (chain) == TREE_LIST)
15629    chain = tsubst_tree_list (chain, args, complain, in_decl);
15630  else if (TYPE_P (chain))
15631    chain = tsubst (chain, args, complain, in_decl);
15632  else
15633    chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15634  if (chain == error_mark_node)
15635    return error_mark_node;
15636
15637  if (purpose == TREE_PURPOSE (t)
15638      && value == TREE_VALUE (t)
15639      && chain == TREE_CHAIN (t))
15640    return t;
15641
15642  int len;
15643  /* Determine the number of arguments.  */
15644  if (purposevec)
15645    {
15646      len = TREE_VEC_LENGTH (purposevec);
15647      gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15648    }
15649  else if (valuevec)
15650    len = TREE_VEC_LENGTH (valuevec);
15651  else
15652    len = 1;
15653
15654  for (int i = len; i-- > 0; )
15655    {
15656      if (purposevec)
15657	purpose = TREE_VEC_ELT (purposevec, i);
15658      if (valuevec)
15659	value = TREE_VEC_ELT (valuevec, i);
15660
15661      if (value && TYPE_P (value))
15662	chain = hash_tree_cons (purpose, value, chain);
15663      else
15664	chain = tree_cons (purpose, value, chain);
15665    }
15666
15667  return chain;
15668}
15669
15670/* Take the tree structure T and replace template parameters used
15671   therein with the argument vector ARGS.  IN_DECL is an associated
15672   decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15673   Issue error and warning messages under control of COMPLAIN.  Note
15674   that we must be relatively non-tolerant of extensions here, in
15675   order to preserve conformance; if we allow substitutions that
15676   should not be allowed, we may allow argument deductions that should
15677   not succeed, and therefore report ambiguous overload situations
15678   where there are none.  In theory, we could allow the substitution,
15679   but indicate that it should have failed, and allow our caller to
15680   make sure that the right thing happens, but we don't try to do this
15681   yet.
15682
15683   This function is used for dealing with types, decls and the like;
15684   for expressions, use tsubst_expr or tsubst_copy.  */
15685
15686tree
15687tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15688{
15689  enum tree_code code;
15690  tree type, r = NULL_TREE;
15691
15692  if (t == NULL_TREE || t == error_mark_node
15693      || t == integer_type_node
15694      || t == void_type_node
15695      || t == char_type_node
15696      || t == unknown_type_node
15697      || TREE_CODE (t) == NAMESPACE_DECL
15698      || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15699    return t;
15700
15701  if (DECL_P (t))
15702    return tsubst_decl (t, args, complain);
15703
15704  if (args == NULL_TREE)
15705    return t;
15706
15707  code = TREE_CODE (t);
15708
15709  gcc_assert (code != IDENTIFIER_NODE);
15710  type = TREE_TYPE (t);
15711
15712  gcc_assert (type != unknown_type_node);
15713
15714  /* Reuse typedefs.  We need to do this to handle dependent attributes,
15715     such as attribute aligned.  */
15716  if (TYPE_P (t)
15717      && typedef_variant_p (t))
15718    {
15719      tree decl = TYPE_NAME (t);
15720
15721      if (alias_template_specialization_p (t, nt_opaque))
15722	{
15723	  /* DECL represents an alias template and we want to
15724	     instantiate it.  */
15725	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15726	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15727	  r = instantiate_alias_template (tmpl, gen_args, complain);
15728	}
15729      else if (DECL_CLASS_SCOPE_P (decl)
15730	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15731	       && uses_template_parms (DECL_CONTEXT (decl)))
15732	{
15733	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15734	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15735	  r = retrieve_specialization (tmpl, gen_args, 0);
15736	}
15737      else if (DECL_FUNCTION_SCOPE_P (decl)
15738	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15739	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15740	r = retrieve_local_specialization (decl);
15741      else
15742	/* The typedef is from a non-template context.  */
15743	return t;
15744
15745      if (r)
15746	{
15747	  r = TREE_TYPE (r);
15748	  r = cp_build_qualified_type_real
15749	    (r, cp_type_quals (t) | cp_type_quals (r),
15750	     complain | tf_ignore_bad_quals);
15751	  return r;
15752	}
15753      else
15754	{
15755	  /* We don't have an instantiation yet, so drop the typedef.  */
15756	  int quals = cp_type_quals (t);
15757	  t = DECL_ORIGINAL_TYPE (decl);
15758	  t = cp_build_qualified_type_real (t, quals,
15759					    complain | tf_ignore_bad_quals);
15760	}
15761    }
15762
15763  bool fndecl_type = (complain & tf_fndecl_type);
15764  complain &= ~tf_fndecl_type;
15765
15766  bool tst_ok = (complain & tf_tst_ok);
15767  complain &= ~tf_tst_ok;
15768
15769  if (type
15770      && code != TYPENAME_TYPE
15771      && code != TEMPLATE_TYPE_PARM
15772      && code != TEMPLATE_PARM_INDEX
15773      && code != IDENTIFIER_NODE
15774      && code != FUNCTION_TYPE
15775      && code != METHOD_TYPE)
15776    type = tsubst (type, args, complain, in_decl);
15777  if (type == error_mark_node)
15778    return error_mark_node;
15779
15780  switch (code)
15781    {
15782    case RECORD_TYPE:
15783    case UNION_TYPE:
15784    case ENUMERAL_TYPE:
15785      return tsubst_aggr_type (t, args, complain, in_decl,
15786			       /*entering_scope=*/0);
15787
15788    case ERROR_MARK:
15789    case IDENTIFIER_NODE:
15790    case VOID_TYPE:
15791    case OPAQUE_TYPE:
15792    case REAL_TYPE:
15793    case COMPLEX_TYPE:
15794    case VECTOR_TYPE:
15795    case BOOLEAN_TYPE:
15796    case NULLPTR_TYPE:
15797    case LANG_TYPE:
15798      return t;
15799
15800    case INTEGER_TYPE:
15801      if (t == integer_type_node)
15802	return t;
15803
15804      if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15805          && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15806        return t;
15807
15808      {
15809	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15810
15811	max = tsubst_expr (omax, args, complain, in_decl,
15812			   /*integral_constant_expression_p=*/false);
15813
15814	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15815	   needed.  */
15816	if (TREE_CODE (max) == NOP_EXPR
15817	    && TREE_SIDE_EFFECTS (omax)
15818	    && !TREE_TYPE (max))
15819	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15820
15821	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
15822	   with TREE_SIDE_EFFECTS that indicates this is not an integral
15823	   constant expression.  */
15824	if (processing_template_decl
15825	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15826	  {
15827	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
15828	    TREE_SIDE_EFFECTS (max) = 1;
15829	  }
15830
15831	return compute_array_index_type (NULL_TREE, max, complain);
15832      }
15833
15834    case TEMPLATE_TYPE_PARM:
15835      if (template_placeholder_p (t))
15836	{
15837	  tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
15838	  tmpl = tsubst_copy (tmpl, args, complain, in_decl);
15839	  if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
15840	    tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
15841
15842	  if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
15843	    return make_template_placeholder (tmpl);
15844	  else
15845	    return t;
15846	}
15847      /* Fall through.  */
15848    case TEMPLATE_TEMPLATE_PARM:
15849    case BOUND_TEMPLATE_TEMPLATE_PARM:
15850    case TEMPLATE_PARM_INDEX:
15851      {
15852	int idx;
15853	int level;
15854	int levels;
15855	tree arg = NULL_TREE;
15856
15857	r = NULL_TREE;
15858
15859	gcc_assert (TREE_VEC_LENGTH (args) > 0);
15860	template_parm_level_and_index (t, &level, &idx);
15861
15862	levels = TMPL_ARGS_DEPTH (args);
15863	if (level <= levels
15864	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15865	  {
15866	    arg = TMPL_ARG (args, level, idx);
15867
15868	    /* See through ARGUMENT_PACK_SELECT arguments. */
15869	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15870	      arg = argument_pack_select_arg (arg);
15871	  }
15872
15873	if (arg == error_mark_node)
15874	  return error_mark_node;
15875	else if (arg != NULL_TREE)
15876	  {
15877	    if (ARGUMENT_PACK_P (arg))
15878	      /* If ARG is an argument pack, we don't actually want to
15879		 perform a substitution here, because substitutions
15880		 for argument packs are only done
15881		 element-by-element. We can get to this point when
15882		 substituting the type of a non-type template
15883		 parameter pack, when that type actually contains
15884		 template parameter packs from an outer template, e.g.,
15885
15886	         template<typename... Types> struct A {
15887		   template<Types... Values> struct B { };
15888                 };  */
15889	      return t;
15890
15891	    if (code == TEMPLATE_TYPE_PARM)
15892	      {
15893		int quals;
15894
15895		/* When building concept checks for the purpose of
15896		   deducing placeholders, we can end up with wildcards
15897		   where types are expected. Adjust this to the deduced
15898		   value.  */
15899		if (TREE_CODE (arg) == WILDCARD_DECL)
15900		  arg = TREE_TYPE (TREE_TYPE (arg));
15901
15902		gcc_assert (TYPE_P (arg));
15903
15904		quals = cp_type_quals (arg) | cp_type_quals (t);
15905
15906		return cp_build_qualified_type_real
15907		  (arg, quals, complain | tf_ignore_bad_quals);
15908	      }
15909	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15910	      {
15911		/* We are processing a type constructed from a
15912		   template template parameter.  */
15913		tree argvec = tsubst (TYPE_TI_ARGS (t),
15914				      args, complain, in_decl);
15915		if (argvec == error_mark_node)
15916		  return error_mark_node;
15917
15918		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15919			    || TREE_CODE (arg) == TEMPLATE_DECL
15920			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15921
15922		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15923		  /* Consider this code:
15924
15925			template <template <class> class Template>
15926			struct Internal {
15927			template <class Arg> using Bind = Template<Arg>;
15928			};
15929
15930			template <template <class> class Template, class Arg>
15931			using Instantiate = Template<Arg>; //#0
15932
15933			template <template <class> class Template,
15934                                  class Argument>
15935			using Bind =
15936			  Instantiate<Internal<Template>::template Bind,
15937				      Argument>; //#1
15938
15939		     When #1 is parsed, the
15940		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
15941		     parameter `Template' in #0 matches the
15942		     UNBOUND_CLASS_TEMPLATE representing the argument
15943		     `Internal<Template>::template Bind'; We then want
15944		     to assemble the type `Bind<Argument>' that can't
15945		     be fully created right now, because
15946		     `Internal<Template>' not being complete, the Bind
15947		     template cannot be looked up in that context.  So
15948		     we need to "store" `Bind<Argument>' for later
15949		     when the context of Bind becomes complete.  Let's
15950		     store that in a TYPENAME_TYPE.  */
15951		  return make_typename_type (TYPE_CONTEXT (arg),
15952					     build_nt (TEMPLATE_ID_EXPR,
15953						       TYPE_IDENTIFIER (arg),
15954						       argvec),
15955					     typename_type,
15956					     complain);
15957
15958		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
15959		   are resolving nested-types in the signature of a
15960		   member function templates.  Otherwise ARG is a
15961		   TEMPLATE_DECL and is the real template to be
15962		   instantiated.  */
15963		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15964		  arg = TYPE_NAME (arg);
15965
15966		r = lookup_template_class (arg,
15967					   argvec, in_decl,
15968					   DECL_CONTEXT (arg),
15969					    /*entering_scope=*/0,
15970					   complain);
15971		return cp_build_qualified_type_real
15972		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
15973	      }
15974	    else if (code == TEMPLATE_TEMPLATE_PARM)
15975	      return arg;
15976	    else
15977	      /* TEMPLATE_PARM_INDEX.  */
15978	      return convert_from_reference (unshare_expr (arg));
15979	  }
15980
15981	if (level == 1)
15982	  /* This can happen during the attempted tsubst'ing in
15983	     unify.  This means that we don't yet have any information
15984	     about the template parameter in question.  */
15985	  return t;
15986
15987	/* Early in template argument deduction substitution, we don't
15988	   want to reduce the level of 'auto', or it will be confused
15989	   with a normal template parm in subsequent deduction.
15990	   Similarly, don't reduce the level of template parameters to
15991	   avoid mismatches when deducing their types.  */
15992	if (complain & tf_partial)
15993	  return t;
15994
15995	/* If we get here, we must have been looking at a parm for a
15996	   more deeply nested template.  Make a new version of this
15997	   template parameter, but with a lower level.  */
15998	switch (code)
15999	  {
16000	  case TEMPLATE_TYPE_PARM:
16001	  case TEMPLATE_TEMPLATE_PARM:
16002	  case BOUND_TEMPLATE_TEMPLATE_PARM:
16003	    if (cp_type_quals (t))
16004	      {
16005		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
16006		r = cp_build_qualified_type_real
16007		  (r, cp_type_quals (t),
16008		   complain | (code == TEMPLATE_TYPE_PARM
16009			       ? tf_ignore_bad_quals : 0));
16010	      }
16011	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16012		     && PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16013		     && (r = (TEMPLATE_PARM_DESCENDANTS
16014			      (TEMPLATE_TYPE_PARM_INDEX (t))))
16015		     && (r = TREE_TYPE (r))
16016		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r))
16017	      /* Break infinite recursion when substituting the constraints
16018		 of a constrained placeholder.  */;
16019	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16020		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16021		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
16022			 r = TEMPLATE_PARM_DESCENDANTS (arg))
16023		     && (TEMPLATE_PARM_LEVEL (r)
16024			 == TEMPLATE_PARM_LEVEL (arg) - levels))
16025		/* Cache the simple case of lowering a type parameter.  */
16026	      r = TREE_TYPE (r);
16027	    else
16028	      {
16029		r = copy_type (t);
16030		TEMPLATE_TYPE_PARM_INDEX (r)
16031		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16032						r, levels, args, complain);
16033		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16034		TYPE_MAIN_VARIANT (r) = r;
16035		TYPE_POINTER_TO (r) = NULL_TREE;
16036		TYPE_REFERENCE_TO (r) = NULL_TREE;
16037
16038                if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
16039		  if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16040		    /* Propagate constraints on placeholders since they are
16041		       only instantiated during satisfaction.  */
16042		    PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16043
16044		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
16045		  /* We have reduced the level of the template
16046		     template parameter, but not the levels of its
16047		     template parameters, so canonical_type_parameter
16048		     will not be able to find the canonical template
16049		     template parameter for this level. Thus, we
16050		     require structural equality checking to compare
16051		     TEMPLATE_TEMPLATE_PARMs. */
16052		  SET_TYPE_STRUCTURAL_EQUALITY (r);
16053		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
16054		  SET_TYPE_STRUCTURAL_EQUALITY (r);
16055		else
16056		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
16057
16058		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16059		  {
16060		    tree tinfo = TYPE_TEMPLATE_INFO (t);
16061		    /* We might need to substitute into the types of non-type
16062		       template parameters.  */
16063		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16064					complain, in_decl);
16065		    if (tmpl == error_mark_node)
16066		      return error_mark_node;
16067		    tree argvec = tsubst (TI_ARGS (tinfo), args,
16068					  complain, in_decl);
16069		    if (argvec == error_mark_node)
16070		      return error_mark_node;
16071
16072		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
16073		      = build_template_info (tmpl, argvec);
16074		  }
16075	      }
16076	    break;
16077
16078	  case TEMPLATE_PARM_INDEX:
16079	    /* OK, now substitute the type of the non-type parameter.  We
16080	       couldn't do it earlier because it might be an auto parameter,
16081	       and we wouldn't need to if we had an argument.  */
16082	    type = tsubst (type, args, complain, in_decl);
16083	    if (type == error_mark_node)
16084	      return error_mark_node;
16085	    r = reduce_template_parm_level (t, type, levels, args, complain);
16086	    break;
16087
16088	  default:
16089	    gcc_unreachable ();
16090	  }
16091
16092	return r;
16093      }
16094
16095    case TREE_LIST:
16096      return tsubst_tree_list (t, args, complain, in_decl);
16097
16098    case TREE_BINFO:
16099      /* We should never be tsubsting a binfo.  */
16100      gcc_unreachable ();
16101
16102    case TREE_VEC:
16103      /* A vector of template arguments.  */
16104      gcc_assert (!type);
16105      return tsubst_template_args (t, args, complain, in_decl);
16106
16107    case POINTER_TYPE:
16108    case REFERENCE_TYPE:
16109      {
16110	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16111	  return t;
16112
16113	/* [temp.deduct]
16114
16115	   Type deduction may fail for any of the following
16116	   reasons:
16117
16118	   -- Attempting to create a pointer to reference type.
16119	   -- Attempting to create a reference to a reference type or
16120	      a reference to void.
16121
16122	  Core issue 106 says that creating a reference to a reference
16123	  during instantiation is no longer a cause for failure. We
16124	  only enforce this check in strict C++98 mode.  */
16125	if ((TYPE_REF_P (type)
16126	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16127	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16128	  {
16129	    static location_t last_loc;
16130
16131	    /* We keep track of the last time we issued this error
16132	       message to avoid spewing a ton of messages during a
16133	       single bad template instantiation.  */
16134	    if (complain & tf_error
16135		&& last_loc != input_location)
16136	      {
16137		if (VOID_TYPE_P (type))
16138		  error ("forming reference to void");
16139               else if (code == POINTER_TYPE)
16140                 error ("forming pointer to reference type %qT", type);
16141               else
16142		  error ("forming reference to reference type %qT", type);
16143		last_loc = input_location;
16144	      }
16145
16146	    return error_mark_node;
16147	  }
16148	else if (TREE_CODE (type) == FUNCTION_TYPE
16149		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16150		     || type_memfn_rqual (type) != REF_QUAL_NONE))
16151	  {
16152	    if (complain & tf_error)
16153	      {
16154		if (code == POINTER_TYPE)
16155		  error ("forming pointer to qualified function type %qT",
16156			 type);
16157		else
16158		  error ("forming reference to qualified function type %qT",
16159			 type);
16160	      }
16161	    return error_mark_node;
16162	  }
16163	else if (code == POINTER_TYPE)
16164	  {
16165	    r = build_pointer_type (type);
16166	    if (TREE_CODE (type) == METHOD_TYPE)
16167	      r = build_ptrmemfunc_type (r);
16168	  }
16169	else if (TYPE_REF_P (type))
16170	  /* In C++0x, during template argument substitution, when there is an
16171	     attempt to create a reference to a reference type, reference
16172	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16173
16174	     "If a template-argument for a template-parameter T names a type
16175	     that is a reference to a type A, an attempt to create the type
16176	     'lvalue reference to cv T' creates the type 'lvalue reference to
16177	     A,' while an attempt to create the type type rvalue reference to
16178	     cv T' creates the type T"
16179	  */
16180	  r = cp_build_reference_type
16181	      (TREE_TYPE (type),
16182	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16183	else
16184	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16185	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
16186
16187	if (r != error_mark_node)
16188	  /* Will this ever be needed for TYPE_..._TO values?  */
16189	  layout_type (r);
16190
16191	return r;
16192      }
16193    case OFFSET_TYPE:
16194      {
16195	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16196	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16197	  {
16198	    /* [temp.deduct]
16199
16200	       Type deduction may fail for any of the following
16201	       reasons:
16202
16203	       -- Attempting to create "pointer to member of T" when T
16204		  is not a class type.  */
16205	    if (complain & tf_error)
16206	      error ("creating pointer to member of non-class type %qT", r);
16207	    return error_mark_node;
16208	  }
16209	if (TYPE_REF_P (type))
16210	  {
16211	    if (complain & tf_error)
16212	      error ("creating pointer to member reference type %qT", type);
16213	    return error_mark_node;
16214	  }
16215	if (VOID_TYPE_P (type))
16216	  {
16217	    if (complain & tf_error)
16218	      error ("creating pointer to member of type void");
16219	    return error_mark_node;
16220	  }
16221	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16222	if (TREE_CODE (type) == FUNCTION_TYPE)
16223	  {
16224	    /* The type of the implicit object parameter gets its
16225	       cv-qualifiers from the FUNCTION_TYPE. */
16226	    tree memptr;
16227	    tree method_type
16228	      = build_memfn_type (type, r, type_memfn_quals (type),
16229				  type_memfn_rqual (type));
16230	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16231	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
16232						 complain);
16233	  }
16234	else
16235	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
16236					       cp_type_quals (t),
16237					       complain);
16238      }
16239    case FUNCTION_TYPE:
16240    case METHOD_TYPE:
16241      {
16242	tree fntype;
16243	tree specs;
16244	fntype = tsubst_function_type (t, args, complain, in_decl);
16245	if (fntype == error_mark_node)
16246	  return error_mark_node;
16247
16248	/* Substitute the exception specification.  */
16249	specs = tsubst_exception_specification (t, args, complain, in_decl,
16250						/*defer_ok*/fndecl_type);
16251	if (specs == error_mark_node)
16252	  return error_mark_node;
16253	if (specs)
16254	  fntype = build_exception_variant (fntype, specs);
16255	return fntype;
16256      }
16257    case ARRAY_TYPE:
16258      {
16259	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16260	if (domain == error_mark_node)
16261	  return error_mark_node;
16262
16263	/* As an optimization, we avoid regenerating the array type if
16264	   it will obviously be the same as T.  */
16265	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16266	  return t;
16267
16268	/* These checks should match the ones in create_array_type_for_decl.
16269
16270	   [temp.deduct]
16271
16272	   The deduction may fail for any of the following reasons:
16273
16274	   -- Attempting to create an array with an element type that
16275	      is void, a function type, or a reference type, or [DR337]
16276	      an abstract class type.  */
16277	if (VOID_TYPE_P (type)
16278	    || TREE_CODE (type) == FUNCTION_TYPE
16279	    || (TREE_CODE (type) == ARRAY_TYPE
16280		&& TYPE_DOMAIN (type) == NULL_TREE)
16281	    || TYPE_REF_P (type))
16282	  {
16283	    if (complain & tf_error)
16284	      error ("creating array of %qT", type);
16285	    return error_mark_node;
16286	  }
16287
16288	if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16289				  !(complain & tf_error)))
16290	  return error_mark_node;
16291
16292	r = build_cplus_array_type (type, domain);
16293
16294	if (!valid_array_size_p (input_location, r, in_decl,
16295				 (complain & tf_error)))
16296	  return error_mark_node;
16297
16298	if (TYPE_USER_ALIGN (t))
16299	  {
16300	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16301	    TYPE_USER_ALIGN (r) = 1;
16302	  }
16303
16304	return r;
16305      }
16306
16307    case TYPENAME_TYPE:
16308      {
16309	tree ctx = TYPE_CONTEXT (t);
16310	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16311	  {
16312	    ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
16313	    if (ctx == error_mark_node
16314		|| TREE_VEC_LENGTH (ctx) > 1)
16315	      return error_mark_node;
16316	    if (TREE_VEC_LENGTH (ctx) == 0)
16317	      {
16318		if (complain & tf_error)
16319		  error ("%qD is instantiated for an empty pack",
16320			 TYPENAME_TYPE_FULLNAME (t));
16321		return error_mark_node;
16322	      }
16323	    ctx = TREE_VEC_ELT (ctx, 0);
16324	  }
16325	else
16326	  ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
16327				  /*entering_scope=*/1);
16328	if (ctx == error_mark_node)
16329	  return error_mark_node;
16330
16331	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16332			      complain, in_decl);
16333	if (f == error_mark_node)
16334	  return error_mark_node;
16335
16336	if (!MAYBE_CLASS_TYPE_P (ctx))
16337	  {
16338	    if (complain & tf_error)
16339	      error ("%qT is not a class, struct, or union type", ctx);
16340	    return error_mark_node;
16341	  }
16342	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16343	  {
16344	    /* Normally, make_typename_type does not require that the CTX
16345	       have complete type in order to allow things like:
16346
16347		 template <class T> struct S { typename S<T>::X Y; };
16348
16349	       But, such constructs have already been resolved by this
16350	       point, so here CTX really should have complete type, unless
16351	       it's a partial instantiation.  */
16352	    if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16353	      return error_mark_node;
16354	  }
16355
16356	tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16357	if (tst_ok)
16358	  tcomplain |= tf_tst_ok;
16359	f = make_typename_type (ctx, f, typename_type, tcomplain);
16360	if (f == error_mark_node)
16361	  return f;
16362	if (TREE_CODE (f) == TYPE_DECL)
16363	  {
16364	    complain |= tf_ignore_bad_quals;
16365	    f = TREE_TYPE (f);
16366	  }
16367
16368	if (TREE_CODE (f) != TYPENAME_TYPE)
16369	  {
16370	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16371	      {
16372		if (complain & tf_error)
16373		  error ("%qT resolves to %qT, which is not an enumeration type",
16374			 t, f);
16375		else
16376		  return error_mark_node;
16377	      }
16378	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16379	      {
16380		if (complain & tf_error)
16381		  error ("%qT resolves to %qT, which is not a class type",
16382			 t, f);
16383		else
16384		  return error_mark_node;
16385	      }
16386	  }
16387
16388	return cp_build_qualified_type_real
16389	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
16390      }
16391
16392    case UNBOUND_CLASS_TEMPLATE:
16393      {
16394	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16395				     in_decl, /*entering_scope=*/1);
16396	tree name = TYPE_IDENTIFIER (t);
16397	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16398
16399	if (ctx == error_mark_node || name == error_mark_node)
16400	  return error_mark_node;
16401
16402	if (parm_list)
16403	  parm_list = tsubst_template_parms (parm_list, args, complain);
16404	return make_unbound_class_template (ctx, name, parm_list, complain);
16405      }
16406
16407    case TYPEOF_TYPE:
16408      {
16409	tree type;
16410
16411	++cp_unevaluated_operand;
16412	++c_inhibit_evaluation_warnings;
16413
16414	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
16415			    complain, in_decl,
16416			    /*integral_constant_expression_p=*/false);
16417
16418	--cp_unevaluated_operand;
16419	--c_inhibit_evaluation_warnings;
16420
16421	type = finish_typeof (type);
16422	return cp_build_qualified_type_real (type,
16423					     cp_type_quals (t)
16424					     | cp_type_quals (type),
16425					     complain);
16426      }
16427
16428    case DECLTYPE_TYPE:
16429      {
16430	tree type;
16431
16432	++cp_unevaluated_operand;
16433	++c_inhibit_evaluation_warnings;
16434
16435	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16436				      complain|tf_decltype, in_decl,
16437				      /*function_p*/false,
16438				      /*integral_constant_expression*/false);
16439
16440	--cp_unevaluated_operand;
16441	--c_inhibit_evaluation_warnings;
16442
16443	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16444	  type = lambda_capture_field_type (type,
16445					    false /*explicit_init*/,
16446					    DECLTYPE_FOR_REF_CAPTURE (t));
16447	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16448	  type = lambda_proxy_type (type);
16449	else
16450	  {
16451	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16452	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16453		&& EXPR_P (type))
16454	      /* In a template ~id could be either a complement expression
16455		 or an unqualified-id naming a destructor; if instantiating
16456		 it produces an expression, it's not an id-expression or
16457		 member access.  */
16458	      id = false;
16459	    type = finish_decltype_type (type, id, complain);
16460	  }
16461	return cp_build_qualified_type_real (type,
16462					     cp_type_quals (t)
16463					     | cp_type_quals (type),
16464					     complain | tf_ignore_bad_quals);
16465      }
16466
16467    case UNDERLYING_TYPE:
16468      {
16469	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16470			    complain, in_decl);
16471	return finish_underlying_type (type);
16472      }
16473
16474    case TYPE_ARGUMENT_PACK:
16475    case NONTYPE_ARGUMENT_PACK:
16476      return tsubst_argument_pack (t, args, complain, in_decl);
16477
16478    case VOID_CST:
16479    case INTEGER_CST:
16480    case REAL_CST:
16481    case STRING_CST:
16482    case PLUS_EXPR:
16483    case MINUS_EXPR:
16484    case NEGATE_EXPR:
16485    case NOP_EXPR:
16486    case INDIRECT_REF:
16487    case ADDR_EXPR:
16488    case CALL_EXPR:
16489    case ARRAY_REF:
16490    case SCOPE_REF:
16491      /* We should use one of the expression tsubsts for these codes.  */
16492      gcc_unreachable ();
16493
16494    default:
16495      sorry ("use of %qs in template", get_tree_code_name (code));
16496      return error_mark_node;
16497    }
16498}
16499
16500/* OLDFNS is a lookup set of member functions from some class template, and
16501   NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16502   of that class template.  Return the subset of NEWFNS which are
16503   specializations of a function from OLDFNS.  */
16504
16505static tree
16506filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16507{
16508  /* Record all member functions from the old lookup set OLDFNS into
16509     VISIBLE_SET.  */
16510  hash_set<tree> visible_set;
16511  bool seen_dep_using = false;
16512  for (tree fn : lkp_range (oldfns))
16513    {
16514      if (TREE_CODE (fn) == USING_DECL)
16515	{
16516	  /* Imprecisely handle dependent using-decl by keeping all members
16517	     in the new lookup set that are defined in a base class, i.e.
16518	     members that could plausibly have been introduced by this
16519	     dependent using-decl.
16520	     FIXME: Track which members are introduced by a dependent
16521	     using-decl precisely, perhaps by performing another lookup
16522	     from the substituted USING_DECL_SCOPE.  */
16523	  gcc_checking_assert (DECL_DEPENDENT_P (fn));
16524	  seen_dep_using = true;
16525	}
16526      else
16527	visible_set.add (fn);
16528    }
16529
16530  /* Returns true iff (a less specialized version of) FN appeared in
16531     the old lookup set OLDFNS.  */
16532  auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16533    if (DECL_CONTEXT (fn) != newtype)
16534      /* FN is a member function from a base class, introduced via a
16535	 using-decl; if it might have been introduced by a dependent
16536	 using-decl then just conservatively keep it, otherwise look
16537	 in the old lookup set for FN exactly.  */
16538      return seen_dep_using || visible_set.contains (fn);
16539    else if (TREE_CODE (fn) == TEMPLATE_DECL)
16540      /* FN is a member function template from the current class;
16541	 look in the old lookup set for the TEMPLATE_DECL from which
16542	 it was specialized.  */
16543      return visible_set.contains (DECL_TI_TEMPLATE (fn));
16544    else
16545      /* FN is a non-template member function from the current class;
16546	 look in the old lookup set for the FUNCTION_DECL from which
16547	 it was specialized.  */
16548      return visible_set.contains (DECL_TEMPLATE_RESULT
16549				   (DECL_TI_TEMPLATE (fn)));
16550  };
16551
16552  bool lookup_changed_p = false;
16553  for (tree fn : lkp_range (newfns))
16554    if (!visible_p (fn))
16555      {
16556	lookup_changed_p = true;
16557	break;
16558      }
16559  if (!lookup_changed_p)
16560    return newfns;
16561
16562  /* Filter out from NEWFNS the member functions that weren't
16563     previously visible according to OLDFNS.  */
16564  tree filtered_fns = NULL_TREE;
16565  unsigned filtered_size = 0;
16566  for (tree fn : lkp_range (newfns))
16567    if (visible_p (fn))
16568      {
16569	filtered_fns = lookup_add (fn, filtered_fns);
16570	filtered_size++;
16571      }
16572  gcc_checking_assert (seen_dep_using
16573		       ? filtered_size >= visible_set.elements ()
16574		       : filtered_size == visible_set.elements ());
16575
16576  return filtered_fns;
16577}
16578
16579/* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16580   expression on the left-hand side of the "." or "->" operator.  We
16581   only do the lookup if we had a dependent BASELINK.  Otherwise we
16582   adjust it onto the instantiated heirarchy.  */
16583
16584static tree
16585tsubst_baselink (tree baselink, tree object_type,
16586		 tree args, tsubst_flags_t complain, tree in_decl)
16587{
16588  bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16589  tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16590  qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16591
16592  tree optype = BASELINK_OPTYPE (baselink);
16593  optype = tsubst (optype, args, complain, in_decl);
16594
16595  tree template_args = NULL_TREE;
16596  bool template_id_p = false;
16597  tree fns = BASELINK_FUNCTIONS (baselink);
16598  if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16599    {
16600      template_id_p = true;
16601      template_args = TREE_OPERAND (fns, 1);
16602      fns = TREE_OPERAND (fns, 0);
16603      if (template_args)
16604	template_args = tsubst_template_args (template_args, args,
16605					      complain, in_decl);
16606    }
16607
16608  tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16609  binfo_type = tsubst (binfo_type, args, complain, in_decl);
16610  bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16611		      || optype != BASELINK_OPTYPE (baselink));
16612
16613  if (dependent_p)
16614    {
16615      tree name = OVL_NAME (fns);
16616      if (IDENTIFIER_CONV_OP_P (name))
16617	name = make_conv_op_name (optype);
16618
16619      /* See maybe_dependent_member_ref.  */
16620      if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16621	{
16622	  if (template_id_p)
16623	    name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16624			   template_args);
16625	  return build_qualified_name (NULL_TREE, qualifying_scope, name,
16626				       /* ::template */false);
16627	}
16628
16629      if (name == complete_dtor_identifier)
16630	/* Treat as-if non-dependent below.  */
16631	dependent_p = false;
16632
16633      bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16634      baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16635				  complain);
16636      if (maybe_incomplete)
16637	{
16638	  /* Filter out from the new lookup set those functions which didn't
16639	     appear in the original lookup set (in a less specialized form).
16640	     This is needed to preserve the consistency of member lookup
16641	     performed in an incomplete-class context, within which
16642	     later-declared members ought to remain invisible.  */
16643	  BASELINK_FUNCTIONS (baselink)
16644	    = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16645				   binfo_type);
16646	  BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16647	}
16648
16649      if (!baselink)
16650	{
16651	  if ((complain & tf_error)
16652	      && constructor_name_p (name, qualifying_scope))
16653	    error ("cannot call constructor %<%T::%D%> directly",
16654		   qualifying_scope, name);
16655	  return error_mark_node;
16656	}
16657
16658      fns = BASELINK_FUNCTIONS (baselink);
16659    }
16660  else
16661    {
16662      /* We're going to overwrite pieces below, make a duplicate.  */
16663      baselink = copy_node (baselink);
16664
16665      if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16666	{
16667	  /* The decl we found was from non-dependent scope, but we still need
16668	     to update the binfos for the instantiated qualifying_scope.  */
16669	  BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16670	  BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16671						   ba_unique, nullptr, complain);
16672	}
16673    }
16674
16675  /* If lookup found a single function, mark it as used at this point.
16676     (If lookup found multiple functions the one selected later by
16677     overload resolution will be marked as used at that point.)  */
16678  if (!template_id_p && !really_overloaded_fn (fns))
16679    {
16680      tree fn = OVL_FIRST (fns);
16681      bool ok = mark_used (fn, complain);
16682      if (!ok && !(complain & tf_error))
16683	return error_mark_node;
16684      if (ok && BASELINK_P (baselink))
16685	/* We might have instantiated an auto function.  */
16686	TREE_TYPE (baselink) = TREE_TYPE (fn);
16687    }
16688
16689  if (BASELINK_P (baselink))
16690    {
16691      /* Add back the template arguments, if present.  */
16692      if (template_id_p)
16693	BASELINK_FUNCTIONS (baselink)
16694	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16695
16696      /* Update the conversion operator type.  */
16697      BASELINK_OPTYPE (baselink) = optype;
16698    }
16699
16700  if (!object_type)
16701    object_type = current_class_type;
16702
16703  if (qualified_p || !dependent_p)
16704    {
16705      baselink = adjust_result_of_qualified_name_lookup (baselink,
16706							 qualifying_scope,
16707							 object_type);
16708      if (!qualified_p)
16709	/* We need to call adjust_result_of_qualified_name_lookup in case the
16710	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
16711	   so that we still get virtual function binding.  */
16712	BASELINK_QUALIFIED_P (baselink) = false;
16713    }
16714
16715  return baselink;
16716}
16717
16718/* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16719   true if the qualified-id will be a postfix-expression in-and-of
16720   itself; false if more of the postfix-expression follows the
16721   QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16722   of "&".  */
16723
16724static tree
16725tsubst_qualified_id (tree qualified_id, tree args,
16726		     tsubst_flags_t complain, tree in_decl,
16727		     bool done, bool address_p)
16728{
16729  tree expr;
16730  tree scope;
16731  tree name;
16732  bool is_template;
16733  tree template_args;
16734  location_t loc = EXPR_LOCATION (qualified_id);
16735
16736  gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16737
16738  /* Figure out what name to look up.  */
16739  name = TREE_OPERAND (qualified_id, 1);
16740  if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16741    {
16742      is_template = true;
16743      template_args = TREE_OPERAND (name, 1);
16744      if (template_args)
16745	template_args = tsubst_template_args (template_args, args,
16746					      complain, in_decl);
16747      if (template_args == error_mark_node)
16748	return error_mark_node;
16749      name = TREE_OPERAND (name, 0);
16750    }
16751  else
16752    {
16753      is_template = false;
16754      template_args = NULL_TREE;
16755    }
16756
16757  /* Substitute into the qualifying scope.  When there are no ARGS, we
16758     are just trying to simplify a non-dependent expression.  In that
16759     case the qualifying scope may be dependent, and, in any case,
16760     substituting will not help.  */
16761  scope = TREE_OPERAND (qualified_id, 0);
16762  if (args)
16763    {
16764      scope = tsubst (scope, args, complain, in_decl);
16765      expr = tsubst_copy (name, args, complain, in_decl);
16766    }
16767  else
16768    expr = name;
16769
16770  if (dependent_scope_p (scope))
16771    {
16772      if (TREE_CODE (expr) == SCOPE_REF)
16773	/* We built one in tsubst_baselink.  */
16774	gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
16775      else
16776	{
16777	  if (is_template)
16778	    expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
16779				     template_args);
16780	  expr = build_qualified_name (NULL_TREE, scope, expr,
16781				       QUALIFIED_NAME_IS_TEMPLATE
16782				       (qualified_id));
16783	}
16784      REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
16785      return expr;
16786    }
16787
16788  if (!BASELINK_P (name) && !DECL_P (expr))
16789    {
16790      if (TREE_CODE (expr) == BIT_NOT_EXPR)
16791	{
16792	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
16793	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16794	    {
16795	      error ("qualifying type %qT does not match destructor name ~%qT",
16796		     scope, TREE_OPERAND (expr, 0));
16797	      expr = error_mark_node;
16798	    }
16799	  else
16800	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
16801					  LOOK_want::NORMAL, false);
16802	}
16803      else
16804	expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
16805      if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16806		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16807	{
16808	  if (complain & tf_error)
16809	    {
16810	      error ("dependent-name %qE is parsed as a non-type, but "
16811		     "instantiation yields a type", qualified_id);
16812	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16813	    }
16814	  return error_mark_node;
16815	}
16816    }
16817
16818  if (DECL_P (expr))
16819    {
16820      if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16821						scope, complain))
16822	return error_mark_node;
16823      /* Remember that there was a reference to this entity.  */
16824      if (!mark_used (expr, complain) && !(complain & tf_error))
16825	return error_mark_node;
16826    }
16827
16828  if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16829    {
16830      if (complain & tf_error)
16831	qualified_name_lookup_error (scope,
16832				     TREE_OPERAND (qualified_id, 1),
16833				     expr, input_location);
16834      return error_mark_node;
16835    }
16836
16837  if (is_template)
16838    {
16839      /* We may be repeating a check already done during parsing, but
16840	 if it was well-formed and passed then, it will pass again
16841	 now, and if it didn't, we wouldn't have got here.  The case
16842	 we want to catch is when we couldn't tell then, and can now,
16843	 namely when templ prior to substitution was an
16844	 identifier.  */
16845      if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16846	return error_mark_node;
16847
16848      if (variable_template_p (expr))
16849	expr = lookup_and_finish_template_variable (expr, template_args,
16850						    complain);
16851      else
16852	expr = lookup_template_function (expr, template_args);
16853    }
16854
16855  if (expr == error_mark_node && complain & tf_error)
16856    qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16857				 expr, input_location);
16858  else if (TYPE_P (scope))
16859    {
16860      expr = (adjust_result_of_qualified_name_lookup
16861	      (expr, scope, current_nonlambda_class_type ()));
16862      expr = (finish_qualified_id_expr
16863	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16864	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16865	       /*template_arg_p=*/false, complain));
16866    }
16867
16868  /* Expressions do not generally have reference type.  */
16869  if (TREE_CODE (expr) != SCOPE_REF
16870      /* However, if we're about to form a pointer-to-member, we just
16871	 want the referenced member referenced.  */
16872      && TREE_CODE (expr) != OFFSET_REF)
16873    expr = convert_from_reference (expr);
16874
16875  if (REF_PARENTHESIZED_P (qualified_id))
16876    expr = force_paren_expr (expr);
16877
16878  expr = maybe_wrap_with_location (expr, loc);
16879
16880  return expr;
16881}
16882
16883/* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16884   initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16885   for tsubst.  */
16886
16887static tree
16888tsubst_init (tree init, tree decl, tree args,
16889	     tsubst_flags_t complain, tree in_decl)
16890{
16891  if (!init)
16892    return NULL_TREE;
16893
16894  init = tsubst_expr (init, args, complain, in_decl, false);
16895
16896  tree type = TREE_TYPE (decl);
16897
16898  if (!init && type != error_mark_node)
16899    {
16900      if (tree auto_node = type_uses_auto (type))
16901	{
16902	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16903	    {
16904	      if (complain & tf_error)
16905		error ("initializer for %q#D expands to an empty list "
16906		       "of expressions", decl);
16907	      return error_mark_node;
16908	    }
16909	}
16910      else if (!dependent_type_p (type))
16911	{
16912	  /* If we had an initializer but it
16913	     instantiated to nothing,
16914	     value-initialize the object.  This will
16915	     only occur when the initializer was a
16916	     pack expansion where the parameter packs
16917	     used in that expansion were of length
16918	     zero.  */
16919	  init = build_value_init (type, complain);
16920	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
16921	    init = get_target_expr_sfinae (init, complain);
16922	  if (TREE_CODE (init) == TARGET_EXPR)
16923	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
16924	}
16925    }
16926
16927  return init;
16928}
16929
16930/* If T is a reference to a dependent member of the current instantiation C and
16931   we are trying to refer to that member in a partial instantiation of C,
16932   return a SCOPE_REF; otherwise, return NULL_TREE.
16933
16934   This can happen when forming a C++17 deduction guide, as in PR96199.  */
16935
16936static tree
16937maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16938			    tree in_decl)
16939{
16940  if (!(complain & tf_dguide))
16941    return NULL_TREE;
16942
16943  tree ctx = context_for_name_lookup (t);
16944  if (!CLASS_TYPE_P (ctx))
16945    return NULL_TREE;
16946
16947  ctx = tsubst (ctx, args, complain, in_decl);
16948  if (dependent_scope_p (ctx))
16949    return build_qualified_name (NULL_TREE, ctx, DECL_NAME (t),
16950				 /*template_p=*/false);
16951
16952  return NULL_TREE;
16953}
16954
16955/* Like tsubst, but deals with expressions.  This function just replaces
16956   template parms; to finish processing the resultant expression, use
16957   tsubst_copy_and_build or tsubst_expr.  */
16958
16959static tree
16960tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16961{
16962  enum tree_code code;
16963  tree r;
16964
16965  if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16966    return t;
16967
16968  code = TREE_CODE (t);
16969
16970  switch (code)
16971    {
16972    case PARM_DECL:
16973      r = retrieve_local_specialization (t);
16974
16975      if (r == NULL_TREE)
16976	{
16977	  /* We get here for a use of 'this' in an NSDMI.  */
16978	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
16979	    return current_class_ptr;
16980
16981	  /* This can happen for a parameter name used later in a function
16982	     declaration (such as in a late-specified return type).  Just
16983	     make a dummy decl, since it's only used for its type.  */
16984	  gcc_assert (cp_unevaluated_operand != 0);
16985	  r = tsubst_decl (t, args, complain);
16986	  /* Give it the template pattern as its context; its true context
16987	     hasn't been instantiated yet and this is good enough for
16988	     mangling.  */
16989	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
16990	}
16991
16992      if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16993	r = argument_pack_select_arg (r);
16994      if (!mark_used (r, complain) && !(complain & tf_error))
16995	return error_mark_node;
16996      return r;
16997
16998    case CONST_DECL:
16999      {
17000	tree enum_type;
17001	tree v;
17002
17003	if (DECL_TEMPLATE_PARM_P (t))
17004	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17005	if (!uses_template_parms (DECL_CONTEXT (t)))
17006	  return t;
17007
17008	if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
17009	  return ref;
17010
17011	/* Unfortunately, we cannot just call lookup_name here.
17012	   Consider:
17013
17014	     template <int I> int f() {
17015	     enum E { a = I };
17016	     struct S { void g() { E e = a; } };
17017	     };
17018
17019	   When we instantiate f<7>::S::g(), say, lookup_name is not
17020	   clever enough to find f<7>::a.  */
17021	enum_type
17022	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17023			      /*entering_scope=*/0);
17024
17025	for (v = TYPE_VALUES (enum_type);
17026	     v != NULL_TREE;
17027	     v = TREE_CHAIN (v))
17028	  if (TREE_PURPOSE (v) == DECL_NAME (t))
17029	    return TREE_VALUE (v);
17030
17031	  /* We didn't find the name.  That should never happen; if
17032	     name-lookup found it during preliminary parsing, we
17033	     should find it again here during instantiation.  */
17034	gcc_unreachable ();
17035      }
17036      return t;
17037
17038    case FIELD_DECL:
17039      if (DECL_CONTEXT (t))
17040	{
17041	  tree ctx;
17042
17043	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17044				  /*entering_scope=*/1);
17045	  if (ctx != DECL_CONTEXT (t))
17046	    {
17047	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17048	      if (!r)
17049		{
17050		  if (complain & tf_error)
17051		    error ("using invalid field %qD", t);
17052		  return error_mark_node;
17053		}
17054	      return r;
17055	    }
17056	}
17057
17058      return t;
17059
17060    case VAR_DECL:
17061      if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
17062	return ref;
17063      gcc_fallthrough();
17064    case FUNCTION_DECL:
17065      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17066	r = tsubst (t, args, complain, in_decl);
17067      else if (DECL_LOCAL_DECL_P (t))
17068	{
17069	  /* Local specialization will usually have been created when
17070	     we instantiated the DECL_EXPR_DECL. */
17071	  r = retrieve_local_specialization (t);
17072	  if (!r)
17073	    {
17074	      /* We're in a generic lambda referencing a local extern
17075		 from an outer block-scope of a non-template.  */
17076	      gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17077	      r = t;
17078	    }
17079	}
17080      else if (local_variable_p (t)
17081	       && uses_template_parms (DECL_CONTEXT (t)))
17082	{
17083	  r = retrieve_local_specialization (t);
17084	  if (r == NULL_TREE)
17085	    {
17086	      /* First try name lookup to find the instantiation.  */
17087	      r = lookup_name (DECL_NAME (t));
17088	      if (r)
17089		{
17090		  if (!VAR_P (r))
17091		    {
17092		      /* During error-recovery we may find a non-variable,
17093			 even an OVERLOAD: just bail out and avoid ICEs and
17094			 duplicate diagnostics (c++/62207).  */
17095		      gcc_assert (seen_error ());
17096		      return error_mark_node;
17097		    }
17098		  if (!is_capture_proxy (r))
17099		    {
17100		      /* Make sure the one we found is the one we want.  */
17101		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17102		      if (ctx != DECL_CONTEXT (r))
17103			r = NULL_TREE;
17104		    }
17105		}
17106
17107	      if (r)
17108		/* OK */;
17109	      else
17110		{
17111		  /* This can happen for a variable used in a
17112		     late-specified return type of a local lambda, or for a
17113		     local static or constant.  Building a new VAR_DECL
17114		     should be OK in all those cases.  */
17115		  r = tsubst_decl (t, args, complain);
17116		  if (local_specializations)
17117		    /* Avoid infinite recursion (79640).  */
17118		    register_local_specialization (r, t);
17119		  if (decl_maybe_constant_var_p (r))
17120		    {
17121		      /* We can't call cp_finish_decl, so handle the
17122			 initializer by hand.  */
17123		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
17124					       complain, in_decl);
17125		      if (!processing_template_decl)
17126			init = maybe_constant_init (init);
17127		      if (processing_template_decl
17128			  ? potential_constant_expression (init)
17129			  : reduced_constant_expression_p (init))
17130			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17131			  = TREE_CONSTANT (r) = true;
17132		      DECL_INITIAL (r) = init;
17133		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17134			TREE_TYPE (r)
17135			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17136					       complain, adc_variable_type);
17137		    }
17138		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
17139			      || decl_constant_var_p (r)
17140			      || seen_error ());
17141		  if (!processing_template_decl
17142		      && !TREE_STATIC (r))
17143		    r = process_outer_var_ref (r, complain);
17144		}
17145	      /* Remember this for subsequent uses.  */
17146	      if (local_specializations)
17147		register_local_specialization (r, t);
17148	    }
17149	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17150	    r = argument_pack_select_arg (r);
17151	}
17152      else
17153	r = t;
17154      if (!mark_used (r, complain))
17155	return error_mark_node;
17156      return r;
17157
17158    case NAMESPACE_DECL:
17159      return t;
17160
17161    case OVERLOAD:
17162      return t;
17163
17164    case BASELINK:
17165      return tsubst_baselink (t, current_nonlambda_class_type (),
17166			      args, complain, in_decl);
17167
17168    case TEMPLATE_DECL:
17169      if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17170	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17171		       args, complain, in_decl);
17172      else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17173	return tsubst (t, args, complain, in_decl);
17174      else if (DECL_CLASS_SCOPE_P (t)
17175	       && uses_template_parms (DECL_CONTEXT (t)))
17176	{
17177	  /* Template template argument like the following example need
17178	     special treatment:
17179
17180	       template <template <class> class TT> struct C {};
17181	       template <class T> struct D {
17182		 template <class U> struct E {};
17183		 C<E> c;				// #1
17184	       };
17185	       D<int> d;				// #2
17186
17187	     We are processing the template argument `E' in #1 for
17188	     the template instantiation #2.  Originally, `E' is a
17189	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
17190	     have to substitute this with one having context `D<int>'.  */
17191
17192	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
17193	  if ((complain & tf_dguide) && dependent_scope_p (context))
17194	    {
17195	      /* When rewriting a constructor into a deduction guide, a
17196		 non-dependent name can become dependent, so memtmpl<args>
17197		 becomes context::template memtmpl<args>.  */
17198	      if (DECL_TYPE_TEMPLATE_P (t))
17199		return make_unbound_class_template (context, DECL_NAME (t),
17200						    NULL_TREE, complain);
17201	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17202	      return build_qualified_name (type, context, DECL_NAME (t),
17203					   /*template*/true);
17204	    }
17205	  return lookup_field (context, DECL_NAME(t), 0, false);
17206	}
17207      else
17208	/* Ordinary template template argument.  */
17209	return t;
17210
17211    case NON_LVALUE_EXPR:
17212    case VIEW_CONVERT_EXPR:
17213	{
17214	  /* Handle location wrappers by substituting the wrapped node
17215	     first, *then* reusing the resulting type.  Doing the type
17216	     first ensures that we handle template parameters and
17217	     parameter pack expansions.  */
17218	  if (location_wrapper_p (t))
17219	    {
17220	      tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17221				      complain, in_decl);
17222	      return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17223	    }
17224	  tree op = TREE_OPERAND (t, 0);
17225	  if (code == VIEW_CONVERT_EXPR
17226	      && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
17227	    {
17228	      /* Wrapper to make a C++20 template parameter object const.  */
17229	      op = tsubst_copy (op, args, complain, in_decl);
17230	      if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
17231		{
17232		  /* The template argument is not const, presumably because
17233		     it is still dependent, and so not the const template parm
17234		     object.  */
17235		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17236		  gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
17237				       (type, TREE_TYPE (op)));
17238		  if (TREE_CODE (op) == CONSTRUCTOR
17239		      || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
17240		    {
17241		      /* Don't add a wrapper to these.  */
17242		      op = copy_node (op);
17243		      TREE_TYPE (op) = type;
17244		    }
17245		  else
17246		    /* Do add a wrapper otherwise (in particular, if op is
17247		       another TEMPLATE_PARM_INDEX).  */
17248		    op = build1 (code, type, op);
17249		}
17250	      return op;
17251	    }
17252	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
17253	  else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17254	    {
17255	      op = tsubst_copy (op, args, complain, in_decl);
17256	      op = build1 (code, TREE_TYPE (op), op);
17257	      REF_PARENTHESIZED_P (op) = true;
17258	      return op;
17259	    }
17260	  /* We shouldn't see any other uses of these in templates.  */
17261	  gcc_unreachable ();
17262	}
17263
17264    case CAST_EXPR:
17265    case REINTERPRET_CAST_EXPR:
17266    case CONST_CAST_EXPR:
17267    case STATIC_CAST_EXPR:
17268    case DYNAMIC_CAST_EXPR:
17269    case IMPLICIT_CONV_EXPR:
17270    case CONVERT_EXPR:
17271    case NOP_EXPR:
17272      {
17273	tsubst_flags_t tcomplain = complain;
17274	if (code == CAST_EXPR)
17275	  tcomplain |= tf_tst_ok;
17276	tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17277	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17278	return build1 (code, type, op0);
17279      }
17280
17281    case BIT_CAST_EXPR:
17282      {
17283	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17284	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17285	r = build_min (BIT_CAST_EXPR, type, op0);
17286	SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17287	return r;
17288      }
17289
17290    case SIZEOF_EXPR:
17291      if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17292	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17293        {
17294          tree expanded, op = TREE_OPERAND (t, 0);
17295	  int len = 0;
17296
17297	  if (SIZEOF_EXPR_TYPE_P (t))
17298	    op = TREE_TYPE (op);
17299
17300	  ++cp_unevaluated_operand;
17301	  ++c_inhibit_evaluation_warnings;
17302	  /* We only want to compute the number of arguments.  */
17303	  if (PACK_EXPANSION_P (op))
17304	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17305	  else
17306	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17307					     args, complain, in_decl);
17308	  --cp_unevaluated_operand;
17309	  --c_inhibit_evaluation_warnings;
17310
17311	  if (TREE_CODE (expanded) == TREE_VEC)
17312	    {
17313	      len = TREE_VEC_LENGTH (expanded);
17314	      /* Set TREE_USED for the benefit of -Wunused.  */
17315	      for (int i = 0; i < len; i++)
17316		if (DECL_P (TREE_VEC_ELT (expanded, i)))
17317		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17318	    }
17319
17320	  if (expanded == error_mark_node)
17321	    return error_mark_node;
17322	  else if (PACK_EXPANSION_P (expanded)
17323		   || (TREE_CODE (expanded) == TREE_VEC
17324		       && pack_expansion_args_count (expanded)))
17325
17326	    {
17327	      if (PACK_EXPANSION_P (expanded))
17328		/* OK.  */;
17329	      else if (TREE_VEC_LENGTH (expanded) == 1)
17330		expanded = TREE_VEC_ELT (expanded, 0);
17331	      else
17332		expanded = make_argument_pack (expanded);
17333
17334	      if (TYPE_P (expanded))
17335		return cxx_sizeof_or_alignof_type (input_location,
17336						   expanded, SIZEOF_EXPR,
17337						   false,
17338						   complain & tf_error);
17339	      else
17340		return cxx_sizeof_or_alignof_expr (input_location,
17341						   expanded, SIZEOF_EXPR,
17342						   false,
17343                                                   complain & tf_error);
17344	    }
17345	  else
17346	    return build_int_cst (size_type_node, len);
17347        }
17348      if (SIZEOF_EXPR_TYPE_P (t))
17349	{
17350	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17351		      args, complain, in_decl);
17352	  r = build1 (NOP_EXPR, r, error_mark_node);
17353	  r = build1 (SIZEOF_EXPR,
17354		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17355	  SIZEOF_EXPR_TYPE_P (r) = 1;
17356	  return r;
17357	}
17358      /* Fall through */
17359
17360    case INDIRECT_REF:
17361    case NEGATE_EXPR:
17362    case TRUTH_NOT_EXPR:
17363    case BIT_NOT_EXPR:
17364    case ADDR_EXPR:
17365    case UNARY_PLUS_EXPR:      /* Unary + */
17366    case ALIGNOF_EXPR:
17367    case AT_ENCODE_EXPR:
17368    case ARROW_EXPR:
17369    case THROW_EXPR:
17370    case TYPEID_EXPR:
17371    case REALPART_EXPR:
17372    case IMAGPART_EXPR:
17373    case PAREN_EXPR:
17374      {
17375	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17376	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17377	r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17378	if (code == ALIGNOF_EXPR)
17379	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17380	/* For addresses of immediate functions ensure we have EXPR_LOCATION
17381	   set for possible later diagnostics.  */
17382	if (code == ADDR_EXPR
17383	    && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17384	    && TREE_CODE (op0) == FUNCTION_DECL
17385	    && DECL_IMMEDIATE_FUNCTION_P (op0))
17386	  SET_EXPR_LOCATION (r, input_location);
17387	return r;
17388      }
17389
17390    case COMPONENT_REF:
17391      {
17392	tree object;
17393	tree name;
17394
17395	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17396	name = TREE_OPERAND (t, 1);
17397	if (TREE_CODE (name) == BIT_NOT_EXPR)
17398	  {
17399	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17400				complain, in_decl);
17401	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17402	  }
17403	else if (TREE_CODE (name) == SCOPE_REF
17404		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17405	  {
17406	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17407				     complain, in_decl);
17408	    name = TREE_OPERAND (name, 1);
17409	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17410				complain, in_decl);
17411	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17412	    name = build_qualified_name (/*type=*/NULL_TREE,
17413					 base, name,
17414					 /*template_p=*/false);
17415	  }
17416	else if (BASELINK_P (name))
17417	  name = tsubst_baselink (name,
17418				  non_reference (TREE_TYPE (object)),
17419				  args, complain,
17420				  in_decl);
17421	else
17422	  name = tsubst_copy (name, args, complain, in_decl);
17423	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17424      }
17425
17426    case PLUS_EXPR:
17427    case MINUS_EXPR:
17428    case MULT_EXPR:
17429    case TRUNC_DIV_EXPR:
17430    case CEIL_DIV_EXPR:
17431    case FLOOR_DIV_EXPR:
17432    case ROUND_DIV_EXPR:
17433    case EXACT_DIV_EXPR:
17434    case BIT_AND_EXPR:
17435    case BIT_IOR_EXPR:
17436    case BIT_XOR_EXPR:
17437    case TRUNC_MOD_EXPR:
17438    case FLOOR_MOD_EXPR:
17439    case TRUTH_ANDIF_EXPR:
17440    case TRUTH_ORIF_EXPR:
17441    case TRUTH_AND_EXPR:
17442    case TRUTH_OR_EXPR:
17443    case RSHIFT_EXPR:
17444    case LSHIFT_EXPR:
17445    case EQ_EXPR:
17446    case NE_EXPR:
17447    case MAX_EXPR:
17448    case MIN_EXPR:
17449    case LE_EXPR:
17450    case GE_EXPR:
17451    case LT_EXPR:
17452    case GT_EXPR:
17453    case COMPOUND_EXPR:
17454    case DOTSTAR_EXPR:
17455    case MEMBER_REF:
17456    case PREDECREMENT_EXPR:
17457    case PREINCREMENT_EXPR:
17458    case POSTDECREMENT_EXPR:
17459    case POSTINCREMENT_EXPR:
17460      {
17461	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17462	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17463	return build_nt (code, op0, op1);
17464      }
17465
17466    case SCOPE_REF:
17467      {
17468	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17469	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17470	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17471				     QUALIFIED_NAME_IS_TEMPLATE (t));
17472      }
17473
17474    case ARRAY_REF:
17475      {
17476	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17477	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17478	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17479      }
17480
17481    case CALL_EXPR:
17482      {
17483	int n = VL_EXP_OPERAND_LENGTH (t);
17484	tree result = build_vl_exp (CALL_EXPR, n);
17485	int i;
17486	for (i = 0; i < n; i++)
17487	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17488					     complain, in_decl);
17489	return result;
17490      }
17491
17492    case COND_EXPR:
17493    case MODOP_EXPR:
17494    case PSEUDO_DTOR_EXPR:
17495    case VEC_PERM_EXPR:
17496      {
17497	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17498	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17499	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17500	r = build_nt (code, op0, op1, op2);
17501	copy_warning (r, t);
17502	return r;
17503      }
17504
17505    case NEW_EXPR:
17506      {
17507	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17508	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17509	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17510	r = build_nt (code, op0, op1, op2);
17511	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17512	return r;
17513      }
17514
17515    case DELETE_EXPR:
17516      {
17517	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17518	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17519	r = build_nt (code, op0, op1);
17520	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17521	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17522	return r;
17523      }
17524
17525    case TEMPLATE_ID_EXPR:
17526      {
17527	/* Substituted template arguments */
17528	tree tmpl = TREE_OPERAND (t, 0);
17529	tree targs = TREE_OPERAND (t, 1);
17530
17531	tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17532	if (targs)
17533	  targs = tsubst_template_args (targs, args, complain, in_decl);
17534
17535	if (variable_template_p (tmpl))
17536	  return lookup_template_variable (tmpl, targs);
17537	else
17538	  return lookup_template_function (tmpl, targs);
17539      }
17540
17541    case TREE_LIST:
17542      {
17543	tree purpose, value, chain;
17544
17545	if (t == void_list_node)
17546	  return t;
17547
17548	purpose = TREE_PURPOSE (t);
17549	if (purpose)
17550	  purpose = tsubst_copy (purpose, args, complain, in_decl);
17551	value = TREE_VALUE (t);
17552	if (value)
17553	  value = tsubst_copy (value, args, complain, in_decl);
17554	chain = TREE_CHAIN (t);
17555	if (chain && chain != void_type_node)
17556	  chain = tsubst_copy (chain, args, complain, in_decl);
17557	if (purpose == TREE_PURPOSE (t)
17558	    && value == TREE_VALUE (t)
17559	    && chain == TREE_CHAIN (t))
17560	  return t;
17561	return tree_cons (purpose, value, chain);
17562      }
17563
17564    case RECORD_TYPE:
17565    case UNION_TYPE:
17566    case ENUMERAL_TYPE:
17567    case INTEGER_TYPE:
17568    case TEMPLATE_TYPE_PARM:
17569    case TEMPLATE_TEMPLATE_PARM:
17570    case BOUND_TEMPLATE_TEMPLATE_PARM:
17571    case TEMPLATE_PARM_INDEX:
17572    case POINTER_TYPE:
17573    case REFERENCE_TYPE:
17574    case OFFSET_TYPE:
17575    case FUNCTION_TYPE:
17576    case METHOD_TYPE:
17577    case ARRAY_TYPE:
17578    case TYPENAME_TYPE:
17579    case UNBOUND_CLASS_TEMPLATE:
17580    case TYPEOF_TYPE:
17581    case DECLTYPE_TYPE:
17582    case TYPE_DECL:
17583      return tsubst (t, args, complain, in_decl);
17584
17585    case USING_DECL:
17586      t = DECL_NAME (t);
17587      /* Fall through.  */
17588    case IDENTIFIER_NODE:
17589      if (IDENTIFIER_CONV_OP_P (t))
17590	{
17591	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17592	  return make_conv_op_name (new_type);
17593	}
17594      else
17595	return t;
17596
17597    case CONSTRUCTOR:
17598      /* This is handled by tsubst_copy_and_build.  */
17599      gcc_unreachable ();
17600
17601    case VA_ARG_EXPR:
17602      {
17603	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17604	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17605	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17606      }
17607
17608    case CLEANUP_POINT_EXPR:
17609      /* We shouldn't have built any of these during initial template
17610	 generation.  Instead, they should be built during instantiation
17611	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
17612      gcc_unreachable ();
17613
17614    case OFFSET_REF:
17615      {
17616	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17617	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17618	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17619	r = build2 (code, type, op0, op1);
17620	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17621	if (!mark_used (TREE_OPERAND (r, 1), complain)
17622	    && !(complain & tf_error))
17623	  return error_mark_node;
17624	return r;
17625      }
17626
17627    case EXPR_PACK_EXPANSION:
17628      error ("invalid use of pack expansion expression");
17629      return error_mark_node;
17630
17631    case NONTYPE_ARGUMENT_PACK:
17632      error ("use %<...%> to expand argument pack");
17633      return error_mark_node;
17634
17635    case VOID_CST:
17636      gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17637      return t;
17638
17639    case INTEGER_CST:
17640    case REAL_CST:
17641    case COMPLEX_CST:
17642    case VECTOR_CST:
17643      {
17644	/* Instantiate any typedefs in the type.  */
17645	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17646	r = fold_convert (type, t);
17647	gcc_assert (TREE_CODE (r) == code);
17648	return r;
17649      }
17650
17651    case STRING_CST:
17652      {
17653	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17654	r = t;
17655	if (type != TREE_TYPE (t))
17656	  {
17657	    r = copy_node (t);
17658	    TREE_TYPE (r) = type;
17659	  }
17660	return r;
17661      }
17662
17663    case PTRMEM_CST:
17664      /* These can sometimes show up in a partial instantiation, but never
17665	 involve template parms.  */
17666      gcc_assert (!uses_template_parms (t));
17667      return t;
17668
17669    case UNARY_LEFT_FOLD_EXPR:
17670      return tsubst_unary_left_fold (t, args, complain, in_decl);
17671    case UNARY_RIGHT_FOLD_EXPR:
17672      return tsubst_unary_right_fold (t, args, complain, in_decl);
17673    case BINARY_LEFT_FOLD_EXPR:
17674      return tsubst_binary_left_fold (t, args, complain, in_decl);
17675    case BINARY_RIGHT_FOLD_EXPR:
17676      return tsubst_binary_right_fold (t, args, complain, in_decl);
17677    case PREDICT_EXPR:
17678      return t;
17679
17680    case DEBUG_BEGIN_STMT:
17681      /* ??? There's no point in copying it for now, but maybe some
17682	 day it will contain more information, such as a pointer back
17683	 to the containing function, inlined copy or so.  */
17684      return t;
17685
17686    case CO_AWAIT_EXPR:
17687      return tsubst_expr (t, args, complain, in_decl,
17688			  /*integral_constant_expression_p=*/false);
17689      break;
17690
17691    default:
17692      /* We shouldn't get here, but keep going if !flag_checking.  */
17693      if (flag_checking)
17694	gcc_unreachable ();
17695      return t;
17696    }
17697}
17698
17699/* Helper function for tsubst_omp_clauses, used for instantiation of
17700   OMP_CLAUSE_DECL of clauses.  */
17701
17702static tree
17703tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17704			tree in_decl, tree *iterator_cache)
17705{
17706  if (decl == NULL_TREE)
17707    return NULL_TREE;
17708
17709  /* Handle OpenMP iterators.  */
17710  if (TREE_CODE (decl) == TREE_LIST
17711      && TREE_PURPOSE (decl)
17712      && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17713    {
17714      tree ret;
17715      if (iterator_cache[0] == TREE_PURPOSE (decl))
17716	ret = iterator_cache[1];
17717      else
17718	{
17719	  tree *tp = &ret;
17720	  begin_scope (sk_omp, NULL);
17721	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17722	    {
17723	      *tp = copy_node (it);
17724	      TREE_VEC_ELT (*tp, 0)
17725		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17726	      DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17727	      pushdecl (TREE_VEC_ELT (*tp, 0));
17728	      TREE_VEC_ELT (*tp, 1)
17729		= tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17730			       /*integral_constant_expression_p=*/false);
17731	      TREE_VEC_ELT (*tp, 2)
17732		= tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17733			       /*integral_constant_expression_p=*/false);
17734	      TREE_VEC_ELT (*tp, 3)
17735		= tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17736			       /*integral_constant_expression_p=*/false);
17737	      TREE_CHAIN (*tp) = NULL_TREE;
17738	      tp = &TREE_CHAIN (*tp);
17739	    }
17740	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17741	  iterator_cache[0] = TREE_PURPOSE (decl);
17742	  iterator_cache[1] = ret;
17743	}
17744      return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17745							   args, complain,
17746							   in_decl, NULL));
17747    }
17748
17749  /* Handle an OpenMP array section represented as a TREE_LIST (or
17750     OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17751     kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17752     TREE_LIST.  We can handle it exactly the same as an array section
17753     (purpose, value, and a chain), even though the nomenclature
17754     (low_bound, length, etc) is different.  */
17755  if (TREE_CODE (decl) == TREE_LIST)
17756    {
17757      tree low_bound
17758	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17759		       /*integral_constant_expression_p=*/false);
17760      tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17761				 /*integral_constant_expression_p=*/false);
17762      tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17763					   in_decl, NULL);
17764      if (TREE_PURPOSE (decl) == low_bound
17765	  && TREE_VALUE (decl) == length
17766	  && TREE_CHAIN (decl) == chain)
17767	return decl;
17768      tree ret = tree_cons (low_bound, length, chain);
17769      OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17770	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17771      return ret;
17772    }
17773  tree ret = tsubst_expr (decl, args, complain, in_decl,
17774			  /*integral_constant_expression_p=*/false);
17775  /* Undo convert_from_reference tsubst_expr could have called.  */
17776  if (decl
17777      && REFERENCE_REF_P (ret)
17778      && !REFERENCE_REF_P (decl))
17779    ret = TREE_OPERAND (ret, 0);
17780  return ret;
17781}
17782
17783/* Like tsubst_copy, but specifically for OpenMP clauses.  */
17784
17785static tree
17786tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17787		    tree args, tsubst_flags_t complain, tree in_decl)
17788{
17789  tree new_clauses = NULL_TREE, nc, oc;
17790  tree linear_no_step = NULL_TREE;
17791  tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17792
17793  for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17794    {
17795      nc = copy_node (oc);
17796      OMP_CLAUSE_CHAIN (nc) = new_clauses;
17797      new_clauses = nc;
17798
17799      switch (OMP_CLAUSE_CODE (nc))
17800	{
17801	case OMP_CLAUSE_LASTPRIVATE:
17802	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17803	    {
17804	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17805	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17806			   in_decl, /*integral_constant_expression_p=*/false);
17807	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17808		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17809	    }
17810	  /* FALLTHRU */
17811	case OMP_CLAUSE_PRIVATE:
17812	case OMP_CLAUSE_SHARED:
17813	case OMP_CLAUSE_FIRSTPRIVATE:
17814	case OMP_CLAUSE_COPYIN:
17815	case OMP_CLAUSE_COPYPRIVATE:
17816	case OMP_CLAUSE_UNIFORM:
17817	case OMP_CLAUSE_DEPEND:
17818	case OMP_CLAUSE_AFFINITY:
17819	case OMP_CLAUSE_FROM:
17820	case OMP_CLAUSE_TO:
17821	case OMP_CLAUSE_MAP:
17822	case OMP_CLAUSE__CACHE_:
17823	case OMP_CLAUSE_NONTEMPORAL:
17824	case OMP_CLAUSE_USE_DEVICE_PTR:
17825	case OMP_CLAUSE_USE_DEVICE_ADDR:
17826	case OMP_CLAUSE_IS_DEVICE_PTR:
17827	case OMP_CLAUSE_INCLUSIVE:
17828	case OMP_CLAUSE_EXCLUSIVE:
17829	  OMP_CLAUSE_DECL (nc)
17830	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17831				      in_decl, iterator_cache);
17832	  break;
17833	case OMP_CLAUSE_NUM_TEAMS:
17834	  if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17835	    OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17836	      = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17837			     complain, in_decl,
17838			     /*integral_constant_expression_p=*/false);
17839	  /* FALLTHRU */
17840	case OMP_CLAUSE_TILE:
17841	case OMP_CLAUSE_IF:
17842	case OMP_CLAUSE_NUM_THREADS:
17843	case OMP_CLAUSE_SCHEDULE:
17844	case OMP_CLAUSE_COLLAPSE:
17845	case OMP_CLAUSE_FINAL:
17846	case OMP_CLAUSE_DEVICE:
17847	case OMP_CLAUSE_DIST_SCHEDULE:
17848	case OMP_CLAUSE_THREAD_LIMIT:
17849	case OMP_CLAUSE_SAFELEN:
17850	case OMP_CLAUSE_SIMDLEN:
17851	case OMP_CLAUSE_NUM_TASKS:
17852	case OMP_CLAUSE_GRAINSIZE:
17853	case OMP_CLAUSE_PRIORITY:
17854	case OMP_CLAUSE_ORDERED:
17855	case OMP_CLAUSE_HINT:
17856	case OMP_CLAUSE_FILTER:
17857	case OMP_CLAUSE_NUM_GANGS:
17858	case OMP_CLAUSE_NUM_WORKERS:
17859	case OMP_CLAUSE_VECTOR_LENGTH:
17860	case OMP_CLAUSE_WORKER:
17861	case OMP_CLAUSE_VECTOR:
17862	case OMP_CLAUSE_ASYNC:
17863	case OMP_CLAUSE_WAIT:
17864	case OMP_CLAUSE_DETACH:
17865	  OMP_CLAUSE_OPERAND (nc, 0)
17866	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17867			   in_decl, /*integral_constant_expression_p=*/false);
17868	  break;
17869	case OMP_CLAUSE_REDUCTION:
17870	case OMP_CLAUSE_IN_REDUCTION:
17871	case OMP_CLAUSE_TASK_REDUCTION:
17872	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17873	    {
17874	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17875	      if (TREE_CODE (placeholder) == SCOPE_REF)
17876		{
17877		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17878				       complain, in_decl);
17879		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17880		    = build_qualified_name (NULL_TREE, scope,
17881					    TREE_OPERAND (placeholder, 1),
17882					    false);
17883		}
17884	      else
17885		gcc_assert (identifier_p (placeholder));
17886	    }
17887	  OMP_CLAUSE_DECL (nc)
17888	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17889				      in_decl, NULL);
17890	  break;
17891	case OMP_CLAUSE_GANG:
17892	case OMP_CLAUSE_ALIGNED:
17893	  OMP_CLAUSE_DECL (nc)
17894	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17895				      in_decl, NULL);
17896	  OMP_CLAUSE_OPERAND (nc, 1)
17897	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17898			   in_decl, /*integral_constant_expression_p=*/false);
17899	  break;
17900	case OMP_CLAUSE_ALLOCATE:
17901	  OMP_CLAUSE_DECL (nc)
17902	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17903				      in_decl, NULL);
17904	  OMP_CLAUSE_OPERAND (nc, 1)
17905	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17906			   in_decl, /*integral_constant_expression_p=*/false);
17907	  OMP_CLAUSE_OPERAND (nc, 2)
17908	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain,
17909			   in_decl, /*integral_constant_expression_p=*/false);
17910	  break;
17911	case OMP_CLAUSE_LINEAR:
17912	  OMP_CLAUSE_DECL (nc)
17913	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17914				      in_decl, NULL);
17915	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17916	    {
17917	      gcc_assert (!linear_no_step);
17918	      linear_no_step = nc;
17919	    }
17920	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17921	    OMP_CLAUSE_LINEAR_STEP (nc)
17922	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17923					complain, in_decl, NULL);
17924	  else
17925	    OMP_CLAUSE_LINEAR_STEP (nc)
17926	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17927			     in_decl,
17928			     /*integral_constant_expression_p=*/false);
17929	  break;
17930	case OMP_CLAUSE_NOWAIT:
17931	case OMP_CLAUSE_DEFAULT:
17932	case OMP_CLAUSE_UNTIED:
17933	case OMP_CLAUSE_MERGEABLE:
17934	case OMP_CLAUSE_INBRANCH:
17935	case OMP_CLAUSE_NOTINBRANCH:
17936	case OMP_CLAUSE_PROC_BIND:
17937	case OMP_CLAUSE_FOR:
17938	case OMP_CLAUSE_PARALLEL:
17939	case OMP_CLAUSE_SECTIONS:
17940	case OMP_CLAUSE_TASKGROUP:
17941	case OMP_CLAUSE_NOGROUP:
17942	case OMP_CLAUSE_THREADS:
17943	case OMP_CLAUSE_SIMD:
17944	case OMP_CLAUSE_DEFAULTMAP:
17945	case OMP_CLAUSE_ORDER:
17946	case OMP_CLAUSE_BIND:
17947	case OMP_CLAUSE_INDEPENDENT:
17948	case OMP_CLAUSE_AUTO:
17949	case OMP_CLAUSE_SEQ:
17950	case OMP_CLAUSE_IF_PRESENT:
17951	case OMP_CLAUSE_FINALIZE:
17952	case OMP_CLAUSE_NOHOST:
17953	  break;
17954	default:
17955	  gcc_unreachable ();
17956	}
17957      if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17958	switch (OMP_CLAUSE_CODE (nc))
17959	  {
17960	  case OMP_CLAUSE_SHARED:
17961	  case OMP_CLAUSE_PRIVATE:
17962	  case OMP_CLAUSE_FIRSTPRIVATE:
17963	  case OMP_CLAUSE_LASTPRIVATE:
17964	  case OMP_CLAUSE_COPYPRIVATE:
17965	  case OMP_CLAUSE_LINEAR:
17966	  case OMP_CLAUSE_REDUCTION:
17967	  case OMP_CLAUSE_IN_REDUCTION:
17968	  case OMP_CLAUSE_TASK_REDUCTION:
17969	  case OMP_CLAUSE_USE_DEVICE_PTR:
17970	  case OMP_CLAUSE_USE_DEVICE_ADDR:
17971	  case OMP_CLAUSE_IS_DEVICE_PTR:
17972	  case OMP_CLAUSE_INCLUSIVE:
17973	  case OMP_CLAUSE_EXCLUSIVE:
17974	  case OMP_CLAUSE_ALLOCATE:
17975	    /* tsubst_expr on SCOPE_REF results in returning
17976	       finish_non_static_data_member result.  Undo that here.  */
17977	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17978		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17979		    == IDENTIFIER_NODE))
17980	      {
17981		tree t = OMP_CLAUSE_DECL (nc);
17982		tree v = t;
17983		while (v)
17984		  switch (TREE_CODE (v))
17985		    {
17986		    case COMPONENT_REF:
17987		    case MEM_REF:
17988		    case INDIRECT_REF:
17989		    CASE_CONVERT:
17990		    case POINTER_PLUS_EXPR:
17991		      v = TREE_OPERAND (v, 0);
17992		      continue;
17993		    case PARM_DECL:
17994		      if (DECL_CONTEXT (v) == current_function_decl
17995			  && DECL_ARTIFICIAL (v)
17996			  && DECL_NAME (v) == this_identifier)
17997			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17998		      /* FALLTHRU */
17999		    default:
18000		      v = NULL_TREE;
18001		      break;
18002		    }
18003	      }
18004	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
18005		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18006		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18007		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18008		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18009	      {
18010		tree decl = OMP_CLAUSE_DECL (nc);
18011		if (VAR_P (decl))
18012		  {
18013		    retrofit_lang_decl (decl);
18014		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18015		  }
18016	      }
18017	    break;
18018	  default:
18019	    break;
18020	  }
18021    }
18022
18023  new_clauses = nreverse (new_clauses);
18024  if (ort != C_ORT_OMP_DECLARE_SIMD)
18025    {
18026      new_clauses = finish_omp_clauses (new_clauses, ort);
18027      if (linear_no_step)
18028	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18029	  if (nc == linear_no_step)
18030	    {
18031	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18032	      break;
18033	    }
18034    }
18035  return new_clauses;
18036}
18037
18038/* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
18039
18040static tree
18041tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18042			  tree in_decl)
18043{
18044#define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18045
18046  tree purpose, value, chain;
18047
18048  if (t == NULL)
18049    return t;
18050
18051  if (TREE_CODE (t) != TREE_LIST)
18052    return tsubst_copy_and_build (t, args, complain, in_decl,
18053				  /*function_p=*/false,
18054				  /*integral_constant_expression_p=*/false);
18055
18056  if (t == void_list_node)
18057    return t;
18058
18059  purpose = TREE_PURPOSE (t);
18060  if (purpose)
18061    purpose = RECUR (purpose);
18062  value = TREE_VALUE (t);
18063  if (value)
18064    {
18065      if (TREE_CODE (value) != LABEL_DECL)
18066	value = RECUR (value);
18067      else
18068	{
18069	  value = lookup_label (DECL_NAME (value));
18070	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
18071	  TREE_USED (value) = 1;
18072	}
18073    }
18074  chain = TREE_CHAIN (t);
18075  if (chain && chain != void_type_node)
18076    chain = RECUR (chain);
18077  return tree_cons (purpose, value, chain);
18078#undef RECUR
18079}
18080
18081/* Used to temporarily communicate the list of #pragma omp parallel
18082   clauses to #pragma omp for instantiation if they are combined
18083   together.  */
18084
18085static tree *omp_parallel_combined_clauses;
18086
18087static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18088				 tree *, unsigned int *);
18089
18090/* Substitute one OMP_FOR iterator.  */
18091
18092static bool
18093tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18094			 tree initv, tree condv, tree incrv, tree *clauses,
18095			 tree args, tsubst_flags_t complain, tree in_decl,
18096			 bool integral_constant_expression_p)
18097{
18098#define RECUR(NODE)				\
18099  tsubst_expr ((NODE), args, complain, in_decl,	\
18100	       integral_constant_expression_p)
18101  tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18102  bool ret = false;
18103
18104  init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18105  gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18106
18107  decl = TREE_OPERAND (init, 0);
18108  init = TREE_OPERAND (init, 1);
18109  tree decl_expr = NULL_TREE;
18110  bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18111  if (range_for)
18112    {
18113      bool decomp = false;
18114      if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18115	{
18116	  tree v = DECL_VALUE_EXPR (decl);
18117	  if (TREE_CODE (v) == ARRAY_REF
18118	      && VAR_P (TREE_OPERAND (v, 0))
18119	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18120	    {
18121	      tree decomp_first = NULL_TREE;
18122	      unsigned decomp_cnt = 0;
18123	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18124	      maybe_push_decl (d);
18125	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18126				       in_decl, &decomp_first, &decomp_cnt);
18127	      decomp = true;
18128	      if (d == error_mark_node)
18129		decl = error_mark_node;
18130	      else
18131		for (unsigned int i = 0; i < decomp_cnt; i++)
18132		  {
18133		    if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18134		      {
18135			tree v = build_nt (ARRAY_REF, d,
18136					   size_int (decomp_cnt - i - 1),
18137					   NULL_TREE, NULL_TREE);
18138			SET_DECL_VALUE_EXPR (decomp_first, v);
18139			DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18140		      }
18141		    fit_decomposition_lang_decl (decomp_first, d);
18142		    decomp_first = DECL_CHAIN (decomp_first);
18143		  }
18144	    }
18145	}
18146      decl = tsubst_decl (decl, args, complain);
18147      if (!decomp)
18148	maybe_push_decl (decl);
18149    }
18150  else if (init && TREE_CODE (init) == DECL_EXPR)
18151    {
18152      /* We need to jump through some hoops to handle declarations in the
18153	 init-statement, since we might need to handle auto deduction,
18154	 but we need to keep control of initialization.  */
18155      decl_expr = init;
18156      init = DECL_INITIAL (DECL_EXPR_DECL (init));
18157      decl = tsubst_decl (decl, args, complain);
18158    }
18159  else
18160    {
18161      if (TREE_CODE (decl) == SCOPE_REF)
18162	{
18163	  decl = RECUR (decl);
18164	  if (TREE_CODE (decl) == COMPONENT_REF)
18165	    {
18166	      tree v = decl;
18167	      while (v)
18168		switch (TREE_CODE (v))
18169		  {
18170		  case COMPONENT_REF:
18171		  case MEM_REF:
18172		  case INDIRECT_REF:
18173		  CASE_CONVERT:
18174		  case POINTER_PLUS_EXPR:
18175		    v = TREE_OPERAND (v, 0);
18176		    continue;
18177		  case PARM_DECL:
18178		    if (DECL_CONTEXT (v) == current_function_decl
18179			&& DECL_ARTIFICIAL (v)
18180			&& DECL_NAME (v) == this_identifier)
18181		      {
18182			decl = TREE_OPERAND (decl, 1);
18183			decl = omp_privatize_field (decl, false);
18184		      }
18185		    /* FALLTHRU */
18186		  default:
18187		    v = NULL_TREE;
18188		    break;
18189		  }
18190	    }
18191	}
18192      else
18193	decl = RECUR (decl);
18194    }
18195  if (init && TREE_CODE (init) == TREE_VEC)
18196    {
18197      init = copy_node (init);
18198      TREE_VEC_ELT (init, 0)
18199	= tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18200      TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18201      TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18202    }
18203  else
18204    init = RECUR (init);
18205
18206  if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18207    {
18208      tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18209      if (TREE_CODE (o) == TREE_LIST)
18210	TREE_VEC_ELT (orig_declv, i)
18211	  = tree_cons (RECUR (TREE_PURPOSE (o)),
18212		       RECUR (TREE_VALUE (o)),
18213		       NULL_TREE);
18214      else
18215	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18216    }
18217
18218  if (range_for)
18219    {
18220      tree this_pre_body = NULL_TREE;
18221      tree orig_init = NULL_TREE;
18222      tree orig_decl = NULL_TREE;
18223      cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18224				orig_init, cond, incr);
18225      if (orig_decl)
18226	{
18227	  if (orig_declv == NULL_TREE)
18228	    orig_declv = copy_node (declv);
18229	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
18230	  ret = true;
18231	}
18232      else if (orig_declv)
18233	TREE_VEC_ELT (orig_declv, i) = decl;
18234    }
18235
18236  tree auto_node = type_uses_auto (TREE_TYPE (decl));
18237  if (!range_for && auto_node && init)
18238    TREE_TYPE (decl)
18239      = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18240
18241  gcc_assert (!type_dependent_expression_p (decl));
18242
18243  if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18244    {
18245      if (decl_expr)
18246	{
18247	  /* Declare the variable, but don't let that initialize it.  */
18248	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18249	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18250	  RECUR (decl_expr);
18251	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18252	}
18253
18254      if (!range_for)
18255	{
18256	  cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18257	  if (COMPARISON_CLASS_P (cond)
18258	      && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18259	    {
18260	      tree lhs = RECUR (TREE_OPERAND (cond, 0));
18261	      tree rhs = copy_node (TREE_OPERAND (cond, 1));
18262	      TREE_VEC_ELT (rhs, 0)
18263		= tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18264	      TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18265	      TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18266	      cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18267			     lhs, rhs);
18268	    }
18269	  else
18270	    cond = RECUR (cond);
18271	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18272	  if (TREE_CODE (incr) == MODIFY_EXPR)
18273	    {
18274	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
18275	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
18276	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18277					  NOP_EXPR, rhs, NULL_TREE, complain);
18278	    }
18279	  else
18280	    incr = RECUR (incr);
18281	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18282	    TREE_VEC_ELT (orig_declv, i) = decl;
18283	}
18284      TREE_VEC_ELT (declv, i) = decl;
18285      TREE_VEC_ELT (initv, i) = init;
18286      TREE_VEC_ELT (condv, i) = cond;
18287      TREE_VEC_ELT (incrv, i) = incr;
18288      return ret;
18289    }
18290
18291  if (decl_expr)
18292    {
18293      /* Declare and initialize the variable.  */
18294      RECUR (decl_expr);
18295      init = NULL_TREE;
18296    }
18297  else if (init)
18298    {
18299      tree *pc;
18300      int j;
18301      for (j = ((omp_parallel_combined_clauses == NULL
18302		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18303	{
18304	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18305	    {
18306	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18307		  && OMP_CLAUSE_DECL (*pc) == decl)
18308		break;
18309	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18310		       && OMP_CLAUSE_DECL (*pc) == decl)
18311		{
18312		  if (j)
18313		    break;
18314		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
18315		  tree c = *pc;
18316		  *pc = OMP_CLAUSE_CHAIN (c);
18317		  OMP_CLAUSE_CHAIN (c) = *clauses;
18318		  *clauses = c;
18319		}
18320	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18321		       && OMP_CLAUSE_DECL (*pc) == decl)
18322		{
18323		  error ("iteration variable %qD should not be firstprivate",
18324			 decl);
18325		  *pc = OMP_CLAUSE_CHAIN (*pc);
18326		}
18327	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18328		       && OMP_CLAUSE_DECL (*pc) == decl)
18329		{
18330		  error ("iteration variable %qD should not be reduction",
18331			 decl);
18332		  *pc = OMP_CLAUSE_CHAIN (*pc);
18333		}
18334	      else
18335		pc = &OMP_CLAUSE_CHAIN (*pc);
18336	    }
18337	  if (*pc)
18338	    break;
18339	}
18340      if (*pc == NULL_TREE)
18341	{
18342	  tree c = build_omp_clause (input_location,
18343				     TREE_CODE (t) == OMP_LOOP
18344				     ? OMP_CLAUSE_LASTPRIVATE
18345				     : OMP_CLAUSE_PRIVATE);
18346	  OMP_CLAUSE_DECL (c) = decl;
18347	  c = finish_omp_clauses (c, C_ORT_OMP);
18348	  if (c)
18349	    {
18350	      OMP_CLAUSE_CHAIN (c) = *clauses;
18351	      *clauses = c;
18352	    }
18353	}
18354    }
18355  cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18356  if (COMPARISON_CLASS_P (cond))
18357    {
18358      tree op0 = RECUR (TREE_OPERAND (cond, 0));
18359      tree op1 = RECUR (TREE_OPERAND (cond, 1));
18360      cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18361    }
18362  else
18363    cond = RECUR (cond);
18364  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18365  switch (TREE_CODE (incr))
18366    {
18367    case PREINCREMENT_EXPR:
18368    case PREDECREMENT_EXPR:
18369    case POSTINCREMENT_EXPR:
18370    case POSTDECREMENT_EXPR:
18371      incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18372		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18373      break;
18374    case MODIFY_EXPR:
18375      if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18376	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18377	{
18378	  tree rhs = TREE_OPERAND (incr, 1);
18379	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18380	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18381	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18382	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18383			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18384				 rhs0, rhs1));
18385	}
18386      else
18387	incr = RECUR (incr);
18388      break;
18389    case MODOP_EXPR:
18390      if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18391	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18392	{
18393	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18394	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18395			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18396				 TREE_TYPE (decl), lhs,
18397				 RECUR (TREE_OPERAND (incr, 2))));
18398	}
18399      else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18400	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18401		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18402	{
18403	  tree rhs = TREE_OPERAND (incr, 2);
18404	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18405	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18406	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18407	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18408			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18409				 rhs0, rhs1));
18410	}
18411      else
18412	incr = RECUR (incr);
18413      break;
18414    default:
18415      incr = RECUR (incr);
18416      break;
18417    }
18418
18419  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18420    TREE_VEC_ELT (orig_declv, i) = decl;
18421  TREE_VEC_ELT (declv, i) = decl;
18422  TREE_VEC_ELT (initv, i) = init;
18423  TREE_VEC_ELT (condv, i) = cond;
18424  TREE_VEC_ELT (incrv, i) = incr;
18425  return false;
18426#undef RECUR
18427}
18428
18429/* Helper function of tsubst_expr, find OMP_TEAMS inside
18430   of OMP_TARGET's body.  */
18431
18432static tree
18433tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18434{
18435  *walk_subtrees = 0;
18436  switch (TREE_CODE (*tp))
18437    {
18438    case OMP_TEAMS:
18439      return *tp;
18440    case BIND_EXPR:
18441    case STATEMENT_LIST:
18442      *walk_subtrees = 1;
18443      break;
18444    default:
18445      break;
18446    }
18447  return NULL_TREE;
18448}
18449
18450/* Helper function for tsubst_expr.  For decomposition declaration
18451   artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18452   also the corresponding decls representing the identifiers
18453   of the decomposition declaration.  Return DECL if successful
18454   or error_mark_node otherwise, set *FIRST to the first decl
18455   in the list chained through DECL_CHAIN and *CNT to the number
18456   of such decls.  */
18457
18458static tree
18459tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18460		     tsubst_flags_t complain, tree in_decl, tree *first,
18461		     unsigned int *cnt)
18462{
18463  tree decl2, decl3, prev = decl;
18464  *cnt = 0;
18465  gcc_assert (DECL_NAME (decl) == NULL_TREE);
18466  for (decl2 = DECL_CHAIN (pattern_decl);
18467       decl2
18468       && VAR_P (decl2)
18469       && DECL_DECOMPOSITION_P (decl2)
18470       && DECL_NAME (decl2);
18471       decl2 = DECL_CHAIN (decl2))
18472    {
18473      if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18474	{
18475	  gcc_assert (errorcount);
18476	  return error_mark_node;
18477	}
18478      (*cnt)++;
18479      gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18480      gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18481      tree v = DECL_VALUE_EXPR (decl2);
18482      DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18483      SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18484      decl3 = tsubst (decl2, args, complain, in_decl);
18485      SET_DECL_VALUE_EXPR (decl2, v);
18486      DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18487      if (VAR_P (decl3))
18488	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18489      else
18490	{
18491	  gcc_assert (errorcount);
18492	  decl = error_mark_node;
18493	  continue;
18494	}
18495      maybe_push_decl (decl3);
18496      if (error_operand_p (decl3))
18497	decl = error_mark_node;
18498      else if (decl != error_mark_node
18499	       && DECL_CHAIN (decl3) != prev
18500	       && decl != prev)
18501	{
18502	  gcc_assert (errorcount);
18503	  decl = error_mark_node;
18504	}
18505      else
18506	prev = decl3;
18507    }
18508  *first = prev;
18509  return decl;
18510}
18511
18512/* Return the proper local_specialization for init-capture pack DECL.  */
18513
18514static tree
18515lookup_init_capture_pack (tree decl)
18516{
18517  /* We handle normal pack captures by forwarding to the specialization of the
18518     captured parameter.  We can't do that for pack init-captures; we need them
18519     to have their own local_specialization.  We created the individual
18520     VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18521     when we process the DECL_EXPR for the pack init-capture in the template.
18522     So, how do we find them?  We don't know the capture proxy pack when
18523     building the individual resulting proxies, and we don't know the
18524     individual proxies when instantiating the pack.  What we have in common is
18525     the FIELD_DECL.
18526
18527     So...when we instantiate the FIELD_DECL, we stick the result in
18528     local_specializations.  Then at the DECL_EXPR we look up that result, see
18529     how many elements it has, synthesize the names, and look them up.  */
18530
18531  tree cname = DECL_NAME (decl);
18532  tree val = DECL_VALUE_EXPR (decl);
18533  tree field = TREE_OPERAND (val, 1);
18534  gcc_assert (TREE_CODE (field) == FIELD_DECL);
18535  tree fpack = retrieve_local_specialization (field);
18536  if (fpack == error_mark_node)
18537    return error_mark_node;
18538
18539  int len = 1;
18540  tree vec = NULL_TREE;
18541  tree r = NULL_TREE;
18542  if (TREE_CODE (fpack) == TREE_VEC)
18543    {
18544      len = TREE_VEC_LENGTH (fpack);
18545      vec = make_tree_vec (len);
18546      r = make_node (NONTYPE_ARGUMENT_PACK);
18547      SET_ARGUMENT_PACK_ARGS (r, vec);
18548    }
18549  for (int i = 0; i < len; ++i)
18550    {
18551      tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18552      tree elt = lookup_name (ename);
18553      if (vec)
18554	TREE_VEC_ELT (vec, i) = elt;
18555      else
18556	r = elt;
18557    }
18558  return r;
18559}
18560
18561/* Like tsubst_copy for expressions, etc. but also does semantic
18562   processing.  */
18563
18564tree
18565tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
18566	     bool integral_constant_expression_p)
18567{
18568#define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18569#define RECUR(NODE)				\
18570  tsubst_expr ((NODE), args, complain, in_decl,	\
18571	       integral_constant_expression_p)
18572
18573  tree stmt, tmp;
18574  tree r;
18575  location_t loc;
18576
18577  if (t == NULL_TREE || t == error_mark_node)
18578    return t;
18579
18580  loc = input_location;
18581  if (location_t eloc = cp_expr_location (t))
18582    input_location = eloc;
18583  if (STATEMENT_CODE_P (TREE_CODE (t)))
18584    current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18585
18586  switch (TREE_CODE (t))
18587    {
18588    case STATEMENT_LIST:
18589      {
18590	for (tree stmt : tsi_range (t))
18591	  RECUR (stmt);
18592	break;
18593      }
18594
18595    case CTOR_INITIALIZER:
18596      finish_mem_initializers (tsubst_initializer_list
18597			       (TREE_OPERAND (t, 0), args));
18598      break;
18599
18600    case RETURN_EXPR:
18601      finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18602      break;
18603
18604    case CO_RETURN_EXPR:
18605      finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18606      break;
18607
18608    case CO_YIELD_EXPR:
18609      stmt = finish_co_yield_expr (input_location,
18610				   RECUR (TREE_OPERAND (t, 0)));
18611      RETURN (stmt);
18612
18613    case CO_AWAIT_EXPR:
18614      stmt = finish_co_await_expr (input_location,
18615				   RECUR (TREE_OPERAND (t, 0)));
18616      RETURN (stmt);
18617
18618    case EXPR_STMT:
18619      tmp = RECUR (EXPR_STMT_EXPR (t));
18620      if (EXPR_STMT_STMT_EXPR_RESULT (t))
18621	finish_stmt_expr_expr (tmp, cur_stmt_expr);
18622      else
18623	finish_expr_stmt (tmp);
18624      break;
18625
18626    case USING_STMT:
18627      finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18628      break;
18629
18630    case DECL_EXPR:
18631      {
18632	tree decl, pattern_decl;
18633	tree init;
18634
18635	pattern_decl = decl = DECL_EXPR_DECL (t);
18636	if (TREE_CODE (decl) == LABEL_DECL)
18637	  finish_label_decl (DECL_NAME (decl));
18638	else if (TREE_CODE (decl) == USING_DECL)
18639	  {
18640	    tree scope = USING_DECL_SCOPE (decl);
18641	    if (DECL_DEPENDENT_P (decl))
18642	      {
18643		scope = tsubst (scope, args, complain, in_decl);
18644		if (!MAYBE_CLASS_TYPE_P (scope)
18645		    && TREE_CODE (scope) != ENUMERAL_TYPE)
18646		  {
18647		    if (complain & tf_error)
18648		      error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18649				"class, namespace, or enumeration", scope);
18650		    return error_mark_node;
18651		  }
18652		finish_nonmember_using_decl (scope, DECL_NAME (decl));
18653	      }
18654	    else
18655	      {
18656		/* This is a non-dependent using-decl, and we'll have
18657		   used the names it found during template parsing.  We do
18658		   not want to do the lookup again, because we might not
18659		   find the things we found then.  */
18660		gcc_checking_assert (scope == tsubst (scope, args,
18661						      complain, in_decl));
18662		/* We still need to push the bindings so that we can look up
18663		   this name later.  */
18664		push_using_decl_bindings (DECL_NAME (decl),
18665					  USING_DECL_DECLS (decl));
18666	      }
18667	  }
18668	else if (is_capture_proxy (decl)
18669		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18670	  {
18671	    /* We're in tsubst_lambda_expr, we've already inserted a new
18672	       capture proxy, so look it up and register it.  */
18673	    tree inst;
18674	    if (!DECL_PACK_P (decl))
18675	      {
18676		inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18677				    LOOK_want::HIDDEN_LAMBDA);
18678		gcc_assert (inst != decl && is_capture_proxy (inst));
18679	      }
18680	    else if (is_normal_capture_proxy (decl))
18681	      {
18682		inst = (retrieve_local_specialization
18683			(DECL_CAPTURED_VARIABLE (decl)));
18684		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18685			    || DECL_PACK_P (inst));
18686	      }
18687	    else
18688	      inst = lookup_init_capture_pack (decl);
18689
18690	    register_local_specialization (inst, decl);
18691	    break;
18692	  }
18693	else if (DECL_PRETTY_FUNCTION_P (decl))
18694	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18695				  DECL_NAME (decl),
18696				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18697	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18698		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18699	  /* Don't copy the old closure; we'll create a new one in
18700	     tsubst_lambda_expr.  */
18701	  break;
18702	else
18703	  {
18704	    init = DECL_INITIAL (decl);
18705	    decl = tsubst (decl, args, complain, in_decl);
18706	    if (decl != error_mark_node)
18707	      {
18708		/* By marking the declaration as instantiated, we avoid
18709		   trying to instantiate it.  Since instantiate_decl can't
18710		   handle local variables, and since we've already done
18711		   all that needs to be done, that's the right thing to
18712		   do.  */
18713		if (VAR_P (decl))
18714		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18715		if (VAR_P (decl) && !DECL_NAME (decl)
18716		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18717		  /* Anonymous aggregates are a special case.  */
18718		  finish_anon_union (decl);
18719		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18720		  {
18721		    DECL_CONTEXT (decl) = current_function_decl;
18722		    if (DECL_NAME (decl) == this_identifier)
18723		      {
18724			tree lam = DECL_CONTEXT (current_function_decl);
18725			lam = CLASSTYPE_LAMBDA_EXPR (lam);
18726			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18727		      }
18728		    insert_capture_proxy (decl);
18729		  }
18730		else if (DECL_IMPLICIT_TYPEDEF_P (t))
18731		  /* We already did a pushtag.  */;
18732		else if (VAR_OR_FUNCTION_DECL_P (decl)
18733			 && DECL_LOCAL_DECL_P (decl))
18734		  {
18735		    if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18736		      DECL_CONTEXT (decl) = NULL_TREE;
18737		    decl = pushdecl (decl);
18738		    if (TREE_CODE (decl) == FUNCTION_DECL
18739			&& DECL_OMP_DECLARE_REDUCTION_P (decl)
18740			&& cp_check_omp_declare_reduction (decl))
18741		      instantiate_body (pattern_decl, args, decl, true);
18742		  }
18743		else
18744		  {
18745		    bool const_init = false;
18746		    unsigned int cnt = 0;
18747		    tree first = NULL_TREE, ndecl = error_mark_node;
18748		    tree asmspec_tree = NULL_TREE;
18749		    maybe_push_decl (decl);
18750
18751		    if (VAR_P (decl)
18752			&& DECL_LANG_SPECIFIC (decl)
18753			&& DECL_OMP_PRIVATIZED_MEMBER (decl))
18754		      break;
18755
18756		    if (VAR_P (decl)
18757			&& DECL_DECOMPOSITION_P (decl)
18758			&& TREE_TYPE (pattern_decl) != error_mark_node)
18759		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18760						   complain, in_decl, &first,
18761						   &cnt);
18762
18763		    init = tsubst_init (init, decl, args, complain, in_decl);
18764
18765		    if (VAR_P (decl))
18766		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18767				    (pattern_decl));
18768
18769		    if (ndecl != error_mark_node)
18770		      cp_maybe_mangle_decomp (ndecl, first, cnt);
18771
18772		    /* In a non-template function, VLA type declarations are
18773		       handled in grokdeclarator; for templates, handle them
18774		       now.  */
18775		    predeclare_vla (decl);
18776
18777		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18778		      {
18779			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18780			const char *asmspec = IDENTIFIER_POINTER (id);
18781			gcc_assert (asmspec[0] == '*');
18782			asmspec_tree
18783			  = build_string (IDENTIFIER_LENGTH (id) - 1,
18784					  asmspec + 1);
18785			TREE_TYPE (asmspec_tree) = char_array_type_node;
18786		      }
18787
18788		    cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
18789
18790		    if (ndecl != error_mark_node)
18791		      cp_finish_decomp (ndecl, first, cnt);
18792		  }
18793	      }
18794	  }
18795
18796	break;
18797      }
18798
18799    case FOR_STMT:
18800      stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18801      RECUR (FOR_INIT_STMT (t));
18802      finish_init_stmt (stmt);
18803      tmp = RECUR (FOR_COND (t));
18804      finish_for_cond (tmp, stmt, false, 0);
18805      tmp = RECUR (FOR_EXPR (t));
18806      finish_for_expr (tmp, stmt);
18807      {
18808	bool prev = note_iteration_stmt_body_start ();
18809	RECUR (FOR_BODY (t));
18810	note_iteration_stmt_body_end (prev);
18811      }
18812      finish_for_stmt (stmt);
18813      break;
18814
18815    case RANGE_FOR_STMT:
18816      {
18817	/* Construct another range_for, if this is not a final
18818	   substitution (for inside a generic lambda of a
18819	   template).  Otherwise convert to a regular for.  */
18820        tree decl, expr;
18821        stmt = (processing_template_decl
18822		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18823		: begin_for_stmt (NULL_TREE, NULL_TREE));
18824	RECUR (RANGE_FOR_INIT_STMT (t));
18825        decl = RANGE_FOR_DECL (t);
18826        decl = tsubst (decl, args, complain, in_decl);
18827        maybe_push_decl (decl);
18828        expr = RECUR (RANGE_FOR_EXPR (t));
18829
18830	tree decomp_first = NULL_TREE;
18831	unsigned decomp_cnt = 0;
18832	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18833	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18834				      complain, in_decl,
18835				      &decomp_first, &decomp_cnt);
18836
18837	if (processing_template_decl)
18838	  {
18839	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18840	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18841	    finish_range_for_decl (stmt, decl, expr);
18842	    if (decomp_first && decl != error_mark_node)
18843	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
18844	  }
18845	else
18846	  {
18847	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
18848				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18849	    stmt = cp_convert_range_for (stmt, decl, expr,
18850					 decomp_first, decomp_cnt,
18851					 RANGE_FOR_IVDEP (t), unroll);
18852	  }
18853
18854	bool prev = note_iteration_stmt_body_start ();
18855        RECUR (RANGE_FOR_BODY (t));
18856	note_iteration_stmt_body_end (prev);
18857        finish_for_stmt (stmt);
18858      }
18859      break;
18860
18861    case WHILE_STMT:
18862      stmt = begin_while_stmt ();
18863      tmp = RECUR (WHILE_COND (t));
18864      finish_while_stmt_cond (tmp, stmt, false, 0);
18865      {
18866	bool prev = note_iteration_stmt_body_start ();
18867	RECUR (WHILE_BODY (t));
18868	note_iteration_stmt_body_end (prev);
18869      }
18870      finish_while_stmt (stmt);
18871      break;
18872
18873    case DO_STMT:
18874      stmt = begin_do_stmt ();
18875      {
18876	bool prev = note_iteration_stmt_body_start ();
18877	RECUR (DO_BODY (t));
18878	note_iteration_stmt_body_end (prev);
18879      }
18880      finish_do_body (stmt);
18881      tmp = RECUR (DO_COND (t));
18882      finish_do_stmt (tmp, stmt, false, 0);
18883      break;
18884
18885    case IF_STMT:
18886      stmt = begin_if_stmt ();
18887      IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18888      IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18889      if (IF_STMT_CONSTEXPR_P (t))
18890	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18891      tmp = RECUR (IF_COND (t));
18892      tmp = finish_if_stmt_cond (tmp, stmt);
18893      if (IF_STMT_CONSTEXPR_P (t)
18894	  && instantiation_dependent_expression_p (tmp))
18895	{
18896	  /* We're partially instantiating a generic lambda, but the condition
18897	     of the constexpr if is still dependent.  Don't substitute into the
18898	     branches now, just remember the template arguments.  */
18899	  do_poplevel (IF_SCOPE (stmt));
18900	  IF_COND (stmt) = IF_COND (t);
18901	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18902	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18903	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18904	  add_stmt (stmt);
18905	  break;
18906	}
18907      if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18908	/* Don't instantiate the THEN_CLAUSE. */;
18909      else if (IF_STMT_CONSTEVAL_P (t))
18910	{
18911	  bool save_in_consteval_if_p = in_consteval_if_p;
18912	  in_consteval_if_p = true;
18913	  RECUR (THEN_CLAUSE (t));
18914	  in_consteval_if_p = save_in_consteval_if_p;
18915	}
18916      else
18917	{
18918	  tree folded = fold_non_dependent_expr (tmp, complain);
18919	  bool inhibit = integer_zerop (folded);
18920	  if (inhibit)
18921	    ++c_inhibit_evaluation_warnings;
18922	  RECUR (THEN_CLAUSE (t));
18923	  if (inhibit)
18924	    --c_inhibit_evaluation_warnings;
18925	}
18926      finish_then_clause (stmt);
18927
18928      if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18929	/* Don't instantiate the ELSE_CLAUSE. */;
18930      else if (ELSE_CLAUSE (t))
18931	{
18932	  tree folded = fold_non_dependent_expr (tmp, complain);
18933	  bool inhibit = integer_nonzerop (folded);
18934	  begin_else_clause (stmt);
18935	  if (inhibit)
18936	    ++c_inhibit_evaluation_warnings;
18937	  RECUR (ELSE_CLAUSE (t));
18938	  if (inhibit)
18939	    --c_inhibit_evaluation_warnings;
18940	  finish_else_clause (stmt);
18941	}
18942
18943      finish_if_stmt (stmt);
18944      break;
18945
18946    case BIND_EXPR:
18947      if (BIND_EXPR_BODY_BLOCK (t))
18948	stmt = begin_function_body ();
18949      else
18950	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18951				    ? BCS_TRY_BLOCK : 0);
18952
18953      RECUR (BIND_EXPR_BODY (t));
18954
18955      if (BIND_EXPR_BODY_BLOCK (t))
18956	finish_function_body (stmt);
18957      else
18958	finish_compound_stmt (stmt);
18959      break;
18960
18961    case BREAK_STMT:
18962      finish_break_stmt ();
18963      break;
18964
18965    case CONTINUE_STMT:
18966      finish_continue_stmt ();
18967      break;
18968
18969    case SWITCH_STMT:
18970      stmt = begin_switch_stmt ();
18971      tmp = RECUR (SWITCH_STMT_COND (t));
18972      finish_switch_cond (tmp, stmt);
18973      RECUR (SWITCH_STMT_BODY (t));
18974      finish_switch_stmt (stmt);
18975      break;
18976
18977    case CASE_LABEL_EXPR:
18978      {
18979	tree decl = CASE_LABEL (t);
18980	tree low = RECUR (CASE_LOW (t));
18981	tree high = RECUR (CASE_HIGH (t));
18982	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18983	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18984	  {
18985	    tree label = CASE_LABEL (l);
18986	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18987	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18988	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18989	  }
18990      }
18991      break;
18992
18993    case LABEL_EXPR:
18994      {
18995	tree decl = LABEL_EXPR_LABEL (t);
18996	tree label;
18997
18998	label = finish_label_stmt (DECL_NAME (decl));
18999	if (TREE_CODE (label) == LABEL_DECL)
19000	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19001	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19002	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19003      }
19004      break;
19005
19006    case GOTO_EXPR:
19007      tmp = GOTO_DESTINATION (t);
19008      if (TREE_CODE (tmp) != LABEL_DECL)
19009	/* Computed goto's must be tsubst'd into.  On the other hand,
19010	   non-computed gotos must not be; the identifier in question
19011	   will have no binding.  */
19012	tmp = RECUR (tmp);
19013      else
19014	tmp = DECL_NAME (tmp);
19015      finish_goto_stmt (tmp);
19016      break;
19017
19018    case ASM_EXPR:
19019      {
19020	tree string = RECUR (ASM_STRING (t));
19021	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19022						 complain, in_decl);
19023	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19024						complain, in_decl);
19025	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19026	 					  complain, in_decl);
19027	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19028						complain, in_decl);
19029	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19030			       outputs, inputs, clobbers, labels,
19031			       ASM_INLINE_P (t));
19032	tree asm_expr = tmp;
19033	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19034	  asm_expr = TREE_OPERAND (asm_expr, 0);
19035	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19036      }
19037      break;
19038
19039    case TRY_BLOCK:
19040      if (CLEANUP_P (t))
19041	{
19042	  stmt = begin_try_block ();
19043	  RECUR (TRY_STMTS (t));
19044	  finish_cleanup_try_block (stmt);
19045	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19046	}
19047      else
19048	{
19049	  tree compound_stmt = NULL_TREE;
19050
19051	  if (FN_TRY_BLOCK_P (t))
19052	    stmt = begin_function_try_block (&compound_stmt);
19053	  else
19054	    stmt = begin_try_block ();
19055
19056	  RECUR (TRY_STMTS (t));
19057
19058	  if (FN_TRY_BLOCK_P (t))
19059	    finish_function_try_block (stmt);
19060	  else
19061	    finish_try_block (stmt);
19062
19063	  RECUR (TRY_HANDLERS (t));
19064	  if (FN_TRY_BLOCK_P (t))
19065	    finish_function_handler_sequence (stmt, compound_stmt);
19066	  else
19067	    finish_handler_sequence (stmt);
19068	}
19069      break;
19070
19071    case HANDLER:
19072      {
19073	tree decl = HANDLER_PARMS (t);
19074
19075	if (decl)
19076	  {
19077	    decl = tsubst (decl, args, complain, in_decl);
19078	    /* Prevent instantiate_decl from trying to instantiate
19079	       this variable.  We've already done all that needs to be
19080	       done.  */
19081	    if (decl != error_mark_node)
19082	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19083	  }
19084	stmt = begin_handler ();
19085	finish_handler_parms (decl, stmt);
19086	RECUR (HANDLER_BODY (t));
19087	finish_handler (stmt);
19088      }
19089      break;
19090
19091    case TAG_DEFN:
19092      tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19093      if (dependent_type_p (tmp))
19094	/* This is a partial instantiation, try again when full.  */
19095	add_stmt (build_min (TAG_DEFN, tmp));
19096      else if (CLASS_TYPE_P (tmp))
19097	{
19098	  /* Local classes are not independent templates; they are
19099	     instantiated along with their containing function.  And this
19100	     way we don't have to deal with pushing out of one local class
19101	     to instantiate a member of another local class.  */
19102	  /* Closures are handled by the LAMBDA_EXPR.  */
19103	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19104	  complete_type (tmp);
19105	  tree save_ccp = current_class_ptr;
19106	  tree save_ccr = current_class_ref;
19107	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19108	    if ((VAR_P (fld)
19109		 || (TREE_CODE (fld) == FUNCTION_DECL
19110		     && !DECL_ARTIFICIAL (fld)))
19111		&& DECL_TEMPLATE_INSTANTIATION (fld))
19112	      instantiate_decl (fld, /*defer_ok=*/false,
19113				/*expl_inst_class=*/false);
19114	    else if (TREE_CODE (fld) == FIELD_DECL)
19115	      maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19116	  current_class_ptr = save_ccp;
19117	  current_class_ref = save_ccr;
19118	}
19119      break;
19120
19121    case STATIC_ASSERT:
19122      {
19123	tree condition;
19124
19125	++c_inhibit_evaluation_warnings;
19126	condition =
19127	  tsubst_expr (STATIC_ASSERT_CONDITION (t),
19128                       args,
19129                       complain, in_decl,
19130                       /*integral_constant_expression_p=*/true);
19131	--c_inhibit_evaluation_warnings;
19132
19133        finish_static_assert (condition,
19134                              STATIC_ASSERT_MESSAGE (t),
19135                              STATIC_ASSERT_SOURCE_LOCATION (t),
19136			      /*member_p=*/false, /*show_expr_p=*/true);
19137      }
19138      break;
19139
19140    case OACC_KERNELS:
19141    case OACC_PARALLEL:
19142    case OACC_SERIAL:
19143      tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19144				in_decl);
19145      stmt = begin_omp_parallel ();
19146      RECUR (OMP_BODY (t));
19147      finish_omp_construct (TREE_CODE (t), stmt, tmp);
19148      break;
19149
19150    case OMP_PARALLEL:
19151      r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19152      tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19153				complain, in_decl);
19154      if (OMP_PARALLEL_COMBINED (t))
19155	omp_parallel_combined_clauses = &tmp;
19156      stmt = begin_omp_parallel ();
19157      RECUR (OMP_PARALLEL_BODY (t));
19158      gcc_assert (omp_parallel_combined_clauses == NULL);
19159      OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19160	= OMP_PARALLEL_COMBINED (t);
19161      pop_omp_privatization_clauses (r);
19162      break;
19163
19164    case OMP_TASK:
19165      if (OMP_TASK_BODY (t) == NULL_TREE)
19166	{
19167	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19168				    complain, in_decl);
19169	  t = copy_node (t);
19170	  OMP_TASK_CLAUSES (t) = tmp;
19171	  add_stmt (t);
19172	  break;
19173	}
19174      r = push_omp_privatization_clauses (false);
19175      tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19176				complain, in_decl);
19177      stmt = begin_omp_task ();
19178      RECUR (OMP_TASK_BODY (t));
19179      finish_omp_task (tmp, stmt);
19180      pop_omp_privatization_clauses (r);
19181      break;
19182
19183    case OMP_FOR:
19184    case OMP_LOOP:
19185    case OMP_SIMD:
19186    case OMP_DISTRIBUTE:
19187    case OMP_TASKLOOP:
19188    case OACC_LOOP:
19189      {
19190	tree clauses, body, pre_body;
19191	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19192	tree orig_declv = NULL_TREE;
19193	tree incrv = NULL_TREE;
19194	enum c_omp_region_type ort = C_ORT_OMP;
19195	bool any_range_for = false;
19196	int i;
19197
19198	if (TREE_CODE (t) == OACC_LOOP)
19199	  ort = C_ORT_ACC;
19200
19201	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19202	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19203				      in_decl);
19204	if (OMP_FOR_INIT (t) != NULL_TREE)
19205	  {
19206	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19207	    if (OMP_FOR_ORIG_DECLS (t))
19208	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19209	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19210	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19211	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19212	  }
19213
19214	keep_next_level (true);
19215	stmt = begin_omp_structured_block ();
19216
19217	pre_body = push_stmt_list ();
19218	RECUR (OMP_FOR_PRE_BODY (t));
19219	pre_body = pop_stmt_list (pre_body);
19220
19221	if (OMP_FOR_INIT (t) != NULL_TREE)
19222	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19223	    any_range_for
19224	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19225					  condv, incrv, &clauses, args,
19226					  complain, in_decl,
19227					  integral_constant_expression_p);
19228	omp_parallel_combined_clauses = NULL;
19229
19230	if (any_range_for)
19231	  {
19232	    gcc_assert (orig_declv);
19233	    body = begin_omp_structured_block ();
19234	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19235	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19236		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19237		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19238		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19239					 TREE_VEC_ELT (declv, i));
19240	  }
19241	else
19242	  body = push_stmt_list ();
19243	RECUR (OMP_FOR_BODY (t));
19244	if (any_range_for)
19245	  body = finish_omp_structured_block (body);
19246	else
19247	  body = pop_stmt_list (body);
19248
19249	if (OMP_FOR_INIT (t) != NULL_TREE)
19250	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19251			      orig_declv, initv, condv, incrv, body, pre_body,
19252			      NULL, clauses);
19253	else
19254	  {
19255	    t = make_node (TREE_CODE (t));
19256	    TREE_TYPE (t) = void_type_node;
19257	    OMP_FOR_BODY (t) = body;
19258	    OMP_FOR_PRE_BODY (t) = pre_body;
19259	    OMP_FOR_CLAUSES (t) = clauses;
19260	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19261	    add_stmt (t);
19262	  }
19263
19264	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19265					t));
19266	pop_omp_privatization_clauses (r);
19267      }
19268      break;
19269
19270    case OMP_SECTIONS:
19271    case OMP_MASKED:
19272      omp_parallel_combined_clauses = NULL;
19273      /* FALLTHRU */
19274    case OMP_SINGLE:
19275    case OMP_SCOPE:
19276    case OMP_TEAMS:
19277    case OMP_CRITICAL:
19278    case OMP_TASKGROUP:
19279    case OMP_SCAN:
19280      r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19281					  && OMP_TEAMS_COMBINED (t));
19282      tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19283				in_decl);
19284      if (TREE_CODE (t) == OMP_TEAMS)
19285	{
19286	  keep_next_level (true);
19287	  stmt = begin_omp_structured_block ();
19288	  RECUR (OMP_BODY (t));
19289	  stmt = finish_omp_structured_block (stmt);
19290	}
19291      else
19292	{
19293	  stmt = push_stmt_list ();
19294	  RECUR (OMP_BODY (t));
19295	  stmt = pop_stmt_list (stmt);
19296	}
19297
19298      if (TREE_CODE (t) == OMP_CRITICAL
19299	  && tmp != NULL_TREE
19300	  && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19301	{
19302	  error_at (OMP_CLAUSE_LOCATION (tmp),
19303		    "%<#pragma omp critical%> with %<hint%> clause requires "
19304		    "a name, except when %<omp_sync_hint_none%> is used");
19305	  RETURN (error_mark_node);
19306	}
19307      t = copy_node (t);
19308      OMP_BODY (t) = stmt;
19309      OMP_CLAUSES (t) = tmp;
19310      add_stmt (t);
19311      pop_omp_privatization_clauses (r);
19312      break;
19313
19314    case OMP_DEPOBJ:
19315      r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19316      if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19317	{
19318	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
19319	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19320	    {
19321	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19322					args, complain, in_decl);
19323	      if (tmp == NULL_TREE)
19324		tmp = error_mark_node;
19325	    }
19326	  else
19327	    {
19328	      kind = (enum omp_clause_depend_kind)
19329		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19330	      tmp = NULL_TREE;
19331	    }
19332	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19333	}
19334      else
19335	finish_omp_depobj (EXPR_LOCATION (t), r,
19336			   OMP_CLAUSE_DEPEND_SOURCE,
19337			   OMP_DEPOBJ_CLAUSES (t));
19338      break;
19339
19340    case OACC_DATA:
19341    case OMP_TARGET_DATA:
19342    case OMP_TARGET:
19343      tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19344				TREE_CODE (t) == OACC_DATA
19345				? C_ORT_ACC
19346				: TREE_CODE (t) == OMP_TARGET
19347				? C_ORT_OMP_TARGET : C_ORT_OMP,
19348				args, complain, in_decl);
19349      keep_next_level (true);
19350      stmt = begin_omp_structured_block ();
19351
19352      RECUR (OMP_BODY (t));
19353      stmt = finish_omp_structured_block (stmt);
19354
19355      t = copy_node (t);
19356      OMP_BODY (t) = stmt;
19357      OMP_CLAUSES (t) = tmp;
19358
19359      if (TREE_CODE (t) == OMP_TARGET)
19360	finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19361				   &OMP_CLAUSES (t));
19362
19363      if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19364	{
19365	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19366	  if (teams)
19367	    /* For combined target teams, ensure the num_teams and
19368	       thread_limit clause expressions are evaluated on the host,
19369	       before entering the target construct.  */
19370	    for (tree c = OMP_TEAMS_CLAUSES (teams);
19371		 c; c = OMP_CLAUSE_CHAIN (c))
19372	      if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19373		  || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19374		for (int i = 0;
19375		     i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19376		  if (OMP_CLAUSE_OPERAND (c, i)
19377		      && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19378		    {
19379		      tree expr = OMP_CLAUSE_OPERAND (c, i);
19380		      expr = force_target_expr (TREE_TYPE (expr), expr,
19381						tf_none);
19382		      if (expr == error_mark_node)
19383			continue;
19384		      tmp = TARGET_EXPR_SLOT (expr);
19385		      add_stmt (expr);
19386		      OMP_CLAUSE_OPERAND (c, i) = expr;
19387		      tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19388						  OMP_CLAUSE_FIRSTPRIVATE);
19389		      OMP_CLAUSE_DECL (tc) = tmp;
19390		      OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19391		      OMP_TARGET_CLAUSES (t) = tc;
19392		    }
19393	}
19394      add_stmt (t);
19395      break;
19396
19397    case OACC_DECLARE:
19398      t = copy_node (t);
19399      tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19400				complain, in_decl);
19401      OACC_DECLARE_CLAUSES (t) = tmp;
19402      add_stmt (t);
19403      break;
19404
19405    case OMP_TARGET_UPDATE:
19406    case OMP_TARGET_ENTER_DATA:
19407    case OMP_TARGET_EXIT_DATA:
19408      tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19409				complain, in_decl);
19410      t = copy_node (t);
19411      OMP_STANDALONE_CLAUSES (t) = tmp;
19412      add_stmt (t);
19413      break;
19414
19415    case OACC_CACHE:
19416    case OACC_ENTER_DATA:
19417    case OACC_EXIT_DATA:
19418    case OACC_UPDATE:
19419      tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19420				complain, in_decl);
19421      t = copy_node (t);
19422      OMP_STANDALONE_CLAUSES (t) = tmp;
19423      add_stmt (t);
19424      break;
19425
19426    case OMP_ORDERED:
19427      tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19428				complain, in_decl);
19429      stmt = push_stmt_list ();
19430      RECUR (OMP_BODY (t));
19431      stmt = pop_stmt_list (stmt);
19432
19433      t = copy_node (t);
19434      OMP_BODY (t) = stmt;
19435      OMP_ORDERED_CLAUSES (t) = tmp;
19436      add_stmt (t);
19437      break;
19438
19439    case OMP_MASTER:
19440      omp_parallel_combined_clauses = NULL;
19441      /* FALLTHRU */
19442    case OMP_SECTION:
19443      stmt = push_stmt_list ();
19444      RECUR (OMP_BODY (t));
19445      stmt = pop_stmt_list (stmt);
19446
19447      t = copy_node (t);
19448      OMP_BODY (t) = stmt;
19449      add_stmt (t);
19450      break;
19451
19452    case OMP_ATOMIC:
19453      gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19454      tmp = NULL_TREE;
19455      if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19456	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19457				  complain, in_decl);
19458      if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19459	{
19460	  tree op1 = TREE_OPERAND (t, 1);
19461	  tree rhs1 = NULL_TREE;
19462	  tree r = NULL_TREE;
19463	  tree lhs, rhs;
19464	  if (TREE_CODE (op1) == COMPOUND_EXPR)
19465	    {
19466	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
19467	      op1 = TREE_OPERAND (op1, 1);
19468	    }
19469	  if (TREE_CODE (op1) == COND_EXPR)
19470	    {
19471	      gcc_assert (rhs1 == NULL_TREE);
19472	      tree c = TREE_OPERAND (op1, 0);
19473	      if (TREE_CODE (c) == MODIFY_EXPR)
19474		{
19475		  r = RECUR (TREE_OPERAND (c, 0));
19476		  c = TREE_OPERAND (c, 1);
19477		}
19478	      gcc_assert (TREE_CODE (c) == EQ_EXPR);
19479	      rhs = RECUR (TREE_OPERAND (c, 1));
19480	      lhs = RECUR (TREE_OPERAND (op1, 2));
19481	      rhs1 = RECUR (TREE_OPERAND (op1, 1));
19482	    }
19483	  else
19484	    {
19485	      lhs = RECUR (TREE_OPERAND (op1, 0));
19486	      rhs = RECUR (TREE_OPERAND (op1, 1));
19487	    }
19488	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19489			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19490			     tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19491			     OMP_ATOMIC_WEAK (t));
19492	}
19493      else
19494	{
19495	  tree op1 = TREE_OPERAND (t, 1);
19496	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19497	  tree rhs1 = NULL_TREE, r = NULL_TREE;
19498	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19499	  enum tree_code opcode = NOP_EXPR;
19500	  if (code == OMP_ATOMIC_READ)
19501	    {
19502	      v = RECUR (TREE_OPERAND (op1, 0));
19503	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19504	    }
19505	  else if (code == OMP_ATOMIC_CAPTURE_OLD
19506		   || code == OMP_ATOMIC_CAPTURE_NEW)
19507	    {
19508	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19509	      v = RECUR (TREE_OPERAND (op1, 0));
19510	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19511	      if (TREE_CODE (op11) == COMPOUND_EXPR)
19512		{
19513		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
19514		  op11 = TREE_OPERAND (op11, 1);
19515		}
19516	      if (TREE_CODE (op11) == COND_EXPR)
19517		{
19518		  gcc_assert (rhs1 == NULL_TREE);
19519		  tree c = TREE_OPERAND (op11, 0);
19520		  if (TREE_CODE (c) == MODIFY_EXPR)
19521		    {
19522		      r = RECUR (TREE_OPERAND (c, 0));
19523		      c = TREE_OPERAND (c, 1);
19524		    }
19525		  gcc_assert (TREE_CODE (c) == EQ_EXPR);
19526		  rhs = RECUR (TREE_OPERAND (c, 1));
19527		  lhs = RECUR (TREE_OPERAND (op11, 2));
19528		  rhs1 = RECUR (TREE_OPERAND (op11, 1));
19529		}
19530	      else
19531		{
19532		  lhs = RECUR (TREE_OPERAND (op11, 0));
19533		  rhs = RECUR (TREE_OPERAND (op11, 1));
19534		}
19535	      opcode = TREE_CODE (op11);
19536	      if (opcode == MODIFY_EXPR)
19537		opcode = NOP_EXPR;
19538	    }
19539	  else
19540	    {
19541	      code = OMP_ATOMIC;
19542	      lhs = RECUR (TREE_OPERAND (op1, 0));
19543	      rhs = RECUR (TREE_OPERAND (op1, 1));
19544	    }
19545	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19546			     lhs1, rhs1, r, tmp,
19547			     OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19548	}
19549      break;
19550
19551    case TRANSACTION_EXPR:
19552      {
19553	int flags = 0;
19554	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19555	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19556
19557        if (TRANSACTION_EXPR_IS_STMT (t))
19558          {
19559	    tree body = TRANSACTION_EXPR_BODY (t);
19560	    tree noex = NULL_TREE;
19561	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19562	      {
19563		noex = MUST_NOT_THROW_COND (body);
19564		if (noex == NULL_TREE)
19565		  noex = boolean_true_node;
19566		body = TREE_OPERAND (body, 0);
19567	      }
19568            stmt = begin_transaction_stmt (input_location, NULL, flags);
19569            RECUR (body);
19570            finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19571          }
19572        else
19573          {
19574            stmt = build_transaction_expr (EXPR_LOCATION (t),
19575					   RECUR (TRANSACTION_EXPR_BODY (t)),
19576					   flags, NULL_TREE);
19577            RETURN (stmt);
19578          }
19579      }
19580      break;
19581
19582    case MUST_NOT_THROW_EXPR:
19583      {
19584	tree op0 = RECUR (TREE_OPERAND (t, 0));
19585	tree cond = RECUR (MUST_NOT_THROW_COND (t));
19586	RETURN (build_must_not_throw_expr (op0, cond));
19587      }
19588
19589    case EXPR_PACK_EXPANSION:
19590      error ("invalid use of pack expansion expression");
19591      RETURN (error_mark_node);
19592
19593    case NONTYPE_ARGUMENT_PACK:
19594      error ("use %<...%> to expand argument pack");
19595      RETURN (error_mark_node);
19596
19597    case COMPOUND_EXPR:
19598      tmp = RECUR (TREE_OPERAND (t, 0));
19599      if (tmp == NULL_TREE)
19600	/* If the first operand was a statement, we're done with it.  */
19601	RETURN (RECUR (TREE_OPERAND (t, 1)));
19602      RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19603				    RECUR (TREE_OPERAND (t, 1)),
19604				    templated_operator_saved_lookups (t),
19605				    complain));
19606
19607    case ANNOTATE_EXPR:
19608      tmp = RECUR (TREE_OPERAND (t, 0));
19609      RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19610			  TREE_TYPE (tmp), tmp,
19611			  RECUR (TREE_OPERAND (t, 1)),
19612			  RECUR (TREE_OPERAND (t, 2))));
19613
19614    case PREDICT_EXPR:
19615      RETURN (add_stmt (copy_node (t)));
19616
19617    default:
19618      gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19619
19620      RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
19621				    /*function_p=*/false,
19622				    integral_constant_expression_p));
19623    }
19624
19625  RETURN (NULL_TREE);
19626 out:
19627  input_location = loc;
19628  return r;
19629#undef RECUR
19630#undef RETURN
19631}
19632
19633/* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19634   function.  For description of the body see comment above
19635   cp_parser_omp_declare_reduction_exprs.  */
19636
19637static void
19638tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19639{
19640  if (t == NULL_TREE || t == error_mark_node)
19641    return;
19642
19643  gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19644
19645  tree_stmt_iterator tsi;
19646  int i;
19647  tree stmts[7];
19648  memset (stmts, 0, sizeof stmts);
19649  for (i = 0, tsi = tsi_start (t);
19650       i < 7 && !tsi_end_p (tsi);
19651       i++, tsi_next (&tsi))
19652    stmts[i] = tsi_stmt (tsi);
19653  gcc_assert (tsi_end_p (tsi));
19654
19655  if (i >= 3)
19656    {
19657      gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19658		  && TREE_CODE (stmts[1]) == DECL_EXPR);
19659      tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19660			     args, complain, in_decl);
19661      tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19662			    args, complain, in_decl);
19663      /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19664	 expect to be pushing it.  */
19665      DECL_CONTEXT (omp_out) = current_function_decl;
19666      DECL_CONTEXT (omp_in) = current_function_decl;
19667      keep_next_level (true);
19668      tree block = begin_omp_structured_block ();
19669      tsubst_expr (stmts[2], args, complain, in_decl, false);
19670      block = finish_omp_structured_block (block);
19671      block = maybe_cleanup_point_expr_void (block);
19672      add_decl_expr (omp_out);
19673      copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19674      add_decl_expr (omp_in);
19675      finish_expr_stmt (block);
19676    }
19677  if (i >= 6)
19678    {
19679      gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19680		  && TREE_CODE (stmts[4]) == DECL_EXPR);
19681      tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19682			      args, complain, in_decl);
19683      tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19684			      args, complain, in_decl);
19685      DECL_CONTEXT (omp_priv) = current_function_decl;
19686      DECL_CONTEXT (omp_orig) = current_function_decl;
19687      keep_next_level (true);
19688      tree block = begin_omp_structured_block ();
19689      tsubst_expr (stmts[5], args, complain, in_decl, false);
19690      block = finish_omp_structured_block (block);
19691      block = maybe_cleanup_point_expr_void (block);
19692      cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19693      add_decl_expr (omp_priv);
19694      add_decl_expr (omp_orig);
19695      finish_expr_stmt (block);
19696      if (i == 7)
19697	add_decl_expr (omp_orig);
19698    }
19699}
19700
19701/* T is a postfix-expression that is not being used in a function
19702   call.  Return the substituted version of T.  */
19703
19704static tree
19705tsubst_non_call_postfix_expression (tree t, tree args,
19706				    tsubst_flags_t complain,
19707				    tree in_decl)
19708{
19709  if (TREE_CODE (t) == SCOPE_REF)
19710    t = tsubst_qualified_id (t, args, complain, in_decl,
19711			     /*done=*/false, /*address_p=*/false);
19712  else
19713    t = tsubst_copy_and_build (t, args, complain, in_decl,
19714			       /*function_p=*/false,
19715			       /*integral_constant_expression_p=*/false);
19716
19717  return t;
19718}
19719
19720/* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19721   LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
19722   dependent init-capture.  EXPLICIT_P is true if the original list had
19723   explicit captures.  */
19724
19725static void
19726prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19727		     tsubst_flags_t complain)
19728{
19729  if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19730    {
19731      tree type = NULL_TREE;
19732      if (!init)
19733	{
19734	  if (complain & tf_error)
19735	    error ("empty initializer in lambda init-capture");
19736	  init = error_mark_node;
19737	}
19738      else if (TREE_CODE (init) == TREE_LIST)
19739	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19740      if (!type)
19741	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19742      TREE_TYPE (field) = type;
19743      cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19744    }
19745  list = tree_cons (field, init, list);
19746  LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19747}
19748
19749/* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
19750   instantiation context.  Instantiating a pack expansion containing a lambda
19751   might result in multiple lambdas all based on the same lambda in the
19752   template.  */
19753
19754tree
19755tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19756{
19757  tree oldfn = lambda_function (t);
19758  in_decl = oldfn;
19759
19760  tree r = build_lambda_expr ();
19761
19762  LAMBDA_EXPR_LOCATION (r)
19763    = LAMBDA_EXPR_LOCATION (t);
19764  LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19765    = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19766  LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19767  if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19768    LAMBDA_EXPR_REGEN_INFO (r)
19769      = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19770						      preserve_args (args)));
19771  else
19772    LAMBDA_EXPR_REGEN_INFO (r)
19773      = build_template_info (t, preserve_args (args));
19774
19775  gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19776	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19777
19778  vec<tree,va_gc>* field_packs = NULL;
19779
19780  for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19781       cap = TREE_CHAIN (cap))
19782    {
19783      tree ofield = TREE_PURPOSE (cap);
19784      tree init = TREE_VALUE (cap);
19785      if (PACK_EXPANSION_P (init))
19786	init = tsubst_pack_expansion (init, args, complain, in_decl);
19787      else
19788	init = tsubst_copy_and_build (init, args, complain, in_decl,
19789				      /*fn*/false, /*constexpr*/false);
19790
19791      if (init == error_mark_node)
19792	return error_mark_node;
19793
19794      if (init && TREE_CODE (init) == TREE_LIST)
19795	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19796
19797      if (!processing_template_decl
19798	  && init && TREE_CODE (init) != TREE_VEC
19799	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19800	{
19801	  /* For a VLA, simply tsubsting the field type won't work, we need to
19802	     go through add_capture again.  XXX do we want to do this for all
19803	     captures?  */
19804	  tree name = (get_identifier
19805		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19806	  tree ftype = TREE_TYPE (ofield);
19807	  bool by_ref = (TYPE_REF_P (ftype)
19808			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19809			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19810	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19811	  continue;
19812	}
19813
19814      if (PACK_EXPANSION_P (ofield))
19815	ofield = PACK_EXPANSION_PATTERN (ofield);
19816      tree field = tsubst_decl (ofield, args, complain);
19817
19818      if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19819	{
19820	  /* Remember these for when we've pushed local_specializations.  */
19821	  vec_safe_push (field_packs, ofield);
19822	  vec_safe_push (field_packs, field);
19823	}
19824
19825      if (field == error_mark_node)
19826	return error_mark_node;
19827
19828      if (TREE_CODE (field) == TREE_VEC)
19829	{
19830	  int len = TREE_VEC_LENGTH (field);
19831	  gcc_assert (TREE_CODE (init) == TREE_VEC
19832		      && TREE_VEC_LENGTH (init) == len);
19833	  for (int i = 0; i < len; ++i)
19834	    prepend_one_capture (TREE_VEC_ELT (field, i),
19835				 TREE_VEC_ELT (init, i),
19836				 LAMBDA_EXPR_CAPTURE_LIST (r),
19837				 LAMBDA_CAPTURE_EXPLICIT_P (cap),
19838				 complain);
19839	}
19840      else
19841	{
19842	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19843			       LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
19844
19845	  if (id_equal (DECL_NAME (field), "__this"))
19846	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19847	}
19848    }
19849
19850  tree type = begin_lambda_type (r);
19851  if (type == error_mark_node)
19852    return error_mark_node;
19853
19854  if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19855    {
19856      /* A lambda in a default argument outside a class gets no
19857	 LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
19858	 tsubst_default_argument calls start_lambda_scope, so we need to
19859	 specifically ignore it here, and use the global scope.  */
19860      record_null_lambda_scope (r);
19861
19862      /* If we're pushed into another scope (PR105652), fix it.  */
19863      if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19864	TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19865	  = TYPE_CONTEXT (TREE_TYPE (t));
19866    }
19867  else
19868    record_lambda_scope (r);
19869
19870  /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19871  determine_visibility (TYPE_NAME (type));
19872
19873  register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19874
19875  tree oldtmpl = (generic_lambda_fn_p (oldfn)
19876		  ? DECL_TI_TEMPLATE (oldfn)
19877		  : NULL_TREE);
19878
19879  tree fntype = static_fn_type (oldfn);
19880  if (oldtmpl)
19881    ++processing_template_decl;
19882  fntype = tsubst (fntype, args, complain, in_decl);
19883  if (oldtmpl)
19884    --processing_template_decl;
19885
19886  if (fntype == error_mark_node)
19887    r = error_mark_node;
19888  else
19889    {
19890      /* The body of a lambda-expression is not a subexpression of the
19891	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19892	 which would be skipped if cp_unevaluated_operand.  */
19893      cp_evaluated ev;
19894
19895      /* Fix the type of 'this'.  */
19896      fntype = build_memfn_type (fntype, type,
19897				 type_memfn_quals (fntype),
19898				 type_memfn_rqual (fntype));
19899      tree fn, tmpl;
19900      if (oldtmpl)
19901	{
19902	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19903	  if (tmpl == error_mark_node)
19904	    {
19905	      r = error_mark_node;
19906	      goto out;
19907	    }
19908	  fn = DECL_TEMPLATE_RESULT (tmpl);
19909	  finish_member_declaration (tmpl);
19910	}
19911      else
19912	{
19913	  tmpl = NULL_TREE;
19914	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
19915	  if (fn == error_mark_node)
19916	    {
19917	      r = error_mark_node;
19918	      goto out;
19919	    }
19920	  finish_member_declaration (fn);
19921	}
19922
19923      /* Let finish_function set this.  */
19924      DECL_DECLARED_CONSTEXPR_P (fn) = false;
19925
19926      bool nested = cfun;
19927      if (nested)
19928	push_function_context ();
19929      else
19930	/* Still increment function_depth so that we don't GC in the
19931	   middle of an expression.  */
19932	++function_depth;
19933
19934      local_specialization_stack s (lss_copy);
19935
19936      bool save_in_consteval_if_p = in_consteval_if_p;
19937      in_consteval_if_p = false;
19938
19939      tree body = start_lambda_function (fn, r);
19940
19941      /* Now record them for lookup_init_capture_pack.  */
19942      int fplen = vec_safe_length (field_packs);
19943      for (int i = 0; i < fplen; )
19944	{
19945	  tree pack = (*field_packs)[i++];
19946	  tree inst = (*field_packs)[i++];
19947	  register_local_specialization (inst, pack);
19948	}
19949      release_tree_vector (field_packs);
19950
19951      register_parameter_specializations (oldfn, fn);
19952
19953      if (oldtmpl)
19954	{
19955	  /* We might not partially instantiate some parts of the function, so
19956	     copy these flags from the original template.  */
19957	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19958	  current_function_returns_value = ol->returns_value;
19959	  current_function_returns_null = ol->returns_null;
19960	  current_function_returns_abnormally = ol->returns_abnormally;
19961	  current_function_infinite_loop = ol->infinite_loop;
19962	}
19963
19964      /* [temp.deduct] A lambda-expression appearing in a function type or a
19965	 template parameter is not considered part of the immediate context for
19966	 the purposes of template argument deduction. */
19967      complain = tf_warning_or_error;
19968
19969      tree saved = DECL_SAVED_TREE (oldfn);
19970      if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19971	/* We already have a body block from start_lambda_function, we don't
19972	   need another to confuse NRV (91217).  */
19973	saved = BIND_EXPR_BODY (saved);
19974
19975      tsubst_expr (saved, args, complain, r, /*constexpr*/false);
19976
19977      finish_lambda_function (body);
19978
19979      in_consteval_if_p = save_in_consteval_if_p;
19980
19981      if (nested)
19982	pop_function_context ();
19983      else
19984	--function_depth;
19985
19986      /* The capture list was built up in reverse order; fix that now.  */
19987      LAMBDA_EXPR_CAPTURE_LIST (r)
19988	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19989
19990      LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19991
19992      maybe_add_lambda_conv_op (type);
19993    }
19994
19995out:
19996  finish_struct (type, /*attr*/NULL_TREE);
19997
19998  insert_pending_capture_proxies ();
19999
20000  return r;
20001}
20002
20003/* Subroutine of maybe_fold_fn_template_args.  */
20004
20005static bool
20006fold_targs_r (tree targs, tsubst_flags_t complain)
20007{
20008  int len = TREE_VEC_LENGTH (targs);
20009  for (int i = 0; i < len; ++i)
20010    {
20011      tree &elt = TREE_VEC_ELT (targs, i);
20012      if (!elt || TYPE_P (elt)
20013	  || TREE_CODE (elt) == TEMPLATE_DECL)
20014	continue;
20015      if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20016	{
20017	  if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20018	    return false;
20019	}
20020      else if (/* We can only safely preevaluate scalar prvalues.  */
20021	       SCALAR_TYPE_P (TREE_TYPE (elt))
20022	       && !glvalue_p (elt)
20023	       && !TREE_CONSTANT (elt))
20024	{
20025	  elt = cxx_constant_value_sfinae (elt, NULL_TREE, complain);
20026	  if (elt == error_mark_node)
20027	    return false;
20028	}
20029    }
20030
20031  return true;
20032}
20033
20034/* Try to do constant evaluation of any explicit template arguments in FN
20035   before overload resolution, to get any errors only once.  Return true iff
20036   we didn't have any problems folding.  */
20037
20038static bool
20039maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20040{
20041  if (processing_template_decl || fn == NULL_TREE)
20042    return true;
20043  if (fn == error_mark_node)
20044    return false;
20045  if (TREE_CODE (fn) == OFFSET_REF
20046      || TREE_CODE (fn) == COMPONENT_REF)
20047    fn = TREE_OPERAND (fn, 1);
20048  if (BASELINK_P (fn))
20049    fn = BASELINK_FUNCTIONS (fn);
20050  if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20051    return true;
20052  tree targs = TREE_OPERAND (fn, 1);
20053  if (targs == NULL_TREE)
20054    return true;
20055  if (targs == error_mark_node)
20056    return false;
20057  return fold_targs_r (targs, complain);
20058}
20059
20060/* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20061   handling.  */
20062
20063static void
20064tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20065				 tree in_decl,
20066				 bool integral_constant_expression_p,
20067				 releasing_vec &call_args)
20068{
20069  unsigned int nargs = call_expr_nargs (t);
20070  for (unsigned int i = 0; i < nargs; ++i)
20071    {
20072      tree arg = CALL_EXPR_ARG (t, i);
20073
20074      if (!PACK_EXPANSION_P (arg))
20075	vec_safe_push (call_args,
20076		       tsubst_copy_and_build (arg, args, complain, in_decl,
20077					      /*function_p=*/false,
20078					      integral_constant_expression_p));
20079      else
20080	{
20081	  /* Expand the pack expansion and push each entry onto CALL_ARGS.  */
20082	  arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20083	  if (TREE_CODE (arg) == TREE_VEC)
20084	    {
20085	      unsigned int len, j;
20086
20087	      len = TREE_VEC_LENGTH (arg);
20088	      for (j = 0; j < len; ++j)
20089		{
20090		  tree value = TREE_VEC_ELT (arg, j);
20091		  if (value != NULL_TREE)
20092		    value = convert_from_reference (value);
20093		  vec_safe_push (call_args, value);
20094		}
20095	    }
20096	  else
20097	    /* A partial substitution.  Add one entry.  */
20098	    vec_safe_push (call_args, arg);
20099	}
20100    }
20101}
20102
20103/* Like tsubst but deals with expressions and performs semantic
20104   analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)" or
20105   "F<TARGS> (ARGS)".  */
20106
20107tree
20108tsubst_copy_and_build (tree t,
20109		       tree args,
20110		       tsubst_flags_t complain,
20111		       tree in_decl,
20112		       bool function_p,
20113		       bool integral_constant_expression_p)
20114{
20115#define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20116#define RECUR(NODE)						\
20117  tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
20118			 /*function_p=*/false,			\
20119			 integral_constant_expression_p)
20120
20121  tree retval, op1;
20122  location_t save_loc;
20123
20124  if (t == NULL_TREE || t == error_mark_node)
20125    return t;
20126
20127  save_loc = input_location;
20128  if (location_t eloc = cp_expr_location (t))
20129    input_location = eloc;
20130
20131  /* N3276 decltype magic only applies to calls at the top level or on the
20132     right side of a comma.  */
20133  tsubst_flags_t decltype_flag = (complain & tf_decltype);
20134  complain &= ~tf_decltype;
20135
20136  switch (TREE_CODE (t))
20137    {
20138    case USING_DECL:
20139      t = DECL_NAME (t);
20140      /* Fall through.  */
20141    case IDENTIFIER_NODE:
20142      {
20143	tree decl;
20144	cp_id_kind idk;
20145	bool non_integral_constant_expression_p;
20146	const char *error_msg;
20147
20148	if (IDENTIFIER_CONV_OP_P (t))
20149	  {
20150	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20151	    t = make_conv_op_name (new_type);
20152	  }
20153
20154	/* Look up the name.  */
20155	decl = lookup_name (t);
20156
20157	/* By convention, expressions use ERROR_MARK_NODE to indicate
20158	   failure, not NULL_TREE.  */
20159	if (decl == NULL_TREE)
20160	  decl = error_mark_node;
20161
20162	decl = finish_id_expression (t, decl, NULL_TREE,
20163				     &idk,
20164				     integral_constant_expression_p,
20165          /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
20166				     &non_integral_constant_expression_p,
20167				     /*template_p=*/false,
20168				     /*done=*/true,
20169				     /*address_p=*/false,
20170				     /*template_arg_p=*/false,
20171				     &error_msg,
20172				     input_location);
20173	if (error_msg)
20174	  error (error_msg);
20175	if (!function_p && identifier_p (decl))
20176	  {
20177	    if (complain & tf_error)
20178	      unqualified_name_lookup_error (decl);
20179	    decl = error_mark_node;
20180	  }
20181	RETURN (decl);
20182      }
20183
20184    case TEMPLATE_ID_EXPR:
20185      {
20186	tree object;
20187	tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20188					    complain, in_decl,
20189					    function_p,
20190					    integral_constant_expression_p);
20191	tree targs = TREE_OPERAND (t, 1);
20192
20193	if (targs)
20194	  targs = tsubst_template_args (targs, args, complain, in_decl);
20195	if (targs == error_mark_node)
20196	  RETURN (error_mark_node);
20197
20198	if (TREE_CODE (templ) == SCOPE_REF)
20199	  {
20200	    tree name = TREE_OPERAND (templ, 1);
20201	    tree tid = lookup_template_function (name, targs);
20202	    TREE_OPERAND (templ, 1) = tid;
20203	    RETURN (templ);
20204	  }
20205
20206	if (concept_definition_p (templ))
20207	  {
20208	    tree check = build_concept_check (templ, targs, complain);
20209	    if (check == error_mark_node)
20210	      RETURN (error_mark_node);
20211
20212	    tree id = unpack_concept_check (check);
20213
20214	    /* If we built a function concept check, return the underlying
20215	       template-id. So we can evaluate it as a function call.  */
20216	    if (function_concept_p (TREE_OPERAND (id, 0)))
20217	      RETURN (id);
20218
20219	    RETURN (check);
20220	  }
20221
20222	if (variable_template_p (templ))
20223	  {
20224	    tree r = lookup_and_finish_template_variable (templ, targs,
20225							  complain);
20226	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20227	    RETURN (r);
20228	  }
20229
20230	if (TREE_CODE (templ) == COMPONENT_REF)
20231	  {
20232	    object = TREE_OPERAND (templ, 0);
20233	    templ = TREE_OPERAND (templ, 1);
20234	  }
20235	else
20236	  object = NULL_TREE;
20237
20238	tree tid = lookup_template_function (templ, targs);
20239
20240	if (object)
20241	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20242			 object, tid, NULL_TREE));
20243	else if (identifier_p (templ))
20244	  {
20245	    /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20246	       name lookup found nothing when parsing the template name.  */
20247	    gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20248	    RETURN (tid);
20249	  }
20250	else
20251	  RETURN (baselink_for_fns (tid));
20252      }
20253
20254    case INDIRECT_REF:
20255      {
20256	tree r = RECUR (TREE_OPERAND (t, 0));
20257
20258	if (REFERENCE_REF_P (t))
20259	  {
20260	    /* A type conversion to reference type will be enclosed in
20261	       such an indirect ref, but the substitution of the cast
20262	       will have also added such an indirect ref.  */
20263	    r = convert_from_reference (r);
20264	  }
20265	else
20266	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20267				    templated_operator_saved_lookups (t),
20268				    complain|decltype_flag);
20269
20270	if (REF_PARENTHESIZED_P (t))
20271	  r = force_paren_expr (r);
20272
20273	RETURN (r);
20274      }
20275
20276    case NOP_EXPR:
20277      {
20278	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20279	tree op0 = RECUR (TREE_OPERAND (t, 0));
20280	RETURN (build_nop (type, op0));
20281      }
20282
20283    case IMPLICIT_CONV_EXPR:
20284      {
20285	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20286	tree expr = RECUR (TREE_OPERAND (t, 0));
20287	if (dependent_type_p (type) || type_dependent_expression_p (expr))
20288	  {
20289	    retval = copy_node (t);
20290	    TREE_TYPE (retval) = type;
20291	    TREE_OPERAND (retval, 0) = expr;
20292	    RETURN (retval);
20293	  }
20294	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20295	  /* We'll pass this to convert_nontype_argument again, we don't need
20296	     to actually perform any conversion here.  */
20297	  RETURN (expr);
20298	int flags = LOOKUP_IMPLICIT;
20299	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20300	  flags = LOOKUP_NORMAL;
20301	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20302	  flags |= LOOKUP_NO_NARROWING;
20303	RETURN (perform_implicit_conversion_flags (type, expr, complain,
20304						  flags));
20305      }
20306
20307    case CONVERT_EXPR:
20308      {
20309	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20310	tree op0 = RECUR (TREE_OPERAND (t, 0));
20311	if (op0 == error_mark_node)
20312	  RETURN (error_mark_node);
20313	RETURN (build1 (CONVERT_EXPR, type, op0));
20314      }
20315
20316    case CAST_EXPR:
20317    case REINTERPRET_CAST_EXPR:
20318    case CONST_CAST_EXPR:
20319    case DYNAMIC_CAST_EXPR:
20320    case STATIC_CAST_EXPR:
20321      {
20322	tree type;
20323	tree op, r = NULL_TREE;
20324
20325	tsubst_flags_t tcomplain = complain;
20326	if (TREE_CODE (t) == CAST_EXPR)
20327	  tcomplain |= tf_tst_ok;
20328	type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20329	if (integral_constant_expression_p
20330	    && !cast_valid_in_integral_constant_expression_p (type))
20331	  {
20332            if (complain & tf_error)
20333              error ("a cast to a type other than an integral or "
20334                     "enumeration type cannot appear in a constant-expression");
20335	    RETURN (error_mark_node);
20336	  }
20337
20338	op = RECUR (TREE_OPERAND (t, 0));
20339
20340	warning_sentinel s(warn_useless_cast);
20341	warning_sentinel s2(warn_ignored_qualifiers);
20342	warning_sentinel s3(warn_int_in_bool_context);
20343	switch (TREE_CODE (t))
20344	  {
20345	  case CAST_EXPR:
20346	    r = build_functional_cast (input_location, type, op, complain);
20347	    break;
20348	  case REINTERPRET_CAST_EXPR:
20349	    r = build_reinterpret_cast (input_location, type, op, complain);
20350	    break;
20351	  case CONST_CAST_EXPR:
20352	    r = build_const_cast (input_location, type, op, complain);
20353	    break;
20354	  case DYNAMIC_CAST_EXPR:
20355	    r = build_dynamic_cast (input_location, type, op, complain);
20356	    break;
20357	  case STATIC_CAST_EXPR:
20358	    r = build_static_cast (input_location, type, op, complain);
20359	    if (IMPLICIT_RVALUE_P (t))
20360	      set_implicit_rvalue_p (r);
20361	    break;
20362	  default:
20363	    gcc_unreachable ();
20364	  }
20365
20366	RETURN (r);
20367      }
20368
20369    case BIT_CAST_EXPR:
20370      {
20371	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20372	tree op0 = RECUR (TREE_OPERAND (t, 0));
20373	RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20374      }
20375
20376    case POSTDECREMENT_EXPR:
20377    case POSTINCREMENT_EXPR:
20378      op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20379						args, complain, in_decl);
20380      RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20381				templated_operator_saved_lookups (t),
20382				complain|decltype_flag));
20383
20384    case PREDECREMENT_EXPR:
20385    case PREINCREMENT_EXPR:
20386    case NEGATE_EXPR:
20387    case BIT_NOT_EXPR:
20388    case ABS_EXPR:
20389    case TRUTH_NOT_EXPR:
20390    case UNARY_PLUS_EXPR:  /* Unary + */
20391    case REALPART_EXPR:
20392    case IMAGPART_EXPR:
20393      RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20394				RECUR (TREE_OPERAND (t, 0)),
20395				templated_operator_saved_lookups (t),
20396				complain|decltype_flag));
20397
20398    case FIX_TRUNC_EXPR:
20399      /* convert_like should have created an IMPLICIT_CONV_EXPR.  */
20400      gcc_unreachable ();
20401
20402    case ADDR_EXPR:
20403      op1 = TREE_OPERAND (t, 0);
20404      if (TREE_CODE (op1) == LABEL_DECL)
20405	RETURN (finish_label_address_expr (DECL_NAME (op1),
20406					  EXPR_LOCATION (op1)));
20407      if (TREE_CODE (op1) == SCOPE_REF)
20408	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20409				   /*done=*/true, /*address_p=*/true);
20410      else
20411	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20412						  in_decl);
20413      RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20414				templated_operator_saved_lookups (t),
20415				complain|decltype_flag));
20416
20417    case PLUS_EXPR:
20418    case MINUS_EXPR:
20419    case MULT_EXPR:
20420    case TRUNC_DIV_EXPR:
20421    case CEIL_DIV_EXPR:
20422    case FLOOR_DIV_EXPR:
20423    case ROUND_DIV_EXPR:
20424    case EXACT_DIV_EXPR:
20425    case BIT_AND_EXPR:
20426    case BIT_IOR_EXPR:
20427    case BIT_XOR_EXPR:
20428    case TRUNC_MOD_EXPR:
20429    case FLOOR_MOD_EXPR:
20430    case TRUTH_ANDIF_EXPR:
20431    case TRUTH_ORIF_EXPR:
20432    case TRUTH_AND_EXPR:
20433    case TRUTH_OR_EXPR:
20434    case RSHIFT_EXPR:
20435    case LSHIFT_EXPR:
20436    case EQ_EXPR:
20437    case NE_EXPR:
20438    case MAX_EXPR:
20439    case MIN_EXPR:
20440    case LE_EXPR:
20441    case GE_EXPR:
20442    case LT_EXPR:
20443    case GT_EXPR:
20444    case SPACESHIP_EXPR:
20445    case MEMBER_REF:
20446    case DOTSTAR_EXPR:
20447      {
20448	/* If either OP0 or OP1 was value- or type-dependent, suppress
20449	   warnings that depend on the range of the types involved.  */
20450	tree op0 = TREE_OPERAND (t, 0);
20451	tree op1 = TREE_OPERAND (t, 1);
20452	auto dep_p = [](tree t) {
20453	  ++processing_template_decl;
20454	  bool r = (potential_constant_expression (t)
20455		    ? value_dependent_expression_p (t)
20456		    : type_dependent_expression_p (t));
20457	  --processing_template_decl;
20458	  return r;
20459	};
20460	const bool was_dep = dep_p (op0) || dep_p (op1);
20461	op0 = RECUR (op0);
20462	op1 = RECUR (op1);
20463
20464	warning_sentinel s1(warn_type_limits, was_dep);
20465	warning_sentinel s2(warn_div_by_zero, was_dep);
20466	warning_sentinel s3(warn_logical_op, was_dep);
20467	warning_sentinel s4(warn_tautological_compare, was_dep);
20468	warning_sentinel s5(warn_address, was_dep);
20469
20470	tree r = build_x_binary_op
20471	  (input_location, TREE_CODE (t),
20472	   op0,
20473	   (warning_suppressed_p (TREE_OPERAND (t, 0))
20474	    ? ERROR_MARK
20475	    : TREE_CODE (TREE_OPERAND (t, 0))),
20476	   op1,
20477	   (warning_suppressed_p (TREE_OPERAND (t, 1))
20478	    ? ERROR_MARK
20479	    : TREE_CODE (TREE_OPERAND (t, 1))),
20480	   templated_operator_saved_lookups (t),
20481	   /*overload=*/NULL,
20482	   complain|decltype_flag);
20483	if (EXPR_P (r))
20484	  copy_warning (r, t);
20485
20486	RETURN (r);
20487      }
20488
20489    case POINTER_PLUS_EXPR:
20490      {
20491	tree op0 = RECUR (TREE_OPERAND (t, 0));
20492	if (op0 == error_mark_node)
20493	  RETURN (error_mark_node);
20494	tree op1 = RECUR (TREE_OPERAND (t, 1));
20495	if (op1 == error_mark_node)
20496	  RETURN (error_mark_node);
20497	RETURN (fold_build_pointer_plus (op0, op1));
20498      }
20499
20500    case SCOPE_REF:
20501      RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20502				  /*address_p=*/false));
20503
20504    case BASELINK:
20505      RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20506			       args, complain, in_decl));
20507
20508    case ARRAY_REF:
20509      op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20510						args, complain, in_decl);
20511      if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20512	  && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20513	      == ovl_op_identifier (ARRAY_REF)))
20514	{
20515	  tree c = TREE_OPERAND (t, 1);
20516	  releasing_vec index_exp_list;
20517	  tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20518					   integral_constant_expression_p,
20519					   index_exp_list);
20520
20521	  tree r;
20522	  if (vec_safe_length (index_exp_list) == 1
20523	      && !PACK_EXPANSION_P (index_exp_list[0]))
20524	    r = grok_array_decl (EXPR_LOCATION (t), op1,
20525				 index_exp_list[0], NULL,
20526				 complain | decltype_flag);
20527	  else
20528	    r = grok_array_decl (EXPR_LOCATION (t), op1,
20529				 NULL_TREE, &index_exp_list,
20530				 complain | decltype_flag);
20531	  RETURN (r);
20532	}
20533      RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20534				 RECUR (TREE_OPERAND (t, 1)),
20535				 complain|decltype_flag));
20536
20537    case SIZEOF_EXPR:
20538      if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20539	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20540	RETURN (tsubst_copy (t, args, complain, in_decl));
20541      /* Fall through */
20542
20543    case ALIGNOF_EXPR:
20544      {
20545	tree r;
20546
20547	op1 = TREE_OPERAND (t, 0);
20548	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20549	  op1 = TREE_TYPE (op1);
20550	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20551			    && ALIGNOF_EXPR_STD_P (t));
20552        if (!args)
20553	  {
20554	    /* When there are no ARGS, we are trying to evaluate a
20555	       non-dependent expression from the parser.  Trying to do
20556	       the substitutions may not work.  */
20557	    if (!TYPE_P (op1))
20558	      op1 = TREE_TYPE (op1);
20559	  }
20560	else
20561	  {
20562	    ++cp_unevaluated_operand;
20563	    ++c_inhibit_evaluation_warnings;
20564	    if (TYPE_P (op1))
20565	      op1 = tsubst (op1, args, complain, in_decl);
20566	    else
20567	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20568					   /*function_p=*/false,
20569					   /*integral_constant_expression_p=*/
20570					   false);
20571	    --cp_unevaluated_operand;
20572	    --c_inhibit_evaluation_warnings;
20573	  }
20574        if (TYPE_P (op1))
20575	  r = cxx_sizeof_or_alignof_type (input_location,
20576					  op1, TREE_CODE (t), std_alignof,
20577					  complain & tf_error);
20578	else
20579	  r = cxx_sizeof_or_alignof_expr (input_location,
20580					  op1, TREE_CODE (t), std_alignof,
20581					  complain & tf_error);
20582	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20583	  {
20584	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20585	      {
20586		if (!processing_template_decl && TYPE_P (op1))
20587		  {
20588		    r = build_min (SIZEOF_EXPR, size_type_node,
20589				   build1 (NOP_EXPR, op1, error_mark_node));
20590		    SIZEOF_EXPR_TYPE_P (r) = 1;
20591		  }
20592		else
20593		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
20594		TREE_SIDE_EFFECTS (r) = 0;
20595		TREE_READONLY (r) = 1;
20596	      }
20597	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20598	  }
20599	RETURN (r);
20600      }
20601
20602    case AT_ENCODE_EXPR:
20603      {
20604	op1 = TREE_OPERAND (t, 0);
20605	++cp_unevaluated_operand;
20606	++c_inhibit_evaluation_warnings;
20607	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20608				     /*function_p=*/false,
20609				     /*integral_constant_expression_p=*/false);
20610	--cp_unevaluated_operand;
20611	--c_inhibit_evaluation_warnings;
20612	RETURN (objc_build_encode_expr (op1));
20613      }
20614
20615    case NOEXCEPT_EXPR:
20616      op1 = TREE_OPERAND (t, 0);
20617      ++cp_unevaluated_operand;
20618      ++c_inhibit_evaluation_warnings;
20619      ++cp_noexcept_operand;
20620      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20621				   /*function_p=*/false,
20622				   /*integral_constant_expression_p=*/false);
20623      --cp_unevaluated_operand;
20624      --c_inhibit_evaluation_warnings;
20625      --cp_noexcept_operand;
20626      RETURN (finish_noexcept_expr (op1, complain));
20627
20628    case MODOP_EXPR:
20629      {
20630	warning_sentinel s(warn_div_by_zero);
20631	tree lhs = RECUR (TREE_OPERAND (t, 0));
20632	tree rhs = RECUR (TREE_OPERAND (t, 2));
20633
20634	tree r = build_x_modify_expr
20635	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20636	   templated_operator_saved_lookups (t),
20637	   complain|decltype_flag);
20638	/* TREE_NO_WARNING must be set if either the expression was
20639	   parenthesized or it uses an operator such as >>= rather
20640	   than plain assignment.  In the former case, it was already
20641	   set and must be copied.  In the latter case,
20642	   build_x_modify_expr sets it and it must not be reset
20643	   here.  */
20644	if (warning_suppressed_p (t, OPT_Wparentheses))
20645	  suppress_warning (r, OPT_Wparentheses);
20646
20647	RETURN (r);
20648      }
20649
20650    case ARROW_EXPR:
20651      op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20652						args, complain, in_decl);
20653      /* Remember that there was a reference to this entity.  */
20654      if (DECL_P (op1)
20655	  && !mark_used (op1, complain) && !(complain & tf_error))
20656	RETURN (error_mark_node);
20657      RETURN (build_x_arrow (input_location, op1, complain));
20658
20659    case NEW_EXPR:
20660      {
20661	tree placement = RECUR (TREE_OPERAND (t, 0));
20662	tree init = RECUR (TREE_OPERAND (t, 3));
20663	vec<tree, va_gc> *placement_vec;
20664	vec<tree, va_gc> *init_vec;
20665	tree ret;
20666	location_t loc = EXPR_LOCATION (t);
20667
20668	if (placement == NULL_TREE)
20669	  placement_vec = NULL;
20670	else if (placement == error_mark_node)
20671	  RETURN (error_mark_node);
20672	else
20673	  {
20674	    placement_vec = make_tree_vector ();
20675	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20676	      vec_safe_push (placement_vec, TREE_VALUE (placement));
20677	  }
20678
20679	/* If there was an initializer in the original tree, but it
20680	   instantiated to an empty list, then we should pass a
20681	   non-NULL empty vector to tell build_new that it was an
20682	   empty initializer() rather than no initializer.  This can
20683	   only happen when the initializer is a pack expansion whose
20684	   parameter packs are of length zero.  */
20685	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20686	  init_vec = NULL;
20687	else if (init == error_mark_node)
20688	  RETURN (error_mark_node);
20689	else
20690	  {
20691	    init_vec = make_tree_vector ();
20692	    if (init == void_node)
20693	      gcc_assert (init_vec != NULL);
20694	    else
20695	      {
20696		for (; init != NULL_TREE; init = TREE_CHAIN (init))
20697		  vec_safe_push (init_vec, TREE_VALUE (init));
20698	      }
20699	  }
20700
20701	/* Avoid passing an enclosing decl to valid_array_size_p.  */
20702	in_decl = NULL_TREE;
20703
20704	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20705	tree op2 = RECUR (TREE_OPERAND (t, 2));
20706	ret = build_new (loc, &placement_vec, op1, op2,
20707			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20708			 complain);
20709
20710	if (placement_vec != NULL)
20711	  release_tree_vector (placement_vec);
20712	if (init_vec != NULL)
20713	  release_tree_vector (init_vec);
20714
20715	RETURN (ret);
20716      }
20717
20718    case DELETE_EXPR:
20719      {
20720	tree op0 = RECUR (TREE_OPERAND (t, 0));
20721	tree op1 = RECUR (TREE_OPERAND (t, 1));
20722	RETURN (delete_sanity (input_location, op0, op1,
20723			       DELETE_EXPR_USE_VEC (t),
20724			       DELETE_EXPR_USE_GLOBAL (t),
20725			       complain));
20726      }
20727
20728    case COMPOUND_EXPR:
20729      {
20730	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20731					  complain & ~tf_decltype, in_decl,
20732					  /*function_p=*/false,
20733					  integral_constant_expression_p);
20734	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20735				       op0,
20736				       RECUR (TREE_OPERAND (t, 1)),
20737				       templated_operator_saved_lookups (t),
20738				       complain|decltype_flag));
20739      }
20740
20741    case CALL_EXPR:
20742      {
20743	tree function;
20744	unsigned int nargs;
20745	bool qualified_p;
20746	bool koenig_p;
20747	tree ret;
20748
20749	function = CALL_EXPR_FN (t);
20750	/* Internal function with no arguments.  */
20751	if (function == NULL_TREE && call_expr_nargs (t) == 0)
20752	  RETURN (t);
20753
20754	/* When we parsed the expression, we determined whether or
20755	   not Koenig lookup should be performed.  */
20756	koenig_p = KOENIG_LOOKUP_P (t);
20757	if (function == NULL_TREE)
20758	  {
20759	    koenig_p = false;
20760	    qualified_p = false;
20761	  }
20762	else if (TREE_CODE (function) == SCOPE_REF)
20763	  {
20764	    qualified_p = true;
20765	    function = tsubst_qualified_id (function, args, complain, in_decl,
20766					    /*done=*/false,
20767					    /*address_p=*/false);
20768	  }
20769	else if (koenig_p
20770		 && (identifier_p (function)
20771		     || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20772			 && identifier_p (TREE_OPERAND (function, 0)))))
20773	  {
20774	    /* Do nothing; calling tsubst_copy_and_build on an identifier
20775	       would incorrectly perform unqualified lookup again.
20776
20777	       Note that we can also have an IDENTIFIER_NODE if the earlier
20778	       unqualified lookup found a member function; in that case
20779	       koenig_p will be false and we do want to do the lookup
20780	       again to find the instantiated member function.
20781
20782	       FIXME but doing that causes c++/15272, so we need to stop
20783	       using IDENTIFIER_NODE in that situation.  */
20784	    qualified_p = false;
20785
20786	    if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20787	      /* Use tsubst_copy to substitute through the template arguments
20788		 of the template-id without performing unqualified lookup of
20789		 the template name.  */
20790	      function = tsubst_copy (function, args, complain, in_decl);
20791	  }
20792	else
20793	  {
20794	    if (TREE_CODE (function) == COMPONENT_REF)
20795	      {
20796		tree op = TREE_OPERAND (function, 1);
20797
20798		qualified_p = (TREE_CODE (op) == SCOPE_REF
20799			       || (BASELINK_P (op)
20800				   && BASELINK_QUALIFIED_P (op)));
20801	      }
20802	    else
20803	      qualified_p = false;
20804
20805	    if (TREE_CODE (function) == ADDR_EXPR
20806		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20807	      /* Avoid error about taking the address of a constructor.  */
20808	      function = TREE_OPERAND (function, 0);
20809
20810	    tsubst_flags_t subcomplain = complain;
20811	    if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20812	      /* When KOENIG_P, we don't want to mark_used the callee before
20813		 augmenting the overload set via ADL, so during this initial
20814		 substitution we disable mark_used by setting tf_conv (68942).  */
20815	      subcomplain |= tf_conv;
20816	    function = tsubst_copy_and_build (function, args, subcomplain,
20817					      in_decl,
20818					      !qualified_p,
20819					      integral_constant_expression_p);
20820
20821	    if (BASELINK_P (function))
20822	      qualified_p = true;
20823	  }
20824
20825	nargs = call_expr_nargs (t);
20826	releasing_vec call_args;
20827	tsubst_copy_and_build_call_args (t, args, complain, in_decl,
20828					 integral_constant_expression_p,
20829					 call_args);
20830
20831	/* Stripped-down processing for a call in a thunk.  Specifically, in
20832	   the thunk template for a generic lambda.  */
20833	if (call_from_lambda_thunk_p (t))
20834	  {
20835	    /* Now that we've expanded any packs, the number of call args
20836	       might be different.  */
20837	    unsigned int cargs = call_args->length ();
20838	    tree thisarg = NULL_TREE;
20839	    if (TREE_CODE (function) == COMPONENT_REF)
20840	      {
20841		thisarg = TREE_OPERAND (function, 0);
20842		if (TREE_CODE (thisarg) == INDIRECT_REF)
20843		  thisarg = TREE_OPERAND (thisarg, 0);
20844		function = TREE_OPERAND (function, 1);
20845		if (TREE_CODE (function) == BASELINK)
20846		  function = BASELINK_FUNCTIONS (function);
20847	      }
20848	    /* We aren't going to do normal overload resolution, so force the
20849	       template-id to resolve.  */
20850	    function = resolve_nondeduced_context (function, complain);
20851	    for (unsigned i = 0; i < cargs; ++i)
20852	      {
20853		/* In a thunk, pass through args directly, without any
20854		   conversions.  */
20855		tree arg = (*call_args)[i];
20856		while (TREE_CODE (arg) != PARM_DECL)
20857		  arg = TREE_OPERAND (arg, 0);
20858		(*call_args)[i] = arg;
20859	      }
20860	    if (thisarg)
20861	      {
20862		/* If there are no other args, just push 'this'.  */
20863		if (cargs == 0)
20864		  vec_safe_push (call_args, thisarg);
20865		else
20866		  {
20867		    /* Otherwise, shift the other args over to make room.  */
20868		    tree last = (*call_args)[cargs - 1];
20869		    vec_safe_push (call_args, last);
20870		    for (int i = cargs - 1; i > 0; --i)
20871		      (*call_args)[i] = (*call_args)[i - 1];
20872		    (*call_args)[0] = thisarg;
20873		  }
20874	      }
20875	    ret = build_call_a (function, call_args->length (),
20876				call_args->address ());
20877	    /* The thunk location is not interesting.  */
20878	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20879	    CALL_FROM_THUNK_P (ret) = true;
20880	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
20881	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20882
20883	    RETURN (ret);
20884	  }
20885
20886	/* We do not perform argument-dependent lookup if normal
20887	   lookup finds a non-function, in accordance with the
20888	   resolution of DR 218.  */
20889	if (koenig_p
20890	    && ((is_overloaded_fn (function)
20891		 /* If lookup found a member function, the Koenig lookup is
20892		    not appropriate, even if an unqualified-name was used
20893		    to denote the function.  */
20894		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20895		|| identifier_p (function)
20896		/* C++20 P0846: Lookup found nothing.  */
20897		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20898		    && identifier_p (TREE_OPERAND (function, 0))))
20899	    /* Only do this when substitution turns a dependent call
20900	       into a non-dependent call.  */
20901	    && type_dependent_expression_p_push (t)
20902	    && !any_type_dependent_arguments_p (call_args))
20903	  function = perform_koenig_lookup (function, call_args, tf_none);
20904
20905	if (function != NULL_TREE
20906	    && (identifier_p (function)
20907		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20908		    && identifier_p (TREE_OPERAND (function, 0))
20909		    && !any_dependent_template_arguments_p (TREE_OPERAND
20910							    (function, 1))))
20911	    && !any_type_dependent_arguments_p (call_args))
20912	  {
20913	    bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
20914	    if (template_id_p)
20915	      function = TREE_OPERAND (function, 0);
20916	    if (koenig_p && (complain & tf_warning_or_error))
20917	      {
20918		/* For backwards compatibility and good diagnostics, try
20919		   the unqualified lookup again if we aren't in SFINAE
20920		   context.  */
20921		tree unq = (tsubst_copy_and_build
20922			    (function, args, complain, in_decl, true,
20923			     integral_constant_expression_p));
20924		if (unq == error_mark_node)
20925		  RETURN (error_mark_node);
20926
20927		if (unq != function)
20928		  {
20929		    char const *const msg
20930		      = G_("%qD was not declared in this scope, "
20931			   "and no declarations were found by "
20932			   "argument-dependent lookup at the point "
20933			   "of instantiation");
20934
20935		    bool in_lambda = (current_class_type
20936				      && LAMBDA_TYPE_P (current_class_type));
20937		    /* In a lambda fn, we have to be careful to not
20938		       introduce new this captures.  Legacy code can't
20939		       be using lambdas anyway, so it's ok to be
20940		       stricter.  Be strict with C++20 template-id ADL too.  */
20941		    bool strict = in_lambda || template_id_p;
20942		    bool diag = true;
20943		    if (strict)
20944		      error_at (cp_expr_loc_or_input_loc (t),
20945				msg, function);
20946		    else
20947		      diag = permerror (cp_expr_loc_or_input_loc (t),
20948					msg, function);
20949		    if (diag)
20950		      {
20951			tree fn = unq;
20952
20953			if (INDIRECT_REF_P (fn))
20954			  fn = TREE_OPERAND (fn, 0);
20955			if (is_overloaded_fn (fn))
20956			  fn = get_first_fn (fn);
20957
20958			if (!DECL_P (fn))
20959			  /* Can't say anything more.  */;
20960			else if (DECL_CLASS_SCOPE_P (fn))
20961			  {
20962			    location_t loc = cp_expr_loc_or_input_loc (t);
20963			    inform (loc,
20964				    "declarations in dependent base %qT are "
20965				    "not found by unqualified lookup",
20966				    DECL_CLASS_CONTEXT (fn));
20967			    if (current_class_ptr)
20968			      inform (loc,
20969				      "use %<this->%D%> instead", function);
20970			    else
20971			      inform (loc,
20972				      "use %<%T::%D%> instead",
20973				      current_class_name, function);
20974			  }
20975			else
20976			  inform (DECL_SOURCE_LOCATION (fn),
20977				  "%qD declared here, later in the "
20978				  "translation unit", fn);
20979			if (strict)
20980			  RETURN (error_mark_node);
20981		      }
20982
20983		    function = unq;
20984		  }
20985	      }
20986	    if (identifier_p (function))
20987	      {
20988		if (complain & tf_error)
20989		  unqualified_name_lookup_error (function);
20990		RETURN (error_mark_node);
20991	      }
20992	  }
20993
20994	/* Remember that there was a reference to this entity.  */
20995	if (function != NULL_TREE)
20996	  {
20997	    tree inner = function;
20998	    if (TREE_CODE (inner) == ADDR_EXPR
20999		&& TREE_CODE (TREE_OPERAND (inner, 0)) == FUNCTION_DECL)
21000	      /* We should already have called mark_used when taking the
21001		 address of this function, but do so again anyway to make
21002		 sure it's odr-used: at worst this is a no-op, but if we
21003		 obtained this FUNCTION_DECL as part of ahead-of-time overload
21004		 resolution then that call to mark_used wouldn't have marked it
21005		 odr-used yet (53164).  */
21006	      inner = TREE_OPERAND (inner, 0);
21007	    if (DECL_P (inner)
21008		&& !mark_used (inner, complain) && !(complain & tf_error))
21009	      RETURN (error_mark_node);
21010	  }
21011
21012	if (!maybe_fold_fn_template_args (function, complain))
21013	  return error_mark_node;
21014
21015	/* Put back tf_decltype for the actual call.  */
21016	complain |= decltype_flag;
21017
21018	if (function == NULL_TREE)
21019	  switch (CALL_EXPR_IFN (t))
21020	    {
21021	    case IFN_LAUNDER:
21022	      gcc_assert (nargs == 1);
21023	      if (vec_safe_length (call_args) != 1)
21024		{
21025		  error_at (cp_expr_loc_or_input_loc (t),
21026			    "wrong number of arguments to "
21027			    "%<__builtin_launder%>");
21028		  ret = error_mark_node;
21029		}
21030	      else
21031		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21032					      (*call_args)[0], complain);
21033	      break;
21034
21035	    case IFN_VEC_CONVERT:
21036	      gcc_assert (nargs == 1);
21037	      if (vec_safe_length (call_args) != 1)
21038		{
21039		  error_at (cp_expr_loc_or_input_loc (t),
21040			    "wrong number of arguments to "
21041			    "%<__builtin_convertvector%>");
21042		  ret = error_mark_node;
21043		  break;
21044		}
21045	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
21046					  tsubst (TREE_TYPE (t), args,
21047						  complain, in_decl),
21048					  complain);
21049	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21050		RETURN (ret);
21051	      break;
21052
21053	    case IFN_SHUFFLEVECTOR:
21054	      {
21055		ret = build_x_shufflevector (input_location, call_args,
21056					     complain);
21057		if (ret != error_mark_node)
21058		  RETURN (ret);
21059		break;
21060	      }
21061
21062	    default:
21063	      /* Unsupported internal function with arguments.  */
21064	      gcc_unreachable ();
21065	    }
21066	else if (TREE_CODE (function) == OFFSET_REF
21067		 || TREE_CODE (function) == DOTSTAR_EXPR
21068		 || TREE_CODE (function) == MEMBER_REF)
21069	  ret = build_offset_ref_call_from_tree (function, &call_args,
21070						 complain);
21071	else if (TREE_CODE (function) == COMPONENT_REF)
21072	  {
21073	    tree instance = TREE_OPERAND (function, 0);
21074	    tree fn = TREE_OPERAND (function, 1);
21075
21076	    if (processing_template_decl
21077		&& (type_dependent_expression_p (instance)
21078		    || (!BASELINK_P (fn)
21079			&& TREE_CODE (fn) != FIELD_DECL)
21080		    || type_dependent_expression_p (fn)
21081		    || any_type_dependent_arguments_p (call_args)))
21082	      ret = build_min_nt_call_vec (function, call_args);
21083	    else if (!BASELINK_P (fn))
21084	      ret = finish_call_expr (function, &call_args,
21085				       /*disallow_virtual=*/false,
21086				       /*koenig_p=*/false,
21087				       complain);
21088	    else
21089	      ret = (build_new_method_call
21090		      (instance, fn,
21091		       &call_args, NULL_TREE,
21092		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21093		       /*fn_p=*/NULL,
21094		       complain));
21095	  }
21096	else if (concept_check_p (function))
21097	  {
21098	    /* FUNCTION is a template-id referring to a concept definition.  */
21099	    tree id = unpack_concept_check (function);
21100	    tree tmpl = TREE_OPERAND (id, 0);
21101	    tree args = TREE_OPERAND (id, 1);
21102
21103	    /* Calls to standard and variable concepts should have been
21104	       previously diagnosed.  */
21105	    gcc_assert (function_concept_p (tmpl));
21106
21107	    /* Ensure the result is wrapped as a call expression.  */
21108	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
21109	  }
21110	else
21111	  ret = finish_call_expr (function, &call_args,
21112				  /*disallow_virtual=*/qualified_p,
21113				  koenig_p,
21114				  complain);
21115
21116	if (ret != error_mark_node)
21117	  {
21118	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21119	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
21120	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
21121	    if (op || ord || rev)
21122	      if (tree call = extract_call_expr (ret))
21123		{
21124		  CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21125		  CALL_EXPR_ORDERED_ARGS (call) = ord;
21126		  CALL_EXPR_REVERSE_ARGS (call) = rev;
21127		}
21128	  }
21129
21130	RETURN (ret);
21131      }
21132
21133    case COND_EXPR:
21134      {
21135	tree cond = RECUR (TREE_OPERAND (t, 0));
21136	cond = mark_rvalue_use (cond);
21137	tree folded_cond = fold_non_dependent_expr (cond, complain);
21138	tree exp1, exp2;
21139
21140	if (TREE_CODE (folded_cond) == INTEGER_CST)
21141	  {
21142	    if (integer_zerop (folded_cond))
21143	      {
21144		++c_inhibit_evaluation_warnings;
21145		exp1 = RECUR (TREE_OPERAND (t, 1));
21146		--c_inhibit_evaluation_warnings;
21147		exp2 = RECUR (TREE_OPERAND (t, 2));
21148	      }
21149	    else
21150	      {
21151		exp1 = RECUR (TREE_OPERAND (t, 1));
21152		++c_inhibit_evaluation_warnings;
21153		exp2 = RECUR (TREE_OPERAND (t, 2));
21154		--c_inhibit_evaluation_warnings;
21155	      }
21156	    cond = folded_cond;
21157	  }
21158	else
21159	  {
21160	    exp1 = RECUR (TREE_OPERAND (t, 1));
21161	    exp2 = RECUR (TREE_OPERAND (t, 2));
21162	  }
21163
21164	warning_sentinel s(warn_duplicated_branches);
21165	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21166					 cond, exp1, exp2, complain));
21167      }
21168
21169    case PSEUDO_DTOR_EXPR:
21170      {
21171	tree op0 = RECUR (TREE_OPERAND (t, 0));
21172	tree op1 = RECUR (TREE_OPERAND (t, 1));
21173	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21174	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21175					       input_location));
21176      }
21177
21178    case TREE_LIST:
21179      RETURN (tsubst_tree_list (t, args, complain, in_decl));
21180
21181    case COMPONENT_REF:
21182      {
21183	tree object;
21184	tree object_type;
21185	tree member;
21186	tree r;
21187
21188	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21189						     args, complain, in_decl);
21190	/* Remember that there was a reference to this entity.  */
21191	if (DECL_P (object)
21192	    && !mark_used (object, complain) && !(complain & tf_error))
21193	  RETURN (error_mark_node);
21194	object_type = TREE_TYPE (object);
21195
21196	member = TREE_OPERAND (t, 1);
21197	if (BASELINK_P (member))
21198	  member = tsubst_baselink (member,
21199				    non_reference (TREE_TYPE (object)),
21200				    args, complain, in_decl);
21201	else
21202	  member = tsubst_copy (member, args, complain, in_decl);
21203	if (member == error_mark_node)
21204	  RETURN (error_mark_node);
21205
21206	if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21207	    && TREE_CODE (member) == FIELD_DECL)
21208	  {
21209	    r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21210	    RETURN (r);
21211	  }
21212	else if (TREE_CODE (member) == FIELD_DECL)
21213	  {
21214	    r = finish_non_static_data_member (member, object, NULL_TREE);
21215	    if (TREE_CODE (r) == COMPONENT_REF)
21216	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21217	    RETURN (r);
21218	  }
21219	else if (type_dependent_expression_p (object))
21220	  /* We can't do much here.  */;
21221	else if (!CLASS_TYPE_P (object_type))
21222	  {
21223	    if (scalarish_type_p (object_type))
21224	      {
21225		tree s = NULL_TREE;
21226		tree dtor = member;
21227
21228		if (TREE_CODE (dtor) == SCOPE_REF)
21229		  {
21230		    s = TREE_OPERAND (dtor, 0);
21231		    dtor = TREE_OPERAND (dtor, 1);
21232		  }
21233		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21234		  {
21235		    dtor = TREE_OPERAND (dtor, 0);
21236		    if (TYPE_P (dtor))
21237		      RETURN (finish_pseudo_destructor_expr
21238			      (object, s, dtor, input_location));
21239		  }
21240	      }
21241	  }
21242	else if (TREE_CODE (member) == SCOPE_REF
21243		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21244	  {
21245	    /* Lookup the template functions now that we know what the
21246	       scope is.  */
21247	    tree scope = TREE_OPERAND (member, 0);
21248	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21249	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21250	    member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21251					    /*complain=*/false);
21252	    if (BASELINK_P (member))
21253	      {
21254		BASELINK_FUNCTIONS (member)
21255		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21256			      args);
21257		member = (adjust_result_of_qualified_name_lookup
21258			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
21259			   object_type));
21260	      }
21261	    else
21262	      {
21263		qualified_name_lookup_error (scope, tmpl, member,
21264					     input_location);
21265		RETURN (error_mark_node);
21266	      }
21267	  }
21268	else if (TREE_CODE (member) == SCOPE_REF
21269		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21270		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21271	  {
21272	    if (complain & tf_error)
21273	      {
21274		if (TYPE_P (TREE_OPERAND (member, 0)))
21275		  error ("%qT is not a class or namespace",
21276			 TREE_OPERAND (member, 0));
21277		else
21278		  error ("%qD is not a class or namespace",
21279			 TREE_OPERAND (member, 0));
21280	      }
21281	    RETURN (error_mark_node);
21282	  }
21283
21284	r = finish_class_member_access_expr (object, member,
21285					     /*template_p=*/false,
21286					     complain);
21287	if (TREE_CODE (r) == COMPONENT_REF)
21288	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21289	RETURN (r);
21290      }
21291
21292    case THROW_EXPR:
21293      RETURN (build_throw
21294       (input_location, RECUR (TREE_OPERAND (t, 0))));
21295
21296    case CONSTRUCTOR:
21297      {
21298	vec<constructor_elt, va_gc> *n;
21299	constructor_elt *ce;
21300	unsigned HOST_WIDE_INT idx;
21301	bool process_index_p;
21302        int newlen;
21303        bool need_copy_p = false;
21304	tree r;
21305
21306	tsubst_flags_t tcomplain = complain;
21307	if (COMPOUND_LITERAL_P (t))
21308	  tcomplain |= tf_tst_ok;
21309	tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21310	if (type == error_mark_node)
21311	  RETURN (error_mark_node);
21312
21313	/* We do not want to process the index of aggregate
21314	   initializers as they are identifier nodes which will be
21315	   looked up by digest_init.  */
21316	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21317
21318	if (null_member_pointer_value_p (t))
21319	  {
21320	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
21321	    RETURN (t);
21322	  }
21323
21324	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21325        newlen = vec_safe_length (n);
21326	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21327	  {
21328	    if (ce->index && process_index_p
21329		/* An identifier index is looked up in the type
21330		   being initialized, not the current scope.  */
21331		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
21332	      ce->index = RECUR (ce->index);
21333
21334            if (PACK_EXPANSION_P (ce->value))
21335              {
21336                /* Substitute into the pack expansion.  */
21337                ce->value = tsubst_pack_expansion (ce->value, args, complain,
21338                                                  in_decl);
21339
21340		if (ce->value == error_mark_node
21341		    || PACK_EXPANSION_P (ce->value))
21342		  ;
21343		else if (TREE_VEC_LENGTH (ce->value) == 1)
21344                  /* Just move the argument into place.  */
21345                  ce->value = TREE_VEC_ELT (ce->value, 0);
21346                else
21347                  {
21348                    /* Update the length of the final CONSTRUCTOR
21349                       arguments vector, and note that we will need to
21350                       copy.*/
21351                    newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21352                    need_copy_p = true;
21353                  }
21354              }
21355            else
21356              ce->value = RECUR (ce->value);
21357	  }
21358
21359        if (need_copy_p)
21360          {
21361            vec<constructor_elt, va_gc> *old_n = n;
21362
21363            vec_alloc (n, newlen);
21364            FOR_EACH_VEC_ELT (*old_n, idx, ce)
21365              {
21366                if (TREE_CODE (ce->value) == TREE_VEC)
21367                  {
21368                    int i, len = TREE_VEC_LENGTH (ce->value);
21369                    for (i = 0; i < len; ++i)
21370                      CONSTRUCTOR_APPEND_ELT (n, 0,
21371                                              TREE_VEC_ELT (ce->value, i));
21372                  }
21373                else
21374                  CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21375              }
21376          }
21377
21378	r = build_constructor (init_list_type_node, n);
21379	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21380	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21381	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21382
21383	if (TREE_HAS_CONSTRUCTOR (t))
21384	  {
21385	    fcl_t cl = fcl_functional;
21386	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21387	      cl = fcl_c99;
21388	    RETURN (finish_compound_literal (type, r, complain, cl));
21389	  }
21390
21391	TREE_TYPE (r) = type;
21392	RETURN (r);
21393      }
21394
21395    case TYPEID_EXPR:
21396      {
21397	tree operand_0 = TREE_OPERAND (t, 0);
21398	if (TYPE_P (operand_0))
21399	  {
21400	    operand_0 = tsubst (operand_0, args, complain, in_decl);
21401	    RETURN (get_typeid (operand_0, complain));
21402	  }
21403	else
21404	  {
21405	    operand_0 = RECUR (operand_0);
21406	    RETURN (build_typeid (operand_0, complain));
21407	  }
21408      }
21409
21410    case VAR_DECL:
21411      if (!args)
21412	RETURN (t);
21413      /* Fall through */
21414
21415    case PARM_DECL:
21416      {
21417	tree r = tsubst_copy (t, args, complain, in_decl);
21418	/* ??? We're doing a subset of finish_id_expression here.  */
21419	if (tree wrap = maybe_get_tls_wrapper_call (r))
21420	  /* Replace an evaluated use of the thread_local variable with
21421	     a call to its wrapper.  */
21422	  r = wrap;
21423	else if (outer_automatic_var_p (r))
21424	  r = process_outer_var_ref (r, complain);
21425
21426	if (!TYPE_REF_P (TREE_TYPE (t)))
21427	  /* If the original type was a reference, we'll be wrapped in
21428	     the appropriate INDIRECT_REF.  */
21429	  r = convert_from_reference (r);
21430	RETURN (r);
21431      }
21432
21433    case VA_ARG_EXPR:
21434      {
21435	tree op0 = RECUR (TREE_OPERAND (t, 0));
21436	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21437	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21438      }
21439
21440    case OFFSETOF_EXPR:
21441      {
21442	tree object_ptr
21443	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
21444				   in_decl, /*function_p=*/false,
21445				   /*integral_constant_expression_p=*/false);
21446	RETURN (finish_offsetof (object_ptr,
21447				 RECUR (TREE_OPERAND (t, 0)),
21448				 EXPR_LOCATION (t)));
21449      }
21450
21451    case ADDRESSOF_EXPR:
21452      RETURN (cp_build_addressof (EXPR_LOCATION (t),
21453				  RECUR (TREE_OPERAND (t, 0)), complain));
21454
21455    case TRAIT_EXPR:
21456      {
21457	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
21458			     complain, in_decl);
21459	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21460			     complain, in_decl);
21461	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21462				   TRAIT_EXPR_KIND (t), type1, type2));
21463      }
21464
21465    case STMT_EXPR:
21466      {
21467	tree old_stmt_expr = cur_stmt_expr;
21468	tree stmt_expr = begin_stmt_expr ();
21469
21470	cur_stmt_expr = stmt_expr;
21471	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
21472		     integral_constant_expression_p);
21473	stmt_expr = finish_stmt_expr (stmt_expr, false);
21474	cur_stmt_expr = old_stmt_expr;
21475
21476	/* If the resulting list of expression statement is empty,
21477	   fold it further into void_node.  */
21478	if (empty_expr_stmt_p (stmt_expr))
21479	  stmt_expr = void_node;
21480
21481	RETURN (stmt_expr);
21482      }
21483
21484    case LAMBDA_EXPR:
21485      {
21486	if (complain & tf_partial)
21487	  {
21488	    /* We don't have a full set of template arguments yet; don't touch
21489	       the lambda at all.  */
21490	    gcc_assert (processing_template_decl);
21491	    return t;
21492	  }
21493	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21494
21495	RETURN (build_lambda_object (r));
21496      }
21497
21498    case TRANSACTION_EXPR:
21499      RETURN (tsubst_expr(t, args, complain, in_decl,
21500	     integral_constant_expression_p));
21501
21502    case PAREN_EXPR:
21503      if (REF_PARENTHESIZED_P (t))
21504	RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21505      else
21506	/* Recreate the PAREN_EXPR from __builtin_assoc_barrier.  */
21507	{
21508	  tree op0 = RECUR (TREE_OPERAND (t, 0));
21509	  RETURN (build1_loc (input_location, PAREN_EXPR,
21510			      TREE_TYPE (op0), op0));
21511	}
21512
21513    case VEC_PERM_EXPR:
21514      {
21515	tree op0 = RECUR (TREE_OPERAND (t, 0));
21516	tree op1 = RECUR (TREE_OPERAND (t, 1));
21517	tree op2 = RECUR (TREE_OPERAND (t, 2));
21518	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21519				       complain));
21520      }
21521
21522    case REQUIRES_EXPR:
21523      {
21524	tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21525	RETURN (r);
21526      }
21527
21528    case RANGE_EXPR:
21529      /* No need to substitute further, a RANGE_EXPR will always be built
21530	 with constant operands.  */
21531      RETURN (t);
21532
21533    case NON_LVALUE_EXPR:
21534    case VIEW_CONVERT_EXPR:
21535      if (location_wrapper_p (t))
21536	/* We need to do this here as well as in tsubst_copy so we get the
21537	   other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
21538	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
21539					  EXPR_LOCATION (t)));
21540      /* fallthrough.  */
21541
21542    default:
21543      /* Handle Objective-C++ constructs, if appropriate.  */
21544      {
21545	tree subst
21546	  = objcp_tsubst_copy_and_build (t, args, complain,
21547					 in_decl, /*function_p=*/false);
21548	if (subst)
21549	  RETURN (subst);
21550      }
21551      RETURN (tsubst_copy (t, args, complain, in_decl));
21552    }
21553
21554#undef RECUR
21555#undef RETURN
21556 out:
21557  input_location = save_loc;
21558  return retval;
21559}
21560
21561/* Verify that the instantiated ARGS are valid. For type arguments,
21562   make sure that the type's linkage is ok. For non-type arguments,
21563   make sure they are constants if they are integral or enumerations.
21564   Emit an error under control of COMPLAIN, and return TRUE on error.  */
21565
21566static bool
21567check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21568{
21569  if (dependent_template_arg_p (t))
21570    return false;
21571  if (ARGUMENT_PACK_P (t))
21572    {
21573      tree vec = ARGUMENT_PACK_ARGS (t);
21574      int len = TREE_VEC_LENGTH (vec);
21575      bool result = false;
21576      int i;
21577
21578      for (i = 0; i < len; ++i)
21579	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21580	  result = true;
21581      return result;
21582    }
21583  else if (TYPE_P (t))
21584    {
21585      /* [basic.link]: A name with no linkage (notably, the name
21586	 of a class or enumeration declared in a local scope)
21587	 shall not be used to declare an entity with linkage.
21588	 This implies that names with no linkage cannot be used as
21589	 template arguments
21590
21591	 DR 757 relaxes this restriction for C++0x.  */
21592      tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21593		 : no_linkage_check (t, /*relaxed_p=*/false));
21594
21595      if (nt)
21596	{
21597	  /* DR 488 makes use of a type with no linkage cause
21598	     type deduction to fail.  */
21599	  if (complain & tf_error)
21600	    {
21601	      if (TYPE_UNNAMED_P (nt))
21602		error ("%qT is/uses unnamed type", t);
21603	      else
21604		error ("template argument for %qD uses local type %qT",
21605		       tmpl, t);
21606	    }
21607	  return true;
21608	}
21609      /* In order to avoid all sorts of complications, we do not
21610	 allow variably-modified types as template arguments.  */
21611      else if (variably_modified_type_p (t, NULL_TREE))
21612	{
21613	  if (complain & tf_error)
21614	    error ("%qT is a variably modified type", t);
21615	  return true;
21616	}
21617    }
21618  /* Class template and alias template arguments should be OK.  */
21619  else if (DECL_TYPE_TEMPLATE_P (t))
21620    ;
21621  /* A non-type argument of integral or enumerated type must be a
21622     constant.  */
21623  else if (TREE_TYPE (t)
21624	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21625	   && !REFERENCE_REF_P (t)
21626	   && !TREE_CONSTANT (t))
21627    {
21628      if (complain & tf_error)
21629	error ("integral expression %qE is not constant", t);
21630      return true;
21631    }
21632  return false;
21633}
21634
21635static bool
21636check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21637{
21638  int ix, len = DECL_NTPARMS (tmpl);
21639  bool result = false;
21640
21641  for (ix = 0; ix != len; ix++)
21642    {
21643      if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21644	result = true;
21645    }
21646  if (result && (complain & tf_error))
21647    error ("  trying to instantiate %qD", tmpl);
21648  return result;
21649}
21650
21651/* We're out of SFINAE context now, so generate diagnostics for the access
21652   errors we saw earlier when instantiating D from TMPL and ARGS.  */
21653
21654static void
21655recheck_decl_substitution (tree d, tree tmpl, tree args)
21656{
21657  tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21658  tree type = TREE_TYPE (pattern);
21659  location_t loc = input_location;
21660
21661  push_access_scope (d);
21662  push_deferring_access_checks (dk_no_deferred);
21663  input_location = DECL_SOURCE_LOCATION (pattern);
21664  tsubst (type, args, tf_warning_or_error, d);
21665  input_location = loc;
21666  pop_deferring_access_checks ();
21667  pop_access_scope (d);
21668}
21669
21670/* Instantiate the indicated variable, function, or alias template TMPL with
21671   the template arguments in TARG_PTR.  */
21672
21673static tree
21674instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
21675{
21676  tree targ_ptr = orig_args;
21677  tree fndecl;
21678  tree gen_tmpl;
21679  tree spec;
21680  bool access_ok = true;
21681
21682  if (tmpl == error_mark_node)
21683    return error_mark_node;
21684
21685  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21686
21687  if (modules_p ())
21688    lazy_load_pendings (tmpl);
21689
21690  /* If this function is a clone, handle it specially.  */
21691  if (DECL_CLONED_FUNCTION_P (tmpl))
21692    {
21693      tree spec;
21694      tree clone;
21695
21696      /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21697	 DECL_CLONED_FUNCTION.  */
21698      spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21699				   targ_ptr, complain);
21700      if (spec == error_mark_node)
21701	return error_mark_node;
21702
21703      /* Look for the clone.  */
21704      FOR_EACH_CLONE (clone, spec)
21705	if (DECL_NAME (clone) == DECL_NAME (tmpl))
21706	  return clone;
21707      /* We should always have found the clone by now.  */
21708      gcc_unreachable ();
21709      return NULL_TREE;
21710    }
21711
21712  if (targ_ptr == error_mark_node)
21713    return error_mark_node;
21714
21715  /* Check to see if we already have this specialization.  */
21716  gen_tmpl = most_general_template (tmpl);
21717  if (TMPL_ARGS_DEPTH (targ_ptr)
21718      < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21719    /* targ_ptr only has the innermost template args, so add the outer ones
21720       from tmpl, which could be either a partial instantiation or gen_tmpl (in
21721       the case of a non-dependent call within a template definition).  */
21722    targ_ptr = (add_outermost_template_args
21723		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21724		 targ_ptr));
21725
21726  /* It would be nice to avoid hashing here and then again in tsubst_decl,
21727     but it doesn't seem to be on the hot path.  */
21728  spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
21729
21730  gcc_checking_assert (tmpl == gen_tmpl
21731		       || ((fndecl
21732			    = retrieve_specialization (tmpl, orig_args, 0))
21733			   == spec)
21734		       || fndecl == NULL_TREE);
21735
21736  if (spec != NULL_TREE)
21737    {
21738      if (FNDECL_HAS_ACCESS_ERRORS (spec))
21739	{
21740	  if (complain & tf_error)
21741	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21742	  return error_mark_node;
21743	}
21744      return spec;
21745    }
21746
21747  if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21748			       complain))
21749    return error_mark_node;
21750
21751  /* We are building a FUNCTION_DECL, during which the access of its
21752     parameters and return types have to be checked.  However this
21753     FUNCTION_DECL which is the desired context for access checking
21754     is not built yet.  We solve this chicken-and-egg problem by
21755     deferring all checks until we have the FUNCTION_DECL.  */
21756  push_deferring_access_checks (dk_deferred);
21757
21758  /* Instantiation of the function happens in the context of the function
21759     template, not the context of the overload resolution we're doing.  */
21760  push_to_top_level ();
21761  /* If there are dependent arguments, e.g. because we're doing partial
21762     ordering, make sure processing_template_decl stays set.  */
21763  if (uses_template_parms (targ_ptr))
21764    ++processing_template_decl;
21765  if (DECL_CLASS_SCOPE_P (gen_tmpl))
21766    {
21767      tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21768				   complain, gen_tmpl, true);
21769      push_nested_class (ctx);
21770    }
21771
21772  tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21773
21774  fndecl = NULL_TREE;
21775  if (VAR_P (pattern))
21776    {
21777      /* We need to determine if we're using a partial or explicit
21778	 specialization now, because the type of the variable could be
21779	 different.  */
21780      tree tid = lookup_template_variable (tmpl, targ_ptr);
21781      tree elt = most_specialized_partial_spec (tid, complain);
21782      if (elt == error_mark_node)
21783	pattern = error_mark_node;
21784      else if (elt)
21785	{
21786	  tree partial_tmpl = TREE_VALUE (elt);
21787	  tree partial_args = TREE_PURPOSE (elt);
21788	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21789	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
21790	}
21791    }
21792
21793  /* Substitute template parameters to obtain the specialization.  */
21794  if (fndecl == NULL_TREE)
21795    fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
21796  if (DECL_CLASS_SCOPE_P (gen_tmpl))
21797    pop_nested_class ();
21798  pop_from_top_level ();
21799
21800  if (fndecl == error_mark_node)
21801    {
21802      pop_deferring_access_checks ();
21803      return error_mark_node;
21804    }
21805
21806  /* The DECL_TI_TEMPLATE should always be the immediate parent
21807     template, not the most general template.  */
21808  DECL_TI_TEMPLATE (fndecl) = tmpl;
21809  DECL_TI_ARGS (fndecl) = targ_ptr;
21810
21811  set_instantiating_module (fndecl);
21812
21813  /* Now we know the specialization, compute access previously
21814     deferred.  Do no access control for inheriting constructors,
21815     as we already checked access for the inherited constructor.  */
21816  if (!(flag_new_inheriting_ctors
21817	&& DECL_INHERITED_CTOR (fndecl)))
21818    {
21819      push_access_scope (fndecl);
21820      if (!perform_deferred_access_checks (complain))
21821	access_ok = false;
21822      pop_access_scope (fndecl);
21823    }
21824  pop_deferring_access_checks ();
21825
21826  /* If we've just instantiated the main entry point for a function,
21827     instantiate all the alternate entry points as well.  We do this
21828     by cloning the instantiation of the main entry point, not by
21829     instantiating the template clones.  */
21830  if (tree chain = DECL_CHAIN (gen_tmpl))
21831    if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21832      clone_cdtor (fndecl, /*update_methods=*/false);
21833
21834  if (!access_ok)
21835    {
21836      if (!(complain & tf_error))
21837	{
21838	  /* Remember to reinstantiate when we're out of SFINAE so the user
21839	     can see the errors.  */
21840	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21841	}
21842      return error_mark_node;
21843    }
21844  return fndecl;
21845}
21846
21847/* Wrapper for instantiate_template_1.  */
21848
21849tree
21850instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21851{
21852  tree ret;
21853  timevar_push (TV_TEMPLATE_INST);
21854  ret = instantiate_template_1 (tmpl, orig_args,  complain);
21855  timevar_pop (TV_TEMPLATE_INST);
21856  return ret;
21857}
21858
21859/* Instantiate the alias template TMPL with ARGS.  Also push a template
21860   instantiation level, which instantiate_template doesn't do because
21861   functions and variables have sufficient context established by the
21862   callers.  */
21863
21864static tree
21865instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21866{
21867  if (tmpl == error_mark_node || args == error_mark_node)
21868    return error_mark_node;
21869
21870  /* See maybe_dependent_member_ref.  */
21871  if (complain & tf_dguide)
21872    {
21873      tree ctx = tsubst_aggr_type (DECL_CONTEXT (tmpl), args, complain,
21874				   tmpl, true);
21875      if (dependent_scope_p (ctx))
21876	{
21877	  tree name = DECL_NAME (tmpl);
21878	  tree fullname = build_nt (TEMPLATE_ID_EXPR, name,
21879				    INNERMOST_TEMPLATE_ARGS (args));
21880	  tree tname = build_typename_type (ctx, name, fullname, typename_type);
21881	  return TYPE_NAME (tname);
21882	}
21883    }
21884
21885  args =
21886    coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21887				     args, tmpl, complain,
21888				     /*require_all_args=*/true,
21889				     /*use_default_args=*/true);
21890
21891  /* FIXME check for satisfaction in check_instantiated_args.  */
21892  if (flag_concepts
21893      && !any_dependent_template_arguments_p (args)
21894      && !constraints_satisfied_p (tmpl, args))
21895    {
21896      if (complain & tf_error)
21897	{
21898	  auto_diagnostic_group d;
21899	  error ("template constraint failure for %qD", tmpl);
21900	  diagnose_constraints (input_location, tmpl, args);
21901	}
21902      return error_mark_node;
21903    }
21904
21905  if (!push_tinst_level (tmpl, args))
21906    return error_mark_node;
21907  tree r = instantiate_template (tmpl, args, complain);
21908  pop_tinst_level ();
21909
21910  if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21911    {
21912      /* An alias template specialization can be dependent
21913	 even if its underlying type is not.  */
21914      TYPE_DEPENDENT_P (d) = true;
21915      TYPE_DEPENDENT_P_VALID (d) = true;
21916      /* Sometimes a dependent alias spec is equivalent to its expansion,
21917	 sometimes not.  So always use structural_comptypes.  */
21918      SET_TYPE_STRUCTURAL_EQUALITY (d);
21919    }
21920
21921  return r;
21922}
21923
21924/* PARM is a template parameter pack for FN.  Returns true iff
21925   PARM is used in a deducible way in the argument list of FN.  */
21926
21927static bool
21928pack_deducible_p (tree parm, tree fn)
21929{
21930  tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21931  for (; t; t = TREE_CHAIN (t))
21932    {
21933      tree type = TREE_VALUE (t);
21934      tree packs;
21935      if (!PACK_EXPANSION_P (type))
21936	continue;
21937      for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21938	   packs; packs = TREE_CHAIN (packs))
21939	if (template_args_equal (TREE_VALUE (packs), parm))
21940	  {
21941	    /* The template parameter pack is used in a function parameter
21942	       pack.  If this is the end of the parameter list, the
21943	       template parameter pack is deducible.  */
21944	    if (TREE_CHAIN (t) == void_list_node)
21945	      return true;
21946	    else
21947	      /* Otherwise, not.  Well, it could be deduced from
21948		 a non-pack parameter, but doing so would end up with
21949		 a deduction mismatch, so don't bother.  */
21950	      return false;
21951	  }
21952    }
21953  /* The template parameter pack isn't used in any function parameter
21954     packs, but it might be used deeper, e.g. tuple<Args...>.  */
21955  return true;
21956}
21957
21958/* Subroutine of fn_type_unification: check non-dependent parms for
21959   convertibility.  */
21960
21961static int
21962check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21963				 tree fn, unification_kind_t strict, int flags,
21964				 struct conversion **convs, bool explain_p)
21965{
21966  /* Non-constructor methods need to leave a conversion for 'this', which
21967     isn't included in nargs here.  */
21968  unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21969		     && !DECL_CONSTRUCTOR_P (fn));
21970
21971  for (unsigned ia = 0;
21972       parms && parms != void_list_node && ia < nargs; )
21973    {
21974      tree parm = TREE_VALUE (parms);
21975
21976      if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21977	  && (!TREE_CHAIN (parms)
21978	      || TREE_CHAIN (parms) == void_list_node))
21979	/* For a function parameter pack that occurs at the end of the
21980	   parameter-declaration-list, the type A of each remaining
21981	   argument of the call is compared with the type P of the
21982	   declarator-id of the function parameter pack.  */
21983	break;
21984
21985      parms = TREE_CHAIN (parms);
21986
21987      if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21988	/* For a function parameter pack that does not occur at the
21989	   end of the parameter-declaration-list, the type of the
21990	   parameter pack is a non-deduced context.  */
21991	continue;
21992
21993      if (!uses_template_parms (parm))
21994	{
21995	  tree arg = args[ia];
21996	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
21997	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
21998
21999	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
22000					      conv_p, explain_p))
22001	    return 1;
22002	}
22003
22004      ++ia;
22005    }
22006
22007  return 0;
22008}
22009
22010/* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
22011   NARGS elements of the arguments that are being used when calling
22012   it.  TARGS is a vector into which the deduced template arguments
22013   are placed.
22014
22015   Returns either a FUNCTION_DECL for the matching specialization of FN or
22016   NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
22017   true, diagnostics will be printed to explain why it failed.
22018
22019   If FN is a conversion operator, or we are trying to produce a specific
22020   specialization, RETURN_TYPE is the return type desired.
22021
22022   The EXPLICIT_TARGS are explicit template arguments provided via a
22023   template-id.
22024
22025   The parameter STRICT is one of:
22026
22027   DEDUCE_CALL:
22028     We are deducing arguments for a function call, as in
22029     [temp.deduct.call].  If RETURN_TYPE is non-null, we are
22030     deducing arguments for a call to the result of a conversion
22031     function template, as in [over.call.object].
22032
22033   DEDUCE_CONV:
22034     We are deducing arguments for a conversion function, as in
22035     [temp.deduct.conv].
22036
22037   DEDUCE_EXACT:
22038     We are deducing arguments when doing an explicit instantiation
22039     as in [temp.explicit], when determining an explicit specialization
22040     as in [temp.expl.spec], or when taking the address of a function
22041     template, as in [temp.deduct.funcaddr].  */
22042
22043tree
22044fn_type_unification (tree fn,
22045		     tree explicit_targs,
22046		     tree targs,
22047		     const tree *args,
22048		     unsigned int nargs,
22049		     tree return_type,
22050		     unification_kind_t strict,
22051		     int flags,
22052		     struct conversion **convs,
22053		     bool explain_p,
22054		     bool decltype_p)
22055{
22056  tree parms;
22057  tree fntype;
22058  tree decl = NULL_TREE;
22059  tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22060  bool ok;
22061  static int deduction_depth;
22062  /* type_unification_real will pass back any access checks from default
22063     template argument substitution.  */
22064  vec<deferred_access_check, va_gc> *checks = NULL;
22065  /* We don't have all the template args yet.  */
22066  bool incomplete = true;
22067
22068  tree orig_fn = fn;
22069  if (flag_new_inheriting_ctors)
22070    fn = strip_inheriting_ctors (fn);
22071
22072  tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22073  tree r = error_mark_node;
22074
22075  tree full_targs = targs;
22076  if (TMPL_ARGS_DEPTH (targs)
22077      < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22078    full_targs = (add_outermost_template_args
22079		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22080		   targs));
22081
22082  if (decltype_p)
22083    complain |= tf_decltype;
22084
22085  /* In C++0x, it's possible to have a function template whose type depends
22086     on itself recursively.  This is most obvious with decltype, but can also
22087     occur with enumeration scope (c++/48969).  So we need to catch infinite
22088     recursion and reject the substitution at deduction time; this function
22089     will return error_mark_node for any repeated substitution.
22090
22091     This also catches excessive recursion such as when f<N> depends on
22092     f<N-1> across all integers, and returns error_mark_node for all the
22093     substitutions back up to the initial one.
22094
22095     This is, of course, not reentrant.  */
22096  if (excessive_deduction_depth)
22097    return error_mark_node;
22098  ++deduction_depth;
22099
22100  gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22101
22102  fntype = TREE_TYPE (fn);
22103  if (explicit_targs)
22104    {
22105      /* [temp.deduct]
22106
22107	 The specified template arguments must match the template
22108	 parameters in kind (i.e., type, nontype, template), and there
22109	 must not be more arguments than there are parameters;
22110	 otherwise type deduction fails.
22111
22112	 Nontype arguments must match the types of the corresponding
22113	 nontype template parameters, or must be convertible to the
22114	 types of the corresponding nontype parameters as specified in
22115	 _temp.arg.nontype_, otherwise type deduction fails.
22116
22117	 All references in the function type of the function template
22118	 to the corresponding template parameters are replaced by the
22119	 specified template argument values.  If a substitution in a
22120	 template parameter or in the function type of the function
22121	 template results in an invalid type, type deduction fails.  */
22122      int i, len = TREE_VEC_LENGTH (tparms);
22123      location_t loc = input_location;
22124      incomplete = false;
22125
22126      if (explicit_targs == error_mark_node)
22127	goto fail;
22128
22129      if (TMPL_ARGS_DEPTH (explicit_targs)
22130	  < TMPL_ARGS_DEPTH (full_targs))
22131	explicit_targs = add_outermost_template_args (full_targs,
22132						      explicit_targs);
22133
22134      /* Adjust any explicit template arguments before entering the
22135	 substitution context.  */
22136      explicit_targs
22137	= (coerce_template_parms (tparms, explicit_targs, fn,
22138				  complain|tf_partial,
22139				  /*require_all_args=*/false,
22140				  /*use_default_args=*/false));
22141      if (explicit_targs == error_mark_node)
22142	goto fail;
22143
22144      /* Substitute the explicit args into the function type.  This is
22145	 necessary so that, for instance, explicitly declared function
22146	 arguments can match null pointed constants.  If we were given
22147	 an incomplete set of explicit args, we must not do semantic
22148	 processing during substitution as we could create partial
22149	 instantiations.  */
22150      for (i = 0; i < len; i++)
22151        {
22152          tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22153          bool parameter_pack = false;
22154	  tree targ = TREE_VEC_ELT (explicit_targs, i);
22155
22156          /* Dig out the actual parm.  */
22157          if (TREE_CODE (parm) == TYPE_DECL
22158              || TREE_CODE (parm) == TEMPLATE_DECL)
22159            {
22160              parm = TREE_TYPE (parm);
22161              parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22162            }
22163          else if (TREE_CODE (parm) == PARM_DECL)
22164            {
22165              parm = DECL_INITIAL (parm);
22166              parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22167            }
22168
22169	  if (targ == NULL_TREE)
22170	    /* No explicit argument for this template parameter.  */
22171	    incomplete = true;
22172	  else if (parameter_pack && pack_deducible_p (parm, fn))
22173            {
22174              /* Mark the argument pack as "incomplete". We could
22175                 still deduce more arguments during unification.
22176	         We remove this mark in type_unification_real.  */
22177	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22178	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22179		= ARGUMENT_PACK_ARGS (targ);
22180
22181              /* We have some incomplete argument packs.  */
22182              incomplete = true;
22183            }
22184        }
22185
22186      if (incomplete)
22187	{
22188	  if (!push_tinst_level (fn, explicit_targs))
22189	    {
22190	      excessive_deduction_depth = true;
22191	      goto fail;
22192	    }
22193	  ++processing_template_decl;
22194	  input_location = DECL_SOURCE_LOCATION (fn);
22195	  /* Ignore any access checks; we'll see them again in
22196	     instantiate_template and they might have the wrong
22197	     access path at this point.  */
22198	  push_deferring_access_checks (dk_deferred);
22199	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22200	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22201	  pop_deferring_access_checks ();
22202	  input_location = loc;
22203	  --processing_template_decl;
22204	  pop_tinst_level ();
22205
22206	  if (fntype == error_mark_node)
22207	    goto fail;
22208	}
22209
22210      /* Place the explicitly specified arguments in TARGS.  */
22211      explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22212      for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22213	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22214      if (!incomplete && CHECKING_P
22215	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22216	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22217	  (targs, NUM_TMPL_ARGS (explicit_targs));
22218    }
22219
22220  if (return_type && strict != DEDUCE_CALL)
22221    {
22222      tree *new_args = XALLOCAVEC (tree, nargs + 1);
22223      new_args[0] = return_type;
22224      memcpy (new_args + 1, args, nargs * sizeof (tree));
22225      args = new_args;
22226      ++nargs;
22227    }
22228
22229  if (!incomplete)
22230    goto deduced;
22231
22232  /* Never do unification on the 'this' parameter.  */
22233  parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22234
22235  if (return_type && strict == DEDUCE_CALL)
22236    {
22237      /* We're deducing for a call to the result of a template conversion
22238         function.  The parms we really want are in return_type.  */
22239      if (INDIRECT_TYPE_P (return_type))
22240	return_type = TREE_TYPE (return_type);
22241      parms = TYPE_ARG_TYPES (return_type);
22242    }
22243  else if (return_type)
22244    {
22245      parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22246    }
22247
22248  /* We allow incomplete unification without an error message here
22249     because the standard doesn't seem to explicitly prohibit it.  Our
22250     callers must be ready to deal with unification failures in any
22251     event.  */
22252
22253  /* If we aren't explaining yet, push tinst context so we can see where
22254     any errors (e.g. from class instantiations triggered by instantiation
22255     of default template arguments) come from.  If we are explaining, this
22256     context is redundant.  */
22257  if (!explain_p && !push_tinst_level (fn, targs))
22258    {
22259      excessive_deduction_depth = true;
22260      goto fail;
22261    }
22262
22263  ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22264			       full_targs, parms, args, nargs, /*subr=*/0,
22265			       strict, &checks, explain_p);
22266  if (!explain_p)
22267    pop_tinst_level ();
22268  if (!ok)
22269    goto fail;
22270
22271  /* Now that we have bindings for all of the template arguments,
22272     ensure that the arguments deduced for the template template
22273     parameters have compatible template parameter lists.  We cannot
22274     check this property before we have deduced all template
22275     arguments, because the template parameter types of a template
22276     template parameter might depend on prior template parameters
22277     deduced after the template template parameter.  The following
22278     ill-formed example illustrates this issue:
22279
22280       template<typename T, template<T> class C> void f(C<5>, T);
22281
22282       template<int N> struct X {};
22283
22284       void g() {
22285         f(X<5>(), 5l); // error: template argument deduction fails
22286       }
22287
22288     The template parameter list of 'C' depends on the template type
22289     parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22290     'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
22291     time that we deduce 'C'.  */
22292  if (!template_template_parm_bindings_ok_p
22293           (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22294    {
22295      unify_inconsistent_template_template_parameters (explain_p);
22296      goto fail;
22297    }
22298
22299 deduced:
22300
22301  /* CWG2369: Check satisfaction before non-deducible conversions.  */
22302  if (!constraints_satisfied_p (fn, targs))
22303    {
22304      if (explain_p)
22305	diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22306      goto fail;
22307    }
22308
22309  /* DR 1391: All parameters have args, now check non-dependent parms for
22310     convertibility.  We don't do this if all args were explicitly specified,
22311     as the standard says that we substitute explicit args immediately.  */
22312  if (incomplete
22313      && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22314					  convs, explain_p))
22315    goto fail;
22316
22317  /* All is well so far.  Now, check:
22318
22319     [temp.deduct]
22320
22321     When all template arguments have been deduced, all uses of
22322     template parameters in nondeduced contexts are replaced with
22323     the corresponding deduced argument values.  If the
22324     substitution results in an invalid type, as described above,
22325     type deduction fails.  */
22326  if (!push_tinst_level (fn, targs))
22327    {
22328      excessive_deduction_depth = true;
22329      goto fail;
22330    }
22331
22332  /* Also collect access checks from the instantiation.  */
22333  reopen_deferring_access_checks (checks);
22334
22335  decl = instantiate_template (fn, targs, complain);
22336
22337  checks = get_deferred_access_checks ();
22338  pop_deferring_access_checks ();
22339
22340  pop_tinst_level ();
22341
22342  if (decl == error_mark_node)
22343    goto fail;
22344
22345  /* Now perform any access checks encountered during substitution.  */
22346  push_access_scope (decl);
22347  ok = perform_access_checks (checks, complain);
22348  pop_access_scope (decl);
22349  if (!ok)
22350    goto fail;
22351
22352  /* If we're looking for an exact match, check that what we got
22353     is indeed an exact match.  It might not be if some template
22354     parameters are used in non-deduced contexts.  But don't check
22355     for an exact match if we have dependent template arguments;
22356     in that case we're doing partial ordering, and we already know
22357     that we have two candidates that will provide the actual type.  */
22358  if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22359    {
22360      tree substed = TREE_TYPE (decl);
22361      unsigned int i;
22362
22363      tree sarg
22364	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22365      if (return_type)
22366	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22367      for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22368	if (!same_type_p (args[i], TREE_VALUE (sarg)))
22369	  {
22370	    unify_type_mismatch (explain_p, args[i],
22371				 TREE_VALUE (sarg));
22372	    goto fail;
22373	  }
22374      if ((i < nargs || sarg)
22375	  /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22376	     doesn't contain the trailing void, and conv fns are always ().  */
22377	  && !DECL_CONV_FN_P (decl))
22378	{
22379	  unsigned nsargs = i + list_length (sarg);
22380	  unify_arity (explain_p, nargs, nsargs);
22381	  goto fail;
22382	}
22383    }
22384
22385  /* After doing deduction with the inherited constructor, actually return an
22386     instantiation of the inheriting constructor.  */
22387  if (orig_fn != fn)
22388    decl = instantiate_template (orig_fn, targs, complain);
22389
22390  r = decl;
22391
22392 fail:
22393  --deduction_depth;
22394  if (excessive_deduction_depth)
22395    {
22396      if (deduction_depth == 0)
22397	/* Reset once we're all the way out.  */
22398	excessive_deduction_depth = false;
22399    }
22400
22401  return r;
22402}
22403
22404/* Returns true iff PARM is a forwarding reference in the context of
22405   template argument deduction for TMPL.  */
22406
22407static bool
22408forwarding_reference_p (tree parm, tree tmpl)
22409{
22410  /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22411     cv-unqualified template parameter ..."  */
22412  if (TYPE_REF_P (parm)
22413      && TYPE_REF_IS_RVALUE (parm)
22414      && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22415      && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22416    {
22417      parm = TREE_TYPE (parm);
22418      /* [temp.deduct.call], "... that does not represent a template parameter
22419	 of a class template (during class template argument deduction)."  */
22420      if (tmpl
22421	  && deduction_guide_p (tmpl)
22422	  && DECL_ARTIFICIAL (tmpl))
22423	{
22424	  /* Since the template parameters of a synthesized guide consist of
22425	     the template parameters of the class template followed by those of
22426	     the constructor (if any), we can tell if PARM represents a template
22427	     parameter of the class template by comparing its index with the
22428	     arity of the class template.  */
22429	  tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22430	  if (TEMPLATE_TYPE_IDX (parm)
22431	      < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22432	    return false;
22433	}
22434      return true;
22435    }
22436  return false;
22437}
22438
22439/* Adjust types before performing type deduction, as described in
22440   [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
22441   sections are symmetric.  PARM is the type of a function parameter
22442   or the return type of the conversion function.  ARG is the type of
22443   the argument passed to the call, or the type of the value
22444   initialized with the result of the conversion function.
22445   ARG_EXPR is the original argument expression, which may be null.  */
22446
22447static int
22448maybe_adjust_types_for_deduction (tree tparms,
22449				  unification_kind_t strict,
22450				  tree* parm,
22451				  tree* arg,
22452				  tree arg_expr)
22453{
22454  int result = 0;
22455
22456  switch (strict)
22457    {
22458    case DEDUCE_CALL:
22459      break;
22460
22461    case DEDUCE_CONV:
22462      /* Swap PARM and ARG throughout the remainder of this
22463	 function; the handling is precisely symmetric since PARM
22464	 will initialize ARG rather than vice versa.  */
22465      std::swap (parm, arg);
22466      break;
22467
22468    case DEDUCE_EXACT:
22469      /* Core issue #873: Do the DR606 thing (see below) for these cases,
22470	 too, but here handle it by stripping the reference from PARM
22471	 rather than by adding it to ARG.  */
22472      if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22473	  && TYPE_REF_P (*arg)
22474	  && !TYPE_REF_IS_RVALUE (*arg))
22475	*parm = TREE_TYPE (*parm);
22476      /* Nothing else to do in this case.  */
22477      return 0;
22478
22479    default:
22480      gcc_unreachable ();
22481    }
22482
22483  if (!TYPE_REF_P (*parm))
22484    {
22485      /* [temp.deduct.call]
22486
22487	 If P is not a reference type:
22488
22489	 --If A is an array type, the pointer type produced by the
22490	 array-to-pointer standard conversion (_conv.array_) is
22491	 used in place of A for type deduction; otherwise,
22492
22493	 --If A is a function type, the pointer type produced by
22494	 the function-to-pointer standard conversion
22495	 (_conv.func_) is used in place of A for type deduction;
22496	 otherwise,
22497
22498	 --If A is a cv-qualified type, the top level
22499	 cv-qualifiers of A's type are ignored for type
22500	 deduction.  */
22501      if (TREE_CODE (*arg) == ARRAY_TYPE)
22502	*arg = build_pointer_type (TREE_TYPE (*arg));
22503      else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22504	*arg = build_pointer_type (*arg);
22505      else
22506	*arg = TYPE_MAIN_VARIANT (*arg);
22507    }
22508
22509  /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22510     an lvalue, the type 'lvalue reference to A' is used in place of A for
22511     type deduction."  */
22512  if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22513      && (arg_expr ? lvalue_p (arg_expr)
22514	  /* try_one_overload doesn't provide an arg_expr, but
22515	     functions are always lvalues.  */
22516	  : TREE_CODE (*arg) == FUNCTION_TYPE))
22517    *arg = build_reference_type (*arg);
22518
22519  /* [temp.deduct.call]
22520
22521     If P is a cv-qualified type, the top level cv-qualifiers
22522     of P's type are ignored for type deduction.  If P is a
22523     reference type, the type referred to by P is used for
22524     type deduction.  */
22525  *parm = TYPE_MAIN_VARIANT (*parm);
22526  if (TYPE_REF_P (*parm))
22527    {
22528      *parm = TREE_TYPE (*parm);
22529      result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22530    }
22531
22532  /* DR 322. For conversion deduction, remove a reference type on parm
22533     too (which has been swapped into ARG).  */
22534  if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
22535    *arg = TREE_TYPE (*arg);
22536
22537  return result;
22538}
22539
22540/* Subroutine of fn_type_unification.  PARM is a function parameter of a
22541   template which doesn't contain any deducible template parameters; check if
22542   ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
22543   unify_one_argument.  */
22544
22545static int
22546check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22547				int flags, struct conversion **conv_p,
22548				bool explain_p)
22549{
22550  tree type;
22551
22552  if (!TYPE_P (arg))
22553    type = TREE_TYPE (arg);
22554  else
22555    type = arg;
22556
22557  if (same_type_p (parm, type))
22558    return unify_success (explain_p);
22559
22560  tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22561  if (strict == DEDUCE_CONV)
22562    {
22563      if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22564	return unify_success (explain_p);
22565    }
22566  else if (strict == DEDUCE_CALL)
22567    {
22568      bool ok = false;
22569      tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22570      if (conv_p)
22571	/* Avoid recalculating this in add_function_candidate.  */
22572	ok = (*conv_p
22573	      = good_conversion (parm, type, conv_arg, flags, complain));
22574      else
22575	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22576      if (ok)
22577	return unify_success (explain_p);
22578    }
22579
22580  if (strict == DEDUCE_EXACT)
22581    return unify_type_mismatch (explain_p, parm, arg);
22582  else
22583    return unify_arg_conversion (explain_p, parm, type, arg);
22584}
22585
22586static bool uses_deducible_template_parms (tree type);
22587
22588/* Returns true iff the expression EXPR is one from which a template
22589   argument can be deduced.  In other words, if it's an undecorated
22590   use of a template non-type parameter.  */
22591
22592static bool
22593deducible_expression (tree expr)
22594{
22595  /* Strip implicit conversions and implicit INDIRECT_REFs.  */
22596  while (CONVERT_EXPR_P (expr)
22597	 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22598	 || REFERENCE_REF_P (expr))
22599    expr = TREE_OPERAND (expr, 0);
22600  return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22601}
22602
22603/* Returns true iff the array domain DOMAIN uses a template parameter in a
22604   deducible way; that is, if it has a max value of <PARM> - 1.  */
22605
22606static bool
22607deducible_array_bound (tree domain)
22608{
22609  if (domain == NULL_TREE)
22610    return false;
22611
22612  tree max = TYPE_MAX_VALUE (domain);
22613  if (TREE_CODE (max) != MINUS_EXPR)
22614    return false;
22615
22616  return deducible_expression (TREE_OPERAND (max, 0));
22617}
22618
22619/* Returns true iff the template arguments ARGS use a template parameter
22620   in a deducible way.  */
22621
22622static bool
22623deducible_template_args (tree args)
22624{
22625  for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
22626    {
22627      bool deducible;
22628      tree elt = TREE_VEC_ELT (args, i);
22629      if (ARGUMENT_PACK_P (elt))
22630	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22631      else
22632	{
22633	  if (PACK_EXPANSION_P (elt))
22634	    elt = PACK_EXPANSION_PATTERN (elt);
22635	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22636	    deducible = true;
22637	  else if (TYPE_P (elt))
22638	    deducible = uses_deducible_template_parms (elt);
22639	  else
22640	    deducible = deducible_expression (elt);
22641	}
22642      if (deducible)
22643	return true;
22644    }
22645  return false;
22646}
22647
22648/* Returns true iff TYPE contains any deducible references to template
22649   parameters, as per 14.8.2.5.  */
22650
22651static bool
22652uses_deducible_template_parms (tree type)
22653{
22654  if (PACK_EXPANSION_P (type))
22655    type = PACK_EXPANSION_PATTERN (type);
22656
22657  /* T
22658     cv-list T
22659     TT<T>
22660     TT<i>
22661     TT<> */
22662  if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22663      || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22664    return true;
22665
22666  /* T*
22667     T&
22668     T&&  */
22669  if (INDIRECT_TYPE_P (type))
22670    return uses_deducible_template_parms (TREE_TYPE (type));
22671
22672  /* T[integer-constant ]
22673     type [i]  */
22674  if (TREE_CODE (type) == ARRAY_TYPE)
22675    return (uses_deducible_template_parms (TREE_TYPE (type))
22676	    || deducible_array_bound (TYPE_DOMAIN (type)));
22677
22678  /* T type ::*
22679     type T::*
22680     T T::*
22681     T (type ::*)()
22682     type (T::*)()
22683     type (type ::*)(T)
22684     type (T::*)(T)
22685     T (type ::*)(T)
22686     T (T::*)()
22687     T (T::*)(T) */
22688  if (TYPE_PTRMEM_P (type))
22689    return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22690	    || (uses_deducible_template_parms
22691		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22692
22693  /* template-name <T> (where template-name refers to a class template)
22694     template-name <i> (where template-name refers to a class template) */
22695  if (CLASS_TYPE_P (type)
22696      && CLASSTYPE_TEMPLATE_INFO (type)
22697      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22698    return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22699				    (CLASSTYPE_TI_ARGS (type)));
22700
22701  /* type (T)
22702     T()
22703     T(T)  */
22704  if (FUNC_OR_METHOD_TYPE_P (type))
22705    {
22706      if (uses_deducible_template_parms (TREE_TYPE (type)))
22707	return true;
22708      tree parm = TYPE_ARG_TYPES (type);
22709      if (TREE_CODE (type) == METHOD_TYPE)
22710	parm = TREE_CHAIN (parm);
22711      for (; parm; parm = TREE_CHAIN (parm))
22712	if (uses_deducible_template_parms (TREE_VALUE (parm)))
22713	  return true;
22714      if (flag_noexcept_type
22715	  && TYPE_RAISES_EXCEPTIONS (type)
22716	  && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
22717	  && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
22718	return true;
22719    }
22720
22721  return false;
22722}
22723
22724/* Subroutine of type_unification_real and unify_pack_expansion to
22725   handle unification of a single P/A pair.  Parameters are as
22726   for those functions.  */
22727
22728static int
22729unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22730		    int subr, unification_kind_t strict,
22731		    bool explain_p)
22732{
22733  tree arg_expr = NULL_TREE;
22734  int arg_strict;
22735
22736  if (arg == error_mark_node || parm == error_mark_node)
22737    return unify_invalid (explain_p);
22738  if (arg == unknown_type_node)
22739    /* We can't deduce anything from this, but we might get all the
22740       template args from other function args.  */
22741    return unify_success (explain_p);
22742
22743  /* Implicit conversions (Clause 4) will be performed on a function
22744     argument to convert it to the type of the corresponding function
22745     parameter if the parameter type contains no template-parameters that
22746     participate in template argument deduction.  */
22747  if (strict != DEDUCE_EXACT
22748      && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22749    /* For function parameters with no deducible template parameters,
22750       just return.  We'll check non-dependent conversions later.  */
22751    return unify_success (explain_p);
22752
22753  switch (strict)
22754    {
22755    case DEDUCE_CALL:
22756      arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22757		    | UNIFY_ALLOW_MORE_CV_QUAL
22758		    | UNIFY_ALLOW_DERIVED);
22759      break;
22760
22761    case DEDUCE_CONV:
22762      arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22763      break;
22764
22765    case DEDUCE_EXACT:
22766      arg_strict = UNIFY_ALLOW_NONE;
22767      break;
22768
22769    default:
22770      gcc_unreachable ();
22771    }
22772
22773  /* We only do these transformations if this is the top-level
22774     parameter_type_list in a call or declaration matching; in other
22775     situations (nested function declarators, template argument lists) we
22776     won't be comparing a type to an expression, and we don't do any type
22777     adjustments.  */
22778  if (!subr)
22779    {
22780      if (!TYPE_P (arg))
22781	{
22782	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22783	  if (type_unknown_p (arg))
22784	    {
22785	      /* [temp.deduct.type] A template-argument can be
22786		 deduced from a pointer to function or pointer
22787		 to member function argument if the set of
22788		 overloaded functions does not contain function
22789		 templates and at most one of a set of
22790		 overloaded functions provides a unique
22791		 match.  */
22792	      resolve_overloaded_unification (tparms, targs, parm,
22793					      arg, strict,
22794					      arg_strict, explain_p);
22795	      /* If a unique match was not found, this is a
22796	         non-deduced context, so we still succeed. */
22797	      return unify_success (explain_p);
22798	    }
22799
22800	  arg_expr = arg;
22801	  arg = unlowered_expr_type (arg);
22802	  if (arg == error_mark_node)
22803	    return unify_invalid (explain_p);
22804	}
22805
22806      arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
22807						      &parm, &arg, arg_expr);
22808    }
22809  else
22810    if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22811	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22812      return unify_template_argument_mismatch (explain_p, parm, arg);
22813
22814  /* For deduction from an init-list we need the actual list.  */
22815  if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22816    arg = arg_expr;
22817  return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22818}
22819
22820/* for_each_template_parm callback that always returns 0.  */
22821
22822static int
22823zero_r (tree, void *)
22824{
22825  return 0;
22826}
22827
22828/* for_each_template_parm any_fn callback to handle deduction of a template
22829   type argument from the type of an array bound.  */
22830
22831static int
22832array_deduction_r (tree t, void *data)
22833{
22834  tree_pair_p d = (tree_pair_p)data;
22835  tree &tparms = d->purpose;
22836  tree &targs = d->value;
22837
22838  if (TREE_CODE (t) == ARRAY_TYPE)
22839    if (tree dom = TYPE_DOMAIN (t))
22840      if (tree max = TYPE_MAX_VALUE (dom))
22841	{
22842	  if (TREE_CODE (max) == MINUS_EXPR)
22843	    max = TREE_OPERAND (max, 0);
22844	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22845	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
22846		   UNIFY_ALLOW_NONE, /*explain*/false);
22847	}
22848
22849  /* Keep walking.  */
22850  return 0;
22851}
22852
22853/* Try to deduce any not-yet-deduced template type arguments from the type of
22854   an array bound.  This is handled separately from unify because 14.8.2.5 says
22855   "The type of a type parameter is only deduced from an array bound if it is
22856   not otherwise deduced."  */
22857
22858static void
22859try_array_deduction (tree tparms, tree targs, tree parm)
22860{
22861  tree_pair_s data = { tparms, targs };
22862  hash_set<tree> visited;
22863  for_each_template_parm (parm, zero_r, &data, &visited,
22864			  /*nondeduced*/false, array_deduction_r);
22865}
22866
22867/* Most parms like fn_type_unification.
22868
22869   If SUBR is 1, we're being called recursively (to unify the
22870   arguments of a function or method parameter of a function
22871   template).
22872
22873   CHECKS is a pointer to a vector of access checks encountered while
22874   substituting default template arguments.  */
22875
22876static int
22877type_unification_real (tree tparms,
22878		       tree full_targs,
22879		       tree xparms,
22880		       const tree *xargs,
22881		       unsigned int xnargs,
22882		       int subr,
22883		       unification_kind_t strict,
22884		       vec<deferred_access_check, va_gc> **checks,
22885		       bool explain_p)
22886{
22887  tree parm, arg;
22888  int i;
22889  int ntparms = TREE_VEC_LENGTH (tparms);
22890  int saw_undeduced = 0;
22891  tree parms;
22892  const tree *args;
22893  unsigned int nargs;
22894  unsigned int ia;
22895
22896  gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22897  gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22898  gcc_assert (ntparms > 0);
22899
22900  tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22901
22902  /* Reset the number of non-defaulted template arguments contained
22903     in TARGS.  */
22904  NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22905
22906 again:
22907  parms = xparms;
22908  args = xargs;
22909  nargs = xnargs;
22910
22911  /* Only fn_type_unification cares about terminal void.  */
22912  if (nargs && args[nargs-1] == void_type_node)
22913    --nargs;
22914
22915  ia = 0;
22916  while (parms && parms != void_list_node
22917	 && ia < nargs)
22918    {
22919      parm = TREE_VALUE (parms);
22920
22921      if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22922	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
22923	/* For a function parameter pack that occurs at the end of the
22924	   parameter-declaration-list, the type A of each remaining
22925	   argument of the call is compared with the type P of the
22926	   declarator-id of the function parameter pack.  */
22927	break;
22928
22929      parms = TREE_CHAIN (parms);
22930
22931      if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22932	/* For a function parameter pack that does not occur at the
22933	   end of the parameter-declaration-list, the type of the
22934	   parameter pack is a non-deduced context.  */
22935	continue;
22936
22937      arg = args[ia];
22938      ++ia;
22939
22940      if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22941			      explain_p))
22942	return 1;
22943    }
22944
22945  if (parms
22946      && parms != void_list_node
22947      && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22948    {
22949      /* Unify the remaining arguments with the pack expansion type.  */
22950      tree argvec;
22951      tree parmvec = make_tree_vec (1);
22952
22953      /* Allocate a TREE_VEC and copy in all of the arguments */
22954      argvec = make_tree_vec (nargs - ia);
22955      for (i = 0; ia < nargs; ++ia, ++i)
22956	TREE_VEC_ELT (argvec, i) = args[ia];
22957
22958      /* Copy the parameter into parmvec.  */
22959      TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22960      if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22961                                /*subr=*/subr, explain_p))
22962        return 1;
22963
22964      /* Advance to the end of the list of parameters.  */
22965      parms = TREE_CHAIN (parms);
22966    }
22967
22968  /* Fail if we've reached the end of the parm list, and more args
22969     are present, and the parm list isn't variadic.  */
22970  if (ia < nargs && parms == void_list_node)
22971    return unify_too_many_arguments (explain_p, nargs, ia);
22972  /* Fail if parms are left and they don't have default values and
22973     they aren't all deduced as empty packs (c++/57397).  This is
22974     consistent with sufficient_parms_p.  */
22975  if (parms && parms != void_list_node
22976      && TREE_PURPOSE (parms) == NULL_TREE)
22977    {
22978      unsigned int count = nargs;
22979      tree p = parms;
22980      bool type_pack_p;
22981      do
22982	{
22983	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
22984	  if (!type_pack_p)
22985	    count++;
22986	  p = TREE_CHAIN (p);
22987	}
22988      while (p && p != void_list_node);
22989      if (count != nargs)
22990	return unify_too_few_arguments (explain_p, ia, count,
22991					type_pack_p);
22992    }
22993
22994  if (!subr)
22995    {
22996      tsubst_flags_t complain = (explain_p
22997				 ? tf_warning_or_error
22998				 : tf_none);
22999      bool tried_array_deduction = (cxx_dialect < cxx17);
23000
23001      for (i = 0; i < ntparms; i++)
23002	{
23003	  tree targ = TREE_VEC_ELT (targs, i);
23004	  tree tparm = TREE_VEC_ELT (tparms, i);
23005
23006	  /* Clear the "incomplete" flags on all argument packs now so that
23007	     substituting them into later default arguments works.  */
23008	  if (targ && ARGUMENT_PACK_P (targ))
23009            {
23010              ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23011              ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23012            }
23013
23014	  if (targ || tparm == error_mark_node)
23015	    continue;
23016	  tparm = TREE_VALUE (tparm);
23017
23018	  if (TREE_CODE (tparm) == TYPE_DECL
23019	      && !tried_array_deduction)
23020	    {
23021	      try_array_deduction (tparms, targs, xparms);
23022	      tried_array_deduction = true;
23023	      if (TREE_VEC_ELT (targs, i))
23024		continue;
23025	    }
23026
23027	  /* If this is an undeduced nontype parameter that depends on
23028	     a type parameter, try another pass; its type may have been
23029	     deduced from a later argument than the one from which
23030	     this parameter can be deduced.  */
23031	  if (TREE_CODE (tparm) == PARM_DECL
23032	      && uses_template_parms (TREE_TYPE (tparm))
23033	      && saw_undeduced < 2)
23034	    {
23035	      saw_undeduced = 1;
23036	      continue;
23037	    }
23038
23039	  /* Core issue #226 (C++0x) [temp.deduct]:
23040
23041	     If a template argument has not been deduced, its
23042	     default template argument, if any, is used.
23043
23044	     When we are in C++98 mode, TREE_PURPOSE will either
23045	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
23046	     to explicitly check cxx_dialect here.  */
23047	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23048	    /* OK, there is a default argument.  Wait until after the
23049	       conversion check to do substitution.  */
23050	    continue;
23051
23052	  /* If the type parameter is a parameter pack, then it will
23053	     be deduced to an empty parameter pack.  */
23054	  if (template_parameter_pack_p (tparm))
23055	    {
23056	      tree arg;
23057
23058	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
23059		{
23060		  arg = make_node (NONTYPE_ARGUMENT_PACK);
23061		  TREE_CONSTANT (arg) = 1;
23062		}
23063	      else
23064		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23065
23066	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
23067
23068	      TREE_VEC_ELT (targs, i) = arg;
23069	      continue;
23070	    }
23071
23072	  return unify_parameter_deduction_failure (explain_p, tparm);
23073	}
23074
23075      /* During partial ordering, we deduce dependent template args.  */
23076      bool any_dependent_targs = false;
23077
23078      /* Now substitute into the default template arguments.  */
23079      for (i = 0; i < ntparms; i++)
23080	{
23081	  tree targ = TREE_VEC_ELT (targs, i);
23082	  tree tparm = TREE_VEC_ELT (tparms, i);
23083
23084	  if (targ)
23085	    {
23086	      if (!any_dependent_targs && dependent_template_arg_p (targ))
23087		any_dependent_targs = true;
23088	      continue;
23089	    }
23090	  if (tparm == error_mark_node)
23091	    continue;
23092
23093	  tree parm = TREE_VALUE (tparm);
23094	  tree arg = TREE_PURPOSE (tparm);
23095	  reopen_deferring_access_checks (*checks);
23096	  location_t save_loc = input_location;
23097	  if (DECL_P (parm))
23098	    input_location = DECL_SOURCE_LOCATION (parm);
23099
23100	  if (saw_undeduced == 1
23101	      && TREE_CODE (parm) == PARM_DECL
23102	      && uses_template_parms (TREE_TYPE (parm)))
23103	    {
23104	      /* The type of this non-type parameter depends on undeduced
23105		 parameters.  Don't try to use its default argument yet,
23106		 since we might deduce an argument for it on the next pass,
23107		 but do check whether the arguments we already have cause
23108		 substitution failure, so that that happens before we try
23109		 later default arguments (78489).  */
23110	      ++processing_template_decl;
23111	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23112				  NULL_TREE);
23113	      --processing_template_decl;
23114	      if (type == error_mark_node)
23115		arg = error_mark_node;
23116	      else
23117		arg = NULL_TREE;
23118	    }
23119	  else
23120	    {
23121	      /* Even if the call is happening in template context, getting
23122		 here means it's non-dependent, and a default argument is
23123		 considered a separate definition under [temp.decls], so we can
23124		 do this substitution without processing_template_decl.  This
23125		 is important if the default argument contains something that
23126		 might be instantiation-dependent like access (87480).  */
23127	      processing_template_decl_sentinel s (!any_dependent_targs);
23128	      tree substed = NULL_TREE;
23129	      if (saw_undeduced == 1 && !any_dependent_targs)
23130		{
23131		  /* First instatiate in template context, in case we still
23132		     depend on undeduced template parameters.  */
23133		  ++processing_template_decl;
23134		  substed = tsubst_template_arg (arg, full_targs, complain,
23135						 NULL_TREE);
23136		  --processing_template_decl;
23137		  if (substed != error_mark_node
23138		      && !uses_template_parms (substed))
23139		    /* We replaced all the tparms, substitute again out of
23140		       template context.  */
23141		    substed = NULL_TREE;
23142		}
23143	      if (!substed)
23144		substed = tsubst_template_arg (arg, full_targs, complain,
23145					       NULL_TREE);
23146
23147	      if (!uses_template_parms (substed))
23148		arg = convert_template_argument (parm, substed, full_targs,
23149						 complain, i, NULL_TREE);
23150	      else if (saw_undeduced == 1)
23151		arg = NULL_TREE;
23152	      else if (!any_dependent_targs)
23153		arg = error_mark_node;
23154	    }
23155
23156	  input_location = save_loc;
23157	  *checks = get_deferred_access_checks ();
23158	  pop_deferring_access_checks ();
23159
23160	  if (arg == error_mark_node)
23161	    return 1;
23162	  else if (arg)
23163	    {
23164	      TREE_VEC_ELT (targs, i) = arg;
23165	      /* The position of the first default template argument,
23166		 is also the number of non-defaulted arguments in TARGS.
23167		 Record that.  */
23168	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23169		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23170	    }
23171	}
23172
23173      if (saw_undeduced++ == 1)
23174	goto again;
23175    }
23176
23177  if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23178    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23179
23180  return unify_success (explain_p);
23181}
23182
23183/* Subroutine of type_unification_real.  Args are like the variables
23184   at the call site.  ARG is an overloaded function (or template-id);
23185   we try deducing template args from each of the overloads, and if
23186   only one succeeds, we go with that.  Modifies TARGS and returns
23187   true on success.  */
23188
23189static bool
23190resolve_overloaded_unification (tree tparms,
23191				tree targs,
23192				tree parm,
23193				tree arg,
23194				unification_kind_t strict,
23195				int sub_strict,
23196			        bool explain_p)
23197{
23198  tree tempargs = copy_node (targs);
23199  int good = 0;
23200  tree goodfn = NULL_TREE;
23201  bool addr_p;
23202
23203  if (TREE_CODE (arg) == ADDR_EXPR)
23204    {
23205      arg = TREE_OPERAND (arg, 0);
23206      addr_p = true;
23207    }
23208  else
23209    addr_p = false;
23210
23211  if (TREE_CODE (arg) == COMPONENT_REF)
23212    /* Handle `&x' where `x' is some static or non-static member
23213       function name.  */
23214    arg = TREE_OPERAND (arg, 1);
23215
23216  if (TREE_CODE (arg) == OFFSET_REF)
23217    arg = TREE_OPERAND (arg, 1);
23218
23219  /* Strip baselink information.  */
23220  if (BASELINK_P (arg))
23221    arg = BASELINK_FUNCTIONS (arg);
23222
23223  if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23224    {
23225      /* If we got some explicit template args, we need to plug them into
23226	 the affected templates before we try to unify, in case the
23227	 explicit args will completely resolve the templates in question.  */
23228
23229      int ok = 0;
23230      tree expl_subargs = TREE_OPERAND (arg, 1);
23231      arg = TREE_OPERAND (arg, 0);
23232
23233      for (lkp_iterator iter (arg); iter; ++iter)
23234	{
23235	  tree fn = *iter;
23236	  tree subargs, elem;
23237
23238	  if (TREE_CODE (fn) != TEMPLATE_DECL)
23239	    continue;
23240
23241	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23242					   expl_subargs, NULL_TREE, tf_none,
23243					   /*require_all_args=*/true,
23244					   /*use_default_args=*/true);
23245	  if (subargs != error_mark_node
23246	      && !any_dependent_template_arguments_p (subargs))
23247	    {
23248	      fn = instantiate_template (fn, subargs, tf_none);
23249	      if (!constraints_satisfied_p (fn))
23250		continue;
23251	      if (undeduced_auto_decl (fn))
23252		{
23253		  /* Instantiate the function to deduce its return type.  */
23254		  ++function_depth;
23255		  instantiate_decl (fn, /*defer*/false, /*class*/false);
23256		  --function_depth;
23257		}
23258
23259	      if (flag_noexcept_type)
23260		maybe_instantiate_noexcept (fn, tf_none);
23261
23262	      elem = TREE_TYPE (fn);
23263	      if (try_one_overload (tparms, targs, tempargs, parm,
23264				    elem, strict, sub_strict, addr_p, explain_p)
23265		  && (!goodfn || !same_type_p (goodfn, elem)))
23266		{
23267		  goodfn = elem;
23268		  ++good;
23269		}
23270	    }
23271	  else if (subargs)
23272	    ++ok;
23273	}
23274      /* If no templates (or more than one) are fully resolved by the
23275	 explicit arguments, this template-id is a non-deduced context; it
23276	 could still be OK if we deduce all template arguments for the
23277	 enclosing call through other arguments.  */
23278      if (good != 1)
23279	good = ok;
23280    }
23281  else if (!OVL_P (arg))
23282    /* If ARG is, for example, "(0, &f)" then its type will be unknown
23283       -- but the deduction does not succeed because the expression is
23284       not just the function on its own.  */
23285    return false;
23286  else
23287    for (lkp_iterator iter (arg); iter; ++iter)
23288      {
23289	tree fn = *iter;
23290	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23291			      strict, sub_strict, addr_p, explain_p)
23292	    && (!goodfn || !decls_match (goodfn, fn)))
23293	  {
23294	    goodfn = fn;
23295	    ++good;
23296	  }
23297      }
23298
23299  /* [temp.deduct.type] A template-argument can be deduced from a pointer
23300     to function or pointer to member function argument if the set of
23301     overloaded functions does not contain function templates and at most
23302     one of a set of overloaded functions provides a unique match.
23303
23304     So if we found multiple possibilities, we return success but don't
23305     deduce anything.  */
23306
23307  if (good == 1)
23308    {
23309      int i = TREE_VEC_LENGTH (targs);
23310      for (; i--; )
23311	if (TREE_VEC_ELT (tempargs, i))
23312	  {
23313	    tree old = TREE_VEC_ELT (targs, i);
23314	    tree new_ = TREE_VEC_ELT (tempargs, i);
23315	    if (new_ && old && ARGUMENT_PACK_P (old)
23316		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
23317	      /* Don't forget explicit template arguments in a pack.  */
23318	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23319		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
23320	    TREE_VEC_ELT (targs, i) = new_;
23321	  }
23322    }
23323  if (good)
23324    return true;
23325
23326  return false;
23327}
23328
23329/* Core DR 115: In contexts where deduction is done and fails, or in
23330   contexts where deduction is not done, if a template argument list is
23331   specified and it, along with any default template arguments, identifies
23332   a single function template specialization, then the template-id is an
23333   lvalue for the function template specialization.  */
23334
23335tree
23336resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23337{
23338  tree expr, offset, baselink;
23339  bool addr;
23340
23341  if (!type_unknown_p (orig_expr))
23342    return orig_expr;
23343
23344  expr = orig_expr;
23345  addr = false;
23346  offset = NULL_TREE;
23347  baselink = NULL_TREE;
23348
23349  if (TREE_CODE (expr) == ADDR_EXPR)
23350    {
23351      expr = TREE_OPERAND (expr, 0);
23352      addr = true;
23353    }
23354  if (TREE_CODE (expr) == OFFSET_REF)
23355    {
23356      offset = expr;
23357      expr = TREE_OPERAND (expr, 1);
23358    }
23359  if (BASELINK_P (expr))
23360    {
23361      baselink = expr;
23362      expr = BASELINK_FUNCTIONS (expr);
23363    }
23364
23365  if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23366    {
23367      int good = 0;
23368      tree goodfn = NULL_TREE;
23369
23370      /* If we got some explicit template args, we need to plug them into
23371	 the affected templates before we try to unify, in case the
23372	 explicit args will completely resolve the templates in question.  */
23373
23374      tree expl_subargs = TREE_OPERAND (expr, 1);
23375      tree arg = TREE_OPERAND (expr, 0);
23376      tree badfn = NULL_TREE;
23377      tree badargs = NULL_TREE;
23378
23379      for (lkp_iterator iter (arg); iter; ++iter)
23380	{
23381	  tree fn = *iter;
23382	  tree subargs, elem;
23383
23384	  if (TREE_CODE (fn) != TEMPLATE_DECL)
23385	    continue;
23386
23387	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23388					   expl_subargs, NULL_TREE, tf_none,
23389					   /*require_all_args=*/true,
23390					   /*use_default_args=*/true);
23391	  if (subargs != error_mark_node
23392	      && !any_dependent_template_arguments_p (subargs))
23393	    {
23394	      elem = instantiate_template (fn, subargs, tf_none);
23395	      if (elem == error_mark_node)
23396		{
23397		  badfn = fn;
23398		  badargs = subargs;
23399		}
23400	      else if (elem && (!goodfn || !decls_match (goodfn, elem))
23401		       && constraints_satisfied_p (elem))
23402		{
23403		  goodfn = elem;
23404		  ++good;
23405		}
23406	    }
23407	}
23408      if (good == 1)
23409	{
23410	  mark_used (goodfn);
23411	  expr = goodfn;
23412	  if (baselink)
23413	    expr = build_baselink (BASELINK_BINFO (baselink),
23414				   BASELINK_ACCESS_BINFO (baselink),
23415				   expr, BASELINK_OPTYPE (baselink));
23416	  if (offset)
23417	    {
23418	      tree base
23419		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23420	      expr = build_offset_ref (base, expr, addr, complain);
23421	    }
23422	  if (addr)
23423	    expr = cp_build_addr_expr (expr, complain);
23424	  return expr;
23425	}
23426      else if (good == 0 && badargs && (complain & tf_error))
23427	/* There were no good options and at least one bad one, so let the
23428	   user know what the problem is.  */
23429	instantiate_template (badfn, badargs, complain);
23430    }
23431  return orig_expr;
23432}
23433
23434/* As above, but error out if the expression remains overloaded.  */
23435
23436tree
23437resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23438{
23439  exp = resolve_nondeduced_context (exp, complain);
23440  if (type_unknown_p (exp))
23441    {
23442      if (complain & tf_error)
23443	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23444      return error_mark_node;
23445    }
23446  return exp;
23447}
23448
23449/* Subroutine of resolve_overloaded_unification; does deduction for a single
23450   overload.  Fills TARGS with any deduced arguments, or error_mark_node if
23451   different overloads deduce different arguments for a given parm.
23452   ADDR_P is true if the expression for which deduction is being
23453   performed was of the form "& fn" rather than simply "fn".
23454
23455   Returns 1 on success.  */
23456
23457static int
23458try_one_overload (tree tparms,
23459		  tree orig_targs,
23460		  tree targs,
23461		  tree parm,
23462		  tree arg,
23463		  unification_kind_t strict,
23464		  int sub_strict,
23465		  bool addr_p,
23466		  bool explain_p)
23467{
23468  int nargs;
23469  tree tempargs;
23470  int i;
23471
23472  if (arg == error_mark_node)
23473    return 0;
23474
23475  /* [temp.deduct.type] A template-argument can be deduced from a pointer
23476     to function or pointer to member function argument if the set of
23477     overloaded functions does not contain function templates and at most
23478     one of a set of overloaded functions provides a unique match.
23479
23480     So if this is a template, just return success.  */
23481
23482  if (uses_template_parms (arg))
23483    return 1;
23484
23485  if (TREE_CODE (arg) == METHOD_TYPE)
23486    arg = build_ptrmemfunc_type (build_pointer_type (arg));
23487  else if (addr_p)
23488    arg = build_pointer_type (arg);
23489
23490  sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23491						  &parm, &arg, NULL_TREE);
23492
23493  /* We don't copy orig_targs for this because if we have already deduced
23494     some template args from previous args, unify would complain when we
23495     try to deduce a template parameter for the same argument, even though
23496     there isn't really a conflict.  */
23497  nargs = TREE_VEC_LENGTH (targs);
23498  tempargs = make_tree_vec (nargs);
23499
23500  if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23501    return 0;
23502
23503  /* First make sure we didn't deduce anything that conflicts with
23504     explicitly specified args.  */
23505  for (i = nargs; i--; )
23506    {
23507      tree elt = TREE_VEC_ELT (tempargs, i);
23508      tree oldelt = TREE_VEC_ELT (orig_targs, i);
23509
23510      if (!elt)
23511	/*NOP*/;
23512      else if (uses_template_parms (elt))
23513	/* Since we're unifying against ourselves, we will fill in
23514	   template args used in the function parm list with our own
23515	   template parms.  Discard them.  */
23516	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23517      else if (oldelt && ARGUMENT_PACK_P (oldelt))
23518	{
23519	  /* Check that the argument at each index of the deduced argument pack
23520	     is equivalent to the corresponding explicitly specified argument.
23521	     We may have deduced more arguments than were explicitly specified,
23522	     and that's OK.  */
23523
23524	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23525	     that's wrong if we deduce the same argument pack from multiple
23526	     function arguments: it's only incomplete the first time.  */
23527
23528	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23529	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23530
23531	  if (TREE_VEC_LENGTH (deduced_pack)
23532	      < TREE_VEC_LENGTH (explicit_pack))
23533	    return 0;
23534
23535	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23536	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23537				      TREE_VEC_ELT (deduced_pack, j)))
23538	      return 0;
23539	}
23540      else if (oldelt && !template_args_equal (oldelt, elt))
23541	return 0;
23542    }
23543
23544  for (i = nargs; i--; )
23545    {
23546      tree elt = TREE_VEC_ELT (tempargs, i);
23547
23548      if (elt)
23549	TREE_VEC_ELT (targs, i) = elt;
23550    }
23551
23552  return 1;
23553}
23554
23555/* PARM is a template class (perhaps with unbound template
23556   parameters).  ARG is a fully instantiated type.  If ARG can be
23557   bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
23558   TARGS are as for unify.  */
23559
23560static tree
23561try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23562		       bool explain_p)
23563{
23564  tree copy_of_targs;
23565
23566  if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23567    return NULL_TREE;
23568  else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23569    /* Matches anything.  */;
23570  else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23571	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23572    return NULL_TREE;
23573
23574  /* We need to make a new template argument vector for the call to
23575     unify.  If we used TARGS, we'd clutter it up with the result of
23576     the attempted unification, even if this class didn't work out.
23577     We also don't want to commit ourselves to all the unifications
23578     we've already done, since unification is supposed to be done on
23579     an argument-by-argument basis.  In other words, consider the
23580     following pathological case:
23581
23582       template <int I, int J, int K>
23583       struct S {};
23584
23585       template <int I, int J>
23586       struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23587
23588       template <int I, int J, int K>
23589       void f(S<I, J, K>, S<I, I, I>);
23590
23591       void g() {
23592	 S<0, 0, 0> s0;
23593	 S<0, 1, 2> s2;
23594
23595	 f(s0, s2);
23596       }
23597
23598     Now, by the time we consider the unification involving `s2', we
23599     already know that we must have `f<0, 0, 0>'.  But, even though
23600     `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23601     because there are two ways to unify base classes of S<0, 1, 2>
23602     with S<I, I, I>.  If we kept the already deduced knowledge, we
23603     would reject the possibility I=1.  */
23604  copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
23605
23606  if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23607    {
23608      if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
23609	return NULL_TREE;
23610      return arg;
23611    }
23612
23613  /* If unification failed, we're done.  */
23614  if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
23615	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
23616    return NULL_TREE;
23617
23618  return arg;
23619}
23620
23621/* Given a template type PARM and a class type ARG, find the unique
23622   base type in ARG that is an instance of PARM.  We do not examine
23623   ARG itself; only its base-classes.  If there is not exactly one
23624   appropriate base class, return NULL_TREE.  PARM may be the type of
23625   a partial specialization, as well as a plain template type.  Used
23626   by unify.  */
23627
23628static enum template_base_result
23629get_template_base (tree tparms, tree targs, tree parm, tree arg,
23630		   bool explain_p, tree *result)
23631{
23632  tree rval = NULL_TREE;
23633  tree binfo;
23634
23635  gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23636
23637  binfo = TYPE_BINFO (complete_type (arg));
23638  if (!binfo)
23639    {
23640      /* The type could not be completed.  */
23641      *result = NULL_TREE;
23642      return tbr_incomplete_type;
23643    }
23644
23645  /* Walk in inheritance graph order.  The search order is not
23646     important, and this avoids multiple walks of virtual bases.  */
23647  for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23648    {
23649      tree r = try_class_unification (tparms, targs, parm,
23650				      BINFO_TYPE (binfo), explain_p);
23651
23652      if (r)
23653	{
23654	  /* If there is more than one satisfactory baseclass, then:
23655
23656	       [temp.deduct.call]
23657
23658	      If they yield more than one possible deduced A, the type
23659	      deduction fails.
23660
23661	     applies.  */
23662	  if (rval && !same_type_p (r, rval))
23663	    {
23664	      /* [temp.deduct.call]/4.3: If there is a class C that is a
23665		 (direct or indirect) base class of D and derived (directly or
23666		 indirectly) from a class B and that would be a valid deduced
23667		 A, the deduced A cannot be B or pointer to B, respectively. */
23668	      if (DERIVED_FROM_P (r, rval))
23669		/* Ignore r.  */
23670		continue;
23671	      else if (DERIVED_FROM_P (rval, r))
23672		/* Ignore rval.  */;
23673	      else
23674		{
23675		  *result = NULL_TREE;
23676		  return tbr_ambiguous_baseclass;
23677		}
23678	    }
23679
23680	  rval = r;
23681	}
23682    }
23683
23684  *result = rval;
23685  return tbr_success;
23686}
23687
23688/* Returns the level of DECL, which declares a template parameter.  */
23689
23690static int
23691template_decl_level (tree decl)
23692{
23693  switch (TREE_CODE (decl))
23694    {
23695    case TYPE_DECL:
23696    case TEMPLATE_DECL:
23697      return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23698
23699    case PARM_DECL:
23700      return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23701
23702    default:
23703      gcc_unreachable ();
23704    }
23705  return 0;
23706}
23707
23708/* Decide whether ARG can be unified with PARM, considering only the
23709   cv-qualifiers of each type, given STRICT as documented for unify.
23710   Returns nonzero iff the unification is OK on that basis.  */
23711
23712static int
23713check_cv_quals_for_unify (int strict, tree arg, tree parm)
23714{
23715  int arg_quals = cp_type_quals (arg);
23716  int parm_quals = cp_type_quals (parm);
23717
23718  if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23719      && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23720    {
23721      /*  Although a CVR qualifier is ignored when being applied to a
23722	  substituted template parameter ([8.3.2]/1 for example), that
23723	  does not allow us to unify "const T" with "int&" because both
23724	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23725	  It is ok when we're allowing additional CV qualifiers
23726	  at the outer level [14.8.2.1]/3,1st bullet.  */
23727      if ((TYPE_REF_P (arg)
23728	   || FUNC_OR_METHOD_TYPE_P (arg))
23729	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23730	return 0;
23731
23732      if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23733	  && (parm_quals & TYPE_QUAL_RESTRICT))
23734	return 0;
23735    }
23736
23737  if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23738      && (arg_quals & parm_quals) != parm_quals)
23739    return 0;
23740
23741  if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23742      && (parm_quals & arg_quals) != arg_quals)
23743    return 0;
23744
23745  return 1;
23746}
23747
23748/* Determines the LEVEL and INDEX for the template parameter PARM.  */
23749void
23750template_parm_level_and_index (tree parm, int* level, int* index)
23751{
23752  if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23753      || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23754      || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23755    {
23756      *index = TEMPLATE_TYPE_IDX (parm);
23757      *level = TEMPLATE_TYPE_LEVEL (parm);
23758    }
23759  else
23760    {
23761      *index = TEMPLATE_PARM_IDX (parm);
23762      *level = TEMPLATE_PARM_LEVEL (parm);
23763    }
23764}
23765
23766#define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
23767  do {									\
23768    if (unify (TP, TA, P, A, S, EP))					\
23769      return 1;								\
23770  } while (0)
23771
23772/* Unifies the remaining arguments in PACKED_ARGS with the pack
23773   expansion at the end of PACKED_PARMS. Returns 0 if the type
23774   deduction succeeds, 1 otherwise. STRICT is the same as in
23775   fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23776   function call argument list. We'll need to adjust the arguments to make them
23777   types. SUBR tells us if this is from a recursive call to
23778   type_unification_real, or for comparing two template argument
23779   lists. */
23780
23781static int
23782unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23783                      tree packed_args, unification_kind_t strict,
23784                      bool subr, bool explain_p)
23785{
23786  tree parm
23787    = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23788  tree pattern = PACK_EXPANSION_PATTERN (parm);
23789  tree pack, packs = NULL_TREE;
23790  int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23791
23792  /* Add in any args remembered from an earlier partial instantiation.  */
23793  targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23794  int levels = TMPL_ARGS_DEPTH (targs);
23795
23796  packed_args = expand_template_argument_pack (packed_args);
23797
23798  int len = TREE_VEC_LENGTH (packed_args);
23799
23800  /* Determine the parameter packs we will be deducing from the
23801     pattern, and record their current deductions.  */
23802  for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23803       pack; pack = TREE_CHAIN (pack))
23804    {
23805      tree parm_pack = TREE_VALUE (pack);
23806      int idx, level;
23807
23808      /* Only template parameter packs can be deduced, not e.g. function
23809	 parameter packs or __bases or __integer_pack.  */
23810      if (!TEMPLATE_PARM_P (parm_pack))
23811	continue;
23812
23813      /* Determine the index and level of this parameter pack.  */
23814      template_parm_level_and_index (parm_pack, &level, &idx);
23815      if (level < levels)
23816	continue;
23817
23818      /* Keep track of the parameter packs and their corresponding
23819         argument packs.  */
23820      packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23821      TREE_TYPE (packs) = make_tree_vec (len - start);
23822    }
23823
23824  /* Loop through all of the arguments that have not yet been
23825     unified and unify each with the pattern.  */
23826  for (i = start; i < len; i++)
23827    {
23828      tree parm;
23829      bool any_explicit = false;
23830      tree arg = TREE_VEC_ELT (packed_args, i);
23831
23832      /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23833	 or the element of its argument pack at the current index if
23834	 this argument was explicitly specified.  */
23835      for (pack = packs; pack; pack = TREE_CHAIN (pack))
23836        {
23837          int idx, level;
23838          tree arg, pargs;
23839          template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23840
23841          arg = NULL_TREE;
23842          if (TREE_VALUE (pack)
23843              && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23844              && (i - start < TREE_VEC_LENGTH (pargs)))
23845            {
23846              any_explicit = true;
23847              arg = TREE_VEC_ELT (pargs, i - start);
23848            }
23849          TMPL_ARG (targs, level, idx) = arg;
23850        }
23851
23852      /* If we had explicit template arguments, substitute them into the
23853	 pattern before deduction.  */
23854      if (any_explicit)
23855	{
23856	  /* Some arguments might still be unspecified or dependent.  */
23857	  bool dependent;
23858	  ++processing_template_decl;
23859	  dependent = any_dependent_template_arguments_p (targs);
23860	  if (!dependent)
23861	    --processing_template_decl;
23862	  parm = tsubst (pattern, targs,
23863			 explain_p ? tf_warning_or_error : tf_none,
23864			 NULL_TREE);
23865	  if (dependent)
23866	    --processing_template_decl;
23867	  if (parm == error_mark_node)
23868	    return 1;
23869	}
23870      else
23871	parm = pattern;
23872
23873      /* Unify the pattern with the current argument.  */
23874      if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23875			      explain_p))
23876	return 1;
23877
23878      /* For each parameter pack, collect the deduced value.  */
23879      for (pack = packs; pack; pack = TREE_CHAIN (pack))
23880        {
23881          int idx, level;
23882          template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23883
23884          TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
23885            TMPL_ARG (targs, level, idx);
23886        }
23887    }
23888
23889  /* Verify that the results of unification with the parameter packs
23890     produce results consistent with what we've seen before, and make
23891     the deduced argument packs available.  */
23892  for (pack = packs; pack; pack = TREE_CHAIN (pack))
23893    {
23894      tree old_pack = TREE_VALUE (pack);
23895      tree new_args = TREE_TYPE (pack);
23896      int i, len = TREE_VEC_LENGTH (new_args);
23897      int idx, level;
23898      bool nondeduced_p = false;
23899
23900      /* By default keep the original deduced argument pack.
23901	 If necessary, more specific code is going to update the
23902	 resulting deduced argument later down in this function.  */
23903      template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23904      TMPL_ARG (targs, level, idx) = old_pack;
23905
23906      /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23907	 actually deduce anything.  */
23908      for (i = 0; i < len && !nondeduced_p; ++i)
23909	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23910	  nondeduced_p = true;
23911      if (nondeduced_p)
23912	continue;
23913
23914      if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23915        {
23916          /* If we had fewer function args than explicit template args,
23917             just use the explicits.  */
23918          tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23919          int explicit_len = TREE_VEC_LENGTH (explicit_args);
23920          if (len < explicit_len)
23921            new_args = explicit_args;
23922        }
23923
23924      if (!old_pack)
23925        {
23926          tree result;
23927          /* Build the deduced *_ARGUMENT_PACK.  */
23928          if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
23929            {
23930              result = make_node (NONTYPE_ARGUMENT_PACK);
23931              TREE_CONSTANT (result) = 1;
23932            }
23933          else
23934	    result = cxx_make_type (TYPE_ARGUMENT_PACK);
23935
23936          SET_ARGUMENT_PACK_ARGS (result, new_args);
23937
23938          /* Note the deduced argument packs for this parameter
23939             pack.  */
23940          TMPL_ARG (targs, level, idx) = result;
23941        }
23942      else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
23943               && (ARGUMENT_PACK_ARGS (old_pack)
23944                   == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
23945        {
23946          /* We only had the explicitly-provided arguments before, but
23947             now we have a complete set of arguments.  */
23948          tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23949
23950          SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
23951          ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
23952          ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
23953        }
23954      else
23955	{
23956	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23957	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23958	  temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
23959	  /* During template argument deduction for the aggregate deduction
23960	     candidate, the number of elements in a trailing parameter pack
23961	     is only deduced from the number of remaining function
23962	     arguments if it is not otherwise deduced.  */
23963	  if (cxx_dialect >= cxx20
23964	      && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
23965	      /* FIXME This isn't set properly for partial instantiations.  */
23966	      && TPARMS_PRIMARY_TEMPLATE (tparms)
23967	      && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
23968	    TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
23969	  if (!comp_template_args (old_args, new_args,
23970				   &bad_old_arg, &bad_new_arg))
23971	    /* Inconsistent unification of this parameter pack.  */
23972	    return unify_parameter_pack_inconsistent (explain_p,
23973						      bad_old_arg,
23974						      bad_new_arg);
23975	}
23976    }
23977
23978  return unify_success (explain_p);
23979}
23980
23981/* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
23982   INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
23983   parameters and return value are as for unify.  */
23984
23985static int
23986unify_array_domain (tree tparms, tree targs,
23987		    tree parm_dom, tree arg_dom,
23988		    bool explain_p)
23989{
23990  tree parm_max;
23991  tree arg_max;
23992  bool parm_cst;
23993  bool arg_cst;
23994
23995  /* Our representation of array types uses "N - 1" as the
23996     TYPE_MAX_VALUE for an array with "N" elements, if "N" is
23997     not an integer constant.  We cannot unify arbitrarily
23998     complex expressions, so we eliminate the MINUS_EXPRs
23999     here.  */
24000  parm_max = TYPE_MAX_VALUE (parm_dom);
24001  parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24002  if (!parm_cst)
24003    {
24004      gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24005      parm_max = TREE_OPERAND (parm_max, 0);
24006    }
24007  arg_max = TYPE_MAX_VALUE (arg_dom);
24008  arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24009  if (!arg_cst)
24010    {
24011      /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24012	 trying to unify the type of a variable with the type
24013	 of a template parameter.  For example:
24014
24015	   template <unsigned int N>
24016	   void f (char (&) [N]);
24017	   int g();
24018	   void h(int i) {
24019	     char a[g(i)];
24020	     f(a);
24021	   }
24022
24023	 Here, the type of the ARG will be "int [g(i)]", and
24024	 may be a SAVE_EXPR, etc.  */
24025      if (TREE_CODE (arg_max) != MINUS_EXPR)
24026	return unify_vla_arg (explain_p, arg_dom);
24027      arg_max = TREE_OPERAND (arg_max, 0);
24028    }
24029
24030  /* If only one of the bounds used a MINUS_EXPR, compensate
24031     by adding one to the other bound.  */
24032  if (parm_cst && !arg_cst)
24033    parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24034				integer_type_node,
24035				parm_max,
24036				integer_one_node);
24037  else if (arg_cst && !parm_cst)
24038    arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24039			       integer_type_node,
24040			       arg_max,
24041			       integer_one_node);
24042
24043  return unify (tparms, targs, parm_max, arg_max,
24044		UNIFY_ALLOW_INTEGER, explain_p);
24045}
24046
24047/* Returns whether T, a P or A in unify, is a type, template or expression.  */
24048
24049enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24050
24051static pa_kind_t
24052pa_kind (tree t)
24053{
24054  if (PACK_EXPANSION_P (t))
24055    t = PACK_EXPANSION_PATTERN (t);
24056  if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24057      || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24058      || DECL_TYPE_TEMPLATE_P (t))
24059    return pa_tmpl;
24060  else if (TYPE_P (t))
24061    return pa_type;
24062  else
24063    return pa_expr;
24064}
24065
24066/* Deduce the value of template parameters.  TPARMS is the (innermost)
24067   set of template parameters to a template.  TARGS is the bindings
24068   for those template parameters, as determined thus far; TARGS may
24069   include template arguments for outer levels of template parameters
24070   as well.  PARM is a parameter to a template function, or a
24071   subcomponent of that parameter; ARG is the corresponding argument.
24072   This function attempts to match PARM with ARG in a manner
24073   consistent with the existing assignments in TARGS.  If more values
24074   are deduced, then TARGS is updated.
24075
24076   Returns 0 if the type deduction succeeds, 1 otherwise.  The
24077   parameter STRICT is a bitwise or of the following flags:
24078
24079     UNIFY_ALLOW_NONE:
24080       Require an exact match between PARM and ARG.
24081     UNIFY_ALLOW_MORE_CV_QUAL:
24082       Allow the deduced ARG to be more cv-qualified (by qualification
24083       conversion) than ARG.
24084     UNIFY_ALLOW_LESS_CV_QUAL:
24085       Allow the deduced ARG to be less cv-qualified than ARG.
24086     UNIFY_ALLOW_DERIVED:
24087       Allow the deduced ARG to be a template base class of ARG,
24088       or a pointer to a template base class of the type pointed to by
24089       ARG.
24090     UNIFY_ALLOW_INTEGER:
24091       Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
24092       case for more information.
24093     UNIFY_ALLOW_OUTER_LEVEL:
24094       This is the outermost level of a deduction. Used to determine validity
24095       of qualification conversions. A valid qualification conversion must
24096       have const qualified pointers leading up to the inner type which
24097       requires additional CV quals, except at the outer level, where const
24098       is not required [conv.qual]. It would be normal to set this flag in
24099       addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24100     UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24101       This is the outermost level of a deduction, and PARM can be more CV
24102       qualified at this point.
24103     UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24104       This is the outermost level of a deduction, and PARM can be less CV
24105       qualified at this point.  */
24106
24107static int
24108unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24109       bool explain_p)
24110{
24111  int idx;
24112  tree targ;
24113  tree tparm;
24114  int strict_in = strict;
24115  tsubst_flags_t complain = (explain_p
24116			     ? tf_warning_or_error
24117			     : tf_none);
24118
24119  /* I don't think this will do the right thing with respect to types.
24120     But the only case I've seen it in so far has been array bounds, where
24121     signedness is the only information lost, and I think that will be
24122     okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24123     finish_id_expression_1, and are also OK.  */
24124  while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24125    parm = TREE_OPERAND (parm, 0);
24126
24127  if (arg == error_mark_node)
24128    return unify_invalid (explain_p);
24129  if (arg == unknown_type_node
24130      || arg == init_list_type_node)
24131    /* We can't deduce anything from this, but we might get all the
24132       template args from other function args.  */
24133    return unify_success (explain_p);
24134
24135  if (parm == any_targ_node || arg == any_targ_node)
24136    return unify_success (explain_p);
24137
24138  /* If PARM uses template parameters, then we can't bail out here,
24139     even if ARG == PARM, since we won't record unifications for the
24140     template parameters.  We might need them if we're trying to
24141     figure out which of two things is more specialized.  */
24142  if (arg == parm && !uses_template_parms (parm))
24143    return unify_success (explain_p);
24144
24145  /* Handle init lists early, so the rest of the function can assume
24146     we're dealing with a type. */
24147  if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24148    {
24149      tree elttype;
24150      tree orig_parm = parm;
24151
24152      if (!is_std_init_list (parm)
24153	  && TREE_CODE (parm) != ARRAY_TYPE)
24154	/* We can only deduce from an initializer list argument if the
24155	   parameter is std::initializer_list or an array; otherwise this
24156	   is a non-deduced context. */
24157	return unify_success (explain_p);
24158
24159      if (TREE_CODE (parm) == ARRAY_TYPE)
24160	elttype = TREE_TYPE (parm);
24161      else
24162	{
24163	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24164	  /* Deduction is defined in terms of a single type, so just punt
24165	     on the (bizarre) std::initializer_list<T...>.  */
24166	  if (PACK_EXPANSION_P (elttype))
24167	    return unify_success (explain_p);
24168	}
24169
24170      if (strict != DEDUCE_EXACT
24171	  && TYPE_P (elttype)
24172	  && !uses_deducible_template_parms (elttype))
24173	/* If ELTTYPE has no deducible template parms, skip deduction from
24174	   the list elements.  */;
24175      else
24176	for (auto &e: CONSTRUCTOR_ELTS (arg))
24177	  {
24178	    tree elt = e.value;
24179	    int elt_strict = strict;
24180
24181	    if (elt == error_mark_node)
24182	      return unify_invalid (explain_p);
24183
24184	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24185	      {
24186		tree type = TREE_TYPE (elt);
24187		if (type == error_mark_node)
24188		  return unify_invalid (explain_p);
24189		/* It should only be possible to get here for a call.  */
24190		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24191		elt_strict |= maybe_adjust_types_for_deduction
24192		  (tparms, DEDUCE_CALL, &elttype, &type, elt);
24193		elt = type;
24194	      }
24195
24196	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24197				   explain_p);
24198	}
24199
24200      if (TREE_CODE (parm) == ARRAY_TYPE
24201	  && deducible_array_bound (TYPE_DOMAIN (parm)))
24202	{
24203	  /* Also deduce from the length of the initializer list.  */
24204	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
24205	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24206	  if (idx == error_mark_node)
24207	    return unify_invalid (explain_p);
24208	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24209				     idx, explain_p);
24210	}
24211
24212      /* If the std::initializer_list<T> deduction worked, replace the
24213	 deduced A with std::initializer_list<A>.  */
24214      if (orig_parm != parm)
24215	{
24216	  idx = TEMPLATE_TYPE_IDX (orig_parm);
24217	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24218	  targ = listify (targ);
24219	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24220	}
24221      return unify_success (explain_p);
24222    }
24223
24224  /* If parm and arg aren't the same kind of thing (template, type, or
24225     expression), fail early.  */
24226  if (pa_kind (parm) != pa_kind (arg))
24227    return unify_invalid (explain_p);
24228
24229  /* Immediately reject some pairs that won't unify because of
24230     cv-qualification mismatches.  */
24231  if (TREE_CODE (arg) == TREE_CODE (parm)
24232      && TYPE_P (arg)
24233      /* It is the elements of the array which hold the cv quals of an array
24234	 type, and the elements might be template type parms. We'll check
24235	 when we recurse.  */
24236      && TREE_CODE (arg) != ARRAY_TYPE
24237      /* We check the cv-qualifiers when unifying with template type
24238	 parameters below.  We want to allow ARG `const T' to unify with
24239	 PARM `T' for example, when computing which of two templates
24240	 is more specialized, for example.  */
24241      && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24242      && !check_cv_quals_for_unify (strict_in, arg, parm))
24243    return unify_cv_qual_mismatch (explain_p, parm, arg);
24244
24245  if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24246      && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
24247    strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24248  strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24249  strict &= ~UNIFY_ALLOW_DERIVED;
24250  strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24251  strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24252
24253  switch (TREE_CODE (parm))
24254    {
24255    case TYPENAME_TYPE:
24256    case SCOPE_REF:
24257    case UNBOUND_CLASS_TEMPLATE:
24258      /* In a type which contains a nested-name-specifier, template
24259	 argument values cannot be deduced for template parameters used
24260	 within the nested-name-specifier.  */
24261      return unify_success (explain_p);
24262
24263    case TEMPLATE_TYPE_PARM:
24264    case TEMPLATE_TEMPLATE_PARM:
24265    case BOUND_TEMPLATE_TEMPLATE_PARM:
24266      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24267      if (error_operand_p (tparm))
24268	return unify_invalid (explain_p);
24269
24270      if (TEMPLATE_TYPE_LEVEL (parm)
24271	  != template_decl_level (tparm))
24272	/* The PARM is not one we're trying to unify.  Just check
24273	   to see if it matches ARG.  */
24274	{
24275	  if (TREE_CODE (arg) == TREE_CODE (parm)
24276	      && (is_auto (parm) ? is_auto (arg)
24277		  : same_type_p (parm, arg)))
24278	    return unify_success (explain_p);
24279	  else
24280	    return unify_type_mismatch (explain_p, parm, arg);
24281	}
24282      idx = TEMPLATE_TYPE_IDX (parm);
24283      targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24284      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24285      if (error_operand_p (tparm))
24286	return unify_invalid (explain_p);
24287
24288      /* Check for mixed types and values.  */
24289      if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24290	   && TREE_CODE (tparm) != TYPE_DECL)
24291	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24292	      && TREE_CODE (tparm) != TEMPLATE_DECL))
24293	gcc_unreachable ();
24294
24295      if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24296	{
24297	  if ((strict_in & UNIFY_ALLOW_DERIVED)
24298	      && CLASS_TYPE_P (arg))
24299	    {
24300	      /* First try to match ARG directly.  */
24301	      tree t = try_class_unification (tparms, targs, parm, arg,
24302					      explain_p);
24303	      if (!t)
24304		{
24305		  /* Otherwise, look for a suitable base of ARG, as below.  */
24306		  enum template_base_result r;
24307		  r = get_template_base (tparms, targs, parm, arg,
24308					 explain_p, &t);
24309		  if (!t)
24310		    return unify_no_common_base (explain_p, r, parm, arg);
24311		  arg = t;
24312		}
24313	    }
24314	  /* ARG must be constructed from a template class or a template
24315	     template parameter.  */
24316	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24317		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24318	    return unify_template_deduction_failure (explain_p, parm, arg);
24319
24320	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
24321	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24322	    return 1;
24323
24324	  arg = TYPE_TI_TEMPLATE (arg);
24325	  if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24326	    /* If the template is a template template parameter, use the
24327	       TEMPLATE_TEMPLATE_PARM for matching.  */
24328	    arg = TREE_TYPE (arg);
24329
24330	  /* Fall through to deduce template name.  */
24331	}
24332
24333      if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24334	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24335	{
24336	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
24337
24338	  /* Simple cases: Value already set, does match or doesn't.  */
24339	  if (targ != NULL_TREE && template_args_equal (targ, arg))
24340	    return unify_success (explain_p);
24341	  else if (targ)
24342	    return unify_inconsistency (explain_p, parm, targ, arg);
24343	}
24344      else
24345	{
24346	  /* If PARM is `const T' and ARG is only `int', we don't have
24347	     a match unless we are allowing additional qualification.
24348	     If ARG is `const int' and PARM is just `T' that's OK;
24349	     that binds `const int' to `T'.  */
24350	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24351					 arg, parm))
24352	    return unify_cv_qual_mismatch (explain_p, parm, arg);
24353
24354	  /* Consider the case where ARG is `const volatile int' and
24355	     PARM is `const T'.  Then, T should be `volatile int'.  */
24356	  arg = cp_build_qualified_type_real
24357	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24358	  if (arg == error_mark_node)
24359	    return unify_invalid (explain_p);
24360
24361	  /* Simple cases: Value already set, does match or doesn't.  */
24362	  if (targ != NULL_TREE && same_type_p (targ, arg))
24363	    return unify_success (explain_p);
24364	  else if (targ)
24365	    return unify_inconsistency (explain_p, parm, targ, arg);
24366
24367	  /* Make sure that ARG is not a variable-sized array.  (Note
24368	     that were talking about variable-sized arrays (like
24369	     `int[n]'), rather than arrays of unknown size (like
24370	     `int[]').)  We'll get very confused by such a type since
24371	     the bound of the array is not constant, and therefore
24372	     not mangleable.  Besides, such types are not allowed in
24373	     ISO C++, so we can do as we please here.  We do allow
24374	     them for 'auto' deduction, since that isn't ABI-exposed.  */
24375	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24376	    return unify_vla_arg (explain_p, arg);
24377
24378	  /* Strip typedefs as in convert_template_argument.  */
24379	  arg = canonicalize_type_argument (arg, tf_none);
24380	}
24381
24382      /* If ARG is a parameter pack or an expansion, we cannot unify
24383	 against it unless PARM is also a parameter pack.  */
24384      if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24385	  && !template_parameter_pack_p (parm))
24386	return unify_parameter_pack_mismatch (explain_p, parm, arg);
24387
24388      /* If the argument deduction results is a METHOD_TYPE,
24389         then there is a problem.
24390         METHOD_TYPE doesn't map to any real C++ type the result of
24391	 the deduction cannot be of that type.  */
24392      if (TREE_CODE (arg) == METHOD_TYPE)
24393	return unify_method_type_error (explain_p, arg);
24394
24395      TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24396      return unify_success (explain_p);
24397
24398    case TEMPLATE_PARM_INDEX:
24399      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24400      if (error_operand_p (tparm))
24401	return unify_invalid (explain_p);
24402
24403      if (TEMPLATE_PARM_LEVEL (parm)
24404	  != template_decl_level (tparm))
24405	{
24406	  /* The PARM is not one we're trying to unify.  Just check
24407	     to see if it matches ARG.  */
24408	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24409			 && cp_tree_equal (parm, arg));
24410	  if (result)
24411	    unify_expression_unequal (explain_p, parm, arg);
24412	  return result;
24413	}
24414
24415      idx = TEMPLATE_PARM_IDX (parm);
24416      targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24417
24418      if (targ)
24419	{
24420	  if ((strict & UNIFY_ALLOW_INTEGER)
24421	      && TREE_TYPE (targ) && TREE_TYPE (arg)
24422	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24423	    /* We're deducing from an array bound, the type doesn't matter.  */
24424	    arg = fold_convert (TREE_TYPE (targ), arg);
24425	  int x = !cp_tree_equal (targ, arg);
24426	  if (x)
24427	    unify_inconsistency (explain_p, parm, targ, arg);
24428	  return x;
24429	}
24430
24431      /* [temp.deduct.type] If, in the declaration of a function template
24432	 with a non-type template-parameter, the non-type
24433	 template-parameter is used in an expression in the function
24434	 parameter-list and, if the corresponding template-argument is
24435	 deduced, the template-argument type shall match the type of the
24436	 template-parameter exactly, except that a template-argument
24437	 deduced from an array bound may be of any integral type.
24438	 The non-type parameter might use already deduced type parameters.  */
24439      tparm = TREE_TYPE (parm);
24440      if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24441	/* We don't have enough levels of args to do any substitution.  This
24442	   can happen in the context of -fnew-ttp-matching.  */;
24443      else
24444	{
24445	  ++processing_template_decl;
24446	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24447	  --processing_template_decl;
24448
24449	  if (tree a = type_uses_auto (tparm))
24450	    {
24451	      tparm = do_auto_deduction (tparm, arg, a,
24452					 complain, adc_unify, targs);
24453	      if (tparm == error_mark_node)
24454		return 1;
24455	    }
24456	}
24457
24458      if (!TREE_TYPE (arg)
24459	  || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24460	/* Template-parameter dependent expression.  Just accept it for now.
24461	   It will later be processed in convert_template_argument.  */
24462	;
24463      else if (same_type_ignoring_top_level_qualifiers_p
24464	       (non_reference (TREE_TYPE (arg)),
24465		non_reference (tparm)))
24466	/* OK.  Ignore top-level quals here because a class-type template
24467	   parameter object is const.  */;
24468      else if ((strict & UNIFY_ALLOW_INTEGER)
24469	       && CP_INTEGRAL_TYPE_P (tparm))
24470	/* Convert the ARG to the type of PARM; the deduced non-type
24471	   template argument must exactly match the types of the
24472	   corresponding parameter.  */
24473	arg = fold (build_nop (tparm, arg));
24474      else if (uses_template_parms (tparm))
24475	{
24476	  /* We haven't deduced the type of this parameter yet.  */
24477	  if (cxx_dialect >= cxx17
24478	      /* We deduce from array bounds in try_array_deduction.  */
24479	      && !(strict & UNIFY_ALLOW_INTEGER)
24480	      && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24481	    {
24482	      /* Deduce it from the non-type argument.  As above, ignore
24483		 top-level quals here too.  */
24484	      tree atype = cv_unqualified (TREE_TYPE (arg));
24485	      RECUR_AND_CHECK_FAILURE (tparms, targs,
24486				       tparm, atype,
24487				       UNIFY_ALLOW_NONE, explain_p);
24488	      /* Now check whether the type of this parameter is still
24489		 dependent, and give up if so.  */
24490	      ++processing_template_decl;
24491	      tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24492	      --processing_template_decl;
24493	      if (uses_template_parms (tparm))
24494		return unify_success (explain_p);
24495	    }
24496	  else
24497	    /* Try again later.  */
24498	    return unify_success (explain_p);
24499	}
24500      else
24501	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24502
24503      /* If ARG is a parameter pack or an expansion, we cannot unify
24504	 against it unless PARM is also a parameter pack.  */
24505      if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24506	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24507	return unify_parameter_pack_mismatch (explain_p, parm, arg);
24508
24509      {
24510	bool removed_attr = false;
24511	arg = strip_typedefs_expr (arg, &removed_attr);
24512      }
24513      TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24514      return unify_success (explain_p);
24515
24516    case PTRMEM_CST:
24517     {
24518	/* A pointer-to-member constant can be unified only with
24519	 another constant.  */
24520      if (TREE_CODE (arg) != PTRMEM_CST)
24521	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24522
24523      /* Just unify the class member. It would be useless (and possibly
24524	 wrong, depending on the strict flags) to unify also
24525	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24526	 arg refer to the same variable, even if through different
24527	 classes. For instance:
24528
24529	 struct A { int x; };
24530	 struct B : A { };
24531
24532	 Unification of &A::x and &B::x must succeed.  */
24533      return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24534		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
24535     }
24536
24537    case POINTER_TYPE:
24538      {
24539	if (!TYPE_PTR_P (arg))
24540	  return unify_type_mismatch (explain_p, parm, arg);
24541
24542	/* [temp.deduct.call]
24543
24544	   A can be another pointer or pointer to member type that can
24545	   be converted to the deduced A via a qualification
24546	   conversion (_conv.qual_).
24547
24548	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24549	   This will allow for additional cv-qualification of the
24550	   pointed-to types if appropriate.  */
24551
24552	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24553	  /* The derived-to-base conversion only persists through one
24554	     level of pointers.  */
24555	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24556
24557	return unify (tparms, targs, TREE_TYPE (parm),
24558		      TREE_TYPE (arg), strict, explain_p);
24559      }
24560
24561    case REFERENCE_TYPE:
24562      if (!TYPE_REF_P (arg))
24563	return unify_type_mismatch (explain_p, parm, arg);
24564      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24565		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24566
24567    case ARRAY_TYPE:
24568      if (TREE_CODE (arg) != ARRAY_TYPE)
24569	return unify_type_mismatch (explain_p, parm, arg);
24570      if ((TYPE_DOMAIN (parm) == NULL_TREE)
24571	  != (TYPE_DOMAIN (arg) == NULL_TREE))
24572	return unify_type_mismatch (explain_p, parm, arg);
24573      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24574			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24575      if (TYPE_DOMAIN (parm) != NULL_TREE)
24576	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24577				   TYPE_DOMAIN (arg), explain_p);
24578      return unify_success (explain_p);
24579
24580    case REAL_TYPE:
24581    case COMPLEX_TYPE:
24582    case VECTOR_TYPE:
24583    case INTEGER_TYPE:
24584    case BOOLEAN_TYPE:
24585    case ENUMERAL_TYPE:
24586    case VOID_TYPE:
24587    case OPAQUE_TYPE:
24588    case NULLPTR_TYPE:
24589      if (TREE_CODE (arg) != TREE_CODE (parm))
24590	return unify_type_mismatch (explain_p, parm, arg);
24591
24592      /* We have already checked cv-qualification at the top of the
24593	 function.  */
24594      if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24595	return unify_type_mismatch (explain_p, parm, arg);
24596
24597      /* As far as unification is concerned, this wins.	 Later checks
24598	 will invalidate it if necessary.  */
24599      return unify_success (explain_p);
24600
24601      /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
24602      /* Type INTEGER_CST can come from ordinary constant template args.  */
24603    case INTEGER_CST:
24604      while (CONVERT_EXPR_P (arg))
24605	arg = TREE_OPERAND (arg, 0);
24606
24607      if (TREE_CODE (arg) != INTEGER_CST)
24608	return unify_template_argument_mismatch (explain_p, parm, arg);
24609      return (tree_int_cst_equal (parm, arg)
24610	      ? unify_success (explain_p)
24611	      : unify_template_argument_mismatch (explain_p, parm, arg));
24612
24613    case TREE_VEC:
24614      {
24615	int i, len, argslen;
24616	int parm_variadic_p = 0;
24617
24618	if (TREE_CODE (arg) != TREE_VEC)
24619	  return unify_template_argument_mismatch (explain_p, parm, arg);
24620
24621	len = TREE_VEC_LENGTH (parm);
24622	argslen = TREE_VEC_LENGTH (arg);
24623
24624	/* Check for pack expansions in the parameters.  */
24625	for (i = 0; i < len; ++i)
24626	  {
24627	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24628	      {
24629		if (i == len - 1)
24630		  /* We can unify against something with a trailing
24631		     parameter pack.  */
24632		  parm_variadic_p = 1;
24633		else
24634		  /* [temp.deduct.type]/9: If the template argument list of
24635		     P contains a pack expansion that is not the last
24636		     template argument, the entire template argument list
24637		     is a non-deduced context.  */
24638		  return unify_success (explain_p);
24639	      }
24640	  }
24641
24642        /* If we don't have enough arguments to satisfy the parameters
24643           (not counting the pack expression at the end), or we have
24644           too many arguments for a parameter list that doesn't end in
24645           a pack expression, we can't unify.  */
24646	if (parm_variadic_p
24647	    ? argslen < len - parm_variadic_p
24648	    : argslen != len)
24649	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24650
24651	/* Unify all of the parameters that precede the (optional)
24652	   pack expression.  */
24653	for (i = 0; i < len - parm_variadic_p; ++i)
24654	  {
24655	    RECUR_AND_CHECK_FAILURE (tparms, targs,
24656				     TREE_VEC_ELT (parm, i),
24657				     TREE_VEC_ELT (arg, i),
24658				     UNIFY_ALLOW_NONE, explain_p);
24659	  }
24660	if (parm_variadic_p)
24661	  return unify_pack_expansion (tparms, targs, parm, arg,
24662				       DEDUCE_EXACT,
24663				       /*subr=*/true, explain_p);
24664	return unify_success (explain_p);
24665      }
24666
24667    case RECORD_TYPE:
24668    case UNION_TYPE:
24669      if (TREE_CODE (arg) != TREE_CODE (parm))
24670	return unify_type_mismatch (explain_p, parm, arg);
24671
24672      if (TYPE_PTRMEMFUNC_P (parm))
24673	{
24674	  if (!TYPE_PTRMEMFUNC_P (arg))
24675	    return unify_type_mismatch (explain_p, parm, arg);
24676
24677	  return unify (tparms, targs,
24678			TYPE_PTRMEMFUNC_FN_TYPE (parm),
24679			TYPE_PTRMEMFUNC_FN_TYPE (arg),
24680			strict, explain_p);
24681	}
24682      else if (TYPE_PTRMEMFUNC_P (arg))
24683	return unify_type_mismatch (explain_p, parm, arg);
24684
24685      if (CLASSTYPE_TEMPLATE_INFO (parm))
24686	{
24687	  tree t = NULL_TREE;
24688
24689	  if (strict_in & UNIFY_ALLOW_DERIVED)
24690	    {
24691	      /* First, we try to unify the PARM and ARG directly.  */
24692	      t = try_class_unification (tparms, targs,
24693					 parm, arg, explain_p);
24694
24695	      if (!t)
24696		{
24697		  /* Fallback to the special case allowed in
24698		     [temp.deduct.call]:
24699
24700		       If P is a class, and P has the form
24701		       template-id, then A can be a derived class of
24702		       the deduced A.  Likewise, if P is a pointer to
24703		       a class of the form template-id, A can be a
24704		       pointer to a derived class pointed to by the
24705		       deduced A.  */
24706		  enum template_base_result r;
24707		  r = get_template_base (tparms, targs, parm, arg,
24708					 explain_p, &t);
24709
24710		  if (!t)
24711		    {
24712		      /* Don't give the derived diagnostic if we're
24713			 already dealing with the same template.  */
24714		      bool same_template
24715			= (CLASSTYPE_TEMPLATE_INFO (arg)
24716			   && (CLASSTYPE_TI_TEMPLATE (parm)
24717			       == CLASSTYPE_TI_TEMPLATE (arg)));
24718		      return unify_no_common_base (explain_p && !same_template,
24719						   r, parm, arg);
24720		    }
24721		}
24722	    }
24723	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
24724		   && (CLASSTYPE_TI_TEMPLATE (parm)
24725		       == CLASSTYPE_TI_TEMPLATE (arg)))
24726	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
24727	       Then, we should unify `int' and `U'.  */
24728	    t = arg;
24729	  else
24730	    /* There's no chance of unification succeeding.  */
24731	    return unify_type_mismatch (explain_p, parm, arg);
24732
24733	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24734			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
24735	}
24736      else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24737	return unify_type_mismatch (explain_p, parm, arg);
24738      return unify_success (explain_p);
24739
24740    case METHOD_TYPE:
24741    case FUNCTION_TYPE:
24742      {
24743	unsigned int nargs;
24744	tree *args;
24745	tree a;
24746	unsigned int i;
24747
24748	if (TREE_CODE (arg) != TREE_CODE (parm))
24749	  return unify_type_mismatch (explain_p, parm, arg);
24750
24751	/* CV qualifications for methods can never be deduced, they must
24752	   match exactly.  We need to check them explicitly here,
24753	   because type_unification_real treats them as any other
24754	   cv-qualified parameter.  */
24755	if (TREE_CODE (parm) == METHOD_TYPE
24756	    && (!check_cv_quals_for_unify
24757		(UNIFY_ALLOW_NONE,
24758		 class_of_this_parm (arg),
24759		 class_of_this_parm (parm))))
24760	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24761	if (TREE_CODE (arg) == FUNCTION_TYPE
24762	    && type_memfn_quals (parm) != type_memfn_quals (arg))
24763	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24764	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24765	  return unify_type_mismatch (explain_p, parm, arg);
24766
24767	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24768				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24769
24770	nargs = list_length (TYPE_ARG_TYPES (arg));
24771	args = XALLOCAVEC (tree, nargs);
24772	for (a = TYPE_ARG_TYPES (arg), i = 0;
24773	     a != NULL_TREE && a != void_list_node;
24774	     a = TREE_CHAIN (a), ++i)
24775	  args[i] = TREE_VALUE (a);
24776	nargs = i;
24777
24778	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24779				   args, nargs, 1, DEDUCE_EXACT,
24780				   NULL, explain_p))
24781	  return 1;
24782
24783	if (flag_noexcept_type)
24784	  {
24785	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24786	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24787	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24788	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24789	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24790		&& uses_template_parms (TREE_PURPOSE (pspec)))
24791	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24792				       TREE_PURPOSE (aspec),
24793				       UNIFY_ALLOW_NONE, explain_p);
24794	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
24795	      return unify_type_mismatch (explain_p, parm, arg);
24796	  }
24797
24798	return 0;
24799      }
24800
24801    case OFFSET_TYPE:
24802      /* Unify a pointer to member with a pointer to member function, which
24803	 deduces the type of the member as a function type. */
24804      if (TYPE_PTRMEMFUNC_P (arg))
24805	{
24806	  /* Check top-level cv qualifiers */
24807	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24808	    return unify_cv_qual_mismatch (explain_p, parm, arg);
24809
24810	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24811				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24812				   UNIFY_ALLOW_NONE, explain_p);
24813
24814	  /* Determine the type of the function we are unifying against. */
24815	  tree fntype = static_fn_type (arg);
24816
24817	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24818	}
24819
24820      if (TREE_CODE (arg) != OFFSET_TYPE)
24821	return unify_type_mismatch (explain_p, parm, arg);
24822      RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24823			       TYPE_OFFSET_BASETYPE (arg),
24824			       UNIFY_ALLOW_NONE, explain_p);
24825      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24826		    strict, explain_p);
24827
24828    case CONST_DECL:
24829      if (DECL_TEMPLATE_PARM_P (parm))
24830	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
24831      if (arg != scalar_constant_value (parm))
24832	return unify_template_argument_mismatch (explain_p, parm, arg);
24833      return unify_success (explain_p);
24834
24835    case FIELD_DECL:
24836    case TEMPLATE_DECL:
24837      /* Matched cases are handled by the ARG == PARM test above.  */
24838      return unify_template_argument_mismatch (explain_p, parm, arg);
24839
24840    case VAR_DECL:
24841      /* We might get a variable as a non-type template argument in parm if the
24842	 corresponding parameter is type-dependent.  Make any necessary
24843	 adjustments based on whether arg is a reference.  */
24844      if (CONSTANT_CLASS_P (arg))
24845	parm = fold_non_dependent_expr (parm, complain);
24846      else if (REFERENCE_REF_P (arg))
24847	{
24848	  tree sub = TREE_OPERAND (arg, 0);
24849	  STRIP_NOPS (sub);
24850	  if (TREE_CODE (sub) == ADDR_EXPR)
24851	    arg = TREE_OPERAND (sub, 0);
24852	}
24853      /* Now use the normal expression code to check whether they match.  */
24854      goto expr;
24855
24856    case TYPE_ARGUMENT_PACK:
24857    case NONTYPE_ARGUMENT_PACK:
24858      return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24859		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24860
24861    case TYPEOF_TYPE:
24862    case DECLTYPE_TYPE:
24863    case UNDERLYING_TYPE:
24864      /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24865	 or UNDERLYING_TYPE nodes.  */
24866      return unify_success (explain_p);
24867
24868    case ERROR_MARK:
24869      /* Unification fails if we hit an error node.  */
24870      return unify_invalid (explain_p);
24871
24872    case INDIRECT_REF:
24873      if (REFERENCE_REF_P (parm))
24874	{
24875	  bool pexp = PACK_EXPANSION_P (arg);
24876	  if (pexp)
24877	    arg = PACK_EXPANSION_PATTERN (arg);
24878	  if (REFERENCE_REF_P (arg))
24879	    arg = TREE_OPERAND (arg, 0);
24880	  if (pexp)
24881	    arg = make_pack_expansion (arg, complain);
24882	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
24883			strict, explain_p);
24884	}
24885      /* FALLTHRU */
24886
24887    default:
24888      /* An unresolved overload is a nondeduced context.  */
24889      if (is_overloaded_fn (parm) || type_unknown_p (parm))
24890	return unify_success (explain_p);
24891      gcc_assert (EXPR_P (parm)
24892		  || TREE_CODE (parm) == CONSTRUCTOR
24893		  || TREE_CODE (parm) == TRAIT_EXPR);
24894    expr:
24895      /* We must be looking at an expression.  This can happen with
24896	 something like:
24897
24898	   template <int I>
24899	   void foo(S<I>, S<I + 2>);
24900
24901	 or
24902
24903	   template<typename T>
24904	   void foo(A<T, T{}>);
24905
24906	 This is a "non-deduced context":
24907
24908	   [deduct.type]
24909
24910	   The non-deduced contexts are:
24911
24912	   --A non-type template argument or an array bound in which
24913	     a subexpression references a template parameter.
24914
24915	 In these cases, we assume deduction succeeded, but don't
24916	 actually infer any unifications.  */
24917
24918      if (!uses_template_parms (parm)
24919	  && !template_args_equal (parm, arg))
24920	return unify_expression_unequal (explain_p, parm, arg);
24921      else
24922	return unify_success (explain_p);
24923    }
24924}
24925#undef RECUR_AND_CHECK_FAILURE
24926
24927/* Note that DECL can be defined in this translation unit, if
24928   required.  */
24929
24930static void
24931mark_definable (tree decl)
24932{
24933  tree clone;
24934  DECL_NOT_REALLY_EXTERN (decl) = 1;
24935  FOR_EACH_CLONE (clone, decl)
24936    DECL_NOT_REALLY_EXTERN (clone) = 1;
24937}
24938
24939/* Called if RESULT is explicitly instantiated, or is a member of an
24940   explicitly instantiated class.  */
24941
24942void
24943mark_decl_instantiated (tree result, int extern_p)
24944{
24945  SET_DECL_EXPLICIT_INSTANTIATION (result);
24946
24947  /* If this entity has already been written out, it's too late to
24948     make any modifications.  */
24949  if (TREE_ASM_WRITTEN (result))
24950    return;
24951
24952  /* consteval functions are never emitted.  */
24953  if (TREE_CODE (result) == FUNCTION_DECL
24954      && DECL_IMMEDIATE_FUNCTION_P (result))
24955    return;
24956
24957  /* For anonymous namespace we don't need to do anything.  */
24958  if (decl_anon_ns_mem_p (result))
24959    {
24960      gcc_assert (!TREE_PUBLIC (result));
24961      return;
24962    }
24963
24964  if (TREE_CODE (result) != FUNCTION_DECL)
24965    /* The TREE_PUBLIC flag for function declarations will have been
24966       set correctly by tsubst.  */
24967    TREE_PUBLIC (result) = 1;
24968
24969  if (extern_p)
24970    {
24971      DECL_EXTERNAL (result) = 1;
24972      DECL_NOT_REALLY_EXTERN (result) = 0;
24973    }
24974  else
24975    {
24976      mark_definable (result);
24977      mark_needed (result);
24978      /* Always make artificials weak.  */
24979      if (DECL_ARTIFICIAL (result) && flag_weak)
24980	comdat_linkage (result);
24981      /* For WIN32 we also want to put explicit instantiations in
24982	 linkonce sections.  */
24983      else if (TREE_PUBLIC (result))
24984	maybe_make_one_only (result);
24985      if (TREE_CODE (result) == FUNCTION_DECL
24986	  && DECL_TEMPLATE_INSTANTIATED (result))
24987	/* If the function has already been instantiated, clear DECL_EXTERNAL,
24988	   since start_preparsed_function wouldn't have if we had an earlier
24989	   extern explicit instantiation.  */
24990	DECL_EXTERNAL (result) = 0;
24991    }
24992
24993  /* If EXTERN_P, then this function will not be emitted -- unless
24994     followed by an explicit instantiation, at which point its linkage
24995     will be adjusted.  If !EXTERN_P, then this function will be
24996     emitted here.  In neither circumstance do we want
24997     import_export_decl to adjust the linkage.  */
24998  DECL_INTERFACE_KNOWN (result) = 1;
24999}
25000
25001/* Subroutine of more_specialized_fn: check whether TARGS is missing any
25002   important template arguments.  If any are missing, we check whether
25003   they're important by using error_mark_node for substituting into any
25004   args that were used for partial ordering (the ones between ARGS and END)
25005   and seeing if it bubbles up.  */
25006
25007static bool
25008check_undeduced_parms (tree targs, tree args, tree end)
25009{
25010  bool found = false;
25011  int i;
25012  for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
25013    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
25014      {
25015	found = true;
25016	TREE_VEC_ELT (targs, i) = error_mark_node;
25017      }
25018  if (found)
25019    {
25020      tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25021      if (substed == error_mark_node)
25022	return true;
25023    }
25024  return false;
25025}
25026
25027/* Given two function templates PAT1 and PAT2, return:
25028
25029   1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25030   -1 if PAT2 is more specialized than PAT1.
25031   0 if neither is more specialized.
25032
25033   LEN indicates the number of parameters we should consider
25034   (defaulted parameters should not be considered).
25035
25036   The 1998 std underspecified function template partial ordering, and
25037   DR214 addresses the issue.  We take pairs of arguments, one from
25038   each of the templates, and deduce them against each other.  One of
25039   the templates will be more specialized if all the *other*
25040   template's arguments deduce against its arguments and at least one
25041   of its arguments *does* *not* deduce against the other template's
25042   corresponding argument.  Deduction is done as for class templates.
25043   The arguments used in deduction have reference and top level cv
25044   qualifiers removed.  Iff both arguments were originally reference
25045   types *and* deduction succeeds in both directions, an lvalue reference
25046   wins against an rvalue reference and otherwise the template
25047   with the more cv-qualified argument wins for that pairing (if
25048   neither is more cv-qualified, they both are equal).  Unlike regular
25049   deduction, after all the arguments have been deduced in this way,
25050   we do *not* verify the deduced template argument values can be
25051   substituted into non-deduced contexts.
25052
25053   The logic can be a bit confusing here, because we look at deduce1 and
25054   targs1 to see if pat2 is at least as specialized, and vice versa; if we
25055   can find template arguments for pat1 to make arg1 look like arg2, that
25056   means that arg2 is at least as specialized as arg1.  */
25057
25058int
25059more_specialized_fn (tree pat1, tree pat2, int len)
25060{
25061  tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25062  tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25063  tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25064  tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25065  tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25066  tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25067  tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25068  tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25069  tree origs1, origs2;
25070  bool lose1 = false;
25071  bool lose2 = false;
25072
25073  /* Remove the this parameter from non-static member functions.  If
25074     one is a non-static member function and the other is not a static
25075     member function, remove the first parameter from that function
25076     also.  This situation occurs for operator functions where we
25077     locate both a member function (with this pointer) and non-member
25078     operator (with explicit first operand).  */
25079  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25080    {
25081      len--; /* LEN is the number of significant arguments for DECL1 */
25082      args1 = TREE_CHAIN (args1);
25083      if (!DECL_STATIC_FUNCTION_P (decl2))
25084	args2 = TREE_CHAIN (args2);
25085    }
25086  else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25087    {
25088      args2 = TREE_CHAIN (args2);
25089      if (!DECL_STATIC_FUNCTION_P (decl1))
25090	{
25091	  len--;
25092	  args1 = TREE_CHAIN (args1);
25093	}
25094    }
25095
25096  /* If only one is a conversion operator, they are unordered.  */
25097  if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25098    return 0;
25099
25100  /* Consider the return type for a conversion function */
25101  if (DECL_CONV_FN_P (decl1))
25102    {
25103      args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25104      args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25105      len++;
25106    }
25107
25108  processing_template_decl++;
25109
25110  origs1 = args1;
25111  origs2 = args2;
25112
25113  while (len--
25114	 /* Stop when an ellipsis is seen.  */
25115	 && args1 != NULL_TREE && args2 != NULL_TREE)
25116    {
25117      tree arg1 = TREE_VALUE (args1);
25118      tree arg2 = TREE_VALUE (args2);
25119      int deduce1, deduce2;
25120      int quals1 = -1;
25121      int quals2 = -1;
25122      int ref1 = 0;
25123      int ref2 = 0;
25124
25125      if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25126          && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25127        {
25128          /* When both arguments are pack expansions, we need only
25129             unify the patterns themselves.  */
25130          arg1 = PACK_EXPANSION_PATTERN (arg1);
25131          arg2 = PACK_EXPANSION_PATTERN (arg2);
25132
25133          /* This is the last comparison we need to do.  */
25134          len = 0;
25135        }
25136
25137      if (TYPE_REF_P (arg1))
25138	{
25139	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25140	  arg1 = TREE_TYPE (arg1);
25141	  quals1 = cp_type_quals (arg1);
25142	}
25143
25144      if (TYPE_REF_P (arg2))
25145	{
25146	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25147	  arg2 = TREE_TYPE (arg2);
25148	  quals2 = cp_type_quals (arg2);
25149	}
25150
25151      arg1 = TYPE_MAIN_VARIANT (arg1);
25152      arg2 = TYPE_MAIN_VARIANT (arg2);
25153
25154      if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25155        {
25156          int i, len2 = remaining_arguments (args2);
25157          tree parmvec = make_tree_vec (1);
25158          tree argvec = make_tree_vec (len2);
25159          tree ta = args2;
25160
25161          /* Setup the parameter vector, which contains only ARG1.  */
25162          TREE_VEC_ELT (parmvec, 0) = arg1;
25163
25164          /* Setup the argument vector, which contains the remaining
25165             arguments.  */
25166          for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25167            TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25168
25169          deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25170					   argvec, DEDUCE_EXACT,
25171					   /*subr=*/true, /*explain_p=*/false)
25172		     == 0);
25173
25174          /* We cannot deduce in the other direction, because ARG1 is
25175             a pack expansion but ARG2 is not.  */
25176          deduce2 = 0;
25177        }
25178      else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25179        {
25180          int i, len1 = remaining_arguments (args1);
25181          tree parmvec = make_tree_vec (1);
25182          tree argvec = make_tree_vec (len1);
25183          tree ta = args1;
25184
25185          /* Setup the parameter vector, which contains only ARG1.  */
25186          TREE_VEC_ELT (parmvec, 0) = arg2;
25187
25188          /* Setup the argument vector, which contains the remaining
25189             arguments.  */
25190          for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25191            TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25192
25193          deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25194					   argvec, DEDUCE_EXACT,
25195					   /*subr=*/true, /*explain_p=*/false)
25196		     == 0);
25197
25198          /* We cannot deduce in the other direction, because ARG2 is
25199             a pack expansion but ARG1 is not.*/
25200          deduce1 = 0;
25201        }
25202
25203      else
25204        {
25205          /* The normal case, where neither argument is a pack
25206             expansion.  */
25207          deduce1 = (unify (tparms1, targs1, arg1, arg2,
25208			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
25209		     == 0);
25210          deduce2 = (unify (tparms2, targs2, arg2, arg1,
25211			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
25212		     == 0);
25213        }
25214
25215      /* If we couldn't deduce arguments for tparms1 to make arg1 match
25216	 arg2, then arg2 is not as specialized as arg1.  */
25217      if (!deduce1)
25218	lose2 = true;
25219      if (!deduce2)
25220	lose1 = true;
25221
25222      /* "If, for a given type, deduction succeeds in both directions
25223	 (i.e., the types are identical after the transformations above)
25224	 and both P and A were reference types (before being replaced with
25225	 the type referred to above):
25226	 - if the type from the argument template was an lvalue reference and
25227	 the type from the parameter template was not, the argument type is
25228	 considered to be more specialized than the other; otherwise,
25229	 - if the type from the argument template is more cv-qualified
25230	 than the type from the parameter template (as described above),
25231	 the argument type is considered to be more specialized than the other;
25232	 otherwise,
25233	 - neither type is more specialized than the other."  */
25234
25235      if (deduce1 && deduce2)
25236	{
25237	  if (ref1 && ref2 && ref1 != ref2)
25238	    {
25239	      if (ref1 > ref2)
25240		lose1 = true;
25241	      else
25242		lose2 = true;
25243	    }
25244	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25245	    {
25246	      if ((quals1 & quals2) == quals2)
25247		lose2 = true;
25248	      if ((quals1 & quals2) == quals1)
25249		lose1 = true;
25250	    }
25251	}
25252
25253      if (lose1 && lose2)
25254	/* We've failed to deduce something in either direction.
25255	   These must be unordered.  */
25256	break;
25257
25258      if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25259          || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25260        /* We have already processed all of the arguments in our
25261           handing of the pack expansion type.  */
25262        len = 0;
25263
25264      args1 = TREE_CHAIN (args1);
25265      args2 = TREE_CHAIN (args2);
25266    }
25267
25268  /* "In most cases, all template parameters must have values in order for
25269     deduction to succeed, but for partial ordering purposes a template
25270     parameter may remain without a value provided it is not used in the
25271     types being used for partial ordering."
25272
25273     Thus, if we are missing any of the targs1 we need to substitute into
25274     origs1, then pat2 is not as specialized as pat1.  This can happen when
25275     there is a nondeduced context.  */
25276  if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25277    lose2 = true;
25278  if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25279    lose1 = true;
25280
25281  processing_template_decl--;
25282
25283  /* If both deductions succeed, the partial ordering selects the more
25284     constrained template.  */
25285  /* P2113: If the corresponding template-parameters of the
25286     template-parameter-lists are not equivalent ([temp.over.link]) or if
25287     the function parameters that positionally correspond between the two
25288     templates are not of the same type, neither template is more
25289     specialized than the other.  */
25290  if (!lose1 && !lose2
25291      && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25292			      DECL_TEMPLATE_PARMS (pat2))
25293      && compparms (origs1, origs2))
25294    {
25295      int winner = more_constrained (decl1, decl2);
25296      if (winner > 0)
25297	lose2 = true;
25298      else if (winner < 0)
25299	lose1 = true;
25300    }
25301
25302  /* All things being equal, if the next argument is a pack expansion
25303     for one function but not for the other, prefer the
25304     non-variadic function.  FIXME this is bogus; see c++/41958.  */
25305  if (lose1 == lose2
25306      && args1 && TREE_VALUE (args1)
25307      && args2 && TREE_VALUE (args2))
25308    {
25309      lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25310      lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25311    }
25312
25313  if (lose1 == lose2)
25314    return 0;
25315  else if (!lose1)
25316    return 1;
25317  else
25318    return -1;
25319}
25320
25321/* Determine which of two partial specializations of TMPL is more
25322   specialized.
25323
25324   PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25325   to the first partial specialization.  The TREE_PURPOSE is the
25326   innermost set of template parameters for the partial
25327   specialization.  PAT2 is similar, but for the second template.
25328
25329   Return 1 if the first partial specialization is more specialized;
25330   -1 if the second is more specialized; 0 if neither is more
25331   specialized.
25332
25333   See [temp.class.order] for information about determining which of
25334   two templates is more specialized.  */
25335
25336static int
25337more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25338{
25339  tree targs;
25340  int winner = 0;
25341  bool any_deductions = false;
25342
25343  tree tmpl1 = TREE_VALUE (pat1);
25344  tree tmpl2 = TREE_VALUE (pat2);
25345  tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25346  tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25347
25348  /* Just like what happens for functions, if we are ordering between
25349     different template specializations, we may encounter dependent
25350     types in the arguments, and we need our dependency check functions
25351     to behave correctly.  */
25352  ++processing_template_decl;
25353  targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25354  if (targs)
25355    {
25356      --winner;
25357      any_deductions = true;
25358    }
25359
25360  targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25361  if (targs)
25362    {
25363      ++winner;
25364      any_deductions = true;
25365    }
25366  --processing_template_decl;
25367
25368  /* If both deductions succeed, the partial ordering selects the more
25369     constrained template.  */
25370  if (!winner && any_deductions)
25371    winner = more_constrained (tmpl1, tmpl2);
25372
25373  /* In the case of a tie where at least one of the templates
25374     has a parameter pack at the end, the template with the most
25375     non-packed parameters wins.  */
25376  if (winner == 0
25377      && any_deductions
25378      && (template_args_variadic_p (TREE_PURPOSE (pat1))
25379          || template_args_variadic_p (TREE_PURPOSE (pat2))))
25380    {
25381      tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25382      tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25383      int len1 = TREE_VEC_LENGTH (args1);
25384      int len2 = TREE_VEC_LENGTH (args2);
25385
25386      /* We don't count the pack expansion at the end.  */
25387      if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25388        --len1;
25389      if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25390        --len2;
25391
25392      if (len1 > len2)
25393        return 1;
25394      else if (len1 < len2)
25395        return -1;
25396    }
25397
25398  return winner;
25399}
25400
25401/* Return the template arguments that will produce the function signature
25402   DECL from the function template FN, with the explicit template
25403   arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
25404   also match.  Return NULL_TREE if no satisfactory arguments could be
25405   found.  */
25406
25407static tree
25408get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25409{
25410  int ntparms = DECL_NTPARMS (fn);
25411  tree targs = make_tree_vec (ntparms);
25412  tree decl_type = TREE_TYPE (decl);
25413  tree decl_arg_types;
25414  tree *args;
25415  unsigned int nargs, ix;
25416  tree arg;
25417
25418  gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25419
25420  /* Never do unification on the 'this' parameter.  */
25421  decl_arg_types = skip_artificial_parms_for (decl,
25422					      TYPE_ARG_TYPES (decl_type));
25423
25424  nargs = list_length (decl_arg_types);
25425  args = XALLOCAVEC (tree, nargs);
25426  for (arg = decl_arg_types, ix = 0;
25427       arg != NULL_TREE;
25428       arg = TREE_CHAIN (arg), ++ix)
25429    args[ix] = TREE_VALUE (arg);
25430
25431  if (fn_type_unification (fn, explicit_args, targs,
25432			   args, ix,
25433			   (check_rettype || DECL_CONV_FN_P (fn)
25434			    ? TREE_TYPE (decl_type) : NULL_TREE),
25435			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25436			   /*explain_p=*/false,
25437			   /*decltype*/false)
25438      == error_mark_node)
25439    return NULL_TREE;
25440
25441  return targs;
25442}
25443
25444/* Return the innermost template arguments that, when applied to a partial
25445   specialization SPEC_TMPL of TMPL, yield the ARGS.
25446
25447   For example, suppose we have:
25448
25449     template <class T, class U> struct S {};
25450     template <class T> struct S<T*, int> {};
25451
25452   Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
25453   partial specialization and the ARGS will be {double*, int}.  The resulting
25454   vector will be {double}, indicating that `T' is bound to `double'.  */
25455
25456static tree
25457get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25458{
25459  tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25460  tree spec_args
25461    = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25462  int i, ntparms = TREE_VEC_LENGTH (tparms);
25463  tree deduced_args;
25464  tree innermost_deduced_args;
25465
25466  innermost_deduced_args = make_tree_vec (ntparms);
25467  if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25468    {
25469      deduced_args = copy_node (args);
25470      SET_TMPL_ARGS_LEVEL (deduced_args,
25471			   TMPL_ARGS_DEPTH (deduced_args),
25472			   innermost_deduced_args);
25473    }
25474  else
25475    deduced_args = innermost_deduced_args;
25476
25477  bool tried_array_deduction = (cxx_dialect < cxx17);
25478 again:
25479  if (unify (tparms, deduced_args,
25480	     INNERMOST_TEMPLATE_ARGS (spec_args),
25481	     INNERMOST_TEMPLATE_ARGS (args),
25482	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
25483    return NULL_TREE;
25484
25485  for (i =  0; i < ntparms; ++i)
25486    if (! TREE_VEC_ELT (innermost_deduced_args, i))
25487      {
25488	if (!tried_array_deduction)
25489	  {
25490	    try_array_deduction (tparms, innermost_deduced_args,
25491				 INNERMOST_TEMPLATE_ARGS (spec_args));
25492	    tried_array_deduction = true;
25493	    if (TREE_VEC_ELT (innermost_deduced_args, i))
25494	      goto again;
25495	  }
25496	return NULL_TREE;
25497      }
25498
25499  if (!push_tinst_level (spec_tmpl, deduced_args))
25500    {
25501      excessive_deduction_depth = true;
25502      return NULL_TREE;
25503    }
25504
25505  /* Verify that nondeduced template arguments agree with the type
25506     obtained from argument deduction.
25507
25508     For example:
25509
25510       struct A { typedef int X; };
25511       template <class T, class U> struct C {};
25512       template <class T> struct C<T, typename T::X> {};
25513
25514     Then with the instantiation `C<A, int>', we can deduce that
25515     `T' is `A' but unify () does not check whether `typename T::X'
25516     is `int'.  */
25517  spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25518
25519  if (spec_args != error_mark_node)
25520    spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25521				       INNERMOST_TEMPLATE_ARGS (spec_args),
25522				       tmpl, tf_none, false, false);
25523
25524  pop_tinst_level ();
25525
25526  if (spec_args == error_mark_node
25527      /* We only need to check the innermost arguments; the other
25528	 arguments will always agree.  */
25529      || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25530				     INNERMOST_TEMPLATE_ARGS (args)))
25531    return NULL_TREE;
25532
25533  /* Now that we have bindings for all of the template arguments,
25534     ensure that the arguments deduced for the template template
25535     parameters have compatible template parameter lists.  See the use
25536     of template_template_parm_bindings_ok_p in fn_type_unification
25537     for more information.  */
25538  if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25539    return NULL_TREE;
25540
25541  return deduced_args;
25542}
25543
25544// Compare two function templates T1 and T2 by deducing bindings
25545// from one against the other. If both deductions succeed, compare
25546// constraints to see which is more constrained.
25547static int
25548more_specialized_inst (tree t1, tree t2)
25549{
25550  int fate = 0;
25551  int count = 0;
25552
25553  if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25554    {
25555      --fate;
25556      ++count;
25557    }
25558
25559  if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25560    {
25561      ++fate;
25562      ++count;
25563    }
25564
25565  // If both deductions succeed, then one may be more constrained.
25566  if (count == 2 && fate == 0)
25567    fate = more_constrained (t1, t2);
25568
25569  return fate;
25570}
25571
25572/* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
25573   Return the TREE_LIST node with the most specialized template, if
25574   any.  If there is no most specialized template, the error_mark_node
25575   is returned.
25576
25577   Note that this function does not look at, or modify, the
25578   TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
25579   returned is one of the elements of INSTANTIATIONS, callers may
25580   store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25581   and retrieve it from the value returned.  */
25582
25583tree
25584most_specialized_instantiation (tree templates)
25585{
25586  tree fn, champ;
25587
25588  ++processing_template_decl;
25589
25590  champ = templates;
25591  for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25592    {
25593      gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25594      int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25595      if (fate == -1)
25596	champ = fn;
25597      else if (!fate)
25598	{
25599	  /* Equally specialized, move to next function.  If there
25600	     is no next function, nothing's most specialized.  */
25601	  fn = TREE_CHAIN (fn);
25602	  champ = fn;
25603	  if (!fn)
25604	    break;
25605	}
25606    }
25607
25608  if (champ)
25609    /* Now verify that champ is better than everything earlier in the
25610       instantiation list.  */
25611    for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25612      if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25613      {
25614        champ = NULL_TREE;
25615        break;
25616      }
25617    }
25618
25619  processing_template_decl--;
25620
25621  if (!champ)
25622    return error_mark_node;
25623
25624  return champ;
25625}
25626
25627/* If DECL is a specialization of some template, return the most
25628   general such template.  Otherwise, returns NULL_TREE.
25629
25630   For example, given:
25631
25632     template <class T> struct S { template <class U> void f(U); };
25633
25634   if TMPL is `template <class U> void S<int>::f(U)' this will return
25635   the full template.  This function will not trace past partial
25636   specializations, however.  For example, given in addition:
25637
25638     template <class T> struct S<T*> { template <class U> void f(U); };
25639
25640   if TMPL is `template <class U> void S<int*>::f(U)' this will return
25641   `template <class T> template <class U> S<T*>::f(U)'.  */
25642
25643tree
25644most_general_template (tree decl)
25645{
25646  if (TREE_CODE (decl) != TEMPLATE_DECL)
25647    {
25648      if (tree tinfo = get_template_info (decl))
25649	decl = TI_TEMPLATE (tinfo);
25650      /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25651	 template friend, or a FIELD_DECL for a capture pack.  */
25652      if (TREE_CODE (decl) != TEMPLATE_DECL)
25653	return NULL_TREE;
25654    }
25655
25656  /* Look for more and more general templates.  */
25657  while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25658    {
25659      /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25660	 (See cp-tree.h for details.)  */
25661      if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25662	break;
25663
25664      if (CLASS_TYPE_P (TREE_TYPE (decl))
25665	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25666	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25667	break;
25668
25669      /* Stop if we run into an explicitly specialized class template.  */
25670      if (!DECL_NAMESPACE_SCOPE_P (decl)
25671	  && DECL_CONTEXT (decl)
25672	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25673	break;
25674
25675      decl = DECL_TI_TEMPLATE (decl);
25676    }
25677
25678  return decl;
25679}
25680
25681/* Return the most specialized of the template partial specializations
25682   which can produce TARGET, a specialization of some class or variable
25683   template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
25684   a TEMPLATE_DECL node corresponding to the partial specialization, while
25685   the TREE_PURPOSE is the set of template arguments that must be
25686   substituted into the template pattern in order to generate TARGET.
25687
25688   If the choice of partial specialization is ambiguous, a diagnostic
25689   is issued, and the error_mark_node is returned.  If there are no
25690   partial specializations matching TARGET, then NULL_TREE is
25691   returned, indicating that the primary template should be used.  */
25692
25693tree
25694most_specialized_partial_spec (tree target, tsubst_flags_t complain)
25695{
25696  tree list = NULL_TREE;
25697  tree t;
25698  tree champ;
25699  int fate;
25700  bool ambiguous_p;
25701  tree outer_args = NULL_TREE;
25702  tree tmpl, args;
25703
25704  tree decl;
25705  if (TYPE_P (target))
25706    {
25707      tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25708      tmpl = TI_TEMPLATE (tinfo);
25709      args = TI_ARGS (tinfo);
25710      decl = TYPE_NAME (target);
25711    }
25712  else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25713    {
25714      tmpl = TREE_OPERAND (target, 0);
25715      args = TREE_OPERAND (target, 1);
25716      decl = DECL_TEMPLATE_RESULT (tmpl);
25717    }
25718  else if (VAR_P (target))
25719    {
25720      tree tinfo = DECL_TEMPLATE_INFO (target);
25721      tmpl = TI_TEMPLATE (tinfo);
25722      args = TI_ARGS (tinfo);
25723      decl = target;
25724    }
25725  else
25726    gcc_unreachable ();
25727
25728  push_access_scope_guard pas (decl);
25729  deferring_access_check_sentinel acs (dk_no_deferred);
25730
25731  tree main_tmpl = most_general_template (tmpl);
25732
25733  /* For determining which partial specialization to use, only the
25734     innermost args are interesting.  */
25735  if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25736    {
25737      outer_args = strip_innermost_template_args (args, 1);
25738      args = INNERMOST_TEMPLATE_ARGS (args);
25739    }
25740
25741  /* The caller hasn't called push_to_top_level yet, but we need
25742     get_partial_spec_bindings to be done in non-template context so that we'll
25743     fully resolve everything.  */
25744  processing_template_decl_sentinel ptds;
25745
25746  for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
25747    {
25748      const tree ospec_tmpl = TREE_VALUE (t);
25749
25750      tree spec_tmpl;
25751      if (outer_args)
25752	{
25753	  /* Substitute in the template args from the enclosing class.  */
25754	  ++processing_template_decl;
25755	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25756	  --processing_template_decl;
25757	  if (spec_tmpl == error_mark_node)
25758	    return error_mark_node;
25759	}
25760      else
25761	spec_tmpl = ospec_tmpl;
25762
25763      tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25764      if (spec_args)
25765	{
25766	  if (outer_args)
25767	    spec_args = add_to_template_args (outer_args, spec_args);
25768
25769          /* Keep the candidate only if the constraints are satisfied,
25770             or if we're not compiling with concepts.  */
25771          if (!flag_concepts
25772	      || constraints_satisfied_p (ospec_tmpl, spec_args))
25773            {
25774	      list = tree_cons (spec_args, ospec_tmpl, list);
25775              TREE_TYPE (list) = TREE_TYPE (t);
25776            }
25777	}
25778    }
25779
25780  if (! list)
25781    return NULL_TREE;
25782
25783  ambiguous_p = false;
25784  t = list;
25785  champ = t;
25786  t = TREE_CHAIN (t);
25787  for (; t; t = TREE_CHAIN (t))
25788    {
25789      fate = more_specialized_partial_spec (tmpl, champ, t);
25790      if (fate == 1)
25791	;
25792      else
25793	{
25794	  if (fate == 0)
25795	    {
25796	      t = TREE_CHAIN (t);
25797	      if (! t)
25798		{
25799		  ambiguous_p = true;
25800		  break;
25801		}
25802	    }
25803	  champ = t;
25804	}
25805    }
25806
25807  if (!ambiguous_p)
25808    for (t = list; t && t != champ; t = TREE_CHAIN (t))
25809      {
25810	fate = more_specialized_partial_spec (tmpl, champ, t);
25811	if (fate != 1)
25812	  {
25813	    ambiguous_p = true;
25814	    break;
25815	  }
25816      }
25817
25818  if (ambiguous_p)
25819    {
25820      const char *str;
25821      char *spaces = NULL;
25822      if (!(complain & tf_error))
25823	return error_mark_node;
25824      if (TYPE_P (target))
25825	error ("ambiguous template instantiation for %q#T", target);
25826      else
25827	error ("ambiguous template instantiation for %q#D", target);
25828      str = ngettext ("candidate is:", "candidates are:", list_length (list));
25829      for (t = list; t; t = TREE_CHAIN (t))
25830        {
25831	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25832          inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25833		  "%s %#qS", spaces ? spaces : str, subst);
25834          spaces = spaces ? spaces : get_spaces (str);
25835        }
25836      free (spaces);
25837      return error_mark_node;
25838    }
25839
25840  return champ;
25841}
25842
25843/* Explicitly instantiate DECL.  */
25844
25845void
25846do_decl_instantiation (tree decl, tree storage)
25847{
25848  tree result = NULL_TREE;
25849  int extern_p = 0;
25850
25851  if (!decl || decl == error_mark_node)
25852    /* An error occurred, for which grokdeclarator has already issued
25853       an appropriate message.  */
25854    return;
25855  else if (! DECL_LANG_SPECIFIC (decl))
25856    {
25857      error ("explicit instantiation of non-template %q#D", decl);
25858      return;
25859    }
25860  else if (DECL_DECLARED_CONCEPT_P (decl))
25861    {
25862      if (VAR_P (decl))
25863	error ("explicit instantiation of variable concept %q#D", decl);
25864      else
25865	error ("explicit instantiation of function concept %q#D", decl);
25866      return;
25867    }
25868
25869  bool var_templ = (DECL_TEMPLATE_INFO (decl)
25870                    && variable_template_p (DECL_TI_TEMPLATE (decl)));
25871
25872  if (VAR_P (decl) && !var_templ)
25873    {
25874      /* There is an asymmetry here in the way VAR_DECLs and
25875	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
25876	 the latter, the DECL we get back will be marked as a
25877	 template instantiation, and the appropriate
25878	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
25879	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
25880	 should handle VAR_DECLs as it currently handles
25881	 FUNCTION_DECLs.  */
25882      if (!DECL_CLASS_SCOPE_P (decl))
25883	{
25884	  error ("%qD is not a static data member of a class template", decl);
25885	  return;
25886	}
25887      result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
25888      if (!result || !VAR_P (result))
25889	{
25890	  error ("no matching template for %qD found", decl);
25891	  return;
25892	}
25893      if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
25894	{
25895	  error ("type %qT for explicit instantiation %qD does not match "
25896		 "declared type %qT", TREE_TYPE (result), decl,
25897		 TREE_TYPE (decl));
25898	  return;
25899	}
25900    }
25901  else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
25902    {
25903      error ("explicit instantiation of %q#D", decl);
25904      return;
25905    }
25906  else
25907    result = decl;
25908
25909  /* Check for various error cases.  Note that if the explicit
25910     instantiation is valid the RESULT will currently be marked as an
25911     *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
25912     until we get here.  */
25913
25914  if (DECL_TEMPLATE_SPECIALIZATION (result))
25915    {
25916      /* DR 259 [temp.spec].
25917
25918	 Both an explicit instantiation and a declaration of an explicit
25919	 specialization shall not appear in a program unless the explicit
25920	 instantiation follows a declaration of the explicit specialization.
25921
25922	 For a given set of template parameters, if an explicit
25923	 instantiation of a template appears after a declaration of an
25924	 explicit specialization for that template, the explicit
25925	 instantiation has no effect.  */
25926      return;
25927    }
25928  else if (DECL_EXPLICIT_INSTANTIATION (result))
25929    {
25930      /* [temp.spec]
25931
25932	 No program shall explicitly instantiate any template more
25933	 than once.
25934
25935	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
25936	 the first instantiation was `extern' and the second is not,
25937	 and EXTERN_P for the opposite case.  */
25938      if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
25939	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
25940      /* If an "extern" explicit instantiation follows an ordinary
25941	 explicit instantiation, the template is instantiated.  */
25942      if (extern_p)
25943	return;
25944    }
25945  else if (!DECL_IMPLICIT_INSTANTIATION (result))
25946    {
25947      error ("no matching template for %qD found", result);
25948      return;
25949    }
25950  else if (!DECL_TEMPLATE_INFO (result))
25951    {
25952      permerror (input_location, "explicit instantiation of non-template %q#D", result);
25953      return;
25954    }
25955
25956  if (storage == NULL_TREE)
25957    ;
25958  else if (storage == ridpointers[(int) RID_EXTERN])
25959    {
25960      if (cxx_dialect == cxx98)
25961	pedwarn (input_location, OPT_Wpedantic,
25962		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
25963		 "instantiations");
25964      extern_p = 1;
25965    }
25966  else
25967    error ("storage class %qD applied to template instantiation", storage);
25968
25969  check_explicit_instantiation_namespace (result);
25970  mark_decl_instantiated (result, extern_p);
25971  if (! extern_p)
25972    instantiate_decl (result, /*defer_ok=*/true,
25973		      /*expl_inst_class_mem_p=*/false);
25974}
25975
25976static void
25977mark_class_instantiated (tree t, int extern_p)
25978{
25979  SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25980  SET_CLASSTYPE_INTERFACE_KNOWN (t);
25981  CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25982  TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25983  if (! extern_p)
25984    {
25985      CLASSTYPE_DEBUG_REQUESTED (t) = 1;
25986      rest_of_type_compilation (t, 1);
25987    }
25988}
25989
25990/* Perform an explicit instantiation of template class T.  STORAGE, if
25991   non-null, is the RID for extern, inline or static.  COMPLAIN is
25992   nonzero if this is called from the parser, zero if called recursively,
25993   since the standard is unclear (as detailed below).  */
25994
25995void
25996do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
25997{
25998  if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
25999    {
26000      if (tree ti = TYPE_TEMPLATE_INFO (t))
26001	error ("explicit instantiation of non-class template %qD",
26002	       TI_TEMPLATE (ti));
26003      else
26004	error ("explicit instantiation of non-template type %qT", t);
26005      return;
26006    }
26007
26008  complete_type (t);
26009
26010  if (!COMPLETE_TYPE_P (t))
26011    {
26012      if (complain & tf_error)
26013	error ("explicit instantiation of %q#T before definition of template",
26014	       t);
26015      return;
26016    }
26017
26018  /* At most one of these will be true.  */
26019  bool extern_p = false;
26020  bool nomem_p = false;
26021  bool static_p = false;
26022
26023  if (storage != NULL_TREE)
26024    {
26025      if (storage == ridpointers[(int) RID_EXTERN])
26026	{
26027	  if (cxx_dialect == cxx98)
26028	    pedwarn (input_location, OPT_Wpedantic,
26029		     "ISO C++ 1998 forbids the use of %<extern%> on "
26030		     "explicit instantiations");
26031	}
26032      else
26033	pedwarn (input_location, OPT_Wpedantic,
26034		 "ISO C++ forbids the use of %qE"
26035		 " on explicit instantiations", storage);
26036
26037      if (storage == ridpointers[(int) RID_INLINE])
26038	nomem_p = true;
26039      else if (storage == ridpointers[(int) RID_EXTERN])
26040	extern_p = true;
26041      else if (storage == ridpointers[(int) RID_STATIC])
26042	static_p = true;
26043      else
26044	error ("storage class %qD applied to template instantiation",
26045	       storage);
26046    }
26047
26048  if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26049    /* DR 259 [temp.spec].
26050
26051       Both an explicit instantiation and a declaration of an explicit
26052       specialization shall not appear in a program unless the
26053       explicit instantiation follows a declaration of the explicit
26054       specialization.
26055
26056       For a given set of template parameters, if an explicit
26057       instantiation of a template appears after a declaration of an
26058       explicit specialization for that template, the explicit
26059       instantiation has no effect.  */
26060    return;
26061
26062  if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26063    {
26064      /* We've already instantiated the template.  */
26065
26066      /* [temp.spec]
26067
26068	 No program shall explicitly instantiate any template more
26069	 than once.
26070
26071	 If EXTERN_P then this is ok.  */
26072      if (!extern_p && (complain & tf_error))
26073	permerror (input_location,
26074		   "duplicate explicit instantiation of %q#T", t);
26075
26076      return;
26077    }
26078
26079  check_explicit_instantiation_namespace (TYPE_NAME (t));
26080  mark_class_instantiated (t, extern_p);
26081
26082  if (nomem_p)
26083    return;
26084
26085  /* In contrast to implicit instantiation, where only the
26086     declarations, and not the definitions, of members are
26087     instantiated, we have here:
26088
26089	 [temp.explicit]
26090
26091	 An explicit instantiation that names a class template
26092	 specialization is also an explicit instantiation of the same
26093	 kind (declaration or definition) of each of its members (not
26094	 including members inherited from base classes and members
26095	 that are templates) that has not been previously explicitly
26096	 specialized in the translation unit containing the explicit
26097	 instantiation, provided that the associated constraints, if
26098	 any, of that member are satisfied by the template arguments
26099	 of the explicit instantiation.  */
26100  for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26101    if ((VAR_P (fld)
26102	 || (TREE_CODE (fld) == FUNCTION_DECL
26103	     && !static_p
26104	     && user_provided_p (fld)))
26105	&& DECL_TEMPLATE_INSTANTIATION (fld)
26106	&& constraints_satisfied_p (fld))
26107      {
26108	mark_decl_instantiated (fld, extern_p);
26109	if (! extern_p)
26110	  instantiate_decl (fld, /*defer_ok=*/true,
26111			    /*expl_inst_class_mem_p=*/true);
26112      }
26113    else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26114      {
26115	tree type = TREE_TYPE (fld);
26116
26117	if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26118	    && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26119	  do_type_instantiation (type, storage, 0);
26120      }
26121}
26122
26123/* Given a function DECL, which is a specialization of TMPL, modify
26124   DECL to be a re-instantiation of TMPL with the same template
26125   arguments.  TMPL should be the template into which tsubst'ing
26126   should occur for DECL, not the most general template.
26127
26128   One reason for doing this is a scenario like this:
26129
26130     template <class T>
26131     void f(const T&, int i);
26132
26133     void g() { f(3, 7); }
26134
26135     template <class T>
26136     void f(const T& t, const int i) { }
26137
26138   Note that when the template is first instantiated, with
26139   instantiate_template, the resulting DECL will have no name for the
26140   first parameter, and the wrong type for the second.  So, when we go
26141   to instantiate the DECL, we regenerate it.  */
26142
26143static void
26144regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26145{
26146  /* The arguments used to instantiate DECL, from the most general
26147     template.  */
26148  tree code_pattern;
26149
26150  code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26151
26152  /* Make sure that we can see identifiers, and compute access
26153     correctly.  */
26154  push_access_scope (decl);
26155
26156  if (TREE_CODE (decl) == FUNCTION_DECL)
26157    {
26158      tree specs;
26159      int args_depth;
26160      int parms_depth;
26161
26162      /* Use the source location of the definition.  */
26163      DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26164
26165      args_depth = TMPL_ARGS_DEPTH (args);
26166      parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26167      if (args_depth > parms_depth)
26168	args = get_innermost_template_args (args, parms_depth);
26169
26170      /* Instantiate a dynamic exception-specification.  noexcept will be
26171	 handled below.  */
26172      if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26173	if (TREE_VALUE (raises))
26174	  {
26175	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26176						    args, tf_error, NULL_TREE,
26177						    /*defer_ok*/false);
26178	    if (specs && specs != error_mark_node)
26179	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26180							  specs);
26181	  }
26182
26183      /* Merge parameter declarations.  */
26184      if (tree pattern_parm
26185	  = skip_artificial_parms_for (code_pattern,
26186				       DECL_ARGUMENTS (code_pattern)))
26187	{
26188	  tree *p = &DECL_ARGUMENTS (decl);
26189	  for (int skip = num_artificial_parms_for (decl); skip; --skip)
26190	    p = &DECL_CHAIN (*p);
26191	  *p = tsubst_decl (pattern_parm, args, tf_error);
26192	  for (tree t = *p; t; t = DECL_CHAIN (t))
26193	    DECL_CONTEXT (t) = decl;
26194	}
26195
26196      /* Merge additional specifiers from the CODE_PATTERN.  */
26197      if (DECL_DECLARED_INLINE_P (code_pattern)
26198	  && !DECL_DECLARED_INLINE_P (decl))
26199	DECL_DECLARED_INLINE_P (decl) = 1;
26200
26201      maybe_instantiate_noexcept (decl, tf_error);
26202    }
26203  else if (VAR_P (decl))
26204    {
26205      start_lambda_scope (decl);
26206      DECL_INITIAL (decl) =
26207	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26208		     tf_error, DECL_TI_TEMPLATE (decl));
26209      finish_lambda_scope ();
26210      if (VAR_HAD_UNKNOWN_BOUND (decl))
26211	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26212				   tf_error, DECL_TI_TEMPLATE (decl));
26213    }
26214  else
26215    gcc_unreachable ();
26216
26217  pop_access_scope (decl);
26218}
26219
26220/* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26221   substituted to get DECL.  */
26222
26223tree
26224template_for_substitution (tree decl)
26225{
26226  tree tmpl = DECL_TI_TEMPLATE (decl);
26227
26228  /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26229     for the instantiation.  This is not always the most general
26230     template.  Consider, for example:
26231
26232	template <class T>
26233	struct S { template <class U> void f();
26234		   template <> void f<int>(); };
26235
26236     and an instantiation of S<double>::f<int>.  We want TD to be the
26237     specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
26238  while (/* An instantiation cannot have a definition, so we need a
26239	    more general template.  */
26240	 DECL_TEMPLATE_INSTANTIATION (tmpl)
26241	   /* We must also deal with friend templates.  Given:
26242
26243		template <class T> struct S {
26244		  template <class U> friend void f() {};
26245		};
26246
26247	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26248	      so far as the language is concerned, but that's still
26249	      where we get the pattern for the instantiation from.  On
26250	      other hand, if the definition comes outside the class, say:
26251
26252		template <class T> struct S {
26253		  template <class U> friend void f();
26254		};
26255		template <class U> friend void f() {}
26256
26257	      we don't need to look any further.  That's what the check for
26258	      DECL_INITIAL is for.  */
26259	  || (TREE_CODE (decl) == FUNCTION_DECL
26260	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26261	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26262    {
26263      /* The present template, TD, should not be a definition.  If it
26264	 were a definition, we should be using it!  Note that we
26265	 cannot restructure the loop to just keep going until we find
26266	 a template with a definition, since that might go too far if
26267	 a specialization was declared, but not defined.  */
26268
26269      /* Fetch the more general template.  */
26270      tmpl = DECL_TI_TEMPLATE (tmpl);
26271    }
26272
26273  return tmpl;
26274}
26275
26276/* Returns true if we need to instantiate this template instance even if we
26277   know we aren't going to emit it.  */
26278
26279bool
26280always_instantiate_p (tree decl)
26281{
26282  /* We always instantiate inline functions so that we can inline them.  An
26283     explicit instantiation declaration prohibits implicit instantiation of
26284     non-inline functions.  With high levels of optimization, we would
26285     normally inline non-inline functions -- but we're not allowed to do
26286     that for "extern template" functions.  Therefore, we check
26287     DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
26288  return ((TREE_CODE (decl) == FUNCTION_DECL
26289	   && (DECL_DECLARED_INLINE_P (decl)
26290	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26291	  /* And we need to instantiate static data members so that
26292	     their initializers are available in integral constant
26293	     expressions.  */
26294	  || (VAR_P (decl)
26295	      && decl_maybe_constant_var_p (decl)));
26296}
26297
26298/* If FN has a noexcept-specifier that hasn't been instantiated yet,
26299   instantiate it now, modifying TREE_TYPE (fn).  Returns false on
26300   error, true otherwise.  */
26301
26302bool
26303maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26304{
26305  if (fn == error_mark_node)
26306    return false;
26307
26308  /* Don't instantiate a noexcept-specification from template context.  */
26309  if (processing_template_decl
26310      && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26311    return true;
26312
26313  tree fntype = TREE_TYPE (fn);
26314  tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26315
26316  if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26317      && DECL_MAYBE_DELETED (fn))
26318    {
26319      if (fn == current_function_decl)
26320	/* We're in start_preparsed_function, keep going.  */
26321	return true;
26322
26323      ++function_depth;
26324      maybe_synthesize_method (fn);
26325      --function_depth;
26326      return !DECL_DELETED_FN (fn);
26327    }
26328
26329  if (!spec || !TREE_PURPOSE (spec))
26330    return true;
26331
26332  tree noex = TREE_PURPOSE (spec);
26333  if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26334      && TREE_CODE (noex) != DEFERRED_PARSE)
26335    return true;
26336
26337  tree orig_fn = NULL_TREE;
26338  /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
26339     its FUNCTION_DECL for the rest of this function -- push_access_scope
26340     doesn't accept TEMPLATE_DECLs.  */
26341  if (DECL_FUNCTION_TEMPLATE_P (fn))
26342    {
26343      orig_fn = fn;
26344      fn = DECL_TEMPLATE_RESULT (fn);
26345    }
26346
26347  if (DECL_CLONED_FUNCTION_P (fn))
26348    {
26349      tree prime = DECL_CLONED_FUNCTION (fn);
26350      if (!maybe_instantiate_noexcept (prime, complain))
26351	return false;
26352      spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26353    }
26354  else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26355    {
26356      static hash_set<tree>* fns = new hash_set<tree>;
26357      bool added = false;
26358      if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26359	{
26360	  spec = get_defaulted_eh_spec (fn, complain);
26361	  if (spec == error_mark_node)
26362	    /* This might have failed because of an unparsed DMI, so
26363	       let's try again later.  */
26364	    return false;
26365	}
26366      else if (!(added = !fns->add (fn)))
26367	{
26368	  /* If hash_set::add returns true, the element was already there.  */
26369	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26370					    DECL_SOURCE_LOCATION (fn));
26371	  error_at (loc,
26372		    "exception specification of %qD depends on itself",
26373		    fn);
26374	  spec = noexcept_false_spec;
26375	}
26376      else if (push_tinst_level (fn))
26377	{
26378	  push_to_top_level ();
26379	  push_access_scope (fn);
26380	  push_deferring_access_checks (dk_no_deferred);
26381	  input_location = DECL_SOURCE_LOCATION (fn);
26382
26383	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26384	      && !DECL_LOCAL_DECL_P (fn))
26385	    {
26386	      /* If needed, set current_class_ptr for the benefit of
26387		 tsubst_copy/PARM_DECL.  */
26388	      tree this_parm = DECL_ARGUMENTS (fn);
26389	      current_class_ptr = NULL_TREE;
26390	      current_class_ref = cp_build_fold_indirect_ref (this_parm);
26391	      current_class_ptr = this_parm;
26392	    }
26393
26394	  /* If this function is represented by a TEMPLATE_DECL, then
26395	     the deferred noexcept-specification might still contain
26396	     dependent types, even after substitution.  And we need the
26397	     dependency check functions to work in build_noexcept_spec.  */
26398	  if (orig_fn)
26399	    ++processing_template_decl;
26400
26401	  /* Do deferred instantiation of the noexcept-specifier.  */
26402	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26403					DEFERRED_NOEXCEPT_ARGS (noex),
26404					tf_warning_or_error, fn,
26405					/*function_p=*/false,
26406					/*i_c_e_p=*/true);
26407
26408	  /* Build up the noexcept-specification.  */
26409	  spec = build_noexcept_spec (noex, tf_warning_or_error);
26410
26411	  if (orig_fn)
26412	    --processing_template_decl;
26413
26414	  pop_deferring_access_checks ();
26415	  pop_access_scope (fn);
26416	  pop_tinst_level ();
26417	  pop_from_top_level ();
26418	}
26419      else
26420	spec = noexcept_false_spec;
26421
26422      if (added)
26423	fns->remove (fn);
26424    }
26425
26426  if (spec == error_mark_node)
26427    {
26428      /* This failed with a hard error, so let's go with false.  */
26429      gcc_assert (seen_error ());
26430      spec = noexcept_false_spec;
26431    }
26432
26433  TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26434  if (orig_fn)
26435    TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26436
26437  return true;
26438}
26439
26440/* We're starting to process the function INST, an instantiation of PATTERN;
26441   add their parameters to local_specializations.  */
26442
26443static void
26444register_parameter_specializations (tree pattern, tree inst)
26445{
26446  tree tmpl_parm = DECL_ARGUMENTS (pattern);
26447  tree spec_parm = DECL_ARGUMENTS (inst);
26448  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26449    {
26450      register_local_specialization (spec_parm, tmpl_parm);
26451      spec_parm = skip_artificial_parms_for (inst, spec_parm);
26452      tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26453    }
26454  for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26455    {
26456      if (!DECL_PACK_P (tmpl_parm))
26457	{
26458	  register_local_specialization (spec_parm, tmpl_parm);
26459	  spec_parm = DECL_CHAIN (spec_parm);
26460	}
26461      else
26462	{
26463	  /* Register the (value) argument pack as a specialization of
26464	     TMPL_PARM, then move on.  */
26465	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26466	  register_local_specialization (argpack, tmpl_parm);
26467	}
26468    }
26469  gcc_assert (!spec_parm);
26470}
26471
26472/* Instantiate the body of D using PATTERN with ARGS.  We have
26473   already determined PATTERN is the correct template to use.
26474   NESTED_P is true if this is a nested function, in which case
26475   PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL.  */
26476
26477static void
26478instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26479{
26480  tree td = NULL_TREE;
26481  tree code_pattern = pattern;
26482
26483  if (!nested_p)
26484    {
26485      td = pattern;
26486      code_pattern = DECL_TEMPLATE_RESULT (td);
26487    }
26488  else
26489    /* Only OMP reductions are nested.  */
26490    gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26491
26492  vec<tree> omp_privatization_save;
26493  if (current_function_decl)
26494    save_omp_privatization_clauses (omp_privatization_save);
26495
26496  bool push_to_top
26497    = !(current_function_decl
26498	&& !LAMBDA_FUNCTION_P (d)
26499	&& decl_function_context (d) == current_function_decl);
26500
26501  if (push_to_top)
26502    push_to_top_level ();
26503  else
26504    {
26505      gcc_assert (!processing_template_decl);
26506      push_function_context ();
26507      cp_unevaluated_operand = 0;
26508      c_inhibit_evaluation_warnings = 0;
26509    }
26510
26511  if (VAR_P (d))
26512    {
26513      /* The variable might be a lambda's extra scope, and that
26514	 lambda's visibility depends on D's.  */
26515      maybe_commonize_var (d);
26516      determine_visibility (d);
26517    }
26518
26519  /* Mark D as instantiated so that recursive calls to
26520     instantiate_decl do not try to instantiate it again.  */
26521  DECL_TEMPLATE_INSTANTIATED (d) = 1;
26522
26523  if (td)
26524    /* Regenerate the declaration in case the template has been modified
26525       by a subsequent redeclaration.  */
26526    regenerate_decl_from_template (d, td, args);
26527
26528  /* We already set the file and line above.  Reset them now in case
26529     they changed as a result of calling regenerate_decl_from_template.  */
26530  input_location = DECL_SOURCE_LOCATION (d);
26531
26532  if (VAR_P (d))
26533    {
26534      /* Clear out DECL_RTL; whatever was there before may not be right
26535	 since we've reset the type of the declaration.  */
26536      SET_DECL_RTL (d, NULL);
26537      DECL_IN_AGGR_P (d) = 0;
26538
26539      /* The initializer is placed in DECL_INITIAL by
26540	 regenerate_decl_from_template so we don't need to
26541	 push/pop_access_scope again here.  Pull it out so that
26542	 cp_finish_decl can process it.  */
26543      bool const_init = false;
26544      tree init = DECL_INITIAL (d);
26545      DECL_INITIAL (d) = NULL_TREE;
26546      DECL_INITIALIZED_P (d) = 0;
26547
26548      /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26549	 initializer.  That function will defer actual emission until
26550	 we have a chance to determine linkage.  */
26551      DECL_EXTERNAL (d) = 0;
26552
26553      /* Enter the scope of D so that access-checking works correctly.  */
26554      bool enter_context = DECL_CLASS_SCOPE_P (d);
26555      if (enter_context)
26556        push_nested_class (DECL_CONTEXT (d));
26557
26558      const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26559      cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26560
26561      if (enter_context)
26562        pop_nested_class ();
26563    }
26564  else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26565    synthesize_method (d);
26566  else if (TREE_CODE (d) == FUNCTION_DECL)
26567    {
26568      /* Set up the list of local specializations.  */
26569      local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26570      tree block = NULL_TREE;
26571
26572      /* Set up context.  */
26573      if (nested_p)
26574	block = push_stmt_list ();
26575      else
26576	{
26577	  start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26578
26579	  perform_instantiation_time_access_checks (code_pattern, args);
26580	}
26581
26582      /* Create substitution entries for the parameters.  */
26583      register_parameter_specializations (code_pattern, d);
26584
26585      /* Substitute into the body of the function.  */
26586      if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26587	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26588			tf_warning_or_error, d);
26589      else
26590	{
26591	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26592		       tf_warning_or_error, DECL_TI_TEMPLATE (d),
26593		       /*integral_constant_expression_p=*/false);
26594
26595	  /* Set the current input_location to the end of the function
26596	     so that finish_function knows where we are.  */
26597	  input_location
26598	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26599
26600	  /* Remember if we saw an infinite loop in the template.  */
26601	  current_function_infinite_loop
26602	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26603	}
26604
26605      /* Finish the function.  */
26606      if (nested_p)
26607	DECL_SAVED_TREE (d) = pop_stmt_list (block);
26608      else
26609	{
26610	  d = finish_function (/*inline_p=*/false);
26611	  expand_or_defer_fn (d);
26612	}
26613
26614      if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26615	cp_check_omp_declare_reduction (d);
26616    }
26617
26618  /* We're not deferring instantiation any more.  */
26619  if (!nested_p)
26620    TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26621
26622  if (push_to_top)
26623    pop_from_top_level ();
26624  else
26625    pop_function_context ();
26626
26627  if (current_function_decl)
26628    restore_omp_privatization_clauses (omp_privatization_save);
26629}
26630
26631/* Produce the definition of D, a _DECL generated from a template.  If
26632   DEFER_OK is true, then we don't have to actually do the
26633   instantiation now; we just have to do it sometime.  Normally it is
26634   an error if this is an explicit instantiation but D is undefined.
26635   EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26636   instantiated class template.  */
26637
26638tree
26639instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26640{
26641  tree tmpl = DECL_TI_TEMPLATE (d);
26642  tree gen_args;
26643  tree args;
26644  tree td;
26645  tree code_pattern;
26646  tree spec;
26647  tree gen_tmpl;
26648  bool pattern_defined;
26649  location_t saved_loc = input_location;
26650  int saved_unevaluated_operand = cp_unevaluated_operand;
26651  int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26652  bool external_p;
26653  bool deleted_p;
26654
26655  /* This function should only be used to instantiate templates for
26656     functions and static member variables.  */
26657  gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26658
26659  /* A concept is never instantiated. */
26660  gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26661
26662  gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26663
26664  if (modules_p ())
26665    /* We may have a pending instantiation of D itself.  */
26666    lazy_load_pendings (d);
26667
26668  /* Variables are never deferred; if instantiation is required, they
26669     are instantiated right away.  That allows for better code in the
26670     case that an expression refers to the value of the variable --
26671     if the variable has a constant value the referring expression can
26672     take advantage of that fact.  */
26673  if (VAR_P (d))
26674    defer_ok = false;
26675
26676  /* Don't instantiate cloned functions.  Instead, instantiate the
26677     functions they cloned.  */
26678  if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26679    d = DECL_CLONED_FUNCTION (d);
26680
26681  if (DECL_TEMPLATE_INSTANTIATED (d)
26682      || TREE_TYPE (d) == error_mark_node
26683      || (TREE_CODE (d) == FUNCTION_DECL
26684	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26685      || DECL_TEMPLATE_SPECIALIZATION (d))
26686    /* D has already been instantiated or explicitly specialized, so
26687       there's nothing for us to do here.
26688
26689       It might seem reasonable to check whether or not D is an explicit
26690       instantiation, and, if so, stop here.  But when an explicit
26691       instantiation is deferred until the end of the compilation,
26692       DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26693       the instantiation.  */
26694    return d;
26695
26696  /* Check to see whether we know that this template will be
26697     instantiated in some other file, as with "extern template"
26698     extension.  */
26699  external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26700
26701  /* In general, we do not instantiate such templates.  */
26702  if (external_p && !always_instantiate_p (d))
26703    return d;
26704
26705  gen_tmpl = most_general_template (tmpl);
26706  gen_args = DECL_TI_ARGS (d);
26707
26708  /* We should already have the extra args.  */
26709  gcc_checking_assert (tmpl == gen_tmpl
26710		       || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26711			   == TMPL_ARGS_DEPTH (gen_args)));
26712  /* And what's in the hash table should match D.  */
26713  gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26714		       == d
26715		       || spec == NULL_TREE);
26716
26717  /* This needs to happen before any tsubsting.  */
26718  if (! push_tinst_level (d))
26719    return d;
26720
26721  timevar_push (TV_TEMPLATE_INST);
26722
26723  /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26724     for the instantiation.  */
26725  td = template_for_substitution (d);
26726  args = gen_args;
26727
26728  if (variable_template_specialization_p (d))
26729    {
26730      /* Look up an explicit specialization, if any.  */
26731      tree elt = most_specialized_partial_spec (d, tf_warning_or_error);
26732      if (elt && elt != error_mark_node)
26733	{
26734	  td = TREE_VALUE (elt);
26735	  args = TREE_PURPOSE (elt);
26736	}
26737    }
26738
26739  code_pattern = DECL_TEMPLATE_RESULT (td);
26740
26741  /* We should never be trying to instantiate a member of a class
26742     template or partial specialization.  */
26743  gcc_assert (d != code_pattern);
26744
26745  if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26746      || DECL_TEMPLATE_SPECIALIZATION (td))
26747    /* In the case of a friend template whose definition is provided
26748       outside the class, we may have too many arguments.  Drop the
26749       ones we don't need.  The same is true for specializations.  */
26750    args = get_innermost_template_args
26751      (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26752
26753  if (TREE_CODE (d) == FUNCTION_DECL)
26754    {
26755      deleted_p = DECL_DELETED_FN (code_pattern);
26756      pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26757			  && DECL_INITIAL (code_pattern) != error_mark_node)
26758			 || DECL_DEFAULTED_FN (code_pattern)
26759			 || deleted_p);
26760    }
26761  else
26762    {
26763      deleted_p = false;
26764      if (DECL_CLASS_SCOPE_P (code_pattern))
26765	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26766      else
26767	pattern_defined = ! DECL_EXTERNAL (code_pattern);
26768    }
26769
26770  /* We may be in the middle of deferred access check.  Disable it now.  */
26771  push_deferring_access_checks (dk_no_deferred);
26772
26773  /* Unless an explicit instantiation directive has already determined
26774     the linkage of D, remember that a definition is available for
26775     this entity.  */
26776  if (pattern_defined
26777      && !DECL_INTERFACE_KNOWN (d)
26778      && !DECL_NOT_REALLY_EXTERN (d))
26779    mark_definable (d);
26780
26781  DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26782  DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26783  input_location = DECL_SOURCE_LOCATION (d);
26784
26785  /* If D is a member of an explicitly instantiated class template,
26786     and no definition is available, treat it like an implicit
26787     instantiation.  */
26788  if (!pattern_defined && expl_inst_class_mem_p
26789      && DECL_EXPLICIT_INSTANTIATION (d))
26790    {
26791      /* Leave linkage flags alone on instantiations with anonymous
26792	 visibility.  */
26793      if (TREE_PUBLIC (d))
26794	{
26795	  DECL_NOT_REALLY_EXTERN (d) = 0;
26796	  DECL_INTERFACE_KNOWN (d) = 0;
26797	}
26798      SET_DECL_IMPLICIT_INSTANTIATION (d);
26799    }
26800
26801  /* Defer all other templates, unless we have been explicitly
26802     forbidden from doing so.  */
26803  if (/* If there is no definition, we cannot instantiate the
26804	 template.  */
26805      ! pattern_defined
26806      /* If it's OK to postpone instantiation, do so.  */
26807      || defer_ok
26808      /* If this is a static data member that will be defined
26809	 elsewhere, we don't want to instantiate the entire data
26810	 member, but we do want to instantiate the initializer so that
26811	 we can substitute that elsewhere.  */
26812      || (external_p && VAR_P (d))
26813      /* Handle here a deleted function too, avoid generating
26814	 its body (c++/61080).  */
26815      || deleted_p)
26816    {
26817      /* The definition of the static data member is now required so
26818	 we must substitute the initializer.  */
26819      if (VAR_P (d)
26820	  && !DECL_INITIAL (d)
26821	  && DECL_INITIAL (code_pattern))
26822	{
26823	  tree ns;
26824	  tree init;
26825	  bool const_init = false;
26826	  bool enter_context = DECL_CLASS_SCOPE_P (d);
26827
26828	  ns = decl_namespace_context (d);
26829	  push_nested_namespace (ns);
26830	  if (enter_context)
26831	    push_nested_class (DECL_CONTEXT (d));
26832	  init = tsubst_expr (DECL_INITIAL (code_pattern),
26833			      args,
26834			      tf_warning_or_error, NULL_TREE,
26835			      /*integral_constant_expression_p=*/false);
26836	  /* If instantiating the initializer involved instantiating this
26837	     again, don't call cp_finish_decl twice.  */
26838	  if (!DECL_INITIAL (d))
26839	    {
26840	      /* Make sure the initializer is still constant, in case of
26841		 circular dependency (template/instantiate6.C). */
26842	      const_init
26843		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26844	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26845			      /*asmspec_tree=*/NULL_TREE, 0);
26846	    }
26847	  if (enter_context)
26848	    pop_nested_class ();
26849	  pop_nested_namespace (ns);
26850	}
26851
26852      /* We restore the source position here because it's used by
26853	 add_pending_template.  */
26854      input_location = saved_loc;
26855
26856      if (at_eof && !pattern_defined
26857	  && DECL_EXPLICIT_INSTANTIATION (d)
26858	  && DECL_NOT_REALLY_EXTERN (d))
26859	/* [temp.explicit]
26860
26861	   The definition of a non-exported function template, a
26862	   non-exported member function template, or a non-exported
26863	   member function or static data member of a class template
26864	   shall be present in every translation unit in which it is
26865	   explicitly instantiated.  */
26866	permerror (input_location,  "explicit instantiation of %qD "
26867		   "but no definition available", d);
26868
26869      /* If we're in unevaluated context, we just wanted to get the
26870	 constant value; this isn't an odr use, so don't queue
26871	 a full instantiation.  */
26872      if (!cp_unevaluated_operand
26873	  /* ??? Historically, we have instantiated inline functions, even
26874	     when marked as "extern template".  */
26875	  && !(external_p && VAR_P (d)))
26876	add_pending_template (d);
26877    }
26878  else
26879    {
26880      set_instantiating_module (d);
26881      if (variable_template_p (gen_tmpl))
26882	note_variable_template_instantiation (d);
26883      instantiate_body (td, args, d, false);
26884    }
26885
26886  pop_deferring_access_checks ();
26887  timevar_pop (TV_TEMPLATE_INST);
26888  pop_tinst_level ();
26889  input_location = saved_loc;
26890  cp_unevaluated_operand = saved_unevaluated_operand;
26891  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26892
26893  return d;
26894}
26895
26896/* Run through the list of templates that we wish we could
26897   instantiate, and instantiate any we can.  RETRIES is the
26898   number of times we retry pending template instantiation.  */
26899
26900void
26901instantiate_pending_templates (int retries)
26902{
26903  int reconsider;
26904  location_t saved_loc = input_location;
26905
26906  /* Instantiating templates may trigger vtable generation.  This in turn
26907     may require further template instantiations.  We place a limit here
26908     to avoid infinite loop.  */
26909  if (pending_templates && retries >= max_tinst_depth)
26910    {
26911      tree decl = pending_templates->tinst->maybe_get_node ();
26912
26913      fatal_error (input_location,
26914		   "template instantiation depth exceeds maximum of %d"
26915		   " instantiating %q+D, possibly from virtual table generation"
26916		   " (use %<-ftemplate-depth=%> to increase the maximum)",
26917		   max_tinst_depth, decl);
26918      if (TREE_CODE (decl) == FUNCTION_DECL)
26919	/* Pretend that we defined it.  */
26920	DECL_INITIAL (decl) = error_mark_node;
26921      return;
26922    }
26923
26924  do
26925    {
26926      struct pending_template **t = &pending_templates;
26927      struct pending_template *last = NULL;
26928      reconsider = 0;
26929      while (*t)
26930	{
26931	  tree instantiation = reopen_tinst_level ((*t)->tinst);
26932	  bool complete = false;
26933
26934	  if (TYPE_P (instantiation))
26935	    {
26936	      if (!COMPLETE_TYPE_P (instantiation))
26937		{
26938		  instantiate_class_template (instantiation);
26939		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26940		    for (tree fld = TYPE_FIELDS (instantiation);
26941			 fld; fld = TREE_CHAIN (fld))
26942		      if ((VAR_P (fld)
26943			   || (TREE_CODE (fld) == FUNCTION_DECL
26944			       && !DECL_ARTIFICIAL (fld)))
26945			  && DECL_TEMPLATE_INSTANTIATION (fld))
26946			instantiate_decl (fld,
26947					  /*defer_ok=*/false,
26948					  /*expl_inst_class_mem_p=*/false);
26949
26950		  if (COMPLETE_TYPE_P (instantiation))
26951		    reconsider = 1;
26952		}
26953
26954	      complete = COMPLETE_TYPE_P (instantiation);
26955	    }
26956	  else
26957	    {
26958	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26959		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26960		{
26961		  instantiation
26962		    = instantiate_decl (instantiation,
26963					/*defer_ok=*/false,
26964					/*expl_inst_class_mem_p=*/false);
26965		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26966		    reconsider = 1;
26967		}
26968
26969	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26970			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
26971	    }
26972
26973	  if (complete)
26974	    {
26975	      /* If INSTANTIATION has been instantiated, then we don't
26976		 need to consider it again in the future.  */
26977	      struct pending_template *drop = *t;
26978	      *t = (*t)->next;
26979	      set_refcount_ptr (drop->tinst);
26980	      pending_template_freelist ().free (drop);
26981	    }
26982	  else
26983	    {
26984	      last = *t;
26985	      t = &(*t)->next;
26986	    }
26987	  tinst_depth = 0;
26988	  set_refcount_ptr (current_tinst_level);
26989	}
26990      last_pending_template = last;
26991    }
26992  while (reconsider);
26993
26994  input_location = saved_loc;
26995}
26996
26997/* Substitute ARGVEC into T, which is a list of initializers for
26998   either base class or a non-static data member.  The TREE_PURPOSEs
26999   are DECLs, and the TREE_VALUEs are the initializer values.  Used by
27000   instantiate_decl.  */
27001
27002static tree
27003tsubst_initializer_list (tree t, tree argvec)
27004{
27005  tree inits = NULL_TREE;
27006  tree target_ctor = error_mark_node;
27007
27008  for (; t; t = TREE_CHAIN (t))
27009    {
27010      tree decl;
27011      tree init;
27012      tree expanded_bases = NULL_TREE;
27013      tree expanded_arguments = NULL_TREE;
27014      int i, len = 1;
27015
27016      if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27017        {
27018          tree expr;
27019          tree arg;
27020
27021          /* Expand the base class expansion type into separate base
27022             classes.  */
27023          expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27024                                                 tf_warning_or_error,
27025                                                 NULL_TREE);
27026          if (expanded_bases == error_mark_node)
27027            continue;
27028
27029          /* We'll be building separate TREE_LISTs of arguments for
27030             each base.  */
27031          len = TREE_VEC_LENGTH (expanded_bases);
27032          expanded_arguments = make_tree_vec (len);
27033          for (i = 0; i < len; i++)
27034            TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27035
27036          /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27037             expand each argument in the TREE_VALUE of t.  */
27038          expr = make_node (EXPR_PACK_EXPANSION);
27039	  PACK_EXPANSION_LOCAL_P (expr) = true;
27040          PACK_EXPANSION_PARAMETER_PACKS (expr) =
27041            PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27042
27043	  if (TREE_VALUE (t) == void_type_node)
27044	    /* VOID_TYPE_NODE is used to indicate
27045	       value-initialization.  */
27046	    {
27047	      for (i = 0; i < len; i++)
27048		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27049	    }
27050	  else
27051	    {
27052	      /* Substitute parameter packs into each argument in the
27053		 TREE_LIST.  */
27054	      in_base_initializer = 1;
27055	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27056		{
27057		  tree expanded_exprs;
27058
27059		  /* Expand the argument.  */
27060		  tree value;
27061		  if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27062		    value = TREE_VALUE (arg);
27063		  else
27064		    {
27065		      value = expr;
27066		      SET_PACK_EXPANSION_PATTERN (value, TREE_VALUE (arg));
27067		    }
27068		  expanded_exprs
27069		    = tsubst_pack_expansion (value, argvec,
27070					     tf_warning_or_error,
27071					     NULL_TREE);
27072		  if (expanded_exprs == error_mark_node)
27073		    continue;
27074
27075		  /* Prepend each of the expanded expressions to the
27076		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
27077		  for (i = 0; i < len; i++)
27078		    if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27079		      for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27080			TREE_VEC_ELT (expanded_arguments, i)
27081			  = tree_cons (NULL_TREE,
27082				       TREE_VEC_ELT (expanded_exprs, j),
27083				       TREE_VEC_ELT (expanded_arguments, i));
27084		    else
27085		      TREE_VEC_ELT (expanded_arguments, i)
27086			= tree_cons (NULL_TREE,
27087				     TREE_VEC_ELT (expanded_exprs, i),
27088				     TREE_VEC_ELT (expanded_arguments, i));
27089		}
27090	      in_base_initializer = 0;
27091
27092	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27093		 since we built them backwards.  */
27094	      for (i = 0; i < len; i++)
27095		{
27096		  TREE_VEC_ELT (expanded_arguments, i) =
27097		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
27098		}
27099	    }
27100        }
27101
27102      for (i = 0; i < len; ++i)
27103        {
27104          if (expanded_bases)
27105            {
27106              decl = TREE_VEC_ELT (expanded_bases, i);
27107              decl = expand_member_init (decl);
27108              init = TREE_VEC_ELT (expanded_arguments, i);
27109            }
27110          else
27111            {
27112	      tree tmp;
27113              decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27114                                  tf_warning_or_error, NULL_TREE);
27115
27116              decl = expand_member_init (decl);
27117              if (decl && !DECL_P (decl))
27118                in_base_initializer = 1;
27119
27120	      init = TREE_VALUE (t);
27121	      tmp = init;
27122	      if (init != void_type_node)
27123		init = tsubst_expr (init, argvec,
27124				    tf_warning_or_error, NULL_TREE,
27125				    /*integral_constant_expression_p=*/false);
27126	      if (init == NULL_TREE && tmp != NULL_TREE)
27127		/* If we had an initializer but it instantiated to nothing,
27128		   value-initialize the object.  This will only occur when
27129		   the initializer was a pack expansion where the parameter
27130		   packs used in that expansion were of length zero.  */
27131		init = void_type_node;
27132              in_base_initializer = 0;
27133            }
27134
27135	  if (target_ctor != error_mark_node
27136	      && init != error_mark_node)
27137	    {
27138	      error ("mem-initializer for %qD follows constructor delegation",
27139		     decl);
27140	      return inits;
27141	    }
27142	  /* Look for a target constructor. */
27143	  if (init != error_mark_node
27144	      && decl && CLASS_TYPE_P (decl)
27145	      && same_type_p (decl, current_class_type))
27146	    {
27147	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27148	      if (inits)
27149		{
27150		  error ("constructor delegation follows mem-initializer for %qD",
27151			 TREE_PURPOSE (inits));
27152		  continue;
27153		}
27154	      target_ctor = init;
27155	    }
27156
27157          if (decl)
27158            {
27159              init = build_tree_list (decl, init);
27160	      /* Carry over the dummy TREE_TYPE node containing the source
27161		 location.  */
27162	      TREE_TYPE (init) = TREE_TYPE (t);
27163              TREE_CHAIN (init) = inits;
27164              inits = init;
27165            }
27166        }
27167    }
27168  return inits;
27169}
27170
27171/* Instantiate an enumerated type.  TAG is the template type, NEWTAG
27172   is the instantiation (which should have been created with
27173   start_enum) and ARGS are the template arguments to use.  */
27174
27175static void
27176tsubst_enum (tree tag, tree newtag, tree args)
27177{
27178  tree e;
27179
27180  if (SCOPED_ENUM_P (newtag))
27181    begin_scope (sk_scoped_enum, newtag);
27182
27183  for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27184    {
27185      tree value;
27186      tree decl = TREE_VALUE (e);
27187
27188      /* Note that in a template enum, the TREE_VALUE is the
27189	 CONST_DECL, not the corresponding INTEGER_CST.  */
27190      value = tsubst_expr (DECL_INITIAL (decl),
27191			   args, tf_warning_or_error, NULL_TREE,
27192			   /*integral_constant_expression_p=*/true);
27193
27194      /* Give this enumeration constant the correct access.  */
27195      set_current_access_from_decl (decl);
27196
27197      /* Actually build the enumerator itself.  Here we're assuming that
27198	 enumerators can't have dependent attributes.  */
27199      tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27200				       DECL_ATTRIBUTES (decl),
27201				       DECL_SOURCE_LOCATION (decl));
27202      /* Attribute deprecated without an argument isn't sticky: it'll
27203	 melt into a tree flag, so we need to propagate the flag here,
27204	 since we just created a new enumerator.  */
27205      TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27206      TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27207    }
27208
27209  if (SCOPED_ENUM_P (newtag))
27210    finish_scope ();
27211
27212  finish_enum_value_list (newtag);
27213  finish_enum (newtag);
27214
27215  DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27216    = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27217  TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27218  TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27219}
27220
27221/* DECL is a FUNCTION_DECL that is a template specialization.  Return
27222   its type -- but without substituting the innermost set of template
27223   arguments.  So, innermost set of template parameters will appear in
27224   the type.  */
27225
27226tree
27227get_mostly_instantiated_function_type (tree decl)
27228{
27229  /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
27230  return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27231}
27232
27233/* Return truthvalue if we're processing a template different from
27234   the last one involved in diagnostics.  */
27235bool
27236problematic_instantiation_changed (void)
27237{
27238  return current_tinst_level != last_error_tinst_level;
27239}
27240
27241/* Remember current template involved in diagnostics.  */
27242void
27243record_last_problematic_instantiation (void)
27244{
27245  set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27246}
27247
27248struct tinst_level *
27249current_instantiation (void)
27250{
27251  return current_tinst_level;
27252}
27253
27254/* Return TRUE if current_function_decl is being instantiated, false
27255   otherwise.  */
27256
27257bool
27258instantiating_current_function_p (void)
27259{
27260  return (current_instantiation ()
27261	  && (current_instantiation ()->maybe_get_node ()
27262	      == current_function_decl));
27263}
27264
27265/* [temp.param] Check that template non-type parm TYPE is of an allowable
27266   type.  Return false for ok, true for disallowed.  Issue error and
27267   inform messages under control of COMPLAIN.  */
27268
27269static bool
27270invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27271{
27272  if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27273    return false;
27274  else if (TYPE_PTR_P (type))
27275    return false;
27276  else if (TYPE_REF_P (type)
27277	   && !TYPE_REF_IS_RVALUE (type))
27278    return false;
27279  else if (TYPE_PTRMEM_P (type))
27280    return false;
27281  else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27282    {
27283      if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27284	{
27285	  if (complain & tf_error)
27286	    error ("non-type template parameters of deduced class type only "
27287		   "available with %<-std=c++20%> or %<-std=gnu++20%>");
27288	  return true;
27289	}
27290      return false;
27291    }
27292  else if (TREE_CODE (type) == NULLPTR_TYPE)
27293    return false;
27294  else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27295	   && cxx_dialect < cxx11)
27296    /* Fall through; before C++11 alias templates, a bound ttp
27297       always instantiates into a class type.  */;
27298  else if (WILDCARD_TYPE_P (type))
27299    /* Any other wildcard type not already handled above is allowed.  */
27300    return false;
27301  else if (TREE_CODE (type) == COMPLEX_TYPE)
27302    /* Fall through.  */;
27303  else if (VOID_TYPE_P (type))
27304    /* Fall through.  */;
27305  else if (cxx_dialect >= cxx20)
27306    {
27307      if (dependent_type_p (type))
27308	return false;
27309      if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27310	return true;
27311      if (structural_type_p (type))
27312	return false;
27313      if (complain & tf_error)
27314	{
27315	  auto_diagnostic_group d;
27316	  error ("%qT is not a valid type for a template non-type "
27317		 "parameter because it is not structural", type);
27318	  structural_type_p (type, true);
27319	}
27320      return true;
27321    }
27322  else if (CLASS_TYPE_P (type))
27323    {
27324      if (complain & tf_error)
27325	error ("non-type template parameters of class type only available "
27326	       "with %<-std=c++20%> or %<-std=gnu++20%>");
27327      return true;
27328    }
27329
27330  if (complain & tf_error)
27331    {
27332      if (type == error_mark_node)
27333	inform (input_location, "invalid template non-type parameter");
27334      else
27335	error ("%q#T is not a valid type for a template non-type parameter",
27336	       type);
27337    }
27338  return true;
27339}
27340
27341/* Returns true iff the noexcept-specifier for TYPE is value-dependent.  */
27342
27343static bool
27344value_dependent_noexcept_spec_p (tree type)
27345{
27346  if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27347    if (tree noex = TREE_PURPOSE (spec))
27348      /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27349	 affect overload resolution and treating it as dependent breaks
27350	 things.  Same for an unparsed noexcept expression.  */
27351      if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27352	  && TREE_CODE (noex) != DEFERRED_PARSE
27353	  && value_dependent_expression_p (noex))
27354	return true;
27355
27356  return false;
27357}
27358
27359/* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27360   Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27361
27362static bool
27363dependent_type_p_r (tree type)
27364{
27365  tree scope;
27366
27367  /* [temp.dep.type]
27368
27369     A type is dependent if it is:
27370
27371     -- a template parameter. Template template parameters are types
27372	for us (since TYPE_P holds true for them) so we handle
27373	them here.  */
27374  if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27375      || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27376    return true;
27377  /* -- a qualified-id with a nested-name-specifier which contains a
27378	class-name that names a dependent type or whose unqualified-id
27379	names a dependent type.  */
27380  if (TREE_CODE (type) == TYPENAME_TYPE)
27381    return true;
27382
27383  /* An alias template specialization can be dependent even if the
27384     resulting type is not.  */
27385  if (dependent_alias_template_spec_p (type, nt_transparent))
27386    return true;
27387
27388  /* -- a cv-qualified type where the cv-unqualified type is
27389	dependent.
27390     No code is necessary for this bullet; the code below handles
27391     cv-qualified types, and we don't want to strip aliases with
27392     TYPE_MAIN_VARIANT because of DR 1558.  */
27393  /* -- a compound type constructed from any dependent type.  */
27394  if (TYPE_PTRMEM_P (type))
27395    return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27396	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27397					   (type)));
27398  else if (INDIRECT_TYPE_P (type))
27399    return dependent_type_p (TREE_TYPE (type));
27400  else if (FUNC_OR_METHOD_TYPE_P (type))
27401    {
27402      tree arg_type;
27403
27404      if (dependent_type_p (TREE_TYPE (type)))
27405	return true;
27406      for (arg_type = TYPE_ARG_TYPES (type);
27407	   arg_type;
27408	   arg_type = TREE_CHAIN (arg_type))
27409	if (dependent_type_p (TREE_VALUE (arg_type)))
27410	  return true;
27411      if (cxx_dialect >= cxx17
27412	  && value_dependent_noexcept_spec_p (type))
27413	/* A value-dependent noexcept-specifier makes the type dependent.  */
27414	return true;
27415      return false;
27416    }
27417  /* -- an array type constructed from any dependent type or whose
27418	size is specified by a constant expression that is
27419	value-dependent.
27420
27421        We checked for type- and value-dependence of the bounds in
27422        compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
27423  if (TREE_CODE (type) == ARRAY_TYPE)
27424    {
27425      if (TYPE_DOMAIN (type)
27426	  && dependent_type_p (TYPE_DOMAIN (type)))
27427	return true;
27428      return dependent_type_p (TREE_TYPE (type));
27429    }
27430
27431  /* -- a template-id in which either the template name is a template
27432     parameter ...  */
27433  if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27434    return true;
27435  /* ... or any of the template arguments is a dependent type or
27436	an expression that is type-dependent or value-dependent.  */
27437  else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27438	   && (any_dependent_template_arguments_p
27439	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27440    return true;
27441
27442  /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
27443     dependent; if the argument of the `typeof' expression is not
27444     type-dependent, then it should already been have resolved.  */
27445  if (TREE_CODE (type) == TYPEOF_TYPE
27446      || TREE_CODE (type) == DECLTYPE_TYPE
27447      || TREE_CODE (type) == UNDERLYING_TYPE)
27448    return true;
27449
27450  /* A template argument pack is dependent if any of its packed
27451     arguments are.  */
27452  if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27453    {
27454      tree args = ARGUMENT_PACK_ARGS (type);
27455      int i, len = TREE_VEC_LENGTH (args);
27456      for (i = 0; i < len; ++i)
27457        if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27458          return true;
27459    }
27460
27461  /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27462     be template parameters.  */
27463  if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27464    return true;
27465
27466  if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27467    return true;
27468
27469  if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27470    return true;
27471
27472  /* The standard does not specifically mention types that are local
27473     to template functions or local classes, but they should be
27474     considered dependent too.  For example:
27475
27476       template <int I> void f() {
27477	 enum E { a = I };
27478	 S<sizeof (E)> s;
27479       }
27480
27481     The size of `E' cannot be known until the value of `I' has been
27482     determined.  Therefore, `E' must be considered dependent.  */
27483  scope = TYPE_CONTEXT (type);
27484  if (scope && TYPE_P (scope))
27485    return dependent_type_p (scope);
27486  /* Don't use type_dependent_expression_p here, as it can lead
27487     to infinite recursion trying to determine whether a lambda
27488     nested in a lambda is dependent (c++/47687).  */
27489  else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27490	   && DECL_LANG_SPECIFIC (scope)
27491	   && DECL_TEMPLATE_INFO (scope)
27492	   && (any_dependent_template_arguments_p
27493	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27494    return true;
27495
27496  /* Other types are non-dependent.  */
27497  return false;
27498}
27499
27500/* Returns TRUE if TYPE is dependent, in the sense of
27501   [temp.dep.type].  Note that a NULL type is considered dependent.  */
27502
27503bool
27504dependent_type_p (tree type)
27505{
27506  /* If there are no template parameters in scope, then there can't be
27507     any dependent types.  */
27508  if (!processing_template_decl)
27509    {
27510      /* If we are not processing a template, then nobody should be
27511	 providing us with a dependent type.  */
27512      gcc_assert (type);
27513      gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27514      return false;
27515    }
27516
27517  /* If the type is NULL, we have not computed a type for the entity
27518     in question; in that case, the type is dependent.  */
27519  if (!type)
27520    return true;
27521
27522  /* Erroneous types can be considered non-dependent.  */
27523  if (type == error_mark_node)
27524    return false;
27525
27526  /* If we have not already computed the appropriate value for TYPE,
27527     do so now.  */
27528  if (!TYPE_DEPENDENT_P_VALID (type))
27529    {
27530      TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27531      TYPE_DEPENDENT_P_VALID (type) = 1;
27532    }
27533
27534  return TYPE_DEPENDENT_P (type);
27535}
27536
27537/* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27538   lookup.  In other words, a dependent type that is not the current
27539   instantiation.  */
27540
27541bool
27542dependent_scope_p (tree scope)
27543{
27544  return (scope && TYPE_P (scope) && dependent_type_p (scope)
27545	  && !currently_open_class (scope));
27546}
27547
27548/* True if we might find more declarations in SCOPE during instantiation than
27549   we can when parsing the template.  */
27550
27551bool
27552dependentish_scope_p (tree scope)
27553{
27554  return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27555}
27556
27557/* T is a SCOPE_REF.  Return whether it represents a non-static member of
27558   an unknown base of 'this' (and is therefore instantiation-dependent).  */
27559
27560static bool
27561unknown_base_ref_p (tree t)
27562{
27563  if (!current_class_ptr)
27564    return false;
27565
27566  tree mem = TREE_OPERAND (t, 1);
27567  if (shared_member_p (mem))
27568    return false;
27569
27570  tree cur = current_nonlambda_class_type ();
27571  if (!any_dependent_bases_p (cur))
27572    return false;
27573
27574  tree ctx = TREE_OPERAND (t, 0);
27575  if (DERIVED_FROM_P (ctx, cur))
27576    return false;
27577
27578  return true;
27579}
27580
27581/* T is a SCOPE_REF; return whether we need to consider it
27582    instantiation-dependent so that we can check access at instantiation
27583    time even though we know which member it resolves to.  */
27584
27585static bool
27586instantiation_dependent_scope_ref_p (tree t)
27587{
27588  if (DECL_P (TREE_OPERAND (t, 1))
27589      && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27590      && !dependent_scope_p (TREE_OPERAND (t, 0))
27591      && !unknown_base_ref_p (t)
27592      && accessible_in_template_p (TREE_OPERAND (t, 0),
27593				   TREE_OPERAND (t, 1)))
27594    return false;
27595  else
27596    return true;
27597}
27598
27599/* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27600   [temp.dep.constexpr].  EXPRESSION is already known to be a constant
27601   expression.  */
27602
27603/* Note that this predicate is not appropriate for general expressions;
27604   only constant expressions (that satisfy potential_constant_expression)
27605   can be tested for value dependence.  */
27606
27607bool
27608value_dependent_expression_p (tree expression)
27609{
27610  if (!processing_template_decl || expression == NULL_TREE)
27611    return false;
27612
27613  /* A type-dependent expression is also value-dependent.  */
27614  if (type_dependent_expression_p (expression))
27615    return true;
27616
27617  switch (TREE_CODE (expression))
27618    {
27619    case BASELINK:
27620      /* A dependent member function of the current instantiation.  */
27621      return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27622
27623    case FUNCTION_DECL:
27624      /* A dependent member function of the current instantiation.  */
27625      if (DECL_CLASS_SCOPE_P (expression)
27626	  && dependent_type_p (DECL_CONTEXT (expression)))
27627	return true;
27628      break;
27629
27630    case IDENTIFIER_NODE:
27631      /* A name that has not been looked up -- must be dependent.  */
27632      return true;
27633
27634    case TEMPLATE_PARM_INDEX:
27635      /* A non-type template parm.  */
27636      return true;
27637
27638    case CONST_DECL:
27639      /* A non-type template parm.  */
27640      if (DECL_TEMPLATE_PARM_P (expression))
27641	return true;
27642      return value_dependent_expression_p (DECL_INITIAL (expression));
27643
27644    case VAR_DECL:
27645       /* A constant with literal type and is initialized
27646	  with an expression that is value-dependent.  */
27647      if (DECL_DEPENDENT_INIT_P (expression)
27648	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
27649	  || TYPE_REF_P (TREE_TYPE (expression)))
27650	return true;
27651      if (DECL_HAS_VALUE_EXPR_P (expression))
27652	{
27653	  tree value_expr = DECL_VALUE_EXPR (expression);
27654	  if (value_dependent_expression_p (value_expr)
27655	      /* __PRETTY_FUNCTION__ inside a template function is dependent
27656		 on the name of the function.  */
27657	      || (DECL_PRETTY_FUNCTION_P (expression)
27658		  /* It might be used in a template, but not a template
27659		     function, in which case its DECL_VALUE_EXPR will be
27660		     "top level".  */
27661		  && value_expr == error_mark_node))
27662	    return true;
27663	}
27664      return false;
27665
27666    case DYNAMIC_CAST_EXPR:
27667    case STATIC_CAST_EXPR:
27668    case CONST_CAST_EXPR:
27669    case REINTERPRET_CAST_EXPR:
27670    case CAST_EXPR:
27671    case IMPLICIT_CONV_EXPR:
27672      /* These expressions are value-dependent if the type to which
27673	 the cast occurs is dependent or the expression being casted
27674	 is value-dependent.  */
27675      {
27676	tree type = TREE_TYPE (expression);
27677
27678	if (dependent_type_p (type))
27679	  return true;
27680
27681	/* A functional cast has a list of operands.  */
27682	expression = TREE_OPERAND (expression, 0);
27683	if (!expression)
27684	  {
27685	    /* If there are no operands, it must be an expression such
27686	       as "int()". This should not happen for aggregate types
27687	       because it would form non-constant expressions.  */
27688	    gcc_assert (cxx_dialect >= cxx11
27689			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27690
27691	    return false;
27692	  }
27693
27694	if (TREE_CODE (expression) == TREE_LIST)
27695	  return any_value_dependent_elements_p (expression);
27696
27697	if (TREE_CODE (type) == REFERENCE_TYPE
27698	    && has_value_dependent_address (expression))
27699	  return true;
27700
27701	return value_dependent_expression_p (expression);
27702      }
27703
27704    case SIZEOF_EXPR:
27705      if (SIZEOF_EXPR_TYPE_P (expression))
27706	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27707      /* FALLTHRU */
27708    case ALIGNOF_EXPR:
27709    case TYPEID_EXPR:
27710      /* A `sizeof' expression is value-dependent if the operand is
27711	 type-dependent or is a pack expansion.  */
27712      expression = TREE_OPERAND (expression, 0);
27713      if (PACK_EXPANSION_P (expression))
27714        return true;
27715      else if (TYPE_P (expression))
27716	return dependent_type_p (expression);
27717      return instantiation_dependent_uneval_expression_p (expression);
27718
27719    case AT_ENCODE_EXPR:
27720      /* An 'encode' expression is value-dependent if the operand is
27721	 type-dependent.  */
27722      expression = TREE_OPERAND (expression, 0);
27723      return dependent_type_p (expression);
27724
27725    case NOEXCEPT_EXPR:
27726      expression = TREE_OPERAND (expression, 0);
27727      return instantiation_dependent_uneval_expression_p (expression);
27728
27729    case SCOPE_REF:
27730      /* All instantiation-dependent expressions should also be considered
27731	 value-dependent.  */
27732      return instantiation_dependent_scope_ref_p (expression);
27733
27734    case COMPONENT_REF:
27735      return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27736	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
27737
27738    case NONTYPE_ARGUMENT_PACK:
27739      /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
27740         is value-dependent.  */
27741      {
27742        tree values = ARGUMENT_PACK_ARGS (expression);
27743        int i, len = TREE_VEC_LENGTH (values);
27744
27745        for (i = 0; i < len; ++i)
27746          if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
27747            return true;
27748
27749        return false;
27750      }
27751
27752    case TRAIT_EXPR:
27753      {
27754	tree type2 = TRAIT_EXPR_TYPE2 (expression);
27755
27756	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
27757	  return true;
27758
27759	if (!type2)
27760	  return false;
27761
27762	if (TREE_CODE (type2) != TREE_LIST)
27763	  return dependent_type_p (type2);
27764
27765	for (; type2; type2 = TREE_CHAIN (type2))
27766	  if (dependent_type_p (TREE_VALUE (type2)))
27767	    return true;
27768
27769	return false;
27770      }
27771
27772    case MODOP_EXPR:
27773      return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27774	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27775
27776    case ARRAY_REF:
27777      return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27778	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27779
27780    case ADDR_EXPR:
27781      {
27782	tree op = TREE_OPERAND (expression, 0);
27783	return (value_dependent_expression_p (op)
27784		|| has_value_dependent_address (op));
27785      }
27786
27787    case REQUIRES_EXPR:
27788      /* Treat all requires-expressions as value-dependent so
27789         we don't try to fold them.  */
27790      return true;
27791
27792    case TYPE_REQ:
27793      return dependent_type_p (TREE_OPERAND (expression, 0));
27794
27795    case CALL_EXPR:
27796      {
27797	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27798	  return true;
27799	tree fn = get_callee_fndecl (expression);
27800	int i, nargs;
27801	nargs = call_expr_nargs (expression);
27802	for (i = 0; i < nargs; ++i)
27803	  {
27804	    tree op = CALL_EXPR_ARG (expression, i);
27805	    /* In a call to a constexpr member function, look through the
27806	       implicit ADDR_EXPR on the object argument so that it doesn't
27807	       cause the call to be considered value-dependent.  We also
27808	       look through it in potential_constant_expression.  */
27809	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27810		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27811		&& TREE_CODE (op) == ADDR_EXPR)
27812	      op = TREE_OPERAND (op, 0);
27813	    if (value_dependent_expression_p (op))
27814	      return true;
27815	  }
27816	return false;
27817      }
27818
27819    case TEMPLATE_ID_EXPR:
27820      return concept_definition_p (TREE_OPERAND (expression, 0))
27821	&& any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
27822
27823    case CONSTRUCTOR:
27824      {
27825	unsigned ix;
27826	tree val;
27827	if (dependent_type_p (TREE_TYPE (expression)))
27828	  return true;
27829	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27830	  if (value_dependent_expression_p (val))
27831	    return true;
27832	return false;
27833      }
27834
27835    case STMT_EXPR:
27836      /* Treat a GNU statement expression as dependent to avoid crashing
27837	 under instantiate_non_dependent_expr; it can't be constant.  */
27838      return true;
27839
27840    default:
27841      /* A constant expression is value-dependent if any subexpression is
27842	 value-dependent.  */
27843      switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27844	{
27845	case tcc_reference:
27846	case tcc_unary:
27847	case tcc_comparison:
27848	case tcc_binary:
27849	case tcc_expression:
27850	case tcc_vl_exp:
27851	  {
27852	    int i, len = cp_tree_operand_length (expression);
27853
27854	    for (i = 0; i < len; i++)
27855	      {
27856		tree t = TREE_OPERAND (expression, i);
27857
27858		/* In some cases, some of the operands may be missing.
27859		   (For example, in the case of PREDECREMENT_EXPR, the
27860		   amount to increment by may be missing.)  That doesn't
27861		   make the expression dependent.  */
27862		if (t && value_dependent_expression_p (t))
27863		  return true;
27864	      }
27865	  }
27866	  break;
27867	default:
27868	  break;
27869	}
27870      break;
27871    }
27872
27873  /* The expression is not value-dependent.  */
27874  return false;
27875}
27876
27877/* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
27878   [temp.dep.expr].  Note that an expression with no type is
27879   considered dependent.  Other parts of the compiler arrange for an
27880   expression with type-dependent subexpressions to have no type, so
27881   this function doesn't have to be fully recursive.  */
27882
27883bool
27884type_dependent_expression_p (tree expression)
27885{
27886  if (!processing_template_decl)
27887    return false;
27888
27889  if (expression == NULL_TREE || expression == error_mark_node)
27890    return false;
27891
27892  STRIP_ANY_LOCATION_WRAPPER (expression);
27893
27894  /* An unresolved name is always dependent.  */
27895  if (identifier_p (expression)
27896      || TREE_CODE (expression) == USING_DECL
27897      || TREE_CODE (expression) == WILDCARD_DECL)
27898    return true;
27899
27900  /* A lambda-expression in template context is dependent.  dependent_type_p is
27901     true for a lambda in the scope of a class or function template, but that
27902     doesn't cover all template contexts, like a default template argument.  */
27903  if (TREE_CODE (expression) == LAMBDA_EXPR)
27904    return true;
27905
27906  /* A fold expression is type-dependent. */
27907  if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
27908      || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
27909      || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
27910      || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
27911    return true;
27912
27913  /* Some expression forms are never type-dependent.  */
27914  if (TREE_CODE (expression) == SIZEOF_EXPR
27915      || TREE_CODE (expression) == ALIGNOF_EXPR
27916      || TREE_CODE (expression) == AT_ENCODE_EXPR
27917      || TREE_CODE (expression) == NOEXCEPT_EXPR
27918      || TREE_CODE (expression) == TRAIT_EXPR
27919      || TREE_CODE (expression) == TYPEID_EXPR
27920      || TREE_CODE (expression) == DELETE_EXPR
27921      || TREE_CODE (expression) == VEC_DELETE_EXPR
27922      || TREE_CODE (expression) == THROW_EXPR
27923      || TREE_CODE (expression) == REQUIRES_EXPR)
27924    return false;
27925
27926  /* The types of these expressions depends only on the type to which
27927     the cast occurs.  */
27928  if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
27929      || TREE_CODE (expression) == STATIC_CAST_EXPR
27930      || TREE_CODE (expression) == CONST_CAST_EXPR
27931      || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
27932      || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
27933      || TREE_CODE (expression) == CAST_EXPR)
27934    return dependent_type_p (TREE_TYPE (expression));
27935
27936  /* The types of these expressions depends only on the type created
27937     by the expression.  */
27938  if (TREE_CODE (expression) == NEW_EXPR
27939      || TREE_CODE (expression) == VEC_NEW_EXPR)
27940    {
27941      /* For NEW_EXPR tree nodes created inside a template, either
27942	 the object type itself or a TREE_LIST may appear as the
27943	 operand 1.  */
27944      tree type = TREE_OPERAND (expression, 1);
27945      if (TREE_CODE (type) == TREE_LIST)
27946	/* This is an array type.  We need to check array dimensions
27947	   as well.  */
27948	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
27949	       || value_dependent_expression_p
27950		    (TREE_OPERAND (TREE_VALUE (type), 1));
27951      /* Array type whose dimension has to be deduced.  */
27952      else if (TREE_CODE (type) == ARRAY_TYPE
27953	       && TREE_OPERAND (expression, 2) == NULL_TREE)
27954	return true;
27955      else
27956	return dependent_type_p (type);
27957    }
27958
27959  if (TREE_CODE (expression) == SCOPE_REF)
27960    {
27961      tree scope = TREE_OPERAND (expression, 0);
27962      tree name = TREE_OPERAND (expression, 1);
27963
27964      /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
27965	 contains an identifier associated by name lookup with one or more
27966	 declarations declared with a dependent type, or...a
27967	 nested-name-specifier or qualified-id that names a member of an
27968	 unknown specialization.  */
27969      return (type_dependent_expression_p (name)
27970	      || dependent_scope_p (scope));
27971    }
27972
27973  if (TREE_CODE (expression) == TEMPLATE_DECL
27974      && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27975    return uses_outer_template_parms (expression);
27976
27977  if (TREE_CODE (expression) == STMT_EXPR)
27978    expression = stmt_expr_value_expr (expression);
27979
27980  if (BRACE_ENCLOSED_INITIALIZER_P (expression))
27981    {
27982      for (auto &elt : CONSTRUCTOR_ELTS (expression))
27983	if (type_dependent_expression_p (elt.value))
27984	  return true;
27985      return false;
27986    }
27987
27988  /* A static data member of the current instantiation with incomplete
27989     array type is type-dependent, as the definition and specializations
27990     can have different bounds.  */
27991  if (VAR_P (expression)
27992      && DECL_CLASS_SCOPE_P (expression)
27993      && dependent_type_p (DECL_CONTEXT (expression))
27994      && VAR_HAD_UNKNOWN_BOUND (expression))
27995    return true;
27996
27997  /* An array of unknown bound depending on a variadic parameter, eg:
27998
27999     template<typename... Args>
28000       void foo (Args... args)
28001       {
28002         int arr[] = { args... };
28003       }
28004
28005     template<int... vals>
28006       void bar ()
28007       {
28008         int arr[] = { vals... };
28009       }
28010
28011     If the array has no length and has an initializer, it must be that
28012     we couldn't determine its length in cp_complete_array_type because
28013     it is dependent.  */
28014  if (((VAR_P (expression) && DECL_INITIAL (expression))
28015       || COMPOUND_LITERAL_P (expression))
28016      && TREE_TYPE (expression) != NULL_TREE
28017      && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28018      && !TYPE_DOMAIN (TREE_TYPE (expression)))
28019   return true;
28020
28021  /* Pull a FUNCTION_DECL out of a BASELINK if we can.  */
28022  if (BASELINK_P (expression))
28023    {
28024      if (BASELINK_OPTYPE (expression)
28025	  && dependent_type_p (BASELINK_OPTYPE (expression)))
28026	return true;
28027      expression = BASELINK_FUNCTIONS (expression);
28028    }
28029
28030  /* A function or variable template-id is type-dependent if it has any
28031     dependent template arguments.  */
28032  if (VAR_OR_FUNCTION_DECL_P (expression)
28033      && DECL_LANG_SPECIFIC (expression)
28034      && DECL_TEMPLATE_INFO (expression))
28035    {
28036      /* Consider the innermost template arguments, since those are the ones
28037	 that come from the template-id; the template arguments for the
28038	 enclosing class do not make it type-dependent unless they are used in
28039	 the type of the decl.  */
28040      if (instantiates_primary_template_p (expression)
28041	  && (any_dependent_template_arguments_p
28042	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28043	return true;
28044    }
28045
28046  /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28047     type-dependent.  Checking this is important for functions with auto return
28048     type, which looks like a dependent type.  */
28049  if (TREE_CODE (expression) == FUNCTION_DECL
28050      && !(DECL_CLASS_SCOPE_P (expression)
28051	   && dependent_type_p (DECL_CONTEXT (expression)))
28052      && !(DECL_LANG_SPECIFIC (expression)
28053	   && DECL_UNIQUE_FRIEND_P (expression)
28054	   && (!DECL_FRIEND_CONTEXT (expression)
28055	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28056      && !DECL_LOCAL_DECL_P (expression))
28057    {
28058      gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28059		  || undeduced_auto_decl (expression));
28060      return false;
28061    }
28062
28063  /* Otherwise, its constraints could still depend on outer template parameters
28064     from its (dependent) scope.  */
28065  if (TREE_CODE (expression) == FUNCTION_DECL
28066      /* As an optimization, check this cheaper sufficient condition first.
28067	 (At this point we've established that we're looking at a member of
28068	 a dependent class, so it makes sense to start treating say undeduced
28069	 auto as dependent.)  */
28070      && !dependent_type_p (TREE_TYPE (expression))
28071      && uses_outer_template_parms_in_constraints (expression))
28072    return true;
28073
28074  /* Always dependent, on the number of arguments if nothing else.  */
28075  if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28076    return true;
28077
28078  if (TREE_TYPE (expression) == unknown_type_node)
28079    {
28080      if (TREE_CODE (expression) == ADDR_EXPR)
28081	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28082      if (TREE_CODE (expression) == COMPONENT_REF
28083	  || TREE_CODE (expression) == OFFSET_REF)
28084	{
28085	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28086	    return true;
28087	  expression = TREE_OPERAND (expression, 1);
28088	  if (identifier_p (expression))
28089	    return false;
28090	}
28091      /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
28092      if (TREE_CODE (expression) == SCOPE_REF)
28093	return false;
28094
28095      /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
28096      if (TREE_CODE (expression) == CO_AWAIT_EXPR
28097	  || TREE_CODE (expression) == CO_YIELD_EXPR)
28098	return true;
28099
28100      if (BASELINK_P (expression))
28101	{
28102	  if (BASELINK_OPTYPE (expression)
28103	      && dependent_type_p (BASELINK_OPTYPE (expression)))
28104	    return true;
28105	  expression = BASELINK_FUNCTIONS (expression);
28106	}
28107
28108      if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28109	{
28110	  if (any_dependent_template_arguments_p
28111	      (TREE_OPERAND (expression, 1)))
28112	    return true;
28113	  expression = TREE_OPERAND (expression, 0);
28114	  if (identifier_p (expression))
28115	    return true;
28116	}
28117
28118      gcc_assert (OVL_P (expression));
28119
28120      for (lkp_iterator iter (expression); iter; ++iter)
28121	if (type_dependent_expression_p (*iter))
28122	  return true;
28123
28124      return false;
28125    }
28126
28127  /* The type of a non-type template parm declared with a placeholder type
28128     depends on the corresponding template argument, even though
28129     placeholders are not normally considered dependent.  */
28130  if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28131      && is_auto (TREE_TYPE (expression)))
28132    return true;
28133
28134  gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28135
28136  /* Dependent type attributes might not have made it from the decl to
28137     the type yet.  */
28138  if (DECL_P (expression)
28139      && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28140    return true;
28141
28142  return (dependent_type_p (TREE_TYPE (expression)));
28143}
28144
28145/* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28146   type-dependent if the expression refers to a member of the current
28147   instantiation and the type of the referenced member is dependent, or the
28148   class member access expression refers to a member of an unknown
28149   specialization.
28150
28151   This function returns true if the OBJECT in such a class member access
28152   expression is of an unknown specialization.  */
28153
28154bool
28155type_dependent_object_expression_p (tree object)
28156{
28157  /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28158     dependent.  */
28159  if (TREE_CODE (object) == IDENTIFIER_NODE)
28160    return true;
28161  tree scope = TREE_TYPE (object);
28162  return (!scope || dependent_scope_p (scope));
28163}
28164
28165/* walk_tree callback function for instantiation_dependent_expression_p,
28166   below.  Returns non-zero if a dependent subexpression is found.  */
28167
28168static tree
28169instantiation_dependent_r (tree *tp, int *walk_subtrees,
28170			   void * /*data*/)
28171{
28172  if (TYPE_P (*tp))
28173    {
28174      /* We don't have to worry about decltype currently because decltype
28175	 of an instantiation-dependent expr is a dependent type.  This
28176	 might change depending on the resolution of DR 1172.  */
28177      *walk_subtrees = false;
28178      return NULL_TREE;
28179    }
28180  enum tree_code code = TREE_CODE (*tp);
28181  switch (code)
28182    {
28183      /* Don't treat an argument list as dependent just because it has no
28184	 TREE_TYPE.  */
28185    case TREE_LIST:
28186    case TREE_VEC:
28187    case NONTYPE_ARGUMENT_PACK:
28188      return NULL_TREE;
28189
28190    case TEMPLATE_PARM_INDEX:
28191      if (dependent_type_p (TREE_TYPE (*tp)))
28192	return *tp;
28193      if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28194	return *tp;
28195      /* We'll check value-dependence separately.  */
28196      return NULL_TREE;
28197
28198      /* Handle expressions with type operands.  */
28199    case SIZEOF_EXPR:
28200    case ALIGNOF_EXPR:
28201    case TYPEID_EXPR:
28202    case AT_ENCODE_EXPR:
28203      {
28204	tree op = TREE_OPERAND (*tp, 0);
28205	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28206	  op = TREE_TYPE (op);
28207	if (TYPE_P (op))
28208	  {
28209	    if (dependent_type_p (op))
28210	      return *tp;
28211	    else
28212	      {
28213		*walk_subtrees = false;
28214		return NULL_TREE;
28215	      }
28216	  }
28217	break;
28218      }
28219
28220    case COMPONENT_REF:
28221      if (identifier_p (TREE_OPERAND (*tp, 1)))
28222	/* In a template, finish_class_member_access_expr creates a
28223	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28224	   type-dependent, so that we can check access control at
28225	   instantiation time (PR 42277).  See also Core issue 1273.  */
28226	return *tp;
28227      break;
28228
28229    case SCOPE_REF:
28230      if (instantiation_dependent_scope_ref_p (*tp))
28231	return *tp;
28232      else
28233	break;
28234
28235      /* Treat statement-expressions as dependent.  */
28236    case BIND_EXPR:
28237      return *tp;
28238
28239      /* Treat requires-expressions as dependent. */
28240    case REQUIRES_EXPR:
28241      return *tp;
28242
28243    case CONSTRUCTOR:
28244      if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28245	return *tp;
28246      break;
28247
28248    case TEMPLATE_DECL:
28249    case FUNCTION_DECL:
28250      /* Before C++17, a noexcept-specifier isn't part of the function type
28251	 so it doesn't affect type dependence, but we still want to consider it
28252	 for instantiation dependence.  */
28253      if (cxx_dialect < cxx17
28254	  && DECL_DECLARES_FUNCTION_P (*tp)
28255	  && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28256	return *tp;
28257      break;
28258
28259    default:
28260      break;
28261    }
28262
28263  if (type_dependent_expression_p (*tp))
28264    return *tp;
28265  else
28266    return NULL_TREE;
28267}
28268
28269/* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28270   sense defined by the ABI:
28271
28272   "An expression is instantiation-dependent if it is type-dependent
28273   or value-dependent, or it has a subexpression that is type-dependent
28274   or value-dependent."
28275
28276   Except don't actually check value-dependence for unevaluated expressions,
28277   because in sizeof(i) we don't care about the value of i.  Checking
28278   type-dependence will in turn check value-dependence of array bounds/template
28279   arguments as needed.  */
28280
28281bool
28282instantiation_dependent_uneval_expression_p (tree expression)
28283{
28284  tree result;
28285
28286  if (!processing_template_decl)
28287    return false;
28288
28289  if (expression == error_mark_node)
28290    return false;
28291
28292  result = cp_walk_tree_without_duplicates (&expression,
28293					    instantiation_dependent_r, NULL);
28294  return result != NULL_TREE;
28295}
28296
28297/* As above, but also check value-dependence of the expression as a whole.  */
28298
28299bool
28300instantiation_dependent_expression_p (tree expression)
28301{
28302  return (instantiation_dependent_uneval_expression_p (expression)
28303	  || (processing_template_decl
28304	      && potential_constant_expression (expression)
28305	      && value_dependent_expression_p (expression)));
28306}
28307
28308/* Like type_dependent_expression_p, but it also works while not processing
28309   a template definition, i.e. during substitution or mangling.  */
28310
28311bool
28312type_dependent_expression_p_push (tree expr)
28313{
28314  bool b;
28315  ++processing_template_decl;
28316  b = type_dependent_expression_p (expr);
28317  --processing_template_decl;
28318  return b;
28319}
28320
28321/* Returns TRUE if ARGS contains a type-dependent expression.  */
28322
28323bool
28324any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28325{
28326  unsigned int i;
28327  tree arg;
28328
28329  FOR_EACH_VEC_SAFE_ELT (args, i, arg)
28330    {
28331      if (type_dependent_expression_p (arg))
28332	return true;
28333    }
28334  return false;
28335}
28336
28337/* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28338   expressions) contains any type-dependent expressions.  */
28339
28340bool
28341any_type_dependent_elements_p (const_tree list)
28342{
28343  for (; list; list = TREE_CHAIN (list))
28344    if (type_dependent_expression_p (TREE_VALUE (list)))
28345      return true;
28346
28347  return false;
28348}
28349
28350/* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28351   expressions) contains any value-dependent expressions.  */
28352
28353bool
28354any_value_dependent_elements_p (const_tree list)
28355{
28356  for (; list; list = TREE_CHAIN (list))
28357    if (value_dependent_expression_p (TREE_VALUE (list)))
28358      return true;
28359
28360  return false;
28361}
28362
28363/* Returns TRUE if the ARG (a template argument) is dependent.  */
28364
28365bool
28366dependent_template_arg_p (tree arg)
28367{
28368  if (!processing_template_decl)
28369    return false;
28370
28371  /* Assume a template argument that was wrongly written by the user
28372     is dependent. This is consistent with what
28373     any_dependent_template_arguments_p [that calls this function]
28374     does.  */
28375  if (!arg || arg == error_mark_node)
28376    return true;
28377
28378  if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28379    arg = argument_pack_select_arg (arg);
28380
28381  if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28382    return true;
28383  if (TREE_CODE (arg) == TEMPLATE_DECL)
28384    {
28385      if (DECL_TEMPLATE_PARM_P (arg))
28386	return true;
28387      /* A member template of a dependent class is not necessarily
28388	 type-dependent, but it is a dependent template argument because it
28389	 will be a member of an unknown specialization to that template.  */
28390      tree scope = CP_DECL_CONTEXT (arg);
28391      return TYPE_P (scope) && dependent_type_p (scope);
28392    }
28393  else if (ARGUMENT_PACK_P (arg))
28394    {
28395      tree args = ARGUMENT_PACK_ARGS (arg);
28396      int i, len = TREE_VEC_LENGTH (args);
28397      for (i = 0; i < len; ++i)
28398        {
28399          if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
28400            return true;
28401        }
28402
28403      return false;
28404    }
28405  else if (TYPE_P (arg))
28406    return dependent_type_p (arg);
28407  else
28408    return value_dependent_expression_p (arg);
28409}
28410
28411/* Identify any expressions that use function parms.  */
28412
28413static tree
28414find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28415{
28416  tree t = *tp;
28417  if (TREE_CODE (t) == PARM_DECL)
28418    {
28419      *walk_subtrees = 0;
28420      return t;
28421    }
28422  return NULL_TREE;
28423}
28424
28425/* Returns true if ARGS (a collection of template arguments) contains
28426   any types that require structural equality testing.  */
28427
28428bool
28429any_template_arguments_need_structural_equality_p (tree args)
28430{
28431  int i;
28432  int j;
28433
28434  if (!args)
28435    return false;
28436  if (args == error_mark_node)
28437    return true;
28438
28439  for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28440    {
28441      tree level = TMPL_ARGS_LEVEL (args, i + 1);
28442      for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28443	{
28444	  tree arg = TREE_VEC_ELT (level, j);
28445	  tree packed_args = NULL_TREE;
28446	  int k, len = 1;
28447
28448	  if (ARGUMENT_PACK_P (arg))
28449	    {
28450	      /* Look inside the argument pack.  */
28451	      packed_args = ARGUMENT_PACK_ARGS (arg);
28452	      len = TREE_VEC_LENGTH (packed_args);
28453	    }
28454
28455	  for (k = 0; k < len; ++k)
28456	    {
28457	      if (packed_args)
28458		arg = TREE_VEC_ELT (packed_args, k);
28459
28460	      if (error_operand_p (arg))
28461		return true;
28462	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
28463		continue;
28464	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
28465		return true;
28466	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
28467		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
28468		return true;
28469	      /* Checking current_function_decl because this structural
28470		 comparison is only necessary for redeclaration.  */
28471	      else if (!current_function_decl
28472		       && dependent_template_arg_p (arg)
28473		       && (cp_walk_tree_without_duplicates
28474			   (&arg, find_parm_usage_r, NULL)))
28475		return true;
28476	    }
28477	}
28478    }
28479
28480  return false;
28481}
28482
28483/* Returns true if ARGS (a collection of template arguments) contains
28484   any dependent arguments.  */
28485
28486bool
28487any_dependent_template_arguments_p (const_tree args)
28488{
28489  int i;
28490  int j;
28491
28492  if (!args)
28493    return false;
28494  if (args == error_mark_node)
28495    return true;
28496
28497  for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28498    {
28499      const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28500      for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28501	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
28502	  return true;
28503    }
28504
28505  return false;
28506}
28507
28508/* Returns true if ARGS contains any errors.  */
28509
28510bool
28511any_erroneous_template_args_p (const_tree args)
28512{
28513  int i;
28514  int j;
28515
28516  if (args == error_mark_node)
28517    return true;
28518
28519  if (args && TREE_CODE (args) != TREE_VEC)
28520    {
28521      if (tree ti = get_template_info (args))
28522	args = TI_ARGS (ti);
28523      else
28524	args = NULL_TREE;
28525    }
28526
28527  if (!args)
28528    return false;
28529
28530  for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28531    {
28532      const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28533      for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28534	if (error_operand_p (TREE_VEC_ELT (level, j)))
28535	  return true;
28536    }
28537
28538  return false;
28539}
28540
28541/* Returns TRUE if the template TMPL is type-dependent.  */
28542
28543bool
28544dependent_template_p (tree tmpl)
28545{
28546  if (TREE_CODE (tmpl) == OVERLOAD)
28547    {
28548      for (lkp_iterator iter (tmpl); iter; ++iter)
28549	if (dependent_template_p (*iter))
28550	  return true;
28551      return false;
28552    }
28553
28554  /* Template template parameters are dependent.  */
28555  if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28556      || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28557    return true;
28558  /* So are names that have not been looked up.  */
28559  if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28560    return true;
28561  return false;
28562}
28563
28564/* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
28565
28566bool
28567dependent_template_id_p (tree tmpl, tree args)
28568{
28569  return (dependent_template_p (tmpl)
28570	  || any_dependent_template_arguments_p (args));
28571}
28572
28573/* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28574   are dependent.  */
28575
28576bool
28577dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28578{
28579  int i;
28580
28581  if (!processing_template_decl)
28582    return false;
28583
28584  for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28585    {
28586      tree decl = TREE_VEC_ELT (declv, i);
28587      tree init = TREE_VEC_ELT (initv, i);
28588      tree cond = TREE_VEC_ELT (condv, i);
28589      tree incr = TREE_VEC_ELT (incrv, i);
28590
28591      if (type_dependent_expression_p (decl)
28592	  || TREE_CODE (decl) == SCOPE_REF)
28593	return true;
28594
28595      if (init && type_dependent_expression_p (init))
28596	return true;
28597
28598      if (cond == global_namespace)
28599	return true;
28600
28601      if (type_dependent_expression_p (cond))
28602	return true;
28603
28604      if (COMPARISON_CLASS_P (cond)
28605	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28606	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28607	return true;
28608
28609      if (TREE_CODE (incr) == MODOP_EXPR)
28610	{
28611	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28612	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28613	    return true;
28614	}
28615      else if (type_dependent_expression_p (incr))
28616	return true;
28617      else if (TREE_CODE (incr) == MODIFY_EXPR)
28618	{
28619	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28620	    return true;
28621	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28622	    {
28623	      tree t = TREE_OPERAND (incr, 1);
28624	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28625		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28626		return true;
28627
28628	      /* If this loop has a class iterator with != comparison
28629		 with increment other than i++/++i/i--/--i, make sure the
28630		 increment is constant.  */
28631	      if (CLASS_TYPE_P (TREE_TYPE (decl))
28632		  && TREE_CODE (cond) == NE_EXPR)
28633		{
28634		  if (TREE_OPERAND (t, 0) == decl)
28635		    t = TREE_OPERAND (t, 1);
28636		  else
28637		    t = TREE_OPERAND (t, 0);
28638		  if (TREE_CODE (t) != INTEGER_CST)
28639		    return true;
28640		}
28641	    }
28642	}
28643    }
28644
28645  return false;
28646}
28647
28648/* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
28649   TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
28650   no such TYPE can be found.  Note that this function peers inside
28651   uninstantiated templates and therefore should be used only in
28652   extremely limited situations.  ONLY_CURRENT_P restricts this
28653   peering to the currently open classes hierarchy (which is required
28654   when comparing types).  */
28655
28656tree
28657resolve_typename_type (tree type, bool only_current_p)
28658{
28659  tree scope;
28660  tree name;
28661  tree decl;
28662  int quals;
28663  tree pushed_scope;
28664  tree result;
28665
28666  gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28667
28668  scope = TYPE_CONTEXT (type);
28669  /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
28670  gcc_checking_assert (uses_template_parms (scope));
28671
28672  /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28673     TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
28674     TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
28675     representing the typedef. In that case TYPE_IDENTIFIER (type) is
28676     not the non-qualified identifier of the TYPENAME_TYPE anymore.
28677     So by getting the TYPE_IDENTIFIER of the _main declaration_ of
28678     the TYPENAME_TYPE instead, we avoid messing up with a possible
28679     typedef variant case.  */
28680  name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
28681
28682  /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
28683     it first before we can figure out what NAME refers to.  */
28684  if (TREE_CODE (scope) == TYPENAME_TYPE)
28685    {
28686      if (TYPENAME_IS_RESOLVING_P (scope))
28687	/* Given a class template A with a dependent base with nested type C,
28688	   typedef typename A::C::C C will land us here, as trying to resolve
28689	   the initial A::C leads to the local C typedef, which leads back to
28690	   A::C::C.  So we break the recursion now.  */
28691	return type;
28692      else
28693	scope = resolve_typename_type (scope, only_current_p);
28694    }
28695  /* If we don't know what SCOPE refers to, then we cannot resolve the
28696     TYPENAME_TYPE.  */
28697  if (!CLASS_TYPE_P (scope))
28698    return type;
28699  /* If this is a typedef, we don't want to look inside (c++/11987).  */
28700  if (typedef_variant_p (type))
28701    return type;
28702  /* If SCOPE isn't the template itself, it will not have a valid
28703     TYPE_FIELDS list.  */
28704  if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
28705    /* scope is either the template itself or a compatible instantiation
28706       like X<T>, so look up the name in the original template.  */
28707    scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
28708  /* If scope has no fields, it can't be a current instantiation.  Check this
28709     before currently_open_class to avoid infinite recursion (71515).  */
28710  if (!TYPE_FIELDS (scope))
28711    return type;
28712  /* If the SCOPE is not the current instantiation, there's no reason
28713     to look inside it.  */
28714  if (only_current_p && !currently_open_class (scope))
28715    return type;
28716  /* Enter the SCOPE so that name lookup will be resolved as if we
28717     were in the class definition.  In particular, SCOPE will no
28718     longer be considered a dependent type.  */
28719  pushed_scope = push_scope (scope);
28720  /* Look up the declaration.  */
28721  decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
28722			tf_warning_or_error);
28723
28724  result = NULL_TREE;
28725
28726  /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
28727     find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
28728  tree fullname = TYPENAME_TYPE_FULLNAME (type);
28729  if (!decl)
28730    /*nop*/;
28731  else if (identifier_p (fullname)
28732	   && TREE_CODE (decl) == TYPE_DECL)
28733    {
28734      result = TREE_TYPE (decl);
28735      if (result == error_mark_node)
28736	result = NULL_TREE;
28737    }
28738  else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
28739	   && DECL_CLASS_TEMPLATE_P (decl))
28740    {
28741      /* Obtain the template and the arguments.  */
28742      tree tmpl = TREE_OPERAND (fullname, 0);
28743      if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
28744	{
28745	  /* We get here with a plain identifier because a previous tentative
28746	     parse of the nested-name-specifier as part of a ptr-operator saw
28747	     ::template X<A>.  The use of ::template is necessary in a
28748	     ptr-operator, but wrong in a declarator-id.
28749
28750	     [temp.names]: In a qualified-id of a declarator-id, the keyword
28751	     template shall not appear at the top level.  */
28752	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
28753		   "keyword %<template%> not allowed in declarator-id");
28754	  tmpl = decl;
28755	}
28756      tree args = TREE_OPERAND (fullname, 1);
28757      /* Instantiate the template.  */
28758      result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
28759				      /*entering_scope=*/true,
28760				      tf_error | tf_user);
28761      if (result == error_mark_node)
28762	result = NULL_TREE;
28763    }
28764
28765  /* Leave the SCOPE.  */
28766  if (pushed_scope)
28767    pop_scope (pushed_scope);
28768
28769  /* If we failed to resolve it, return the original typename.  */
28770  if (!result)
28771    return type;
28772
28773  /* If lookup found a typename type, resolve that too.  */
28774  if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
28775    {
28776      /* Ill-formed programs can cause infinite recursion here, so we
28777	 must catch that.  */
28778      TYPENAME_IS_RESOLVING_P (result) = 1;
28779      result = resolve_typename_type (result, only_current_p);
28780      TYPENAME_IS_RESOLVING_P (result) = 0;
28781    }
28782
28783  /* Qualify the resulting type.  */
28784  quals = cp_type_quals (type);
28785  if (quals)
28786    result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
28787
28788  return result;
28789}
28790
28791/* EXPR is an expression which is not type-dependent.  Return a proxy
28792   for EXPR that can be used to compute the types of larger
28793   expressions containing EXPR.  */
28794
28795tree
28796build_non_dependent_expr (tree expr)
28797{
28798  tree orig_expr = expr;
28799  tree inner_expr;
28800
28801  /* When checking, try to get a constant value for all non-dependent
28802     expressions in order to expose bugs in *_dependent_expression_p
28803     and constexpr.  This can affect code generation, see PR70704, so
28804     only do this for -fchecking=2.  */
28805  if (flag_checking > 1
28806      && cxx_dialect >= cxx11
28807      /* Don't do this during nsdmi parsing as it can lead to
28808	 unexpected recursive instantiations.  */
28809      && !parsing_nsdmi ()
28810      /* Don't do this during concept processing either and for
28811         the same reason.  */
28812      && !processing_constraint_expression_p ())
28813    fold_non_dependent_expr (expr, tf_none);
28814
28815  STRIP_ANY_LOCATION_WRAPPER (expr);
28816
28817  /* Preserve OVERLOADs; the functions must be available to resolve
28818     types.  */
28819  inner_expr = expr;
28820  if (TREE_CODE (inner_expr) == STMT_EXPR)
28821    inner_expr = stmt_expr_value_expr (inner_expr);
28822  if (TREE_CODE (inner_expr) == ADDR_EXPR)
28823    inner_expr = TREE_OPERAND (inner_expr, 0);
28824  if (TREE_CODE (inner_expr) == COMPONENT_REF)
28825    inner_expr = TREE_OPERAND (inner_expr, 1);
28826  if (is_overloaded_fn (inner_expr)
28827      || TREE_CODE (inner_expr) == OFFSET_REF)
28828    return orig_expr;
28829  /* There is no need to return a proxy for a variable, parameter
28830     or enumerator.  */
28831  if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
28832      || TREE_CODE (expr) == CONST_DECL)
28833    return orig_expr;
28834  /* Preserve string constants; conversions from string constants to
28835     "char *" are allowed, even though normally a "const char *"
28836     cannot be used to initialize a "char *".  */
28837  if (TREE_CODE (expr) == STRING_CST)
28838    return orig_expr;
28839  /* Preserve void and arithmetic constants, as an optimization -- there is no
28840     reason to create a new node.  */
28841  if (TREE_CODE (expr) == VOID_CST
28842      || TREE_CODE (expr) == INTEGER_CST
28843      || TREE_CODE (expr) == REAL_CST)
28844    return orig_expr;
28845  /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
28846     There is at least one place where we want to know that a
28847     particular expression is a throw-expression: when checking a ?:
28848     expression, there are special rules if the second or third
28849     argument is a throw-expression.  */
28850  if (TREE_CODE (expr) == THROW_EXPR)
28851    return orig_expr;
28852
28853  /* Don't wrap an initializer list, we need to be able to look inside.  */
28854  if (BRACE_ENCLOSED_INITIALIZER_P (expr))
28855    return orig_expr;
28856
28857  /* Don't wrap a dummy object, we need to be able to test for it.  */
28858  if (is_dummy_object (expr))
28859    return orig_expr;
28860
28861  if (TREE_CODE (expr) == COND_EXPR)
28862    return build3 (COND_EXPR,
28863		   TREE_TYPE (expr),
28864		   build_non_dependent_expr (TREE_OPERAND (expr, 0)),
28865		   (TREE_OPERAND (expr, 1)
28866		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
28867		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
28868		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
28869  if (TREE_CODE (expr) == COMPOUND_EXPR)
28870    return build2 (COMPOUND_EXPR,
28871		   TREE_TYPE (expr),
28872		   TREE_OPERAND (expr, 0),
28873		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
28874
28875  /* If the type is unknown, it can't really be non-dependent */
28876  gcc_assert (TREE_TYPE (expr) != unknown_type_node);
28877
28878  /* Otherwise, build a NON_DEPENDENT_EXPR.  */
28879  return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
28880		     TREE_TYPE (expr), expr);
28881}
28882
28883/* ARGS is a vector of expressions as arguments to a function call.
28884   Replace the arguments with equivalent non-dependent expressions.
28885   This modifies ARGS in place.  */
28886
28887void
28888make_args_non_dependent (vec<tree, va_gc> *args)
28889{
28890  unsigned int ix;
28891  tree arg;
28892
28893  FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
28894    {
28895      tree newarg = build_non_dependent_expr (arg);
28896      if (newarg != arg)
28897	(*args)[ix] = newarg;
28898    }
28899}
28900
28901/* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
28902   TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
28903   by default.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
28904
28905static tree
28906make_auto_1 (tree name, bool set_canonical, int level = -1)
28907{
28908  if (level == -1)
28909    level = current_template_depth + 1;
28910  tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28911  TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28912  TYPE_STUB_DECL (au) = TYPE_NAME (au);
28913  TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28914    (0, level, level, TYPE_NAME (au), NULL_TREE);
28915  if (set_canonical)
28916    TYPE_CANONICAL (au) = canonical_type_parameter (au);
28917  DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28918  SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28919  if (name == decltype_auto_identifier)
28920    AUTO_IS_DECLTYPE (au) = true;
28921
28922  return au;
28923}
28924
28925tree
28926make_decltype_auto (void)
28927{
28928  return make_auto_1 (decltype_auto_identifier, true);
28929}
28930
28931tree
28932make_auto (void)
28933{
28934  return make_auto_1 (auto_identifier, true);
28935}
28936
28937/* Return a C++17 deduction placeholder for class template TMPL.
28938   There are represented as an 'auto' with the special level 0 and
28939   CLASS_PLACEHOLDER_TEMPLATE set.  */
28940
28941tree
28942make_template_placeholder (tree tmpl)
28943{
28944  tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
28945  CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
28946  /* Our canonical type depends on the placeholder.  */
28947  TYPE_CANONICAL (t) = canonical_type_parameter (t);
28948  return t;
28949}
28950
28951/* True iff T is a C++17 class template deduction placeholder.  */
28952
28953bool
28954template_placeholder_p (tree t)
28955{
28956  return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
28957}
28958
28959/* Make a "constrained auto" type-specifier. This is an auto or
28960  decltype(auto) type with constraints that must be associated after
28961  deduction.  The constraint is formed from the given concept CON
28962  and its optional sequence of template arguments ARGS.
28963
28964  TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28965
28966static tree
28967make_constrained_placeholder_type (tree type, tree con, tree args)
28968{
28969  /* Build the constraint. */
28970  tree tmpl = DECL_TI_TEMPLATE (con);
28971  tree expr = tmpl;
28972  if (TREE_CODE (con) == FUNCTION_DECL)
28973    expr = ovl_make (tmpl);
28974  ++processing_template_decl;
28975  expr = build_concept_check (expr, type, args, tf_warning_or_error);
28976  --processing_template_decl;
28977
28978  PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
28979    = build_tree_list (current_template_parms, expr);
28980
28981  /* Our canonical type depends on the constraint.  */
28982  TYPE_CANONICAL (type) = canonical_type_parameter (type);
28983
28984  /* Attach the constraint to the type declaration. */
28985  return TYPE_NAME (type);
28986}
28987
28988/* Make a "constrained auto" type-specifier.  */
28989
28990tree
28991make_constrained_auto (tree con, tree args)
28992{
28993  tree type = make_auto_1 (auto_identifier, false);
28994  return make_constrained_placeholder_type (type, con, args);
28995}
28996
28997/* Make a "constrained decltype(auto)" type-specifier.  */
28998
28999tree
29000make_constrained_decltype_auto (tree con, tree args)
29001{
29002  tree type = make_auto_1 (decltype_auto_identifier, false);
29003  return make_constrained_placeholder_type (type, con, args);
29004}
29005
29006/* Returns true if the placeholder type constraint T has any dependent
29007   (explicit) template arguments.  */
29008
29009static bool
29010placeholder_type_constraint_dependent_p (tree t)
29011{
29012  tree id = unpack_concept_check (t);
29013  tree args = TREE_OPERAND (id, 1);
29014  tree first = TREE_VEC_ELT (args, 0);
29015  if (ARGUMENT_PACK_P (first))
29016    {
29017      args = expand_template_argument_pack (args);
29018      first = TREE_VEC_ELT (args, 0);
29019    }
29020  gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29021		       || is_auto (first));
29022  for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29023    if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29024      return true;
29025  return false;
29026}
29027
29028/* Build and return a concept definition. Like other templates, the
29029   CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
29030   the TEMPLATE_DECL. */
29031
29032tree
29033finish_concept_definition (cp_expr id, tree init)
29034{
29035  gcc_assert (identifier_p (id));
29036  gcc_assert (processing_template_decl);
29037
29038  location_t loc = id.get_location();
29039
29040  /* A concept-definition shall not have associated constraints.  */
29041  if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29042    {
29043      error_at (loc, "a concept cannot be constrained");
29044      TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29045    }
29046
29047  /* A concept-definition shall appear in namespace scope.  Templates
29048     aren't allowed in block scope, so we only need to check for class
29049     scope.  */
29050  if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29051    {
29052      error_at (loc, "concept %qE not in namespace scope", *id);
29053      return error_mark_node;
29054    }
29055
29056  if (current_template_depth > 1)
29057    {
29058      error_at (loc, "concept %qE has multiple template parameter lists", *id);
29059      return error_mark_node;
29060    }
29061
29062  /* Initially build the concept declaration; its type is bool.  */
29063  tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29064  DECL_CONTEXT (decl) = current_scope ();
29065  DECL_INITIAL (decl) = init;
29066
29067  set_originating_module (decl, false);
29068
29069  /* Push the enclosing template.  */
29070  return push_template_decl (decl);
29071}
29072
29073/* Given type ARG, return std::initializer_list<ARG>.  */
29074
29075static tree
29076listify (tree arg)
29077{
29078  tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
29079
29080  if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
29081    {
29082      gcc_rich_location richloc (input_location);
29083      maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29084      error_at (&richloc,
29085		"deducing from brace-enclosed initializer list"
29086		" requires %<#include <initializer_list>%>");
29087
29088      return error_mark_node;
29089    }
29090  tree argvec = make_tree_vec (1);
29091  TREE_VEC_ELT (argvec, 0) = arg;
29092
29093  return lookup_template_class (std_init_list, argvec, NULL_TREE,
29094				NULL_TREE, 0, tf_warning_or_error);
29095}
29096
29097/* Replace auto in TYPE with std::initializer_list<auto>.  */
29098
29099static tree
29100listify_autos (tree type, tree auto_node)
29101{
29102  tree init_auto = listify (strip_top_quals (auto_node));
29103  tree argvec = make_tree_vec (1);
29104  TREE_VEC_ELT (argvec, 0) = init_auto;
29105  if (processing_template_decl)
29106    argvec = add_to_template_args (current_template_args (), argvec);
29107  return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29108}
29109
29110/* Hash traits for hashing possibly constrained 'auto'
29111   TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
29112
29113struct auto_hash : default_hash_traits<tree>
29114{
29115  static inline hashval_t hash (tree);
29116  static inline bool equal (tree, tree);
29117};
29118
29119/* Hash the 'auto' T.  */
29120
29121inline hashval_t
29122auto_hash::hash (tree t)
29123{
29124  if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29125    /* Matching constrained-type-specifiers denote the same template
29126       parameter, so hash the constraint.  */
29127    return hash_placeholder_constraint (c);
29128  else
29129    /* But unconstrained autos are all separate, so just hash the pointer.  */
29130    return iterative_hash_object (t, 0);
29131}
29132
29133/* Compare two 'auto's.  */
29134
29135inline bool
29136auto_hash::equal (tree t1, tree t2)
29137{
29138  if (t1 == t2)
29139    return true;
29140
29141  tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29142  tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29143
29144  /* Two unconstrained autos are distinct.  */
29145  if (!c1 || !c2)
29146    return false;
29147
29148  return equivalent_placeholder_constraints (c1, c2);
29149}
29150
29151/* for_each_template_parm callback for extract_autos: if t is a (possibly
29152   constrained) auto, add it to the vector.  */
29153
29154static int
29155extract_autos_r (tree t, void *data)
29156{
29157  hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29158  if (is_auto (t) && !template_placeholder_p (t))
29159    {
29160      /* All the autos were built with index 0; fix that up now.  */
29161      tree *p = hash.find_slot (t, INSERT);
29162      unsigned idx;
29163      if (*p)
29164	/* If this is a repeated constrained-type-specifier, use the index we
29165	   chose before.  */
29166	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
29167      else
29168	{
29169	  /* Otherwise this is new, so use the current count.  */
29170	  *p = t;
29171	  idx = hash.elements () - 1;
29172	}
29173      TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
29174    }
29175
29176  /* Always keep walking.  */
29177  return 0;
29178}
29179
29180/* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29181   says they can appear anywhere in the type.  */
29182
29183static tree
29184extract_autos (tree type)
29185{
29186  hash_set<tree> visited;
29187  hash_table<auto_hash> hash (2);
29188
29189  for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29190
29191  tree tree_vec = make_tree_vec (hash.elements());
29192  for (tree elt : hash)
29193    {
29194      unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29195      TREE_VEC_ELT (tree_vec, i)
29196	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
29197    }
29198
29199  return tree_vec;
29200}
29201
29202/* The stem for deduction guide names.  */
29203const char *const dguide_base = "__dguide_";
29204
29205/* Return the name for a deduction guide for class template TMPL.  */
29206
29207tree
29208dguide_name (tree tmpl)
29209{
29210  tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29211  tree tname = TYPE_IDENTIFIER (type);
29212  char *buf = (char *) alloca (1 + strlen (dguide_base)
29213			       + IDENTIFIER_LENGTH (tname));
29214  memcpy (buf, dguide_base, strlen (dguide_base));
29215  memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29216	  IDENTIFIER_LENGTH (tname) + 1);
29217  tree dname = get_identifier (buf);
29218  TREE_TYPE (dname) = type;
29219  return dname;
29220}
29221
29222/* True if NAME is the name of a deduction guide.  */
29223
29224bool
29225dguide_name_p (tree name)
29226{
29227  return (TREE_CODE (name) == IDENTIFIER_NODE
29228	  && TREE_TYPE (name)
29229	  && startswith (IDENTIFIER_POINTER (name), dguide_base));
29230}
29231
29232/* True if FN is a deduction guide.  */
29233
29234bool
29235deduction_guide_p (const_tree fn)
29236{
29237  if (DECL_P (fn))
29238    if (tree name = DECL_NAME (fn))
29239      return dguide_name_p (name);
29240  return false;
29241}
29242
29243/* True if FN is the copy deduction guide, i.e. A(A)->A.  */
29244
29245bool
29246copy_guide_p (const_tree fn)
29247{
29248  gcc_assert (deduction_guide_p (fn));
29249  if (!DECL_ARTIFICIAL (fn))
29250    return false;
29251  tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29252  return (TREE_CHAIN (parms) == void_list_node
29253	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29254}
29255
29256/* True if FN is a guide generated from a constructor template.  */
29257
29258bool
29259template_guide_p (const_tree fn)
29260{
29261  gcc_assert (deduction_guide_p (fn));
29262  if (!DECL_ARTIFICIAL (fn))
29263    return false;
29264  tree tmpl = DECL_TI_TEMPLATE (fn);
29265  if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29266    return PRIMARY_TEMPLATE_P (org);
29267  return false;
29268}
29269
29270/* True if FN is an aggregate initialization guide or the copy deduction
29271   guide.  */
29272
29273bool
29274builtin_guide_p (const_tree fn)
29275{
29276  if (!deduction_guide_p (fn))
29277    return false;
29278  if (!DECL_ARTIFICIAL (fn))
29279    /* Explicitly declared.  */
29280    return false;
29281  if (DECL_ABSTRACT_ORIGIN (fn))
29282    /* Derived from a constructor.  */
29283    return false;
29284  return true;
29285}
29286
29287/* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
29288   LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29289   template parameter types.  Note that the handling of template template
29290   parameters relies on current_template_parms being set appropriately for the
29291   new template.  */
29292
29293static tree
29294rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29295		       tree tsubst_args, tsubst_flags_t complain)
29296{
29297  if (olddecl == error_mark_node)
29298    return error_mark_node;
29299
29300  tree oldidx = get_template_parm_index (olddecl);
29301
29302  tree newtype;
29303  if (TREE_CODE (olddecl) == TYPE_DECL
29304      || TREE_CODE (olddecl) == TEMPLATE_DECL)
29305    {
29306      tree oldtype = TREE_TYPE (olddecl);
29307      newtype = cxx_make_type (TREE_CODE (oldtype));
29308      TYPE_MAIN_VARIANT (newtype) = newtype;
29309    }
29310  else
29311    {
29312      newtype = TREE_TYPE (olddecl);
29313      if (type_uses_auto (newtype))
29314	{
29315	  // Substitute once to fix references to other template parameters.
29316	  newtype = tsubst (newtype, tsubst_args,
29317			    complain|tf_partial, NULL_TREE);
29318	  // Now substitute again to reduce the level of the auto.
29319	  newtype = tsubst (newtype, current_template_args (),
29320			    complain, NULL_TREE);
29321	}
29322      else
29323	newtype = tsubst (newtype, tsubst_args,
29324			  complain, NULL_TREE);
29325    }
29326
29327  tree newdecl
29328    = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29329		  DECL_NAME (olddecl), newtype);
29330  SET_DECL_TEMPLATE_PARM_P (newdecl);
29331
29332  tree newidx;
29333  if (TREE_CODE (olddecl) == TYPE_DECL
29334      || TREE_CODE (olddecl) == TEMPLATE_DECL)
29335    {
29336      newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29337	= build_template_parm_index (index, level, level,
29338				     newdecl, newtype);
29339      TEMPLATE_PARM_PARAMETER_PACK (newidx)
29340	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29341      TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29342      if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29343	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29344      else
29345	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29346
29347      if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29348	{
29349	  DECL_TEMPLATE_RESULT (newdecl)
29350	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29351			  DECL_NAME (olddecl), newtype);
29352	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29353	  // First create a copy (ttargs) of tsubst_args with an
29354	  // additional level for the template template parameter's own
29355	  // template parameters (ttparms).
29356	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
29357			  (DECL_TEMPLATE_PARMS (olddecl)));
29358	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29359	  tree ttargs = make_tree_vec (depth + 1);
29360	  for (int i = 0; i < depth; ++i)
29361	    TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29362	  TREE_VEC_ELT (ttargs, depth)
29363	    = template_parms_level_to_args (ttparms);
29364	  // Substitute ttargs into ttparms to fix references to
29365	  // other template parameters.
29366	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
29367						 complain|tf_partial);
29368	  // Now substitute again with args based on tparms, to reduce
29369	  // the level of the ttparms.
29370	  ttargs = current_template_args ();
29371	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
29372						 complain);
29373	  // Finally, tack the adjusted parms onto tparms.
29374	  ttparms = tree_cons (size_int (level + 1), ttparms,
29375			       copy_node (current_template_parms));
29376	  // As with all template template parms, the parameter list captured
29377	  // by this template template parm that corresponds to its own level
29378	  // should be empty.  This avoids infinite recursion when structurally
29379	  // comparing two such rewritten template template parms (PR102479).
29380	  gcc_assert (!TREE_VEC_LENGTH
29381		      (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29382	  gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29383	  TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29384	  // All done.
29385	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29386	}
29387    }
29388  else
29389    {
29390      tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29391      tree newconst
29392	= build_decl (DECL_SOURCE_LOCATION (oldconst),
29393		      TREE_CODE (oldconst),
29394		      DECL_NAME (oldconst), newtype);
29395      TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29396	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29397      SET_DECL_TEMPLATE_PARM_P (newconst);
29398      newidx = build_template_parm_index (index, level, level,
29399					  newconst, newtype);
29400      TEMPLATE_PARM_PARAMETER_PACK (newidx)
29401	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29402      DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29403    }
29404
29405  return newdecl;
29406}
29407
29408/* As rewrite_template_parm, but for the whole TREE_LIST representing a
29409   template parameter.  */
29410
29411static tree
29412rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29413		    tree targs, unsigned targs_index, tsubst_flags_t complain)
29414{
29415  tree olddecl = TREE_VALUE (oldelt);
29416  tree newdecl = rewrite_template_parm (olddecl, index, level,
29417					targs, complain);
29418  if (newdecl == error_mark_node)
29419    return error_mark_node;
29420  tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29421				     targs, complain, NULL_TREE);
29422  tree list = build_tree_list (newdef, newdecl);
29423  TEMPLATE_PARM_CONSTRAINTS (list)
29424    = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29425			      targs, complain, NULL_TREE);
29426  int depth = TMPL_ARGS_DEPTH (targs);
29427  TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29428  return list;
29429}
29430
29431/* Returns a C++17 class deduction guide template based on the constructor
29432   CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
29433   guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29434   aggregate initialization guide.  OUTER_ARGS are the template arguments
29435   for the enclosing scope of the class.  */
29436
29437static tree
29438build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29439{
29440  tree tparms, targs, fparms, fargs, ci;
29441  bool memtmpl = false;
29442  bool explicit_p;
29443  location_t loc;
29444  tree fn_tmpl = NULL_TREE;
29445
29446  if (outer_args)
29447    {
29448      ++processing_template_decl;
29449      type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29450      --processing_template_decl;
29451    }
29452
29453  if (!DECL_DECLARES_FUNCTION_P (ctor))
29454    {
29455      if (TYPE_P (ctor))
29456	{
29457	  bool copy_p = TYPE_REF_P (ctor);
29458	  if (copy_p)
29459	    fparms = tree_cons (NULL_TREE, type, void_list_node);
29460	  else
29461	    fparms = void_list_node;
29462	}
29463      else if (TREE_CODE (ctor) == TREE_LIST)
29464	fparms = ctor;
29465      else
29466	gcc_unreachable ();
29467
29468      tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29469      tparms = DECL_TEMPLATE_PARMS (ctmpl);
29470      targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29471      ci = NULL_TREE;
29472      fargs = NULL_TREE;
29473      loc = DECL_SOURCE_LOCATION (ctmpl);
29474      explicit_p = false;
29475    }
29476  else
29477    {
29478      ++processing_template_decl;
29479      bool ok = true;
29480
29481      complain |= tf_dguide;
29482
29483      fn_tmpl
29484	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29485	   : DECL_TI_TEMPLATE (ctor));
29486      if (outer_args)
29487	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29488      ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29489
29490      tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29491      /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29492	 fully specialized args for the enclosing class.  Strip those off, as
29493	 the deduction guide won't have those template parameters.  */
29494      targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29495						TMPL_PARMS_DEPTH (tparms));
29496      /* Discard the 'this' parameter.  */
29497      fparms = FUNCTION_ARG_CHAIN (ctor);
29498      fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29499      ci = get_constraints (ctor);
29500      loc = DECL_SOURCE_LOCATION (ctor);
29501      explicit_p = DECL_NONCONVERTING_P (ctor);
29502
29503      if (PRIMARY_TEMPLATE_P (fn_tmpl))
29504	{
29505	  memtmpl = true;
29506
29507	  /* For a member template constructor, we need to flatten the two
29508	     template parameter lists into one, and then adjust the function
29509	     signature accordingly.  This gets...complicated.  */
29510	  tree save_parms = current_template_parms;
29511
29512	  /* For a member template we should have two levels of parms/args, one
29513	     for the class and one for the constructor.  We stripped
29514	     specialized args for further enclosing classes above.  */
29515	  const int depth = 2;
29516	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29517
29518	  /* Template args for translating references to the two-level template
29519	     parameters into references to the one-level template parameters we
29520	     are creating.  */
29521	  tree tsubst_args = copy_node (targs);
29522	  TMPL_ARGS_LEVEL (tsubst_args, depth)
29523	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29524
29525	  /* Template parms for the constructor template.  */
29526	  tree ftparms = TREE_VALUE (tparms);
29527	  unsigned flen = TREE_VEC_LENGTH (ftparms);
29528	  /* Template parms for the class template.  */
29529	  tparms = TREE_CHAIN (tparms);
29530	  tree ctparms = TREE_VALUE (tparms);
29531	  unsigned clen = TREE_VEC_LENGTH (ctparms);
29532	  /* Template parms for the deduction guide start as a copy of the
29533	     template parms for the class.  We set current_template_parms for
29534	     lookup_template_class_1.  */
29535	  current_template_parms = tparms = copy_node (tparms);
29536	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29537	  for (unsigned i = 0; i < clen; ++i)
29538	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29539
29540	  /* Now we need to rewrite the constructor parms to append them to the
29541	     class parms.  */
29542	  for (unsigned i = 0; i < flen; ++i)
29543	    {
29544	      unsigned index = i + clen;
29545	      unsigned level = 1;
29546	      tree oldelt = TREE_VEC_ELT (ftparms, i);
29547	      tree newelt
29548		= rewrite_tparm_list (oldelt, index, level,
29549				      tsubst_args, i, complain);
29550	      if (newelt == error_mark_node)
29551		ok = false;
29552	      TREE_VEC_ELT (new_vec, index) = newelt;
29553	    }
29554
29555	  /* Now we have a final set of template parms to substitute into the
29556	     function signature.  */
29557	  targs = template_parms_to_args (tparms);
29558	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29559				     complain, ctor);
29560	  if (fparms == error_mark_node)
29561	    ok = false;
29562	  if (ci)
29563	    {
29564	      if (outer_args)
29565		/* FIXME: We'd like to avoid substituting outer template
29566		   arguments into the constraint ahead of time, but the
29567		   construction of tsubst_args assumes that outer arguments
29568		   are already substituted in.  */
29569		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29570	      ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29571	    }
29572
29573	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29574	     cp_unevaluated_operand.  */
29575	  cp_evaluated ev;
29576	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
29577	  current_template_parms = save_parms;
29578	}
29579      else
29580	{
29581	  /* Substitute in the same arguments to rewrite class members into
29582	     references to members of an unknown specialization.  */
29583	  cp_evaluated ev;
29584	  fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29585	  fargs = tsubst (fargs, targs, complain, ctor);
29586	  if (ci)
29587	    {
29588	      if (outer_args)
29589		/* FIXME: As above.  */
29590		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29591	      ci = tsubst_constraint_info (ci, targs, complain, ctor);
29592	    }
29593	}
29594
29595      --processing_template_decl;
29596      if (!ok)
29597	return error_mark_node;
29598    }
29599
29600  if (!memtmpl)
29601    {
29602      /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
29603      tparms = copy_node (tparms);
29604      INNERMOST_TEMPLATE_PARMS (tparms)
29605	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29606    }
29607
29608  tree fntype = build_function_type (type, fparms);
29609  tree ded_fn = build_lang_decl_loc (loc,
29610				     FUNCTION_DECL,
29611				     dguide_name (type), fntype);
29612  DECL_ARGUMENTS (ded_fn) = fargs;
29613  DECL_ARTIFICIAL (ded_fn) = true;
29614  DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29615  tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29616  DECL_ARTIFICIAL (ded_tmpl) = true;
29617  DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29618  DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29619  if (DECL_P (ctor))
29620    DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29621  if (ci)
29622    set_constraints (ded_tmpl, ci);
29623
29624  return ded_tmpl;
29625}
29626
29627/* Add to LIST the member types for the reshaped initializer CTOR.  */
29628
29629static tree
29630collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29631{
29632  vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29633  tree idx, val; unsigned i;
29634  FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29635    {
29636      tree ftype = elt ? elt : TREE_TYPE (idx);
29637      if (BRACE_ENCLOSED_INITIALIZER_P (val)
29638	  && CONSTRUCTOR_BRACES_ELIDED_P (val))
29639	{
29640	  tree subelt = NULL_TREE;
29641	  if (TREE_CODE (ftype) == ARRAY_TYPE)
29642	    subelt = TREE_TYPE (ftype);
29643	  list = collect_ctor_idx_types (val, list, subelt);
29644	  continue;
29645	}
29646      tree arg = NULL_TREE;
29647      if (i == v->length() - 1
29648	  && PACK_EXPANSION_P (ftype))
29649	/* Give the trailing pack expansion parameter a default argument to
29650	   match aggregate initialization behavior, even if we deduce the
29651	   length of the pack separately to more than we have initializers. */
29652	arg = build_constructor (init_list_type_node, NULL);
29653      /* if ei is of array type and xi is a braced-init-list or string literal,
29654	 Ti is an rvalue reference to the declared type of ei */
29655      STRIP_ANY_LOCATION_WRAPPER (val);
29656      if (TREE_CODE (ftype) == ARRAY_TYPE
29657	  && (BRACE_ENCLOSED_INITIALIZER_P (val)
29658	      || TREE_CODE (val) == STRING_CST))
29659	{
29660	  if (TREE_CODE (val) == STRING_CST)
29661	    ftype = cp_build_qualified_type
29662	      (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
29663	  ftype = (cp_build_reference_type
29664		   (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
29665	}
29666      list = tree_cons (arg, ftype, list);
29667    }
29668
29669  return list;
29670}
29671
29672/* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
29673
29674static bool
29675is_spec_or_derived (tree etype, tree tmpl)
29676{
29677  if (!etype || !CLASS_TYPE_P (etype))
29678    return false;
29679
29680  etype = cv_unqualified (etype);
29681  tree type = TREE_TYPE (tmpl);
29682  tree tparms = (INNERMOST_TEMPLATE_PARMS
29683		 (DECL_TEMPLATE_PARMS (tmpl)));
29684  tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29685  int err = unify (tparms, targs, type, etype,
29686		   UNIFY_ALLOW_DERIVED, /*explain*/false);
29687  ggc_free (targs);
29688  return !err;
29689}
29690
29691static tree alias_ctad_tweaks (tree, tree);
29692
29693/* Return a C++20 aggregate deduction candidate for TYPE initialized from
29694   INIT.  */
29695
29696static tree
29697maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
29698{
29699  if (cxx_dialect < cxx20)
29700    return NULL_TREE;
29701
29702  if (init == NULL_TREE)
29703    return NULL_TREE;
29704
29705  if (DECL_ALIAS_TEMPLATE_P (tmpl))
29706    {
29707      tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29708      tree tinfo = get_template_info (under);
29709      if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
29710	return alias_ctad_tweaks (tmpl, guide);
29711      return NULL_TREE;
29712    }
29713
29714  /* We might be creating a guide for a class member template, e.g.,
29715
29716       template<typename U> struct A {
29717	 template<typename T> struct B { T t; };
29718       };
29719
29720     At this point, A will have been instantiated.  Below, we need to
29721     use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types.  */
29722  const bool member_template_p
29723    = (DECL_TEMPLATE_INFO (tmpl)
29724       && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
29725  tree type = TREE_TYPE (tmpl);
29726  tree template_type = (member_template_p
29727			? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
29728			: type);
29729  if (!CP_AGGREGATE_TYPE_P (template_type))
29730    return NULL_TREE;
29731
29732  /* No aggregate candidate for copy-initialization.  */
29733  if (args->length() == 1)
29734    {
29735      tree val = (*args)[0];
29736      if (is_spec_or_derived (TREE_TYPE (val), tmpl))
29737	return NULL_TREE;
29738    }
29739
29740  /* If we encounter a problem, we just won't add the candidate.  */
29741  tsubst_flags_t complain = tf_none;
29742
29743  tree parms = NULL_TREE;
29744  if (BRACE_ENCLOSED_INITIALIZER_P (init))
29745    {
29746      init = reshape_init (template_type, init, complain);
29747      if (init == error_mark_node)
29748	return NULL_TREE;
29749      parms = collect_ctor_idx_types (init, parms);
29750      /* If we're creating a deduction guide for a member class template,
29751	 we've used the original template pattern type for the reshape_init
29752	 above; this is done because we want PARMS to be a template parameter
29753	 type, something that can be deduced when used as a function template
29754	 parameter.  At this point the outer class template has already been
29755	 partially instantiated (we deferred the deduction until the enclosing
29756	 scope is non-dependent).  Therefore we have to partially instantiate
29757	 PARMS, so that its template level is properly reduced and we don't get
29758	 mismatches when deducing types using the guide with PARMS.  */
29759      if (member_template_p)
29760	{
29761	  ++processing_template_decl;
29762	  parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
29763	  --processing_template_decl;
29764	}
29765    }
29766  else if (TREE_CODE (init) == TREE_LIST)
29767    {
29768      int len = list_length (init);
29769      for (tree field = TYPE_FIELDS (type);
29770	   len;
29771	   --len, field = DECL_CHAIN (field))
29772	{
29773	  field = next_initializable_field (field);
29774	  if (!field)
29775	    return NULL_TREE;
29776	  tree ftype = finish_decltype_type (field, true, complain);
29777	  parms = tree_cons (NULL_TREE, ftype, parms);
29778	}
29779    }
29780  else
29781    /* Aggregate initialization doesn't apply to an initializer expression.  */
29782    return NULL_TREE;
29783
29784  if (parms)
29785    {
29786      tree last = parms;
29787      parms = nreverse (parms);
29788      TREE_CHAIN (last) = void_list_node;
29789      tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
29790      return guide;
29791    }
29792
29793  return NULL_TREE;
29794}
29795
29796/* UGUIDES are the deduction guides for the underlying template of alias
29797   template TMPL; adjust them to be deduction guides for TMPL.  */
29798
29799static tree
29800alias_ctad_tweaks (tree tmpl, tree uguides)
29801{
29802  /* [over.match.class.deduct]: When resolving a placeholder for a deduced
29803     class type (9.2.8.2) where the template-name names an alias template A,
29804     the defining-type-id of A must be of the form
29805
29806     typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29807
29808     as specified in 9.2.8.2. The guides of A are the set of functions or
29809     function templates formed as follows. For each function or function
29810     template f in the guides of the template named by the simple-template-id
29811     of the defining-type-id, the template arguments of the return type of f
29812     are deduced from the defining-type-id of A according to the process in
29813     13.10.2.5 with the exception that deduction does not fail if not all
29814     template arguments are deduced. Let g denote the result of substituting
29815     these deductions into f. If substitution succeeds, form a function or
29816     function template f' with the following properties and add it to the set
29817     of guides of A:
29818
29819     * The function type of f' is the function type of g.
29820
29821     * If f is a function template, f' is a function template whose template
29822     parameter list consists of all the template parameters of A (including
29823     their default template arguments) that appear in the above deductions or
29824     (recursively) in their default template arguments, followed by the
29825     template parameters of f that were not deduced (including their default
29826     template arguments), otherwise f' is not a function template.
29827
29828     * The associated constraints (13.5.2) are the conjunction of the
29829     associated constraints of g and a constraint that is satisfied if and only
29830     if the arguments of A are deducible (see below) from the return type.
29831
29832     * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29833     be so as well.
29834
29835     * If f was generated from a deduction-guide (12.4.1.8), then f' is
29836     considered to be so as well.
29837
29838     * The explicit-specifier of f' is the explicit-specifier of g (if
29839     any).  */
29840
29841  /* This implementation differs from the above in two significant ways:
29842
29843     1) We include all template parameters of A, not just some.
29844     2) The added constraint is same_type instead of deducible.
29845
29846     I believe that while it's probably possible to construct a testcase that
29847     behaves differently with this simplification, it should have the same
29848     effect for real uses.  Including all template parameters means that we
29849     deduce all parameters of A when resolving the call, so when we're in the
29850     constraint we don't need to deduce them again, we can just check whether
29851     the deduction produced the desired result.  */
29852
29853  tsubst_flags_t complain = tf_warning_or_error;
29854  tree atype = TREE_TYPE (tmpl);
29855  tree aguides = NULL_TREE;
29856  tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
29857  unsigned natparms = TREE_VEC_LENGTH (atparms);
29858  tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29859  for (ovl_iterator iter (uguides); iter; ++iter)
29860    {
29861      tree f = *iter;
29862      tree in_decl = f;
29863      location_t loc = DECL_SOURCE_LOCATION (f);
29864      tree ret = TREE_TYPE (TREE_TYPE (f));
29865      tree fprime = f;
29866      if (TREE_CODE (f) == TEMPLATE_DECL)
29867	{
29868	  processing_template_decl_sentinel ptds (/*reset*/false);
29869	  ++processing_template_decl;
29870
29871	  /* Deduce template arguments for f from the type-id of A.  */
29872	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29873	  unsigned len = TREE_VEC_LENGTH (ftparms);
29874	  tree targs = make_tree_vec (len);
29875	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29876	  if (err)
29877	    continue;
29878
29879	  /* The number of parms for f' is the number of parms for A plus
29880	     non-deduced parms of f.  */
29881	  unsigned ndlen = 0;
29882	  unsigned j;
29883	  for (unsigned i = 0; i < len; ++i)
29884	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29885	      ++ndlen;
29886	  tree gtparms = make_tree_vec (natparms + ndlen);
29887
29888	  /* Set current_template_parms as in build_deduction_guide.  */
29889	  auto ctp = make_temp_override (current_template_parms);
29890	  current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
29891	  TREE_VALUE (current_template_parms) = gtparms;
29892
29893	  /* First copy over the parms of A.  */
29894	  for (j = 0; j < natparms; ++j)
29895	    TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
29896	  /* Now rewrite the non-deduced parms of f.  */
29897	  for (unsigned i = 0; ndlen && i < len; ++i)
29898	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29899	      {
29900		--ndlen;
29901		unsigned index = j++;
29902		unsigned level = 1;
29903		tree oldlist = TREE_VEC_ELT (ftparms, i);
29904		tree list = rewrite_tparm_list (oldlist, index, level,
29905						targs, i, complain);
29906		TREE_VEC_ELT (gtparms, index) = list;
29907	      }
29908	  gtparms = build_tree_list (size_one_node, gtparms);
29909
29910	  /* Substitute the deduced arguments plus the rewritten template
29911	     parameters into f to get g.  This covers the type, copyness,
29912	     guideness, and explicit-specifier.  */
29913	  tree g;
29914	    {
29915	      /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
29916		 if cp_unevaluated_operand.  */
29917	      cp_evaluated ev;
29918	      g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29919	    }
29920	  if (g == error_mark_node)
29921	    continue;
29922	  DECL_USE_TEMPLATE (g) = 0;
29923	  fprime = build_template_decl (g, gtparms, false);
29924	  DECL_TEMPLATE_RESULT (fprime) = g;
29925	  TREE_TYPE (fprime) = TREE_TYPE (g);
29926	  tree gtargs = template_parms_to_args (gtparms);
29927	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
29928	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
29929
29930	  /* Substitute the associated constraints.  */
29931	  tree ci = get_constraints (f);
29932	  if (ci)
29933	    ci = tsubst_constraint_info (ci, targs, complain, in_decl);
29934	  if (ci == error_mark_node)
29935	    continue;
29936
29937	  /* Add a constraint that the return type matches the instantiation of
29938	     A with the same template arguments.  */
29939	  ret = TREE_TYPE (TREE_TYPE (fprime));
29940	  if (!same_type_p (atype, ret)
29941	      /* FIXME this should mean they don't compare as equivalent.  */
29942	      || dependent_alias_template_spec_p (atype, nt_opaque))
29943	    {
29944	      tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
29945	      ci = append_constraint (ci, same);
29946	    }
29947
29948	  if (ci)
29949	    {
29950	      remove_constraints (fprime);
29951	      set_constraints (fprime, ci);
29952	    }
29953	}
29954      else
29955	{
29956	  /* For a non-template deduction guide, if the arguments of A aren't
29957	     deducible from the return type, don't add the candidate.  */
29958	  tree targs = make_tree_vec (natparms);
29959	  int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
29960	  for (unsigned i = 0; !err && i < natparms; ++i)
29961	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29962	      err = true;
29963	  if (err)
29964	    continue;
29965	}
29966
29967      aguides = lookup_add (fprime, aguides);
29968    }
29969
29970  return aguides;
29971}
29972
29973/* Return artificial deduction guides built from the constructors of class
29974   template TMPL.  */
29975
29976static tree
29977ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
29978{
29979  tree outer_args = outer_template_args (tmpl);
29980  tree type = TREE_TYPE (most_general_template (tmpl));
29981
29982  tree cands = NULL_TREE;
29983
29984  for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
29985    {
29986      /* Skip inherited constructors.  */
29987      if (iter.using_p ())
29988	continue;
29989
29990      tree guide = build_deduction_guide (type, *iter, outer_args, complain);
29991      cands = lookup_add (guide, cands);
29992    }
29993
29994  /* Add implicit default constructor deduction guide.  */
29995  if (!TYPE_HAS_USER_CONSTRUCTOR (type))
29996    {
29997      tree guide = build_deduction_guide (type, type, outer_args,
29998					  complain);
29999      cands = lookup_add (guide, cands);
30000    }
30001
30002  /* Add copy guide.  */
30003  {
30004    tree gtype = build_reference_type (type);
30005    tree guide = build_deduction_guide (type, gtype, outer_args,
30006					complain);
30007    cands = lookup_add (guide, cands);
30008  }
30009
30010  return cands;
30011}
30012
30013static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30014
30015/* Return the non-aggregate deduction guides for deducible template TMPL.  The
30016   aggregate candidate is added separately because it depends on the
30017   initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
30018   guide.  */
30019
30020static tree
30021deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30022{
30023  tree guides = NULL_TREE;
30024  if (DECL_ALIAS_TEMPLATE_P (tmpl))
30025    {
30026      tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30027      tree tinfo = get_template_info (under);
30028      guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30029				     complain);
30030    }
30031  else
30032    {
30033      guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30034				      dguide_name (tmpl),
30035				      LOOK_want::NORMAL, /*complain*/false);
30036      if (guides == error_mark_node)
30037	guides = NULL_TREE;
30038      else
30039	any_dguides_p = true;
30040    }
30041
30042  /* Cache the deduction guides for a template.  We also remember the result of
30043     lookup, and rebuild everything if it changes; should be very rare.  */
30044  tree_pair_p cache = NULL;
30045  if (tree_pair_p &r
30046      = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30047    {
30048      cache = r;
30049      if (cache->purpose == guides)
30050	return cache->value;
30051    }
30052  else
30053    {
30054      r = cache = ggc_cleared_alloc<tree_pair_s> ();
30055      cache->purpose = guides;
30056    }
30057
30058  tree cands = NULL_TREE;
30059  if (DECL_ALIAS_TEMPLATE_P (tmpl))
30060    cands = alias_ctad_tweaks (tmpl, guides);
30061  else
30062    {
30063      cands = ctor_deduction_guides_for (tmpl, complain);
30064      for (ovl_iterator it (guides); it; ++it)
30065	cands = lookup_add (*it, cands);
30066    }
30067
30068  cache->value = cands;
30069  return cands;
30070}
30071
30072/* Return whether TMPL is a (class template argument-) deducible template.  */
30073
30074bool
30075ctad_template_p (tree tmpl)
30076{
30077  /* A deducible template is either a class template or is an alias template
30078     whose defining-type-id is of the form
30079
30080      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30081
30082     where the nested-name-specifier (if any) is non-dependent and the
30083     template-name of the simple-template-id names a deducible template.  */
30084
30085  if (DECL_CLASS_TEMPLATE_P (tmpl)
30086      || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30087    return true;
30088  if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30089    return false;
30090  tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30091  if (tree tinfo = get_template_info (orig))
30092    return ctad_template_p (TI_TEMPLATE (tinfo));
30093  return false;
30094}
30095
30096/* Deduce template arguments for the class template placeholder PTYPE for
30097   template TMPL based on the initializer INIT, and return the resulting
30098   type.  */
30099
30100static tree
30101do_class_deduction (tree ptype, tree tmpl, tree init,
30102		    int flags, tsubst_flags_t complain)
30103{
30104  /* We should have handled this in the caller.  */
30105  if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30106    return ptype;
30107
30108  /* If the class was erroneous, don't try to deduce, because that
30109     can generate a lot of diagnostic.  */
30110  if (TREE_TYPE (tmpl)
30111      && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30112      && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30113    return ptype;
30114
30115  /* Wait until the enclosing scope is non-dependent.  */
30116  if (DECL_CLASS_SCOPE_P (tmpl)
30117      && dependent_type_p (DECL_CONTEXT (tmpl)))
30118    return ptype;
30119
30120  /* Initializing one placeholder from another.  */
30121  if (init
30122      && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30123	  || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30124	      && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30125		  == TEMPLATE_PARM_INDEX)))
30126      && is_auto (TREE_TYPE (init))
30127      && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30128    return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30129
30130  if (!ctad_template_p (tmpl))
30131    {
30132      if (complain & tf_error)
30133	error ("non-deducible template %qT used without template arguments", tmpl);
30134      return error_mark_node;
30135    }
30136  else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30137    {
30138      if (complain & tf_error)
30139	{
30140	  /* Be permissive with equivalent alias templates.  */
30141	  tree u = get_underlying_template (tmpl);
30142	  diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30143	  bool complained
30144	    = emit_diagnostic (dk, input_location, 0,
30145			       "alias template deduction only available "
30146			       "with %<-std=c++20%> or %<-std=gnu++20%>");
30147	  if (u == tmpl)
30148	    return error_mark_node;
30149	  else if (complained)
30150	    {
30151	      inform (input_location, "use %qD directly instead", u);
30152	      tmpl = u;
30153	    }
30154	}
30155      else
30156	return error_mark_node;
30157    }
30158
30159  /* Wait until the initializer is non-dependent.  */
30160  if (type_dependent_expression_p (init))
30161    return ptype;
30162
30163  /* Don't bother with the alias rules for an equivalent template.  */
30164  tmpl = get_underlying_template (tmpl);
30165
30166  tree type = TREE_TYPE (tmpl);
30167
30168  bool try_list_ctor = false;
30169  bool list_init_p = false;
30170
30171  releasing_vec rv_args = NULL;
30172  vec<tree,va_gc> *&args = *&rv_args;
30173  if (init == NULL_TREE)
30174    args = make_tree_vector ();
30175  else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30176    {
30177      list_init_p = true;
30178      try_list_ctor = TYPE_HAS_LIST_CTOR (type);
30179      if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1
30180	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30181	{
30182	  /* As an exception, the first phase in 16.3.1.7 (considering the
30183	     initializer list as a single argument) is omitted if the
30184	     initializer list consists of a single expression of type cv U,
30185	     where U is a specialization of C or a class derived from a
30186	     specialization of C.  */
30187	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30188	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30189	    try_list_ctor = false;
30190	}
30191      if (try_list_ctor || is_std_init_list (type))
30192	args = make_tree_vector_single (init);
30193      else
30194	args = make_tree_vector_from_ctor (init);
30195    }
30196  else if (TREE_CODE (init) == TREE_LIST)
30197    args = make_tree_vector_from_list (init);
30198  else
30199    args = make_tree_vector_single (init);
30200
30201  /* Do this now to avoid problems with erroneous args later on.  */
30202  args = resolve_args (args, complain);
30203  if (args == NULL)
30204    return error_mark_node;
30205
30206  bool any_dguides_p = false;
30207  tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30208  if (cands == error_mark_node)
30209    return error_mark_node;
30210
30211  /* Prune explicit deduction guides in copy-initialization context (but
30212     not copy-list-initialization).  */
30213  bool elided = false;
30214  if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30215    {
30216      for (lkp_iterator iter (cands); !elided && iter; ++iter)
30217	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30218	  elided = true;
30219
30220      if (elided)
30221	{
30222	  /* Found a nonconverting guide, prune the candidates.  */
30223	  tree pruned = NULL_TREE;
30224	  for (lkp_iterator iter (cands); iter; ++iter)
30225	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30226	      pruned = lookup_add (*iter, pruned);
30227
30228	  cands = pruned;
30229	}
30230    }
30231
30232  if (!any_dguides_p)
30233    if (tree guide = maybe_aggr_guide (tmpl, init, args))
30234      cands = lookup_add (guide, cands);
30235
30236  tree fndecl = error_mark_node;
30237
30238  /* If this is list-initialization and the class has a list constructor, first
30239     try deducing from the list as a single argument, as [over.match.list].  */
30240  tree list_cands = NULL_TREE;
30241  if (try_list_ctor && cands)
30242    for (lkp_iterator iter (cands); iter; ++iter)
30243      {
30244	tree dg = *iter;
30245	if (is_list_ctor (dg))
30246	  list_cands = lookup_add (dg, list_cands);
30247      }
30248  if (list_cands)
30249    {
30250      fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30251
30252      if (fndecl == error_mark_node)
30253	{
30254	  /* That didn't work, now try treating the list as a sequence of
30255	     arguments.  */
30256	  release_tree_vector (args);
30257	  args = make_tree_vector_from_ctor (init);
30258	}
30259    }
30260
30261  if (elided && !cands)
30262    {
30263      error ("cannot deduce template arguments for copy-initialization"
30264	     " of %qT, as it has no non-explicit deduction guides or "
30265	     "user-declared constructors", type);
30266      return error_mark_node;
30267    }
30268  else if (!cands && fndecl == error_mark_node)
30269    {
30270      error ("cannot deduce template arguments of %qT, as it has no viable "
30271	     "deduction guides", type);
30272      return error_mark_node;
30273    }
30274
30275  if (fndecl == error_mark_node)
30276    fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30277
30278  if (fndecl == error_mark_node)
30279    {
30280      if (complain & tf_warning_or_error)
30281	{
30282	  error ("class template argument deduction failed:");
30283	  perform_dguide_overload_resolution (cands, args, complain);
30284	  if (elided)
30285	    inform (input_location, "explicit deduction guides not considered "
30286		    "for copy-initialization");
30287	}
30288      return error_mark_node;
30289    }
30290  /* [over.match.list]/1: In copy-list-initialization, if an explicit
30291     constructor is chosen, the initialization is ill-formed.  */
30292  else if (flags & LOOKUP_ONLYCONVERTING)
30293    {
30294      if (DECL_NONCONVERTING_P (fndecl))
30295	{
30296	  if (complain & tf_warning_or_error)
30297	    {
30298	      // TODO: Pass down location from cp_finish_decl.
30299	      error ("class template argument deduction for %qT failed: "
30300		     "explicit deduction guide selected in "
30301		     "copy-list-initialization", type);
30302	      inform (DECL_SOURCE_LOCATION (fndecl),
30303		      "explicit deduction guide declared here");
30304
30305	    }
30306	  return error_mark_node;
30307	}
30308    }
30309
30310  /* If CTAD succeeded but the type doesn't have any explicit deduction
30311     guides, this deduction might not be what the user intended.  */
30312  if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30313    {
30314      if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30315	   || global_dc->dc_warn_system_headers)
30316	  && warning (OPT_Wctad_maybe_unsupported,
30317		      "%qT may not intend to support class template argument "
30318		      "deduction", type))
30319	inform (input_location, "add a deduction guide to suppress this "
30320		"warning");
30321    }
30322
30323  return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30324				  cp_type_quals (ptype));
30325}
30326
30327/* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30328   from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30329   The CONTEXT determines the context in which auto deduction is performed
30330   and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
30331
30332   OUTER_TARGS is used during template argument deduction (context == adc_unify)
30333   to properly substitute the result.  It's also used in the adc_unify and
30334   adc_requirement contexts to communicate the necessary template arguments
30335   to satisfaction.  OUTER_TARGS is ignored in other contexts.
30336
30337   For partial-concept-ids, extra args may be appended to the list of deduced
30338   template arguments prior to determining constraint satisfaction.  */
30339
30340tree
30341do_auto_deduction (tree type, tree init, tree auto_node,
30342                   tsubst_flags_t complain, auto_deduction_context context,
30343		   tree outer_targs, int flags)
30344{
30345  if (init == error_mark_node)
30346    return error_mark_node;
30347
30348  if (init && type_dependent_expression_p (init)
30349      && context != adc_unify)
30350    /* Defining a subset of type-dependent expressions that we can deduce
30351       from ahead of time isn't worth the trouble.  */
30352    return type;
30353
30354  /* Similarly, we can't deduce from another undeduced decl.  */
30355  if (init && undeduced_auto_decl (init))
30356    return type;
30357
30358  /* We may be doing a partial substitution, but we still want to replace
30359     auto_node.  */
30360  complain &= ~tf_partial;
30361
30362  if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30363    /* C++17 class template argument deduction.  */
30364    return do_class_deduction (type, tmpl, init, flags, complain);
30365
30366  if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30367    /* Nothing we can do with this, even in deduction context.  */
30368    return type;
30369
30370  /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30371     with either a new invented type template parameter U or, if the
30372     initializer is a braced-init-list (8.5.4), with
30373     std::initializer_list<U>.  */
30374  if (BRACE_ENCLOSED_INITIALIZER_P (init))
30375    {
30376      if (!DIRECT_LIST_INIT_P (init))
30377	type = listify_autos (type, auto_node);
30378      else if (CONSTRUCTOR_NELTS (init) == 1)
30379	init = CONSTRUCTOR_ELT (init, 0)->value;
30380      else
30381	{
30382          if (complain & tf_warning_or_error)
30383            {
30384	      if (permerror (input_location, "direct-list-initialization of "
30385			     "%<auto%> requires exactly one element"))
30386	        inform (input_location,
30387		        "for deduction to %<std::initializer_list%>, use copy-"
30388		        "list-initialization (i.e. add %<=%> before the %<{%>)");
30389            }
30390	  type = listify_autos (type, auto_node);
30391	}
30392    }
30393
30394  if (type == error_mark_node)
30395    return error_mark_node;
30396
30397  if (BRACE_ENCLOSED_INITIALIZER_P (init))
30398    {
30399      /* We don't recurse here because we can't deduce from a nested
30400	 initializer_list.  */
30401      if (CONSTRUCTOR_ELTS (init))
30402	for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30403	  elt.value = resolve_nondeduced_context (elt.value, complain);
30404    }
30405  else
30406    init = resolve_nondeduced_context (init, complain);
30407
30408  tree targs;
30409  if (context == adc_decomp_type
30410      && auto_node == type
30411      && init != error_mark_node
30412      && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30413    {
30414      /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30415	 and initializer has array type, deduce cv-qualified array type.  */
30416      targs = make_tree_vec (1);
30417      TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30418    }
30419  else if (AUTO_IS_DECLTYPE (auto_node))
30420    {
30421      /* Figure out if INIT is an unparenthesized id-expression or an
30422	 unparenthesized class member access.  */
30423      tree stripped_init = tree_strip_any_location_wrapper (init);
30424      /* We need to be able to tell '(r)' and 'r' apart (when it's of
30425	 reference type).  Only the latter is an id-expression.  */
30426      if (REFERENCE_REF_P (stripped_init)
30427	  && !REF_PARENTHESIZED_P (stripped_init))
30428	stripped_init = TREE_OPERAND (stripped_init, 0);
30429      const bool id = (DECL_P (stripped_init)
30430		       || ((TREE_CODE (stripped_init) == COMPONENT_REF
30431			    || TREE_CODE (stripped_init) == SCOPE_REF)
30432			   && !REF_PARENTHESIZED_P (stripped_init)));
30433      tree deduced = finish_decltype_type (init, id, complain);
30434      deduced = canonicalize_type_argument (deduced, complain);
30435      if (deduced == error_mark_node)
30436	return error_mark_node;
30437      targs = make_tree_vec (1);
30438      TREE_VEC_ELT (targs, 0) = deduced;
30439    }
30440  else
30441    {
30442      if (error_operand_p (init))
30443	return error_mark_node;
30444
30445      tree parms = build_tree_list (NULL_TREE, type);
30446      tree tparms;
30447
30448      if (flag_concepts_ts)
30449	tparms = extract_autos (type);
30450      else
30451	{
30452	  tparms = make_tree_vec (1);
30453	  TREE_VEC_ELT (tparms, 0)
30454	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30455	}
30456
30457      targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30458      int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30459				       DEDUCE_CALL,
30460				       NULL, /*explain_p=*/false);
30461      if (val > 0)
30462	{
30463	  if (processing_template_decl)
30464	    /* Try again at instantiation time.  */
30465	    return type;
30466	  if (type && type != error_mark_node
30467	      && (complain & tf_error))
30468	    /* If type is error_mark_node a diagnostic must have been
30469	       emitted by now.  Also, having a mention to '<type error>'
30470	       in the diagnostic is not really useful to the user.  */
30471	    {
30472	      if (cfun
30473		  && FNDECL_USED_AUTO (current_function_decl)
30474		  && (auto_node
30475		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30476		  && LAMBDA_FUNCTION_P (current_function_decl))
30477		error ("unable to deduce lambda return type from %qE", init);
30478	      else
30479		error ("unable to deduce %qT from %qE", type, init);
30480	      type_unification_real (tparms, targs, parms, &init, 1, 0,
30481				     DEDUCE_CALL,
30482				     NULL, /*explain_p=*/true);
30483	    }
30484	  return error_mark_node;
30485	}
30486    }
30487
30488  /* Check any placeholder constraints against the deduced type. */
30489  if (processing_template_decl && context == adc_unify)
30490    /* Constraints will be checked after deduction.  */;
30491  else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30492    {
30493      if (processing_template_decl)
30494	{
30495	  gcc_checking_assert (context == adc_variable_type
30496			       || context == adc_return_type
30497			       || context == adc_decomp_type);
30498	  gcc_checking_assert (!type_dependent_expression_p (init));
30499	  /* If the constraint is dependent, we need to wait until
30500	     instantiation time to resolve the placeholder.  */
30501	  if (placeholder_type_constraint_dependent_p (constr))
30502	    return type;
30503	}
30504
30505      if (context == adc_return_type
30506	  || context == adc_variable_type
30507	  || context == adc_decomp_type)
30508	if (tree fn = current_function_decl)
30509	  if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30510	    {
30511	      outer_targs = DECL_TEMPLATE_INFO (fn)
30512		? DECL_TI_ARGS (fn) : NULL_TREE;
30513	      if (LAMBDA_FUNCTION_P (fn))
30514		{
30515		  /* As in satisfy_declaration_constraints.  */
30516		  tree regen_args = lambda_regenerating_args (fn);
30517		  if (outer_targs)
30518		    outer_targs = add_to_template_args (regen_args, outer_targs);
30519		  else
30520		    outer_targs = regen_args;
30521		}
30522	    }
30523
30524      tree full_targs = add_to_template_args (outer_targs, targs);
30525
30526      /* HACK: Compensate for callers not always communicating all levels of
30527	 outer template arguments by filling in the outermost missing levels
30528	 with dummy levels before checking satisfaction.  We'll still crash
30529	 if the constraint depends on a template argument belonging to one of
30530	 these missing levels, but this hack otherwise allows us to handle a
30531	 large subset of possible constraints (including all non-dependent
30532	 constraints).  */
30533      if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
30534				- TMPL_ARGS_DEPTH (full_targs)))
30535	{
30536	  tree dummy_levels = make_tree_vec (missing_levels);
30537	  for (int i = 0; i < missing_levels; ++i)
30538	    TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
30539	  full_targs = add_to_template_args (dummy_levels, full_targs);
30540	}
30541
30542      if (!constraints_satisfied_p (auto_node, full_targs))
30543	{
30544	  if (complain & tf_warning_or_error)
30545	    {
30546	      auto_diagnostic_group d;
30547	      switch (context)
30548		{
30549		case adc_unspecified:
30550		case adc_unify:
30551		  error("placeholder constraints not satisfied");
30552		  break;
30553		case adc_variable_type:
30554		case adc_decomp_type:
30555		  error ("deduced initializer does not satisfy "
30556			 "placeholder constraints");
30557		  break;
30558		case adc_return_type:
30559		  error ("deduced return type does not satisfy "
30560			 "placeholder constraints");
30561		  break;
30562		case adc_requirement:
30563		  error ("deduced expression type does not satisfy "
30564			 "placeholder constraints");
30565		  break;
30566		}
30567	      diagnose_constraints (input_location, auto_node, full_targs);
30568	    }
30569	  return error_mark_node;
30570	}
30571    }
30572
30573  if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
30574    /* The outer template arguments are already substituted into type
30575       (but we still may have used them for constraint checking above).  */;
30576  else if (context == adc_unify)
30577    targs = add_to_template_args (outer_targs, targs);
30578  else if (processing_template_decl)
30579    targs = add_to_template_args (current_template_args (), targs);
30580  return tsubst (type, targs, complain, NULL_TREE);
30581}
30582
30583/* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
30584   result.  */
30585
30586tree
30587splice_late_return_type (tree type, tree late_return_type)
30588{
30589  if (late_return_type)
30590    {
30591      gcc_assert (is_auto (type) || seen_error ());
30592      return late_return_type;
30593    }
30594
30595  if (tree auto_node = find_type_usage (type, is_auto))
30596    if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
30597      {
30598	/* In an abbreviated function template we didn't know we were dealing
30599	   with a function template when we saw the auto return type, so rebuild
30600	   the return type using an auto with the correct level.  */
30601	tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
30602	tree auto_vec = make_tree_vec (1);
30603	TREE_VEC_ELT (auto_vec, 0) = new_auto;
30604	tree targs = add_outermost_template_args (current_template_args (),
30605						  auto_vec);
30606	/* Also rebuild the constraint info in terms of the new auto.  */
30607	if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
30608	  PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
30609	    = build_tree_list (current_template_parms,
30610			       tsubst_constraint (TREE_VALUE (ci), targs,
30611						  tf_none, NULL_TREE));
30612	TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
30613	return tsubst (type, targs, tf_none, NULL_TREE);
30614      }
30615  return type;
30616}
30617
30618/* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
30619   'decltype(auto)' or a deduced class template.  */
30620
30621bool
30622is_auto (const_tree type)
30623{
30624  if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
30625      && (TYPE_IDENTIFIER (type) == auto_identifier
30626	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
30627    return true;
30628  else
30629    return false;
30630}
30631
30632/* for_each_template_parm callback for type_uses_auto.  */
30633
30634int
30635is_auto_r (tree tp, void */*data*/)
30636{
30637  return is_auto (tp);
30638}
30639
30640/* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
30641   a use of `auto'.  Returns NULL_TREE otherwise.  */
30642
30643tree
30644type_uses_auto (tree type)
30645{
30646  if (type == NULL_TREE)
30647    return NULL_TREE;
30648  else if (flag_concepts_ts)
30649    {
30650      /* The Concepts TS allows multiple autos in one type-specifier; just
30651	 return the first one we find, do_auto_deduction will collect all of
30652	 them.  */
30653      if (uses_template_parms (type))
30654	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
30655				       /*visited*/NULL, /*nondeduced*/false);
30656      else
30657	return NULL_TREE;
30658    }
30659  else
30660    return find_type_usage (type, is_auto);
30661}
30662
30663/* Report ill-formed occurrences of auto types in ARGUMENTS.  If
30664   concepts are enabled, auto is acceptable in template arguments, but
30665   only when TEMPL identifies a template class.  Return TRUE if any
30666   such errors were reported.  */
30667
30668bool
30669check_auto_in_tmpl_args (tree tmpl, tree args)
30670{
30671  if (!flag_concepts_ts)
30672    /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
30673       have already been rejected by the parser more generally.  */
30674    return false;
30675
30676  /* If there were previous errors, nevermind.  */
30677  if (!args || TREE_CODE (args) != TREE_VEC)
30678    return false;
30679
30680  /* If TMPL is an identifier, we're parsing and we can't tell yet
30681     whether TMPL is supposed to be a type, a function or a variable.
30682     We'll only be able to tell during template substitution, so we
30683     expect to be called again then.  If concepts are enabled and we
30684     know we have a type, we're ok.  */
30685  if (identifier_p (tmpl)
30686      || (DECL_P (tmpl)
30687	  &&  (DECL_TYPE_TEMPLATE_P (tmpl)
30688	       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
30689    return false;
30690
30691  /* Quickly search for any occurrences of auto; usually there won't
30692     be any, and then we'll avoid allocating the vector.  */
30693  if (!type_uses_auto (args))
30694    return false;
30695
30696  bool errors = false;
30697
30698  tree vec = extract_autos (args);
30699  for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
30700    {
30701      tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
30702      error_at (DECL_SOURCE_LOCATION (xauto),
30703		"invalid use of %qT in template argument", xauto);
30704      errors = true;
30705    }
30706
30707  return errors;
30708}
30709
30710/* Recursively walk over && expressions searching for EXPR. Return a reference
30711   to that expression.  */
30712
30713static tree *find_template_requirement (tree *t, tree key)
30714{
30715  if (*t == key)
30716    return t;
30717  if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
30718    {
30719      if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
30720	return p;
30721      if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
30722	return p;
30723    }
30724  return 0;
30725}
30726
30727/* Convert the generic type parameters in PARM that match the types given in the
30728   range [START_IDX, END_IDX) from the current_template_parms into generic type
30729   packs.  */
30730
30731tree
30732convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
30733{
30734  tree current = current_template_parms;
30735  int depth = TMPL_PARMS_DEPTH (current);
30736  current = INNERMOST_TEMPLATE_PARMS (current);
30737  tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
30738
30739  for (int i = 0; i < start_idx; ++i)
30740    TREE_VEC_ELT (replacement, i)
30741      = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30742
30743  for (int i = start_idx; i < end_idx; ++i)
30744    {
30745      /* Create a distinct parameter pack type from the current parm and add it
30746	 to the replacement args to tsubst below into the generic function
30747	 parameter.  */
30748      tree node = TREE_VEC_ELT (current, i);
30749      tree o = TREE_TYPE (TREE_VALUE (node));
30750      tree t = copy_type (o);
30751      TEMPLATE_TYPE_PARM_INDEX (t)
30752	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
30753				      t, 0, 0, tf_none);
30754      TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
30755      TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
30756      TYPE_MAIN_VARIANT (t) = t;
30757      TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
30758      TYPE_CANONICAL (t) = canonical_type_parameter (t);
30759      TREE_VEC_ELT (replacement, i) = t;
30760
30761      /* Replace the current template parameter with new pack.  */
30762      TREE_VALUE (node) = TREE_CHAIN (t);
30763
30764      /* Surgically adjust the associated constraint of adjusted parameter
30765         and it's corresponding contribution to the current template
30766         requirements.  */
30767      if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
30768	{
30769	  tree id = unpack_concept_check (constr);
30770	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
30771	  tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
30772	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
30773
30774	  /* If there was a constraint, we also need to replace that in
30775	     the template requirements, which we've already built.  */
30776	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
30777	  reqs = find_template_requirement (reqs, constr);
30778	  *reqs = fold;
30779	}
30780    }
30781
30782  for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
30783    TREE_VEC_ELT (replacement, i)
30784      = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30785
30786  /* If there are more levels then build up the replacement with the outer
30787     template parms.  */
30788  if (depth > 1)
30789    replacement = add_to_template_args (template_parms_to_args
30790					(TREE_CHAIN (current_template_parms)),
30791					replacement);
30792
30793  return tsubst (parm, replacement, tf_none, NULL_TREE);
30794}
30795
30796/* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
30797   0..N-1.  */
30798
30799void
30800declare_integer_pack (void)
30801{
30802  tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
30803			       build_function_type_list (integer_type_node,
30804							 integer_type_node,
30805							 NULL_TREE),
30806			       NULL_TREE, ECF_CONST);
30807  DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
30808  set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
30809			      CP_BUILT_IN_INTEGER_PACK);
30810}
30811
30812/* Walk the decl or type specialization table calling FN on each
30813   entry.  */
30814
30815void
30816walk_specializations (bool decls_p,
30817		      void (*fn) (bool decls_p, spec_entry *entry, void *data),
30818		      void *data)
30819{
30820  spec_hash_table *table = decls_p ? decl_specializations
30821    : type_specializations;
30822  spec_hash_table::iterator end (table->end ());
30823  for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
30824    fn (decls_p, *iter, data);
30825}
30826
30827/* Lookup the specialization of *ELT, in the decl or type
30828   specialization table.  Return the SPEC that's already there, or
30829   NULL if nothing.  */
30830
30831tree
30832match_mergeable_specialization (bool decl_p, spec_entry *elt)
30833{
30834  hash_table<spec_hasher> *specializations
30835    = decl_p ? decl_specializations : type_specializations;
30836  hashval_t hash = spec_hasher::hash (elt);
30837  auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
30838
30839  if (slot)
30840    return (*slot)->spec;
30841
30842  return NULL_TREE;
30843}
30844
30845/* Return flags encoding whether SPEC is on the instantiation and/or
30846   specialization lists of TMPL.  */
30847
30848unsigned
30849get_mergeable_specialization_flags (tree tmpl, tree decl)
30850{
30851  unsigned flags = 0;
30852
30853  for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
30854       inst; inst = TREE_CHAIN (inst))
30855    if (TREE_VALUE (inst) == decl)
30856      {
30857	flags |= 1;
30858	break;
30859      }
30860
30861  if (CLASS_TYPE_P (TREE_TYPE (decl))
30862      && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
30863      && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
30864    /* Only need to search if DECL is a partial specialization.  */
30865    for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
30866	 part; part = TREE_CHAIN (part))
30867      if (TREE_VALUE (part) == decl)
30868	{
30869	  flags |= 2;
30870	  break;
30871	}
30872
30873  return flags;
30874}
30875
30876/* Add a new specialization described by SPEC.  DECL is the
30877   maybe-template decl and FLAGS is as returned from
30878   get_mergeable_specialization_flags.  */
30879
30880void
30881add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
30882			      tree decl, unsigned flags)
30883{
30884  hashval_t hash = spec_hasher::hash (elt);
30885  if (decl_p)
30886    {
30887      auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
30888
30889      gcc_checking_assert (!*slot);
30890      auto entry = ggc_alloc<spec_entry> ();
30891      *entry = *elt;
30892      *slot = entry;
30893
30894      if (alias_p)
30895	{
30896	  elt->spec = TREE_TYPE (elt->spec);
30897	  gcc_checking_assert (elt->spec);
30898	}
30899    }
30900
30901  if (!decl_p || alias_p)
30902    {
30903      auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
30904
30905      /* We don't distinguish different constrained partial type
30906	 specializations, so there could be duplicates.  Everything else
30907	 must be new.   */
30908      if (!(flags & 2 && *slot))
30909	{
30910	  gcc_checking_assert (!*slot);
30911
30912	  auto entry = ggc_alloc<spec_entry> ();
30913	  *entry = *elt;
30914	  *slot = entry;
30915	}
30916    }
30917
30918  if (flags & 1)
30919    DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
30920      = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
30921
30922  if (flags & 2)
30923    {
30924      /* A partial specialization.  */
30925      tree cons = tree_cons (elt->args, decl,
30926			     DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
30927      TREE_TYPE (cons) = elt->spec;
30928      DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
30929    }
30930}
30931
30932/* Set up the hash tables for template instantiations.  */
30933
30934void
30935init_template_processing (void)
30936{
30937  decl_specializations = hash_table<spec_hasher>::create_ggc (37);
30938  type_specializations = hash_table<spec_hasher>::create_ggc (37);
30939
30940  if (cxx_dialect >= cxx11)
30941    declare_integer_pack ();
30942}
30943
30944/* Print stats about the template hash tables for -fstats.  */
30945
30946void
30947print_template_statistics (void)
30948{
30949  fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
30950	   "%f collisions\n", (long) decl_specializations->size (),
30951	   (long) decl_specializations->elements (),
30952	   decl_specializations->collisions ());
30953  fprintf (stderr, "type_specializations: size %ld, %ld elements, "
30954	   "%f collisions\n", (long) type_specializations->size (),
30955	   (long) type_specializations->elements (),
30956	   type_specializations->collisions ());
30957}
30958
30959#if CHECKING_P
30960
30961namespace selftest {
30962
30963/* Verify that build_non_dependent_expr () works, for various expressions,
30964   and that location wrappers don't affect the results.  */
30965
30966static void
30967test_build_non_dependent_expr ()
30968{
30969  location_t loc = BUILTINS_LOCATION;
30970
30971  /* Verify constants, without and with location wrappers.  */
30972  tree int_cst = build_int_cst (integer_type_node, 42);
30973  ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
30974
30975  tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
30976  ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
30977  ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
30978
30979  tree string_lit = build_string (4, "foo");
30980  TREE_TYPE (string_lit) = char_array_type_node;
30981  string_lit = fix_string_type (string_lit);
30982  ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
30983
30984  tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
30985  ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
30986  ASSERT_EQ (wrapped_string_lit,
30987	     build_non_dependent_expr (wrapped_string_lit));
30988}
30989
30990/* Verify that type_dependent_expression_p () works correctly, even
30991   in the presence of location wrapper nodes.  */
30992
30993static void
30994test_type_dependent_expression_p ()
30995{
30996  location_t loc = BUILTINS_LOCATION;
30997
30998  tree name = get_identifier ("foo");
30999
31000  /* If no templates are involved, nothing is type-dependent.  */
31001  gcc_assert (!processing_template_decl);
31002  ASSERT_FALSE (type_dependent_expression_p (name));
31003
31004  ++processing_template_decl;
31005
31006  /* Within a template, an unresolved name is always type-dependent.  */
31007  ASSERT_TRUE (type_dependent_expression_p (name));
31008
31009  /* Ensure it copes with NULL_TREE and errors.  */
31010  ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31011  ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31012
31013  /* A USING_DECL in a template should be type-dependent, even if wrapped
31014     with a location wrapper (PR c++/83799).  */
31015  tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31016  TREE_TYPE (using_decl) = integer_type_node;
31017  ASSERT_TRUE (type_dependent_expression_p (using_decl));
31018  tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31019  ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31020  ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31021
31022  --processing_template_decl;
31023}
31024
31025/* Run all of the selftests within this file.  */
31026
31027void
31028cp_pt_cc_tests ()
31029{
31030  test_build_non_dependent_expr ();
31031  test_type_dependent_expression_p ();
31032}
31033
31034} // namespace selftest
31035
31036#endif /* #if CHECKING_P */
31037
31038#include "gt-cp-pt.h"
31039